Merge upstream main (v1.15.1 -> v1.17.0, 152 commits) into the SYCL port

Conflicts, both sides kept:
- abi: RAD_ABI_VERSION 37 (upstream); the fork's RadBuildCtx.plain_norm after upstream's
  expert_file_tier, widened to int64_t so it starts past ABI 37's 208-byte struct instead of in
  its tail padding (abi_layout_test); RadSyclStream rows after RadShapeGen*.
- arch/common/rad_block_gdn_fp8.h: upstream's q8_rot guard and the fork's o_plain guard
  combined; the decode-row q_o.step only where q_o is declared (!o_plain).
- docs/OPS.md: upstream's optional params on sample_logprobs, the fork's q_temp on
  mtp_couple_propose.

Also ignores /baseline-models/ (local model copies).

Host tests: arch_test's MTP lint/graph-pin failures are unchanged from before the merge (the
fork's mtp.fc LinearFP8, 10a99a5); avx_check's hand-built moe_gemm_q w4a8 case also fails on
upstream's own files; images/videos need FFmpeg; three binaries over their CPU budget on this VM.
SYCL card tests 3/3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-11-07 22:13:08 +01:00
commit 45f3b510c7
365 files changed
+56942 -6331

No files matched your search

+1
View File
@@ -6,3 +6,4 @@ compile_commands.json
/sync-jarvis.sh /sync-jarvis.sh
__pycache__/ __pycache__/
.cache/ .cache/
/baseline-models/
+5 -3
View File
@@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.21) cmake_minimum_required(VERSION 3.21)
# VERSION is the server release that /version reports. The plugin ABI version is separate and is # VERSION is the server release that /version reports. The plugin ABI version is separate and is
# read from abi/rad_abi.h below. # read from abi/rad_abi.h below.
project(radiance VERSION 1.15.1 LANGUAGES C CXX) project(radiance VERSION 1.17.0 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -20,6 +20,7 @@ set(RAD_WITH_FFMPEG "AUTO" CACHE STRING
"ON | OFF | AUTO -- decode image, video and audio parts with libavformat/libavcodec/libswscale/libswresample") "ON | OFF | AUTO -- decode image, video and audio parts with libavformat/libavcodec/libswscale/libswresample")
set_property(CACHE RAD_WITH_FFMPEG PROPERTY STRINGS ON OFF AUTO) set_property(CACHE RAD_WITH_FFMPEG PROPERTY STRINGS ON OFF AUTO)
option(RAD_BUILD_TESTS "Build the test suite" ON) option(RAD_BUILD_TESTS "Build the test suite" ON)
option(RAD_ENABLE_KV_ROLLBACK_TEST_HOOK "Compile the test-only device KV rollback observer" OFF)
option(RAD_ASAN "Build host code with AddressSanitizer and UBSan" OFF) option(RAD_ASAN "Build host code with AddressSanitizer and UBSan" OFF)
option(RAD_TSAN "Build host code with ThreadSanitizer" OFF) option(RAD_TSAN "Build host code with ThreadSanitizer" OFF)
# LLVM 24's VOPD pairing is not repeatable unless patched (docker/llvm-vopd-pairing.patch); when # LLVM 24's VOPD pairing is not repeatable unless patched (docker/llvm-vopd-pairing.patch); when
@@ -391,8 +392,9 @@ if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr4d/CMakeLists.txt)
endif() endif()
# libr3d: the RDNA3 kernel library, same shape as libr4d and same guard -- device code needs a HIP # libr3d: the RDNA3 kernel library, same shape as libr4d and same guard -- device code needs a HIP
# toolchain. It declares itself for `^gfx11` and returns without a target when the build's # toolchain. It declares itself for `^gfx11` and returns without a target when the build's
# RAD_GPU_TARGETS holds no RDNA3, so a gfx12-only build of this tree does not produce it. A card # RAD_GPU_TARGETS holds no RDNA3, so a gfx12-only build of this tree does not produce it, and
# with no kernel library of its own refuses device-only ops (docs/PLUGIN.md §10). # declines every machine without a gfx11 card (rad_plugin_open). A card with no kernel library of
# its own refuses device-only ops (docs/PLUGIN.md §10).
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr3d/CMakeLists.txt) if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr3d/CMakeLists.txt)
add_subdirectory(libr3d) add_subdirectory(libr3d)
endif() endif()
+11 -8
View File
@@ -28,10 +28,12 @@
# and refuses a compressed bundle. # and refuses a compressed bundle.
# #
# GPU_TARGETS must be named: a build container has no card to detect, unlike a bare-metal # GPU_TARGETS must be named: a build container has no card to detect, unlike a bare-metal
# ./build.sh. They are the targets of the shipped kernel libraries; libr4d serves RDNA4 only and # ./build.sh. They are the targets of the shipped kernel libraries, each of which keeps only its own
# drops every architecture outside gfx12. The engine's own kernels carry the generic family # family: libr4d takes gfx1201 (RDNA4), libr3d gfx11-generic (every RDNA3 chip) and gfx1151, and
# targets and run on every AMD GPU family, so a kernel library for another card is added by # libhalo gfx1151 (Strix Halo), where the loader prefers it over libr3d. On any one card the other
# mounting it on the search path: # libraries decline or are left out, so the default image serves all three. The engine's own
# kernels carry the generic family targets and run on every AMD GPU family, so a kernel library for
# another card is added by mounting it on the search path:
# docker run ... -v /my/plugins:/plugins -e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance # docker run ... -v /my/plugins:/plugins -e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance
# #
# The image's ROCm userspace must be supported by the host's amdgpu kernel driver; it is pinned to # The image's ROCm userspace must be supported by the host's amdgpu kernel driver; it is pinned to
@@ -131,7 +133,7 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
# ------------------------------------------------------------------------------------------ build # ------------------------------------------------------------------------------------------ build
FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS build FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS build
ARG GPU_TARGETS=gfx1201 ARG GPU_TARGETS="gfx1201;gfx11-generic;gfx1151"
# Parallel compile jobs; empty means one per core. A device-kernel translation unit takes 2-3 GB # 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. # of RAM under hipcc, so lower it on a host that is also serving.
ARG JOBS= ARG JOBS=
@@ -227,11 +229,12 @@ ARG TEST_EXCLUDE=
# perf_event_open, so the tests that bound work count CPU time rather than instructions # perf_event_open, so the tests that bound work count CPU time rather than instructions
# (tests/work_counter.h). The `oot` suite (every shipped plugin rebuilt against the installed # (tests/work_counter.h). The `oot` suite (every shipped plugin rebuilt against the installed
# package) repeats this stage's whole compile, so it runs from the development tree instead # package) repeats this stage's whole compile, so it runs from the development tree instead
# (tests/oot_plugins.sh). # (tests/oot_plugins.sh). The `parity` entry (halo_parity: libhalo's tables against libr4d's) is
# left out until libhalo has ported the ops libr4d added after it (the test names each one).
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
bash /src/docker/llvm-check.sh /build \ bash /src/docker/llvm-check.sh /build \
&& RAD_TEST_CPU_BUDGET_SCALE="${TEST_CPU_BUDGET_SCALE}" \ && RAD_TEST_CPU_BUDGET_SCALE="${TEST_CPU_BUDGET_SCALE}" \
ctest --test-dir /build -LE 'gpu|oot' ${TEST_EXCLUDE:+-E "${TEST_EXCLUDE}"} \ ctest --test-dir /build -LE 'gpu|oot|parity' ${TEST_EXCLUDE:+-E "${TEST_EXCLUDE}"} \
-j"${TEST_JOBS:-${JOBS:-$(( ($(nproc) + 1) / 2 ))}}" --output-on-failure \ -j"${TEST_JOBS:-${JOBS:-$(( ($(nproc) + 1) / 2 ))}}" --output-on-failure \
&& touch /build/host-tests-passed && touch /build/host-tests-passed
@@ -283,7 +286,7 @@ RUN set -e; R=/rootfs; L=$R/usr/lib/x86_64-linux-gnu; \
# ---------------------------------------------------------------------------------------- runtime # ---------------------------------------------------------------------------------------- runtime
FROM scratch AS runtime FROM scratch AS runtime
ARG GPU_TARGETS=gfx1201 ARG GPU_TARGETS="gfx1201;gfx11-generic;gfx1151"
ARG VERSION=dev ARG VERSION=dev
ARG REVISION=unknown ARG REVISION=unknown
+27 -6
View File
@@ -19,13 +19,24 @@ Written by Deadcode, with contributions from:
Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files, Gemma 4's E2B/E4B form (KV-shared Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files, Gemma 4's E2B/E4B form (KV-shared
layers, per-layer embeddings, clipped vision linears) with NVIDIA-Nemotron-3.5-Bolt-E4B, its audio layers, per-layer embeddings, clipped vision linears) with NVIDIA-Nemotron-3.5-Bolt-E4B, its audio
encoder, its i8a8 linears and its KV heads replicated over ranks, 4-bit weights at decode heights encoder, its i8a8 linears and its KV heads replicated over ranks, 4-bit weights at decode heights
through w4a16_asym, and the Ornith-1.5-122B compose files through w4a16_asym, the Ornith-1.5-122B compose files, the Gemma 4 31B's asymmetric int5
linears (w5a8i8 and w5a16), the junctions at quant_act_i8g's grid (rmsnorm_quant_i8g,
gelu_mul_quant_i8g and ar_rmsnorm_quant_i8g) with the prefill overlap on the i8a8, a4 and w5
grids, the 31B's i8g, heretic-ara-i8g and w5 compose files, and Ling-3.0-flash (bailing_hybrid:
KDA, dense latent attention, group-limited sigmoid routing, the clipped SwiGLU and its MTP layer as
a serial drafter) with mla_attn_paged, its w4a8 recipes and compose files, possessive quantifiers
in the tokenizer's patterns, the Grafana dashboard's first screen, and Gemma 4 12B (its picture
and audio embedders, a picture's placeholders read both ways on the sliding layers, the windowed
attention at head_dim 512, suppress_tokens) with its compose files
- mechkbfan: the token embedding in the pinned host pool - 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 - 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 coupling with its cooperative verify (--draft-coupling), the W4A8 prefill's tail scale read, the
ISA instruments' VGPR granule, back-edge count and fail-closed parse, scored steps ISA instruments' VGPR granule, back-edge count and fail-closed parse, scored steps
(rad_declare_scores, RadBatch::score_only), the gated prefill fold, the short-prompt split row and (rad_declare_scores, RadBatch::score_only), the gated prefill fold, the short-prompt split row and
the rows forms of rmsnorm and rope, and LFM2's 8-bit trunk with the d1-3B recipe the rows forms of rmsnorm and rope, LFM2's 8-bit trunk with the d1-3B recipe, the file tier's
routed reads with their own router's counts and its deposit wait, the stop-string hold-back, and
the sampler's planes by the step's token bound, its n-gram ban beside a drafter and no candidate
cut over a top-1 row
- baKon: three-rank tensor parallelism, serving any world size from the shipped container, the - baKon: three-rank tensor parallelism, serving any world size from the shipped container, the
request log, an uneven world's per-rank KV and weights split, --rope-scaling, the model entry's request log, an uneven world's per-rank KV and weights split, --rope-scaling, the model entry's
context length, root and capabilities, /props, the three-rank two-shot all-reduce and tiered-int8 context length, root and capabilities, /props, the three-rank two-shot all-reduce and tiered-int8
@@ -85,7 +96,8 @@ Written by Deadcode, with contributions from:
split by depth, the delta net's out-projection read beside its decode recurrent update, the MXFP4 split by depth, the delta net's out-projection read beside its decode recurrent update, the MXFP4
feed-forward's gated fold up to 16 rows, the three-wave verify floor bounded by the batch's feed-forward's gated fold up to 16 rows, the three-wave verify floor bounded by the batch's
workgroups, the split-KV row sum read with fetch-inactive, KLATE again for the head-256 gqa6 workgroups, the split-KV row sum read with fetch-inactive, KLATE again for the head-256 gqa6
paged prefill, and the preempted-prefill gate past a KV group that holds no blocks paged prefill, the preempted-prefill gate past a KV group that holds no blocks, and the norms'
lane sum issuing its reads eight at a time
- eddie168168: the rotated int8 trunk (i8a8h) and the qwen35_w8a8 plugin serving it, and the - eddie168168: the rotated int8 trunk (i8a8h) and the qwen35_w8a8 plugin serving it, and the
out-of-tree test at the tree's VOPD setting, and its norm and SiLU producers writing the int8 out-of-tree test at the tree's VOPD setting, and its norm and SiLU producers writing the int8
linears' operands directly linears' operands directly
@@ -106,7 +118,8 @@ Written by Deadcode, with contributions from:
one-sequence KV floor over the live plan, and prefill staging paid by expert residency one-sequence KV floor over the live plan, and prefill staging paid by expert residency
- Memoria: the dashboard's decode floor and recent window, the sparklines' percentile range, and - Memoria: the dashboard's decode floor and recent window, the sparklines' percentile range, and
the bringup time in /stats, the acceptance tiles' live figures and statsdump's size-capped the bringup time in /stats, the acceptance tiles' live figures and statsdump's size-capped
rotation rotation, the dashboard's history line, session extremes, card-count changes and Requests-header
JSON export, with the page's JavaScript driven by tests/js
- C_Tamas: control vectors, loaded when the deployment asks and applied as a per-layer residual - 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 projection, KV streaming for a context bigger than VRAM (--kv-resident), and the dashboard's
request history, KV streaming traffic and one-unit KV meter request history, KV streaming traffic and one-unit KV meter
@@ -118,7 +131,11 @@ Written by Deadcode, with contributions from:
- farcryjohn: periodic window snapshots that let an edited prompt reuse its prefix - farcryjohn: periodic window snapshots that let an edited prompt reuse its prefix
- gostar: snapshot-backed prefix KV kept across recomputes, and Tencent's Hy-Memory (HYV3) -- its - gostar: snapshot-backed prefix KV kept across recomputes, and Tencent's Hy-Memory (HYV3) -- its
BF16, FP8 and GGUF adapters, its KV scales, its native sectioned tool calls, and its W4 decode BF16, FP8 and GGUF adapters, its KV scales, its native sectioned tool calls, and its W4 decode
(the per-128 I4 expert packing, the one-row W4/W5 epilogue and the fused prologue and folds) (the per-128 I4 expert packing, the one-row W4/W5 epilogue and the fused prologue and folds),
and the head-256 prefill softmax rescaled by row rather than by wave, Spark 2.5 (spark25: bf16 and
rotated-int8 IQ8R checkpoints, tensor parallelism with exact collectives, reasoning and tagged
tool calls) with its DSpark drafter (exact attention and Markov walk ops), the prefill split keyed
by live KV bounds, and --gpu-memory-mib
- launch80_assets: tuning collectives as the exchange they serve at the served configuration, the - launch80_assets: tuning collectives as the exchange they serve at the served configuration, the
per-layer embeddings' read-ahead queue and gather regimes, and the step loop's stall watch per-layer embeddings' read-ahead queue and gather regimes, and the step loop's stall watch
- hugypufy: M2XFP4 -- its quantiser, its GEMMs and its linears in the Qwen3.8 trunk and the DFlash2 - hugypufy: M2XFP4 -- its quantiser, its GEMMs and its linears in the Qwen3.8 trunk and the DFlash2
@@ -134,7 +151,9 @@ Written by Deadcode, with contributions from:
- Dad_Vibes: hc_read's decode kernels as one grid, its tiled up-mix pipelined and its one-grid - Dad_Vibes: hc_read's decode kernels as one grid, its tiled up-mix pipelined and its one-grid
wait trapping past its deadline, and gemm_fp8a8's narrow form with its scales staged through LDS wait trapping past its deadline, and gemm_fp8a8's narrow form with its scales staged through LDS
and its gated three-tile form at 8 waves and its gated three-tile form at 8 waves
- RikshaDriver: libr3d, the RDNA3 (gfx11) kernel library - 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
- fl0l0u: every request entry point bounded, gated and sanitised (JSON parses bounded in depth, - fl0l0u: every request entry point bounded, gated and sanitised (JSON parses bounded in depth,
errors safe on invalid UTF-8, control bytes kept off the log, the dashboard's CSP, cross-origin errors safe on invalid UTF-8, control bytes kept off the log, the dashboard's CSP, cross-origin
browsers refused on the loopback-only routes, method-scoped API-key exemptions), prompt ids that browsers refused on the loopback-only routes, method-scoped API-key exemptions), prompt ids that
@@ -150,6 +169,8 @@ Written by Deadcode, with contributions from:
hot VRAM cache with its deposits and copyless relabels, and GLM-5.3-Flash's experts read hot VRAM cache with its deposits and copyless relabels, and GLM-5.3-Flash's experts read
file-direct under expert parallelism -- the stall watch counting drive reads as progress, and file-direct under expert parallelism -- the stall watch counting drive reads as progress, and
the DMA lane's lists fenced so a stalled read pointer no longer fills its ring the DMA lane's lists fenced so a stalled read pointer no longer fills its ring
- pokesjw: the n-gram reader refilling its reads as they land, and a decode gather waiting on the
other rank's read of a row instead of reading it again
This product includes software from the following projects, each under the MIT License. The This product includes software from the following projects, each under the MIT License. The
license text is in the file named beside each. license text is in the file named beside each.
+19 -3
View File
@@ -6,7 +6,8 @@ APIs, Anthropic's Messages API and llama-server's native one, so their clients a
unchanged. Model architectures, kernel libraries and quantisers are `.so` plugins; the ones in this unchanged. Model architectures, kernel libraries and quantisers are `.so` plugins; the ones in this
tree are built and loaded the same way a third party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)). tree are built and loaded the same way a third party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)).
The bundled device kernels (`libr4d`) target AMD RDNA4 (`gfx1200`, `gfx1201`). The serve flags The bundled device kernels target AMD RDNA4 (`libr4d`: `gfx1200`, `gfx1201`), RDNA3 (`libr3d`:
`gfx11xx`) and Strix Halo (`libhalo`: `gfx1151`). The serve flags
below are for two 32 GB cards (Radeon AI PRO R9700). The engine starts on any AMD GPU family; below are for two 32 GB cards (Radeon AI PRO R9700). The engine starts on any AMD GPU family;
another card needs a kernel library for it. A machine with no GPU builds the host backend, whose another card needs a kernel library for it. A machine with no GPU builds the host backend, whose
AVX-512/AVX2 kernels (`libavx`) serve every model here: the small ones (EmbeddingGemma 2, AVX-512/AVX2 kernels (`libavx`) serve every model here: the small ones (EmbeddingGemma 2,
@@ -91,6 +92,7 @@ it (`-DRAD_XE2_MKL=OFF`, or `XE2_NO_MKL=1` at run time, keeps the hand-written p
| Qwen3.8-Flash-Next: 4-bit experts, int8 trunk, MTP, vision | `qwen3.8-next-flash-fp8-iq4r-moe.rad` (114 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-fp8-iq4r-moe) | `flashnext.yaml` | | Qwen3.8-Flash-Next: 4-bit experts, int8 trunk, MTP, vision | `qwen3.8-next-flash-fp8-iq4r-moe.rad` (114 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-fp8-iq4r-moe) | `flashnext.yaml` |
| Qwen3.8-27B FP8, DFlash2 drafter, vision | `qwen3.8-27b-fp8.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-fp8) | `qwen3.8-27b-fp8.yaml` | | Qwen3.8-27B FP8, DFlash2 drafter, vision | `qwen3.8-27b-fp8.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-fp8) | `qwen3.8-27b-fp8.yaml` |
| Qwen3.8-27B MXFP4 (AMD Quark AWQ), DFlash2 drafter, vision | `qwen3.8-27b-mxfp4.rad` (19 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-mxfp4) | `qwen3.8-27b-mxfp4.yaml` | | Qwen3.8-27B MXFP4 (AMD Quark AWQ), DFlash2 drafter, vision | `qwen3.8-27b-mxfp4.rad` (19 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-mxfp4) | `qwen3.8-27b-mxfp4.yaml` |
| Qwen3.8-27B IQR-V4, 2.5 to 8 bits a weight ([docs/IQR.md](docs/IQR.md)), DFlash2 drafter, vision | `qwen3.8-27b-iq2r-v4.rad` .. `qwen3.8-27b-iq8r-v4.rad` (10 to 28 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-iqr-v4) | `qwen3.8-27b-iqr-v4.yaml` |
| Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` | | Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` |
| Ornith-1.5-35B-A3B FP8, MTP, vision | `ornith-1.5-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-fp8) | `ornith-1.5-35b-a3b.yaml` | | Ornith-1.5-35B-A3B FP8, MTP, vision | `ornith-1.5-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-fp8) | `ornith-1.5-35b-a3b.yaml` |
| Ornith-1.5-35B-A3B w4a8: 4-bit experts (GPTQ), MTP, vision, fits one card | `ornith-1.5-35b-a3b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-w4a8) | `ornith-1.5-35b-a3b-w4a8.yaml` | | Ornith-1.5-35B-A3B w4a8: 4-bit experts (GPTQ), MTP, vision, fits one card | `ornith-1.5-35b-a3b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-w4a8) | `ornith-1.5-35b-a3b-w4a8.yaml` |
@@ -102,6 +104,7 @@ it (`-DRAD_XE2_MKL=OFF`, or `XE2_NO_MKL=1` at run time, keeps the hand-written p
| Sage-A1.5 FP8, DFlash2 drafter, vision | `sage-a1.5-fp8-df2.rad` (34 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8-df2) | `sage-a1.5-df2.yaml` | | Sage-A1.5 FP8, DFlash2 drafter, vision | `sage-a1.5-fp8-df2.rad` (34 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8-df2) | `sage-a1.5-df2.yaml` |
| MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` | | MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` |
| MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` | | MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` |
| Spark X2.6 4B bf16: thinking and tool calls, one to four cards | `spark-x2.6-4b-bf16.rad` (8.3 GiB) | [convert](#convert-a-checkpoint) | — |
| Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` | | Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` |
| Gemma 4 31B 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) | `gemma4-31b-w5.yaml` | | 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) | `gemma4-31b-w5.yaml` |
| Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | `gemma4-31b-heretic-ara-w4a8.yaml` | | Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | `gemma4-31b-heretic-ara-w4a8.yaml` |
@@ -111,9 +114,14 @@ it (`-DRAD_XE2_MKL=OFF`, or `XE2_NO_MKL=1` at run time, keeps the hand-written p
| Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | `gemma4-31b-q8-df.yaml` | | Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | `gemma4-31b-q8-df.yaml` |
| Gemma 4 31B on four cards: int4 trunk, int8 activations and lm_head, RedHatAI's DFlash2 drafter, vision | `gemma4-31b-dense-w4a8-df2-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2) | `gemma4-31b-w4a8-df2-tp4.yaml` | | Gemma 4 31B on four cards: int4 trunk, int8 activations and lm_head, RedHatAI's DFlash2 drafter, vision | `gemma4-31b-dense-w4a8-df2-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2) | `gemma4-31b-w4a8-df2-tp4.yaml` |
| Gemma 4 31B on four or two cards: int4 trunk, int8 activations and lm_head, a block-16 DFlash2 drafter (15 drafts a step, verified as a tree), vision | `gemma4-31b-dense-w4a8-df2b16-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2-b16) | `gemma4-31b-w4a8-df2b16-tp4.yaml`, `gemma4-31b-w4a8-df2b16-tp2.yaml` | | Gemma 4 31B on four or two cards: int4 trunk, int8 activations and lm_head, a block-16 DFlash2 drafter (15 drafts a step, verified as a tree), vision | `gemma4-31b-dense-w4a8-df2b16-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2-b16) | `gemma4-31b-w4a8-df2b16-tp4.yaml`, `gemma4-31b-w4a8-df2b16-tp2.yaml` |
| Gemma 4 12B bf16: MTP, vision, audio | `gemma4-12b-bf16.rad` (25 GiB) | [download](https://huggingface.co/keptn/gemma4-12b-bf16) | `gemma4-12b-bf16.yaml` |
| Gemma 4 12B int8 (i8a8): MTP, vision, audio | `gemma4-12b-i8g.rad` (14 GiB) | [download](https://huggingface.co/keptn/gemma4-12b-i8g) | `gemma4-12b-i8g.yaml` |
| NVIDIA-Nemotron-3.5-Bolt-E4B bf16 (Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-bf16.rad` (17 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-bf16) | `nemotron-3.5-bolt-e4b-bf16.yaml` | | NVIDIA-Nemotron-3.5-Bolt-E4B bf16 (Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-bf16.rad` (17 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-bf16) | `nemotron-3.5-bolt-e4b-bf16.yaml` |
| NVIDIA-Nemotron-3.5-Bolt-E4B int8 (i8a8, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-i8g.rad` (13 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-i8g) | `nemotron-3.5-bolt-e4b-i8g.yaml` | | NVIDIA-Nemotron-3.5-Bolt-E4B int8 (i8a8, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-i8g.rad` (13 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-i8g) | `nemotron-3.5-bolt-e4b-i8g.yaml` |
| NVIDIA-Nemotron-3.5-Bolt-E4B 4-bit (int4 feed-forward, GPTQ, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-a4.rad` (12 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-a4) | `nemotron-3.5-bolt-e4b-a4.yaml` | | NVIDIA-Nemotron-3.5-Bolt-E4B 4-bit (int4 feed-forward, GPTQ, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-a4.rad` (12 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-a4) | `nemotron-3.5-bolt-e4b-a4.yaml` |
| Ling-3.0-flash-Sante w4a8: 4-bit experts (GPTQ), MTP, four or two cards | `ling-3.0-flash-sante-w4a8.rad` (66 GiB) | [download](https://huggingface.co/keptn/ling-3.0-flash-sante-w4a8) | `ling-3.0-flash-sante-w4a8.yaml`, `ling-3.0-flash-sante-w4a8-tp2.yaml` |
| NVIDIA-Nemotron-3.5-Bolt-74B-A9B w4a8: 4-bit experts, FP8 trunk, NVIDIA's LiLiCorr drafter, vision, two cards | `nemotron-3.5-bolt-74b-w4a8.rad` (43 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-74b-w4a8) | `nemotron-3.5-bolt-74b-w4a8.yaml` |
| NVIDIA-Nemotron-3.5-Bolt-74B-A9B FP8, NVIDIA's LiLiCorr drafter, vision, four cards | `nemotron-3.5-bolt-74b-fp8.rad` (73 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-74b-fp8) | `nemotron-3.5-bolt-74b-fp8.yaml` |
| Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` | | Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` |
| Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` | | Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` |
| Krea 2 Turbo FP8: text to image, one card | `krea-2-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-fp8) | `krea-2-turbo.yaml` | | Krea 2 Turbo FP8: text to image, one card | `krea-2-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-fp8) | `krea-2-turbo.yaml` |
@@ -219,8 +227,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 without it the engine keeps kernel arguments in pinned host memory, and every dispatch reads them
over the link. The image over the link. The image
is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its kernels is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its kernels
built for `gfx1201`. Pull it, clone this repository for its compose files, then start a model from built for `gfx1201` (RDNA4), `gfx11-generic` (RDNA3) and `gfx1151` (Strix Halo). Pull it, clone
one of them: this repository for its compose files, then start a model from one of them:
```sh ```sh
docker pull stilldeadcode/radiance docker pull stilldeadcode/radiance
@@ -349,6 +357,8 @@ budgets, long context, speculative decoding and operating a server.
`data/recipes/` names. Download checkpoints with `scripts/hfget.sh <org/repo> <dir>`. `data/recipes/` names. Download checkpoints with `scripts/hfget.sh <org/repo> <dir>`.
```sh ```sh
# Spark X2.6 uses the checkpoint's BF16 weights, tokenizer and chat template; no recipe required.
build/bin/rad-convert /srv/models/hf/XHToken-Spark-X2.6-4B -o spark-x2.6-4b-bf16.rad --max-ctx 4096
build/bin/rad-convert /srv/models/hf/Qwen/Qwen3.8-27B -o qwen3.8-27b-bf16.rad \ build/bin/rad-convert /srv/models/hf/Qwen/Qwen3.8-27B -o qwen3.8-27b-bf16.rad \
--recipe data/recipes/q38-27b-bf16.recipe --recipe data/recipes/q38-27b-bf16.recipe
build/bin/rad-convert /srv/models/hf/Qwen/Qwen3.8-Flash-Next -o qwen3.8-flash-next-bf16.rad --max-ctx 4096 build/bin/rad-convert /srv/models/hf/Qwen/Qwen3.8-Flash-Next -o qwen3.8-flash-next-bf16.rad --max-ctx 4096
@@ -387,6 +397,12 @@ reads it: NVFP4 (compressed-tensors' and NVIDIA ModelOpt's) to the MXFP4 kernels
Flash-Next's int4 block projections to int8. [docs/GUIDE.md](docs/GUIDE.md) names the recipes of record Flash-Next's int4 block projections to int8. [docs/GUIDE.md](docs/GUIDE.md) names the recipes of record
with their `rad-convert` commands. with their `rad-convert` commands.
Spark X2.6 runs BF16 at `--tp 1`, `2`, `3` or `4` -- and `8`, the worlds libr4d has an exact
all-reduce for -- without a drafter or quantisation recipe. Its checkpoint's chat template enables
thinking by default; replies return reasoning in `reasoning_content`. Set
`chat_template_kwargs.enable_thinking` to `false` for a non-thinking request. Tool calls use the
checkpoint's tagged format and are returned as OpenAI `tool_calls`.
## Test ## Test
```sh ```sh
+18 -3
View File
@@ -21,7 +21,7 @@ extern "C" {
* (e.g. rad_plugin_reference) is not a change of shape: a plugin without it gets the default. * (e.g. rad_plugin_reference) is not a change of shape: a plugin without it gets the default.
* rad_sycl.h is versioned on its own (RAD_SYCL_STREAM_VERSION), since only SYCL kernel libraries * rad_sycl.h is versioned on its own (RAD_SYCL_STREAM_VERSION), since only SYCL kernel libraries
* read it. */ * read it. */
#define RAD_ABI_VERSION 32u #define RAD_ABI_VERSION 37u
/* ================================================================== plugin identity */ /* ================================================================== plugin identity */
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin: /* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
@@ -62,6 +62,16 @@ typedef struct RadArgs {
void* instance; /* whatever init() returned for this resolved instance */ void* instance; /* whatever init() returned for this resolved instance */
int rank; /* tensor-parallel rank and world size, for collectives */ int rank; /* tensor-parallel rank and world size, for collectives */
int world_size; int world_size;
/* ABI 35: host-side maximum KV length represented by this exact launch operand (a seqused
* span or a supported one-sequence prefill boundary), or -1 when it cannot be proven. In a
* decode, verify or draft pass of an architecture with no rad_arch_pass_key it is instead the
* step's context bound plus its longest query, which the recorded pass's key holds. Plugins
* must not infer it from a device pointer or synchronously read device memory to get it. */
int32_t kv_used_max_h;
/* The current rank's WGP count (HIP multiProcessorCount on RDNA); lets split launchers use
* exactly the same per-device occupancy as architecture pass-key callbacks without querying
* the process-global current device on the hot path. */
int32_t wgp_count;
} RadArgs; } RadArgs;
/* Read a parameter by key. Inline definitions, because a plugin links only the ABI headers and /* Read a parameter by key. Inline definitions, because a plugin links only the ABI headers and
@@ -467,15 +477,20 @@ typedef struct RadKernelInfo {
* against: a named skip, not a failure. */ * against: a named skip, not a failure. */
RadUnrelayoutFn unrelayout; RadUnrelayoutFn unrelayout;
/* The chain of conventional ops this kernel computes in one launch, or null if it is not a /* The chain of conventional ops this kernel computes in one launch, or null if it is not a
* fusion. Non-null also counts in rad-kbench's fusion-claim column. * fusion. Non-null also counts in rad-kbench's fusion-claim column. */
RadFuseFn replaces;
/* Flags describing runtime behavior relevant to core safety decisions. Zero means none.
* *
* Keep this field last. Kernel tables are positional aggregate initialisers * Keep this field last. Kernel tables are positional aggregate initialisers
* (`{..., nullptr, nullptr, r4d_rad_embed_lookup, nullptr, ...}`), so a field inserted * (`{..., nullptr, nullptr, r4d_rad_embed_lookup, nullptr, ...}`), so a field inserted
* anywhere else shifts every later initialiser, and since `nullptr` converts to any function * anywhere else shifts every later initialiser, and since `nullptr` converts to any function
* pointer type, part of that shift would still compile. Append new fields after this one. */ * pointer type, part of that shift would still compile. Append new fields after this one. */
RadFuseFn replaces; uint64_t capabilities;
} RadKernelInfo; } RadKernelInfo;
/* This row's launch grid can depend on live seqused during prefill. */
#define RAD_KERNEL_CAP_DYNAMIC_PREFILL_SPLIT (1ull << 0)
/* ================================================================== kernel plugin exports */ /* ================================================================== kernel plugin exports */
/* Every kernel plugin exports the whole set. The first plugin in hierarchy order to declare an op /* Every kernel plugin exports the whole set. The first plugin in hierarchy order to declare an op
* fixes its schema; a later plugin declaring the same op name with a different schema is refused * fixes its schema; a later plugin declaring the same op name with a different schema is refused
+54
View File
@@ -26,6 +26,7 @@ ABI_FIELD(RadArchProbe, state_f16_ok)
ABI_FIELD(RadArchProbe, tree_pays) ABI_FIELD(RadArchProbe, tree_pays)
ABI_FIELD(RadArchProbe, gen_max_pixels) ABI_FIELD(RadArchProbe, gen_max_pixels)
ABI_FIELD(RadArchProbe, gen_max_refs) ABI_FIELD(RadArchProbe, gen_max_refs)
ABI_FIELD(RadArchProbe, gen_shape)
ABI_STRUCT(RadArgs) ABI_STRUCT(RadArgs)
ABI_FIELD(RadArgs, t) ABI_FIELD(RadArgs, t)
ABI_FIELD(RadArgs, n_t) ABI_FIELD(RadArgs, n_t)
@@ -36,6 +37,8 @@ ABI_FIELD(RadArgs, scratch_bytes)
ABI_FIELD(RadArgs, instance) ABI_FIELD(RadArgs, instance)
ABI_FIELD(RadArgs, rank) ABI_FIELD(RadArgs, rank)
ABI_FIELD(RadArgs, world_size) ABI_FIELD(RadArgs, world_size)
ABI_FIELD(RadArgs, kv_used_max_h)
ABI_FIELD(RadArgs, wgp_count)
ABI_STRUCT(RadBatch) ABI_STRUCT(RadBatch)
ABI_FIELD(RadBatch, phase) ABI_FIELD(RadBatch, phase)
ABI_FIELD(RadBatch, step) ABI_FIELD(RadBatch, step)
@@ -93,6 +96,15 @@ ABI_FIELD(RadBatch, plugin_words)
ABI_FIELD(RadBatch, plugin_cu) ABI_FIELD(RadBatch, plugin_cu)
ABI_FIELD(RadBatch, plugin_words_h) ABI_FIELD(RadBatch, plugin_words_h)
ABI_FIELD(RadBatch, plugin_cu_h) ABI_FIELD(RadBatch, plugin_cu_h)
ABI_FIELD(RadBatch, sgen_b)
ABI_FIELD(RadBatch, kv_used_max_h)
ABI_FIELD(RadBatch, positions_h)
ABI_FIELD(RadBatch, n_bidi)
ABI_FIELD(RadBatch, bidi_row)
ABI_FIELD(RadBatch, bidi_n)
ABI_FIELD(RadBatch, bidi_seq)
ABI_FIELD(RadBatch, bidi_used)
ABI_FIELD(RadBatch, anchor_rows)
ABI_STRUCT(RadBufDecl) ABI_STRUCT(RadBufDecl)
ABI_FIELD(RadBufDecl, dtype) ABI_FIELD(RadBufDecl, dtype)
ABI_FIELD(RadBufDecl, rank) ABI_FIELD(RadBufDecl, rank)
@@ -134,6 +146,7 @@ ABI_FIELD(RadBuildCtx, calib_layer_hi)
ABI_FIELD(RadBuildCtx, calib_tokens) ABI_FIELD(RadBuildCtx, calib_tokens)
ABI_FIELD(RadBuildCtx, gen_max_pixels) ABI_FIELD(RadBuildCtx, gen_max_pixels)
ABI_FIELD(RadBuildCtx, gen_max_refs) ABI_FIELD(RadBuildCtx, gen_max_refs)
ABI_FIELD(RadBuildCtx, expert_file_tier)
ABI_FIELD(RadBuildCtx, plain_norm) ABI_FIELD(RadBuildCtx, plain_norm)
ABI_STRUCT(RadAudioGenBatch) ABI_STRUCT(RadAudioGenBatch)
ABI_FIELD(RadAudioGenBatch, n_lane) ABI_FIELD(RadAudioGenBatch, n_lane)
@@ -312,6 +325,7 @@ ABI_FIELD(RadEncoderDecl, max_patches)
ABI_FIELD(RadEncoderDecl, n_embd) ABI_FIELD(RadEncoderDecl, n_embd)
ABI_FIELD(RadEncoderDecl, out) ABI_FIELD(RadEncoderDecl, out)
ABI_FIELD(RadEncoderDecl, one_grid) ABI_FIELD(RadEncoderDecl, one_grid)
ABI_FIELD(RadEncoderDecl, bidirectional)
ABI_STRUCT(RadEncoding) ABI_STRUCT(RadEncoding)
ABI_FIELD(RadEncoding, scheme) ABI_FIELD(RadEncoding, scheme)
ABI_FIELD(RadEncoding, transform) ABI_FIELD(RadEncoding, transform)
@@ -501,6 +515,7 @@ ABI_FIELD(RadKVGroupBatch, state_index_pitch)
ABI_FIELD(RadKVGroupBatch, block_size) ABI_FIELD(RadKVGroupBatch, block_size)
ABI_FIELD(RadKVGroupBatch, max_blocks) ABI_FIELD(RadKVGroupBatch, max_blocks)
ABI_FIELD(RadKVGroupBatch, stream) ABI_FIELD(RadKVGroupBatch, stream)
ABI_FIELD(RadKVGroupBatch, seqused_h)
ABI_STRUCT(RadKVGroupDecl) ABI_STRUCT(RadKVGroupDecl)
ABI_FIELD(RadKVGroupDecl, kind) ABI_FIELD(RadKVGroupDecl, kind)
ABI_FIELD(RadKVGroupDecl, dtype) ABI_FIELD(RadKVGroupDecl, dtype)
@@ -542,6 +557,7 @@ ABI_FIELD(RadKernelInfo, relayout)
ABI_FIELD(RadKernelInfo, opd_shape) ABI_FIELD(RadKernelInfo, opd_shape)
ABI_FIELD(RadKernelInfo, unrelayout) ABI_FIELD(RadKernelInfo, unrelayout)
ABI_FIELD(RadKernelInfo, replaces) ABI_FIELD(RadKernelInfo, replaces)
ABI_FIELD(RadKernelInfo, capabilities)
ABI_STRUCT(RadLayout) ABI_STRUCT(RadLayout)
ABI_FIELD(RadLayout, tag) ABI_FIELD(RadLayout, tag)
ABI_FIELD(RadLayout, dtype) ABI_FIELD(RadLayout, dtype)
@@ -700,6 +716,44 @@ ABI_FIELD(RadSampleParams, hist_len)
ABI_FIELD(RadSampleParams, mask_row) ABI_FIELD(RadSampleParams, mask_row)
ABI_FIELD(RadSampleParams, flags) ABI_FIELD(RadSampleParams, flags)
ABI_FIELD(RadSampleParams, dry_rep_limit) ABI_FIELD(RadSampleParams, dry_rep_limit)
ABI_STRUCT(RadShapeGenBatch)
ABI_FIELD(RadShapeGenBatch, lane)
ABI_FIELD(RadShapeGenBatch, patches)
ABI_FIELD(RadShapeGenBatch, step)
ABI_FIELD(RadShapeGenBatch, n_steps)
ABI_FIELD(RadShapeGenBatch, sigma)
ABI_FIELD(RadShapeGenBatch, sigma_next)
ABI_FIELD(RadShapeGenBatch, cfg)
ABI_FIELD(RadShapeGenBatch, pair)
ABI_FIELD(RadShapeGenBatch, lanes)
ABI_FIELD(RadShapeGenBatch, flags)
ABI_FIELD(RadShapeGenBatch, seed)
ABI_FIELD(RadShapeGenBatch, lat_cu)
ABI_FIELD(RadShapeGenBatch, n_query)
ABI_FIELD(RadShapeGenBatch, query)
ABI_FIELD(RadShapeGenBatch, query_cu)
ABI_STRUCT(RadShapeGenDecl)
ABI_FIELD(RadShapeGenDecl, name)
ABI_FIELD(RadShapeGenDecl, canvas)
ABI_FIELD(RadShapeGenDecl, border_ratio)
ABI_FIELD(RadShapeGenDecl, enc_size)
ABI_FIELD(RadShapeGenDecl, enc_patch)
ABI_FIELD(RadShapeGenDecl, pix_mean)
ABI_FIELD(RadShapeGenDecl, pix_std)
ABI_FIELD(RadShapeGenDecl, latent_rows)
ABI_FIELD(RadShapeGenDecl, latent_channels)
ABI_FIELD(RadShapeGenDecl, step_rows)
ABI_FIELD(RadShapeGenDecl, default_steps)
ABI_FIELD(RadShapeGenDecl, max_steps)
ABI_FIELD(RadShapeGenDecl, default_guidance)
ABI_FIELD(RadShapeGenDecl, bounds)
ABI_FIELD(RadShapeGenDecl, level)
ABI_FIELD(RadShapeGenDecl, default_resolution)
ABI_FIELD(RadShapeGenDecl, min_resolution)
ABI_FIELD(RadShapeGenDecl, max_resolution)
ABI_FIELD(RadShapeGenDecl, max_lanes)
ABI_FIELD(RadShapeGenDecl, max_query)
ABI_FIELD(RadShapeGenDecl, field_out)
ABI_STRUCT(RadSyclStream) ABI_STRUCT(RadSyclStream)
ABI_FIELD(RadSyclStream, magic) ABI_FIELD(RadSyclStream, magic)
ABI_FIELD(RadSyclStream, version) ABI_FIELD(RadSyclStream, version)
+110 -2
View File
@@ -295,6 +295,13 @@ typedef struct RadBuildCtx {
* fixed buffers ignores them, and the core says so at startup. */ * fixed buffers ignores them, and the core says so at startup. */
int64_t gen_max_pixels; int64_t gen_max_pixels;
int64_t gen_max_refs; int64_t gen_max_refs;
/* ---- appended in ABI 37 (where a routed expert may live) */
/* --weights-disk-tier: nonzero when weights may stay in the container. An expert read from the
* drive has to be stored whole, so a plugin that can lay its routed experts out either way
* keeps them whole for this; 0 leaves it free to split them across the ranks by width. */
int expert_file_tier;
/* ---- appended in the SYCL fork (the plain block norm) */ /* ---- appended in the SYCL fork (the plain block norm) */
/* Nonzero: where no reader of a block norm's output takes its E4M3 code pair (every reader a /* Nonzero: where no reader of a block norm's output takes its E4M3 code pair (every reader a
* 4-bit or plain bf16 projection, which reads the bf16 plane), the plugin may run the norm as * 4-bit or plain bf16 projection, which reads the bf16 plane), the plugin may run the norm as
@@ -303,8 +310,9 @@ typedef struct RadBuildCtx {
* quantising norm is bound by libref's ordered sum of squares while its `rmsnorm` is a fast * quantising norm is bound by libref's ordered sum of squares while its `rmsnorm` is a fast
* row (docs/SYCL_PROGRESS.md); 0 elsewhere, so other backends declare what they did. * row (docs/SYCL_PROGRESS.md); 0 elsewhere, so other backends declare what they did.
* *
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. 64-bit
int plain_norm; * so it starts past the end of ABI 37's struct, not in the padding after expert_file_tier. */
int64_t plain_norm;
} RadBuildCtx; } RadBuildCtx;
/* ================================================================== control vectors */ /* ================================================================== control vectors */
@@ -896,6 +904,13 @@ typedef struct RadEncoderDecl {
* position tables or kernels are per geometry; the core ends a pass where the grid changes. * position tables or kernels are per geometry; the core ends a pass where the grid changes.
* 0 packs segments of any grid into a pass. */ * 0 packs segments of any grid into a pass. */
int32_t one_grid; int32_t one_grid;
/* ---- appended in ABI 32 (runs the language model reads both ways) */
/* 1: the language model attends the placeholders of one picture or video frame to each other
* both ways (Gemma 4's use_bidirectional_attention "vision"), text before and after them
* causally. The core then ends no prefill chunk inside such a run and states each trunk pass's
* runs (RadBatch::n_bidi). 0 for an audio encoder. */
int32_t bidirectional;
} RadEncoderDecl; } RadEncoderDecl;
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d); int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d);
@@ -1481,6 +1496,87 @@ typedef struct RadVideoGenDecl {
int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d); int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d);
/* ================================================================== the shape generator */
/* A program that makes a 3-D shape from one picture: an image encoder reads the picture, a
* denoiser steps a set of latent rows by flow matching, guided against an unconditioned branch,
* and a decoder turns the latent into an occupancy field that the core samples at points of its
* choosing and meshes. The core drives the passes (RadBatch::gen, RadShapeGenBatch), one request
* a pass:
*
* RAD_GEN_PASS_SCOND the request's picture through the image encoder into the request's
* lane: what the denoiser reads of it at every step, for both branches
* (the picture's and the unconditioned one).
* RAD_GEN_PASS_SSTEP one denoising step of one lane over both branches, `step_rows` rows:
* each branch's conditioning and latent, laid out as the plugin likes, the
* latents two entries of `latent_rows` (the conditioned first) for the
* image generator's sampler ops. The first step draws the lane's noise.
* RAD_GEN_PASS_SLATENT the lane's final latent through the decoder's network, into the lane:
* what every query pass of the request reads. Runs once, after the last
* step.
* RAD_GEN_PASS_SQUERY the field at `n_query` points (RadShapeGenBatch::query, at most
* `max_query`), one f32 a point in `field_out`, which the core reads
* back.
*
* The picture. The core decodes it with its alpha (opaque without one) and prepares it as
* Hunyuan3D-2's ImageProcessorV2 and image encoder do: the alpha's bounding box (its last row and
* column left out, as the reference's slice leaves them) scaled with OpenCV's INTER_AREA to
* (1 - border_ratio) of the longer side of the square that holds the picture, centred on it and
* flattened onto white; that square resized to `canvas` x `canvas` with INTER_CUBIC; then as 0..1
* values bilinearly resized to `enc_size` x `enc_size` (half-pixel centres, torchvision's), each
* channel normalised by `pix_mean` and `pix_std`, and cut into (enc_size / enc_patch)^2 patches of
* enc_patch x enc_patch pixels, row-major, each patch's values channel-major then row-major (a
* convolution's weight order). An SCOND pass carries those patches.
*
* The sampler: a request's `steps` are sigma grid points, sigma_i = i / (steps - 1) for i in
* [0, steps), numpy's linspace(0, 1) taken to f32; the latent starts as noise at sigma 0 and an
* evaluation at each sigma but the last steps it to the next (the reference evaluates at the
* last too, against itself, a step of zero). The model's timestep is sigma, the guided velocity
* neg + cfg (pos - neg), and the step x + (sigma_next - sigma) v.
*
* The field: the decoder's logit at a point, inside the shape above `level`. The core samples the
* cube [-bounds, bounds]^3 on a grid of `resolution` cells a side ((resolution + 1)^3 points,
* numpy's linspace in f32 along each axis), coarse to fine as FlashVDM's hierarchical decoding
* does: the whole grid at the coarsest level (resolution halved while it stays at least 63), then
* at each finer level only the points near where the coarser one crosses `level` or is within
* 0.95 of it. The surface is marching cubes over the finest grid, a vertex at grid index g placed
* at g 2 bounds / (resolution + 1) - bounds, as the reference places it.
*
* A program declares exactly one of this, the other generators, logits or pooled vectors. */
enum { RAD_GEN_PASS_SCOND = 15, RAD_GEN_PASS_SSTEP = 16, RAD_GEN_PASS_SLATENT = 17,
RAD_GEN_PASS_SQUERY = 18 };
typedef struct RadShapeGenDecl {
const char* name; /* "hunyuan3d-2" -- the served model id and messages */
/* The picture (above). */
int64_t canvas;
double border_ratio;
int64_t enc_size, enc_patch;
double pix_mean[3], pix_std[3];
/* The latent: `latent_rows` rows of `latent_channels` a branch; a step's rows, both branches
* with their conditioning. */
int64_t latent_rows, latent_channels, step_rows;
/* The sampler (above) and the guidance a request that names none runs at. */
int64_t default_steps, max_steps;
double default_guidance;
/* The field (above): the cube's half side, the iso value, and the grid's resolution a request
* that names none is sampled at, with the range a request may name. */
double bounds;
double level;
int64_t default_resolution, min_resolution, max_resolution;
/* `max_lanes` requests may hold state at once. `field_out` is a device f32 buffer of at least
* `max_query` elements. */
int64_t max_lanes;
int64_t max_query;
rad_buf field_out;
} RadShapeGenDecl;
int rad_declare_shape_generator(RadBuilder* b, const RadShapeGenDecl* d);
/* ================================================================== diagnostics */ /* ================================================================== diagnostics */
/* A plugin may annotate the graph dump. Free-form, printed under --debug-graph. */ /* A plugin may annotate the graph dump. Free-form, printed under --debug-graph. */
void rad_note(RadBuilder* b, const char* fmt, ...); void rad_note(RadBuilder* b, const char* fmt, ...);
@@ -1615,6 +1711,12 @@ typedef struct RadArchProbe {
* gen_patches answer for them. */ * gen_patches answer for them. */
int64_t gen_max_pixels; int64_t gen_max_pixels;
int64_t gen_max_refs; int64_t gen_max_refs;
/* ---- appended in ABI 33 (the shape generator) */
/* Nonzero for a shape generator, which the engine sizes as it does a video generator from
* `gen_rows` (its largest pass: a step's two branches, or a query pass's points). It keeps no
* KV. */
int32_t gen_shape;
} RadArchProbe; } RadArchProbe;
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out); int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
@@ -1856,6 +1958,12 @@ int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadB
struct RadCtx; struct RadCtx;
struct RadBatch; struct RadBatch;
void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch); void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch);
/* Optional. Return a stable fingerprint of actual dispatch geometry whose grid depends on live
* per-group seqused values. `kv_used_max_h[g]` is the host maximum for batch->kv[g], and
* rad_ctx_wgp_count(c) supplies the device's WGP count. Return 0 when exact geometry is unknown;
* that pass runs live and is not recorded. */
uint64_t rad_arch_pass_key(struct RadCtx* c, const struct RadBatch* batch,
const int32_t* kv_used_max_h);
#ifdef __cplusplus #ifdef __cplusplus
} /* extern "C" */ } /* extern "C" */
+55
View File
@@ -0,0 +1,55 @@
/* rad_prefill_split.h -- host-pure live-KV prefill split law shared by libr4d launchers and
* architecture pass-key callbacks. Keep this independent of HIP so callbacks can run before tape
* lookup without a device copy or launch.
*/
#pragma once
#include <algorithm>
#include <cstdint>
/* `bq` query positions per workgroup, `tile` keys per KV tile. `units` counts the workgroups that
* do work: a ragged batch's grid is sized from its longest sequence, but a shorter sequence's
* tiles past its end exit at once. Each split keeps at least eight tiles of the supplied context.
*/
static inline int rad_prefill_splits_law(int bq, int tile, int q_len, int total_q, int num_seqs,
int kv_heads, int max_ctx, int wgps) {
const long n = std::max(1, num_seqs);
const long qt = std::min(n * ((std::max(1, q_len) + bq - 1) / bq),
(std::max(1, total_q) + (long)(bq - 1) * n) / bq);
const long units = (long)std::max(1, kv_heads) * std::max(1L, qt);
if (units >= wgps) return 1;
const int s1 = (int)(wgps / units), s2 = (int)(2L * wgps / units);
int sp = s2 > 2 * s1 ? s2 : s1;
const int cap = ((max_ctx > 0 ? max_ctx : (1 << 30) - 1) + tile - 1) / tile / 8;
sp = std::min(sp, std::max(1, cap));
return std::max(1, std::min(sp, 64));
}
/* The launcher's live-context refinement of the initial model-bound law. */
static inline int rad_prefill_splits_for_live(int bq, int tile, int q_len, int total_q,
int num_seqs, int kv_heads, int max_ctx,
int used_ctx, int wgps) {
int splits = rad_prefill_splits_law(bq, tile, q_len, total_q, num_seqs, kv_heads, max_ctx,
wgps);
if (splits > 1 && used_ctx > 0 && (max_ctx <= 0 || used_ctx < max_ctx))
splits = rad_prefill_splits_law(bq, tile, q_len, total_q, num_seqs, kv_heads, used_ctx,
wgps);
return splits;
}
/* Fingerprint one actual launch tuple in packet-global sizes. Use this instead of the raw context
* so equal split grids share a recording key as live context advances. */
static inline uint64_t rad_prefill_grid_key(int q_len, int bq, int splits, int kv_heads,
int num_seqs, int threads) {
const uint64_t gx = (uint64_t)((std::max(1, q_len) + bq - 1) / bq) *
(uint64_t)std::max(1, splits) * (uint64_t)threads;
const uint64_t gy = (uint64_t)std::max(1, kv_heads);
const uint64_t gz = (uint64_t)std::max(1, num_seqs);
uint64_t h = 0x9e3779b97f4a7c15ull;
const uint64_t grid[3] = {gx, gy, gz};
for (uint64_t v : grid) {
h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2);
h *= 0xbf58476d1ce4e5b9ull;
}
return h | 1;
}
+80 -1
View File
@@ -68,8 +68,10 @@ typedef struct RadKVGroupBatch {
int64_t state_index_pitch; int64_t state_index_pitch;
int64_t block_size; int64_t block_size;
int64_t max_blocks; int64_t max_blocks;
/* Null unless this group streams (RadKVStream). Trailing and zero-defaulted. */ /* Null unless this group streams (RadKVStream). */
const RadKVStream* stream; const RadKVStream* stream;
/* ABI 35: host mirror of seqused, retained through this batch for exact sliced-launch bounds. */
const int32_t* seqused_h;
} RadKVGroupBatch; } RadKVGroupBatch;
typedef struct RadBatch { typedef struct RadBatch {
@@ -325,6 +327,42 @@ typedef struct RadBatch {
const int32_t* plugin_cu; /* [n_seq + 1] device */ const int32_t* plugin_cu; /* [n_seq + 1] device */
const int32_t* plugin_words_h; const int32_t* plugin_words_h;
const int32_t* plugin_cu_h; const int32_t* plugin_cu_h;
/* ---- appended in ABI 33 (the shape generator) */
/* A shape generator's pass (rad_declare_shape_generator; `gen` is one of its
* RAD_GEN_PASS_S*): its payload. Null on every other step. */
const struct RadShapeGenBatch* sgen_b;
/* ---- appended in ABI 34: host-side max seqused per entry of kv[], for an architecture's
* optional recorded-pass geometry key. Null when the batch has no host summary. */
const int32_t* kv_used_max_h;
/* ABI 35: host mirror of positions, for a one-sequence prefill op whose exact KV bound is the
* position immediately after its first query piece. Valid through the batch's issue pass. */
const int32_t* positions_h;
/* ---- appended in ABI 35 (runs read both ways) */
/* The runs of a trunk pass whose rows attend to each other both ways
* (RadEncoderDecl::bidirectional): a picture's or a video frame's placeholders inside one
* sequence's chunk. The pass attends them causally like every other row; the plugin attends a
* run's rows again without the causal bound, over the keys before `bidi_used` (the position
* after the run's last token), in place of that result. The scheduler ends no chunk inside such
* a run, so its keys are this pass's or, after a prefix hit, the cache's; a run longer than any
* step is cut where its chunk ends, and that chunk's rows see the run up to the cut.
*
* host: n_bidi and, per run, its first row in this pass, its rows and the index of its sequence
* in the per-sequence arrays; device: [n_bidi] the keys a run's rows see. 0 runs on every other
* pass. */
int64_t n_bidi;
const int32_t* bidi_row; /* host */
const int32_t* bidi_n; /* host */
const int32_t* bidi_seq; /* host */
const int32_t* bidi_used; /* device */
/* ---- appended in ABI 36 (a block drafter's anchor row) */
/* A block drafter's query pass (draft_pass 1): [n_seq] device, for each drafting sequence the
* row of its last committed position in the context pass just run, whose rows are the verify
* step's in order. -1 for a row the card did not position. A drafter that conditions on the
* context state at the anchor (LiLiCorr) gathers it there; the query rows themselves sit past
* that position. Null on every other pass. */
const int32_t* anchor_rows;
} RadBatch; } RadBatch;
/* What a generator pass carries beside the step batch's own fields, which keep their meanings: /* What a generator pass carries beside the step batch's own fields, which keep their meanings:
@@ -712,6 +750,44 @@ typedef struct RadVideoGenBatch {
enum { RAD_SAMPLER_EULER = 0, RAD_SAMPLER_RES_MULTISTEP = 1 }; enum { RAD_SAMPLER_EULER = 0, RAD_SAMPLER_RES_MULTISTEP = 1 };
/* What a shape generator's pass carries beside the step batch's own fields (rad_builder.h,
* RadShapeGenDecl, describes the passes). Every pass is one request's, in lane `lane`:
*
* SCOND `n_tok` is the picture's patches, `patches` [n_tok, 3 enc_patch^2] f32.
* SSTEP `n_tok` is step_rows. The two branches' latents are entries 0 (the picture's) and 1
* (the unconditioned one) of the image generator's sampler ops (`randn_lanes`,
* `lane_gather`, `flow_euler`): `lat_cu` bounds them and the per-entry arrays are
* theirs, entry 0 guided against entry 1 (`pair` {1, -2}) at the request's scale.
* SLATENT `n_tok` is latent_rows; nothing of the pass's own.
* SQUERY `n_tok` is n_query, `query` [n_query, 3] f32: x, y, z a point, and `query_cu`
* {0, n_query}.
*
* `lanes` and `lat_cu` are staged on every pass; the latent's rows are lat_cu[0..1]. Every
* pointer is device memory. */
typedef struct RadShapeGenBatch {
int32_t lane;
/* ---- SCOND */
const float* patches;
/* ---- SSTEP: the step (from 0) of the request's `n_steps` evaluations, then the two
* entries' sampler operands, [2] each but `seed` [2, 2] (low word first) and `lat_cu` [3]. */
int32_t step, n_steps;
const float* sigma;
const float* sigma_next;
const float* cfg;
const int32_t* pair;
const int32_t* lanes;
const int32_t* flags; /* RAD_GEN_F_FIRST on entry 0 of the first step */
const uint32_t* seed;
const int32_t* lat_cu;
/* ---- SQUERY */
int64_t n_query;
const float* query;
const int32_t* query_cu;
} RadShapeGenBatch;
/* RadVideoGenBatch::enc_kind: the media an encode pass carries, numbered from 1 within a kind. A /* RadVideoGenBatch::enc_kind: the media an encode pass carries, numbered from 1 within a kind. A
* keyframe is 1 for the first frame and 2 for the last. */ * keyframe is 1 for the first frame and 2 for the last. */
enum { enum {
@@ -861,6 +937,9 @@ int rad_kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGrou
int rad_kv_stage_next(RadCtx* c, rad_kvgroup group, int layer); int rad_kv_stage_next(RadCtx* c, rad_kvgroup group, int layer);
int rad_rank(RadCtx* c); int rad_rank(RadCtx* c);
int rad_world_size(RadCtx* c); int rad_world_size(RadCtx* c);
/* Workgroups the current rank's card can run concurrently (HIP multiProcessorCount on RDNA;
* 32 on the host backend or when the backend has no positive count). */
int rad_ctx_wgp_count(RadCtx* c);
RadStream rad_stream(RadCtx* c); RadStream rad_stream(RadCtx* c);
/* The routing result for a MoE layer, resolved on device against the current residency table. /* The routing result for a MoE layer, resolved on device against the current residency table.
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/bailing_hybrid -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(bailing_hybrid LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(bailing_hybrid architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid.cpp)
+885
View File
@@ -0,0 +1,885 @@
/* bailing_hybrid -- Ling-3.0-flash and its fine-tunes (`model_type: bailing_hybrid`,
* BailingMoeV3ForCausalLM), from the bf16 checkpoint, the routed experts as a recipe stores them
* (data/recipes/ling3-w4a8-rtn.recipe, ling3-w4a8-gptq.recipe).
*
* ============================== WHAT IT SERVES ==============================
*
* layers 42 in groups of six: five Kimi delta attention (KDA) layers, then one dense
* latent attention (MLA) layer, so layers 5, 11, ..., 41 are MLA
* KDA 32 heads of 128, separate q/k/v projections each with its own causal
* convolution, a full-rank per-channel forget gate (`f_proj`) and output gate
* (`g_proj`), lower bound -5
* MLA no query LoRA, a 512-wide latent and a 64-wide rotary part (interleaved pairs),
* heads of 128 + 64, values of 128, a sigmoid gate per head
* feed-forward layers 0-1 dense (6144); from layer 2, 512 experts of 768 at top-8 under
* group-limited sigmoid routing (8 groups, 4 kept, a correction bias, x2.5), an
* ungated shared expert, and a SwiGLU clipped after the SiLU in the last layers
* (`expert_swiglu_limit_list`, `share_expert_swiglu_limit_list`, as vLLM and
* SGLang serve it; HF's reference ignores it)
*
* The KDA core is GLM-5.3's (KdaState), the router GLM-5.3's with groups (GlmRouter), the
* feed-forward MoeFP8. The KDA and MLA blocks around them are in this file.
*
* ============================== THE LATENT ATTENTION ==============================
*
* The MLA attends in the latent. The query projection is served as two, its heads' rotary rows and
* their nope rows (row maps over q_proj), so each is a plain [T, heads * width] plane: `rope` turns
* the first, and the second is absorbed into the latent through kv_b's key rows (mla_project).
* `mla_attn_paged` scores against a cache row of [normed latent 512 | rotated key 64] and returns
* the latent, gated per head; kv_b's value rows expand it. The cache row is stored as one KV head
* of 288, the latent's first 288 values in the K slot and the rest in the V slot.
*
* ============================== THE DRAFTER ==============================
*
* The MTP layer (checkpoint layer 42: an MLA layer with the full routed feed-forward) is a serial
* drafter around GlmMtp, declared when the deployment speculates.
*
* docs/ARCHITECTURES.md describes the model and its traps. */
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <arch/rad_arch.h>
#include <arch/rad_block_glm_kda.h>
#include <arch/rad_block_glm_mtp.h>
#include <arch/rad_block_mlp_fp8.h>
#include <arch/rad_block_moe_fp8.h>
namespace bailing_hybrid {
using namespace rad::arch;
/* The released geometry this graph is written for; a checkpoint that differs is refused by name. */
struct Shape {
int64_t n_embd = 0, n_layer = 0, heads = 0, head_dim = 0, nope = 0, rope = 0, v_dim = 0,
latent = 0, experts = 0, top_k = 0, groups = 0, topk_groups = 0, ff_exp = 0,
ff_shared = 0, ff_dense = 0, dense_layers = 0, group_size = 0, conv = 0;
double lower = -5, route_scale = 1;
std::vector<double> lim_exp, lim_shared;
};
/* A KDA layer: the q/k/v, beta, forget and output-gate projections into KdaState, then o_proj and
* its all-reduce. */
struct LingKda {
struct Wire {
ActFP8 input{};
rad_buf out = 0;
ActFP8 core_out{};
KdaState::Wire core{};
};
Geom g{};
Wire w{};
KdaState core{};
LinearFP8 qkv{}, beta{}, forget{}, gate{}, output{};
QuantFP8 out_quant{};
rad_op op_ar = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Shape& sh, int l,
const Wire& wire, const char* pre, rad_kvgroup state, rad_kvgroup history) {
g = geom;
w = wire;
const int64_t heads = sh.heads / g.world, width = heads * sh.head_dim;
const auto grp = grp_layer(l);
RAD_ARCH_TRY(qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), 3 * width, g.n_embd,
RAD_SHARD_ROW, grp,
{ nm.ckpt("%s.q_proj.weight", pre), nm.ckpt("%s.k_proj.weight", pre),
nm.ckpt("%s.v_proj.weight", pre) },
w.input, w.core.qkv, 0, { width, width, width }));
RAD_ARCH_TRY(beta.declare(b, nm, g, nm.f("blk.%d.attn_beta", l), heads, g.n_embd,
RAD_SHARD_ROW, grp, { nm.ckpt("%s.b_proj.weight", pre) },
w.input, w.core.beta));
RAD_ARCH_TRY(forget.declare(b, nm, g, nm.f("blk.%d.attn_forget", l), width, g.n_embd,
RAD_SHARD_ROW, grp, { nm.ckpt("%s.f_proj.weight", pre) },
w.input, w.core.a));
RAD_ARCH_TRY(gate.declare(b, nm, g, nm.f("blk.%d.attn_gate", l), width, g.n_embd,
RAD_SHARD_ROW, grp, { nm.ckpt("%s.g_proj.weight", pre) },
w.input, w.core.gate));
KdaState::Config kc;
kc.heads = heads;
kc.dim = sh.head_dim;
kc.width = sh.conv;
kc.lower = sh.lower;
KdaState::Src ks{ nm.ckpt("%s.q_conv1d.weight", pre), nm.ckpt("%s.k_conv1d.weight", pre),
nm.ckpt("%s.v_conv1d.weight", pre), nm.ckpt("%s.A_log", pre),
nm.ckpt("%s.dt_bias", pre), nm.ckpt("%s.o_norm.weight", pre) };
RAD_ARCH_TRY(core.declare(b, nm, g, l, state, history, kc, w.core, ks));
const char* on = nm.f("blk.%d.attn_output", l);
RAD_ARCH_TRY(output.probe(b, nm, g, on, { nm.ckpt("%s.o_proj.weight", pre) }));
if (!output.reads_x) RAD_ARCH_TRY(out_quant.declare(b, g, w.core_out, width));
RAD_ARCH_TRY(output.declare(b, nm, g, on, g.n_embd, width, RAD_SHARD_COL, grp,
{ nm.ckpt("%s.o_proj.weight", pre) }, w.core_out, w.out));
op_ar = GlmTp::reduce(b, g, w.out);
return g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
qkv.step(c, w.input, w.core.qkv, T);
beta.step(c, w.input, w.core.beta, T);
forget.step(c, w.input, w.core.a, T);
gate.step(c, w.input, w.core.gate, T);
core.step(c, batch);
out_quant.step(c, T);
output.step(c, w.core_out, w.out, T);
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.out, T), RAD_NONE);
}
};
/* A dense MLA layer, attending in the latent (the file's head comment). The latent cache is
* replicated: every rank projects and stores the whole row, and splits the heads. */
struct LingMla {
struct Wire {
ActFP8 input{};
rad_buf q_rope = 0; /* [T, heads * rope] */
rad_buf q_nope = 0; /* [T, heads * nope] */
rad_buf row = 0; /* [T, latent + rope], the cache row */
rad_buf q_lat = 0; /* [T, heads, latent] */
rad_buf gate = 0; /* [T, heads] */
rad_buf attn = 0; /* [T, heads, latent] */
ActFP8 value{}; /* [T, heads * v] */
rad_buf out = 0;
};
Geom g{};
Shape s{};
Wire w{};
int layer = 0;
int64_t heads = 0, qw = 0, cw = 0;
rad_kvgroup kv = 0;
LinearFP8 q_rope_proj{}, q_nope_proj{}, kv_a{}, g_proj{}, output{};
QuantFP8 value_quant{};
rad_weight kv_gain = 0, kv_b = 0;
rad_op op_kv_norm = 0, op_q_rope = 0, op_k_rope = 0, op_store = 0, op_absorb = 0, op_attn = 0,
op_expand = 0, op_ar = 0;
int64_t block = 0;
static constexpr int64_t kBlock = 16;
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Shape& shape, int l,
const Wire& wire, const char* pre, rad_kvgroup group) {
g = geom;
s = shape;
w = wire;
layer = l;
kv = group;
heads = s.heads / g.world;
qw = s.rope + s.nope;
cw = s.latent + s.rope;
const auto grp = grp_layer(l);
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv));
/* One row map a part, a piece a head: [h * (nope + rope) + off, + width). Successive ROWS
* maps for one name extend it in call order (rad_builder.h), eight pieces a map. */
const char* qsrc = nm.ckpt("%s.q_proj.weight", pre);
auto part = [&](const char* name, int64_t off, int64_t width) -> int {
for (int64_t h0 = 0; h0 < s.heads; h0 += 8) {
RadNameMap m = map_base(name, RAD_MAP_ROWS);
for (int64_t h = h0; h < std::min(h0 + 8, s.heads); ++h) {
m.src[m.n_src] = qsrc;
m.src_index[m.n_src] = (int)(h * qw + off);
m.src_rows[m.n_src] = width;
++m.n_src;
}
RAD_ARCH_TRY(rad_decl_name_map(b, &m));
}
return RAD_OK;
};
RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_rope.weight", l), s.nope, s.rope));
RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_nope.weight", l), 0, s.nope));
q_rope_proj.mapped = q_nope_proj.mapped = true;
RAD_ARCH_TRY(q_rope_proj.declare(b, nm, g, nm.f("blk.%d.attn_q_rope", l), heads * s.rope,
g.n_embd, RAD_SHARD_ROW, grp, { qsrc }, w.input, w.q_rope));
RAD_ARCH_TRY(q_nope_proj.declare(b, nm, g, nm.f("blk.%d.attn_q_nope", l), heads * s.nope,
g.n_embd, RAD_SHARD_ROW, grp, { qsrc }, w.input, w.q_nope));
RAD_ARCH_TRY(kv_a.declare(b, nm, g, nm.f("blk.%d.attn_kv_a", l), cw, g.n_embd,
RAD_SHARD_NONE, grp, { nm.ckpt("%s.kv_a_proj_with_mqa.weight", pre) },
w.input, w.row));
const char* kn = nm.f("blk.%d.attn_kv_a_norm.weight", l);
RAD_ARCH_TRY(map_copy(b, kn, nm.ckpt("%s.kv_a_layernorm.weight", pre)));
kv_gain = decl_w(b, kn, RAD_F32, { s.latent }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
if (!kv_gain) return RAD_E_INVAL;
op_kv_norm = rw(b,
RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", s.latent),
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(kv_gain)),
{ w.row }, { w.row });
op_q_rope = rw(b, decl_rope(b, g, g.max_tok, s.rope, heads, 0, s.rope, "gptj"), { w.q_rope },
{ w.q_rope });
op_k_rope = rw(b, decl_rope(b, g, g.max_tok, s.rope, 1, 0, s.rope, "gptj"), { w.row },
{ w.row });
/* The first op after the group to carry a block size claims it (rad_builder.cpp,
* find_kv_consumer). */
op_store = rw(b,
RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cw / 2),
RAD_INT("n_head_kv", 1), RAD_INT("block_size", kBlock),
RAD_STR("kv_dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.row }, {});
const char* bn = nm.f("blk.%d.attn_kv_b.weight", l);
RAD_ARCH_TRY(map_copy(b, bn, nm.ckpt("%s.kv_b_proj.weight", pre)));
kv_b = decl_w(b, bn, RAD_BF16, { heads * (s.nope + s.v_dim), s.latent }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_ROW, grp);
if (!op_kv_norm || !op_q_rope || !op_k_rope || !op_store || !kv_b) return RAD_E_INVAL;
op_absorb = rw(b,
RAD_OP(b, "mla_project",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", heads),
RAD_INT("head_dim", s.nope), RAD_INT("latent_dim", s.latent),
RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(kv_b)),
{ w.q_nope }, { w.q_lat });
RAD_ARCH_TRY(g_proj.declare(b, nm, g, nm.f("blk.%d.attn_head_gate", l), heads, g.n_embd,
RAD_SHARD_ROW, grp, { nm.ckpt("%s.g_proj.weight", pre) },
w.input, w.gate));
op_attn = rw(b,
RAD_OP(b, "mla_attn_paged",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", heads),
RAD_INT("latent_dim", s.latent), RAD_INT("rope_dim", s.rope),
RAD_INT("block_size", kBlock),
RAD_F64("scale", 1.0 / std::sqrt((double)qw)),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.q_lat, w.q_rope, w.gate }, { w.attn });
op_expand = rw(b,
RAD_OP(b, "mla_project",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", heads),
RAD_INT("head_dim", s.v_dim), RAD_INT("latent_dim", s.latent),
RAD_STR("mode", "expand"), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(kv_b)),
{ w.attn }, { w.value.x });
if (!op_absorb || !op_attn || !op_expand) return RAD_E_INVAL;
block = rad_kv_block_size(b, kv);
if (block != kBlock) {
fprintf(stderr, "radiance: bailing_hybrid: the latent cache's block is %lld tokens and "
"its ops are declared at %lld\n", (long long)block, (long long)kBlock);
return RAD_E_INVAL;
}
const char* on = nm.f("blk.%d.attn_output", l);
RAD_ARCH_TRY(output.probe(b, nm, g, on, { nm.ckpt("%s.dense.weight", pre) }));
if (!output.reads_x) RAD_ARCH_TRY(value_quant.declare(b, g, w.value, heads * s.v_dim));
RAD_ARCH_TRY(output.declare(b, nm, g, on, g.n_embd, heads * s.v_dim, RAD_SHARD_COL, grp,
{ nm.ckpt("%s.dense.weight", pre) }, w.value, w.out));
op_ar = GlmTp::reduce(b, g, w.out);
return g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const auto* kb = kv_batch(batch, kv);
if (!kb || !kb->slot_mapping || !kb->block_table || !kb->seqused) {
rad_step_fail(c, "bailing_hybrid MLA requires the latent cache's slot mapping, block "
"table and sequence lengths");
return;
}
const int64_t T = batch->n_tok, S = batch->n_seq;
const RadOperand pos = praw(batch->positions, RAD_I32, T);
q_rope_proj.step(c, w.input, w.q_rope, T);
q_nope_proj.step(c, w.input, w.q_nope, T);
kv_a.step(c, w.input, w.row, T);
g_proj.step(c, w.input, w.gate, T);
RAD_ISSUE_N(c, op_kv_norm, T, bcol(w.row, 0, s.latent, T), RAD_W(kv_gain),
bcol(w.row, 0, s.latent, T));
RAD_ISSUE_N(c, op_q_rope, T, brows(w.q_rope, T), pos);
RAD_ISSUE_N(c, op_k_rope, T, bcol(w.row, s.latent, s.rope, T), pos);
RAD_ISSUE_N(c, op_store, T, bcol(w.row, 0, cw / 2, T), bcol(w.row, cw / 2, cw / 2, T),
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
RAD_ISSUE_N(c, op_absorb, T, brows(w.q_nope, T), RAD_W(kv_b), brows(w.q_lat, T));
RAD_ISSUE_N(c, op_attn, T, brows(w.q_lat, T), brows(w.q_rope, T), kv_cache(kv, layer),
praw2(kb->block_table, RAD_I32, S, kb->block_table_pitch),
praw(kb->seqused, RAD_I32, S), praw(batch->cu_seqlens, RAD_I32, S + 1),
brows(w.gate, T), brows(w.attn, T));
RAD_ISSUE_N(c, op_expand, T, brows(w.attn, T), RAD_W(kv_b), brows(w.value.x, T));
value_quant.step(c, T);
output.step(c, w.value, w.out, T);
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.out, T), RAD_NONE);
}
};
struct Layer {
bool mla = false, dense = false;
rad_weight gain = 0;
NormQuantFP8 norm{};
LingKda kda{};
LingMla attn{};
rad_op op_add = 0;
MlpFP8 mlp{};
MoeFP8 moe{};
};
struct Model {
Names nm{};
Geom g{};
Shape s{};
std::vector<Layer> layers;
rad_kvgroup latent = 0, state = 0, conv = 0;
rad_buf x = 0, y = 0, final_hidden = 0, logit_input = 0, logits = 0;
ActFP8 act{};
LingKda::Wire kw{};
LingMla::Wire aw{};
MlpFP8::Wire dw{};
MoeFP8::Wire mw{};
rad_weight token = 0, head = 0, final_gain = 0;
rad_op embed = 0, embed_ar = 0, norm = 0, gather = 0, head_op = 0;
/* The draft head and its layer, declared only when the deployment speculates. */
bool have_mtp = false;
GlmMtp mtp{};
Layer draft{};
};
static Model g_model[MAX_RANKS];
static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) {
return rad_meta_geti(m, key, fallback);
}
static std::vector<double> cfg_list(const RadModelMeta* m, const char* key) {
std::vector<double> v;
for_each_token(rad_meta_gets(m, key, ""), [&](const char* t, size_t) {
v.push_back(std::strtod(t, nullptr));
return true;
});
return v;
}
/* Layer l's SwiGLU clamp from a per-layer list; 0 (none) past its end or where it says 0. */
static double limit_at(const std::vector<double>& v, int64_t l) {
return l < (int64_t)v.size() && v[(size_t)l] > 0 ? v[(size_t)l] : 0;
}
/* The last layer of each group of `layer_group_size` is MLA, and so is every layer of an
* incomplete last group. */
static bool is_mla(const Shape& s, int64_t l) {
return (l + 1) % s.group_size == 0 || l >= s.n_layer / s.group_size * s.group_size;
}
static int read_shape(const RadModelMeta* meta, Shape& s) {
s.n_embd = meta->n_embd;
s.n_layer = meta->n_layers;
s.heads = cfg(meta, "num_attention_heads", 0);
s.head_dim = cfg(meta, "head_dim", 0);
s.nope = cfg(meta, "qk_nope_head_dim", 0);
s.rope = cfg(meta, "qk_rope_head_dim", 0);
s.v_dim = cfg(meta, "v_head_dim", 0);
s.latent = cfg(meta, "kv_lora_rank", 0);
s.experts = cfg(meta, "num_experts", 0);
s.top_k = cfg(meta, "num_experts_per_tok", 0);
s.groups = cfg(meta, "n_group", 1);
s.topk_groups = cfg(meta, "topk_group", s.groups);
s.ff_exp = cfg(meta, "moe_intermediate_size", 0);
s.ff_shared = cfg(meta, "moe_shared_expert_intermediate_size", 0) *
cfg(meta, "num_shared_experts", 0);
s.ff_dense = cfg(meta, "intermediate_size", 0);
s.dense_layers = cfg(meta, "first_k_dense_replace", 0);
s.group_size = cfg(meta, "layer_group_size", 0);
s.conv = cfg(meta, "short_conv_kernel_size", 0);
s.lower = rad_meta_getf(meta, "kda_lower_bound", 0.0);
s.route_scale = rad_meta_getf(meta, "routed_scaling_factor", 0.0);
s.lim_exp = cfg_list(meta, "expert_swiglu_limit_list");
s.lim_shared = cfg_list(meta, "share_expert_swiglu_limit_list");
const struct {
const char* what;
bool ok;
} need[] = {
{ "head_dim 128 (KDA)", s.head_dim == 128 },
{ "qk_nope_head_dim == v_head_dim (mla_project's head)", s.nope > 0 && s.nope == s.v_dim },
{ "an even qk_rope_head_dim", s.rope > 0 && !(s.rope & 1) },
{ "an even kv_lora_rank + qk_rope_head_dim", s.latent > 0 && !((s.latent + s.rope) & 1) },
{ "q_lora_rank null", cfg(meta, "q_lora_rank", 0) == 0 },
{ "no_kda_lora", cfg(meta, "no_kda_lora", 0) != 0 },
{ "kda_safe_gate", cfg(meta, "kda_safe_gate", 1) != 0 },
{ "a negative kda_lower_bound", s.lower < 0 && std::isfinite(s.lower) },
{ "rope_interleave", cfg(meta, "rope_interleave", 0) != 0 },
{ "head-wise gated attention",
!std::strcmp(rad_meta_gets(meta, "gated_attention_proj_granularity_type", ""),
"head_wise") },
{ "sigmoid scoring", !std::strcmp(rad_meta_gets(meta, "score_function",
rad_meta_gets(meta, "scoring_func", "")),
"sigmoid") },
{ "one shared expert", cfg(meta, "num_shared_experts", 0) == 1 },
{ "a layer group", s.group_size > 1 },
{ "a 4-tap short convolution", s.conv == 4 },
{ "experts, top-k and groups", s.experts > 0 && s.top_k > 0 && s.groups >= 1 &&
s.experts % s.groups == 0 && s.topk_groups >= 1 &&
s.topk_groups <= s.groups },
{ "a positive routed_scaling_factor", s.route_scale > 0 },
{ "no rope scaling", !rad_meta_gets(meta, "rope_scaling.type", nullptr) &&
!rad_meta_gets(meta, "rope_scaling.rope_type", nullptr) },
};
for (const auto& n : need)
if (!n.ok) {
fprintf(stderr, "radiance: bailing_hybrid: this plugin serves %s, and the checkpoint "
"differs\n", n.what);
return RAD_E_UNSUPPORTED;
}
return RAD_OK;
}
/* A rank's slice of a width of `blocks` 128-column blocks: blocks [lo, hi) in the order of the
* ranks starting at `first`, the first `blocks % world` ranks of that order one block wider. */
static void slice_of(int64_t blocks, int world, int rank, int first, int64_t* lo, int64_t* hi) {
const int p = ((rank - first) % world + world) % world;
const int64_t base = blocks / world, extra = blocks % world;
*lo = p * base + std::min<int64_t>(p, extra);
*hi = *lo + base + (p < extra ? 1 : 0);
}
/* ============================== The trunk's buffers ============================== */
static int buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& s = m.s;
auto& nm = m.nm;
const int64_t T = g.max_tok, E = g.n_embd, H = s.heads / g.world, W = H * s.head_dim;
auto bf = [&](const char* n, std::initializer_list<int64_t> shape) {
return decl_b(b, nm.f("%s", n), RAD_BF16, shape);
};
m.x = bf("residual", { T, E });
m.y = bf("attn_delta", { T, E });
m.act.x = bf("normed", { T, E });
RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normed", E));
m.final_hidden = decl_b(b, nm.f("final_hidden"), RAD_BF16, { T, E }, RAD_BUF_PERSIST);
m.logit_input = bf("logit_input", { g.max_logit_rows, E });
m.logits = decl_b(b, nm.f("logits"), RAD_F32, { g.max_logit_rows, g.n_vocab });
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
auto& kw = m.kw;
kw.input = m.act;
kw.out = m.y;
kw.core.qkv = bf("kda_qkv", { T, 3 * W });
kw.core.conv = bf("kda_convolved", { T, 3 * W });
kw.core.a = bf("kda_forget", { T, W });
kw.core.beta = bf("kda_beta", { T, H });
kw.core.gate = bf("kda_gate", { T, W });
kw.core.out = bf("kda_out", { T, W });
kw.core_out.x = kw.core.out;
RAD_ARCH_TRY(kw.core_out.declare_qs(b, nm, g, "kda_out", W));
auto& aw = m.aw;
aw.input = m.act;
aw.out = m.y;
aw.q_rope = bf("mla_q_rope", { T, H * s.rope });
aw.q_nope = bf("mla_q_nope", { T, H * s.nope });
aw.row = bf("mla_row", { T, s.latent + s.rope });
aw.q_lat = bf("mla_q_latent", { T, H * s.latent });
aw.gate = bf("mla_gate", { T, H });
aw.attn = bf("mla_attn_latent", { T, H * s.latent });
aw.value.x = bf("mla_value", { T, H * s.v_dim });
RAD_ARCH_TRY(aw.value.declare_qs(b, nm, g, "mla_value", H * s.v_dim));
auto& dw = m.dw;
dw.x = m.x;
dw.h = m.act;
dw.gate_up = bf("dense_gate_up", { T, 2 * g.n_ff });
dw.ffn.x = bf("dense_ff", { T, g.n_ff });
RAD_ARCH_TRY(dw.ffn.declare_qs(b, nm, g, "dense_ff", g.n_ff));
return RAD_OK;
}
static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok, E = g.n_embd, F = mc.n_ff_exp, k = mc.top_k;
auto bf = [&](const char* n, std::initializer_list<int64_t> shape) {
return decl_b(b, nm.f("%s", n), RAD_BF16, shape);
};
auto& mw = m.mw;
mw.x = m.x;
mw.h = m.act;
mw.logits = decl_b(b, nm.f("router_logits"), RAD_F32, { T, mc.n_expert_all });
mw.ids = decl_b(b, nm.f("expert_ids"), RAD_I32, { T, k });
mw.ew = decl_b(b, nm.f("expert_weights"), RAD_F32, { T, k });
mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { mc.n_expert + 1 });
mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { mc.n_expert });
mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { T * k });
mw.egu = bf("expert_gate_up", { T * k, 2 * F });
mw.eff.x = bf("expert_ff", { T * k, F });
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * k));
mw.edn = bf("expert_down", { T * k, E });
if (mc.expert_rot) {
mw.hr.q = decl_b(b, nm.f("normed_rot.q"), RAD_F8E4M3, { T, E });
mw.hr.s = decl_b(b, nm.f("normed_rot.s"), RAD_F32, { T, E / RAD_FP8_BLOCK });
if (!mw.hr.q || !mw.hr.s) return RAD_E_INVAL;
}
if (mc.n_ff_shared > 0) {
mw.sgu = bf("shared_gate_up", { T, 2 * mc.n_ff_shared });
mw.sff.x = bf("shared_ff", { T, mc.n_ff_shared });
RAD_ARCH_TRY(mw.sff.declare_qs(b, nm, g, "shared_ff", mc.n_ff_shared));
mw.sout = bf("shared_out", { T, E });
mw.sgate = bf("shared_one", { T, 1 });
}
return RAD_OK;
}
/* ============================== declare ============================== */
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)
return RAD_E_INVAL;
const int world = ctx->world_size ? ctx->world_size : 1;
/* A sizing declare writes scratch: the step reads g_model, filled by the real declare at the
* real max_tok (RadBuildCtx::shape_probe). */
static thread_local Model probe_model;
Model& m = ctx->shape_probe ? probe_model : g_model[ctx->rank];
m = Model{};
m.nm = Names(ctx->scope);
auto& g = m.g;
auto& s = m.s;
auto& nm = m.nm;
RAD_ARCH_TRY(read_shape(meta, s));
if (world != 1 && world != 2 && world != 4) {
fprintf(stderr, "radiance: bailing_hybrid: --tp %d; the head and expert splits are built "
"for 1, 2 or 4 ranks\n", world);
return RAD_E_UNSUPPORTED;
}
if (s.heads % world || s.ff_exp % RAD_FP8_BLOCK || s.ff_shared % RAD_FP8_BLOCK ||
s.ff_exp / RAD_FP8_BLOCK < world) {
fprintf(stderr, "radiance: bailing_hybrid: %lld heads and experts of %lld do not split "
"over %d ranks in whole heads and 128-column blocks\n",
(long long)s.heads, (long long)s.ff_exp, world);
return RAD_E_UNSUPPORTED;
}
if (ctx->max_spec > 31) {
fprintf(stderr, "radiance: bailing_hybrid: the KDA verify pass takes at most 32 rows a "
"sequence, so --num-speculative-tokens is at most 31\n");
return RAD_E_UNSUPPORTED;
}
if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16) {
fprintf(stderr, "radiance: bailing_hybrid: the latent and KDA caches are bf16; run with "
"--kv-cache-dtype bf16\n");
return RAD_E_UNSUPPORTED;
}
RAD_ARCH_TRY(geom_from(g, meta, ctx, "bf16", RAD_BF16));
g.head_dim = s.head_dim;
/* ---- the routed experts' slice of this rank: whole at one rank, halves at two, and at four
* the six 128-column blocks of an expert split 2, 2, 1, 1 over the ranks, rotated by the
* expert's number mod 4, so every rank carries six blocks per four experts (moe_gemm_q_mod4).
* The shared expert splits the same way, unrotated. */
MoeFP8::Config mc;
mc.n_expert = mc.n_expert_all = s.experts;
mc.top_k = s.top_k;
mc.sigmoid_router = 1;
mc.route_scale = s.route_scale;
mc.norm_topk = cfg(meta, "norm_topk_prob", 1) != 0;
mc.n_group = s.groups;
mc.topk_group = s.topk_groups;
mc.shared_ungated = 1;
mc.swiglu_step = 1;
mc.rows = g.max_tok;
/* GPTQ calibration (RADIANCE_CALIB_DIR): the tap writes each expert's down Hessian over its
* whole width, so a calibration run gives every rank whole experts (below). */
mc.calib = calib_dir() != nullptr ? 1 : 0;
mc.probed_expert = (int64_t)g.rank * (s.experts / world);
const int64_t eb = s.ff_exp / RAD_FP8_BLOCK, sb = s.ff_shared / RAD_FP8_BLOCK;
if (world == 4) {
int64_t widest = 0;
for (int q = 0; q < 4; ++q) {
int64_t lo, hi;
slice_of(eb, world, g.rank, q, &lo, &hi);
mc.ff_lo4[q] = lo * RAD_FP8_BLOCK;
mc.ff_hi4[q] = hi * RAD_FP8_BLOCK;
widest = std::max(widest, mc.ff_hi4[q] - mc.ff_lo4[q]);
}
mc.n_ff_exp = widest;
} else if (eb % world == 0) {
mc.n_ff_exp = s.ff_exp / world;
} else {
fprintf(stderr, "radiance: bailing_hybrid: experts of %lld do not halve into 128-column "
"blocks\n", (long long)s.ff_exp);
return RAD_E_UNSUPPORTED;
}
if (sb % world == 0) {
mc.n_ff_shared = s.ff_shared / world;
} else {
int64_t lo, hi;
slice_of(sb, world, g.rank, 0, &lo, &hi);
mc.shared_lo = lo * RAD_FP8_BLOCK;
mc.shared_hi = hi * RAD_FP8_BLOCK;
mc.n_ff_shared = mc.shared_hi - mc.shared_lo;
}
if (s.ff_dense % (world * RAD_FP8_BLOCK)) {
fprintf(stderr, "radiance: bailing_hybrid: the dense feed-forward's %lld columns do not "
"split over %d ranks in 128-column blocks\n", (long long)s.ff_dense, world);
return RAD_E_UNSUPPORTED;
}
g.n_ff_all = s.ff_dense;
g.n_ff = s.ff_dense / world;
/* ---- each routed layer's expert format, read before any buffer is declared: rotated experts
* need the rotated activation pair, sized here. The MTP layer follows the trunk's. */
const bool mtp = ctx->max_spec > 0 && cfg(meta, "num_nextn_predict_layers", 0) == 1;
std::vector<MoeFP8::Src> msrc((size_t)s.n_layer + 1);
for (int l = (int)s.dense_layers; l < (int)s.n_layer + (mtp ? 1 : 0); ++l) {
const char* pre = nm.ckpt("model.layers.%d", l);
MoeFP8::Src& ms = msrc[(size_t)l];
ms.cfg = mc;
ms.cfg.swiglu_limit = limit_at(s.lim_exp, l);
ms.cfg.shared_swiglu_limit = limit_at(s.lim_shared, l);
ms.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
ms.router = nm.ckpt("%s.mlp.gate.weight", pre);
ms.router_bias = nm.ckpt("%s.mlp.gate.expert_bias", pre);
ms.experts = nm.ckpt("%s.mlp.experts", pre);
ms.shared = nm.ckpt("%s.mlp.shared_experts", pre);
RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, ms, &ms.cfg));
if (ms.cfg.expert_rot) mc.expert_rot = 1;
if (ms.cfg.expert_bf16) mc.expert_bf16 = 1;
}
/* ---- whole experts per rank for a calibration run and for bf16 experts (a slice of a bf16
* expert is not one container run), as qwen4exp does: rank r owns experts [r E/W, (r+1) E/W).
* Served to calibrate and compare, not for decode speed. */
if (world > 1 && (mc.calib || mc.expert_bf16)) {
int64_t per = 0;
RAD_ARCH_TRY(divide_or_fail(s.experts, world, "num_experts", &per));
for (int l = (int)s.dense_layers; l < (int)s.n_layer + (mtp ? 1 : 0); ++l) {
auto& c = msrc[(size_t)l].cfg;
c.n_expert = per;
c.expert_base = (int64_t)g.rank * per;
c.n_ff_exp = s.ff_exp;
for (int q = 0; q < 4; ++q) c.ff_lo4[q] = c.ff_hi4[q] = 0;
}
mc.n_expert = per;
mc.expert_base = (int64_t)g.rank * per;
mc.n_ff_exp = s.ff_exp;
rad_note(b, "%s: rank %d owns experts [%lld, %lld) of %lld whole",
mc.calib ? "calibration (each expert's Hessian is over its whole width)"
: "bf16 experts",
g.rank, (long long)mc.expert_base, (long long)(mc.expert_base + per),
(long long)s.experts);
}
RAD_ARCH_TRY(buffers(b, m));
RAD_ARCH_TRY(moe_buffers(b, m, mc));
/* ---- the caches: the MLA layers' latent rows, the KDA layers' state and convolution
* history. */
{
RadKVGroupDecl d{};
d.kind = RAD_KV_FULL;
d.dtype = RAD_BF16;
d.n_head_kv = 1;
d.head_dim = (s.latent + s.rope) / 2;
m.latent = rad_decl_kv_group(b, nm.f("kv_latent"), &d);
d = {};
d.kind = RAD_KV_LINEAR;
d.dtype = RAD_F32;
d.n_head_kv = s.heads / world;
d.state_dim[0] = d.state_dim[1] = s.head_dim;
m.state = rad_decl_kv_group(b, nm.f("kv_kda"), &d);
d = {};
d.kind = RAD_KV_CONV;
d.dtype = RAD_BF16;
d.n_head_kv = 1;
d.head_dim = 3 * (s.heads / world) * s.head_dim;
d.conv_width = s.conv;
m.conv = rad_decl_kv_group(b, nm.f("kv_kda_conv"), &d);
if (!m.latent || !m.state || !m.conv) return RAD_E_INVAL;
}
/* ---- the embedding, the layers, the final norm and the head. */
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.word_embeddings.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, g.n_embd },
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
m.head = decl_w(b, nm.f("output.weight"), RAD_BF16, { g.n_vocab, g.n_embd }, RAD_ACCESS_VOCAB,
RAD_SHARD_ROW, grp_model());
m.final_gain = decl_w(b, nm.f("output_norm.weight"), RAD_F32, { g.n_embd },
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
m.embed = rw(b,
RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(m.token)),
{}, { m.x });
m.embed_ar = GlmTp::reduce(b, g, m.x, true);
m.layers.resize((size_t)s.n_layer);
for (int l = 0; l < (int)s.n_layer; ++l) {
Layer& lay = m.layers[(size_t)l];
lay.mla = is_mla(s, l);
lay.dense = l < s.dense_layers;
const char* pre = nm.ckpt("model.layers.%d", l);
const char* nn = nm.f("blk.%d.attn_norm.weight", l);
RAD_ARCH_TRY(map_copy(b, nn, nm.ckpt("%s.input_layernorm.weight", pre)));
lay.gain = decl_w(b, nn, RAD_F32, { g.n_embd }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
RAD_ARCH_TRY(lay.norm.declare(b, g, lay.gain, m.x, m.act, g.n_embd));
const char* ap = nm.ckpt("%s.attention", pre);
if (lay.mla) {
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, s, l, m.aw, ap, m.latent));
} else {
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.state));
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.conv));
RAD_ARCH_TRY(lay.kda.declare(b, nm, g, s, l, m.kw, ap, m.state, m.conv));
}
lay.op_add = rw(b,
RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.x, m.y }, { m.x });
if (!lay.op_add) return RAD_E_INVAL;
if (lay.dense) {
MlpFP8::Src ds{ nm.ckpt("%s.post_attention_layernorm.weight", pre),
nm.ckpt("%s.mlp.gate_proj.weight", pre),
nm.ckpt("%s.mlp.up_proj.weight", pre),
nm.ckpt("%s.mlp.down_proj.weight", pre) };
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, l, m.dw, ds));
} else {
RAD_ARCH_TRY(lay.moe.declare(b, nm, g, l, m.mw, msrc[(size_t)l]));
}
}
RAD_ARCH_TRY(rad_kv_group_replicated(b, m.latent));
m.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_STR("dtype", "bf16")),
RAD_WEIGHTS(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", g.n_embd),
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", g.n_embd), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(m.head)),
{ m.logit_input }, { m.logits });
if (!m.embed || !m.norm || !m.gather || !m.head_op) return RAD_E_INVAL;
/* ---- the drafter: GlmMtp at Ling's width and checkpoint names around one more MLA layer
* with the routed feed-forward. It shares the trunk's buffers, latent cache, embedding and
* head. */
if (mtp) {
const int l = (int)s.n_layer;
auto& mt = m.mtp;
mt.width = g.n_embd;
mt.prefix = nm.ckpt("model.layers.%d", l);
mt.layer = l;
mt.norm_src = "final_layernorm.weight";
const GlmMtp::Wire tw{ m.final_hidden, m.logits, m.token, m.head };
RAD_ARCH_TRY(mt.declare_inputs(b, g, tw, false));
Layer& d = m.draft;
d.mla = true;
const char* pre = mt.prefix;
const char* nn = nm.f("blk.%d.attn_norm.weight", l);
RAD_ARCH_TRY(map_copy(b, nn, nm.ckpt("%s.input_layernorm.weight", pre)));
d.gain = decl_w(b, nn, RAD_F32, { g.n_embd }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
RAD_ARCH_TRY(d.norm.declare(b, g, d.gain, mt.x, m.act, g.n_embd));
RAD_ARCH_TRY(d.attn.declare(b, nm, g, s, l, m.aw, nm.ckpt("%s.attention", pre), m.latent));
RAD_ARCH_TRY(mt.declare_join(b, m.y));
auto mw = m.mw;
mw.x = mt.x;
RAD_ARCH_TRY(d.moe.declare(b, nm, g, l, mw, msrc[(size_t)l]));
RAD_ARCH_TRY(mt.declare_head(b));
m.have_mtp = true;
}
rad_note(b,
"Ling-3.0 (bailing_hybrid): TP%d, %lld layers, %lld KDA + %lld dense MLA, %lld experts "
"top-%lld in %lld groups (%lld kept), MTP %s",
world, (long long)s.n_layer, (long long)(s.n_layer - s.n_layer / s.group_size),
(long long)(s.n_layer / s.group_size), (long long)s.experts, (long long)s.top_k,
(long long)s.groups, (long long)s.topk_groups, m.have_mtp ? "enabled" : "not declared");
return RAD_OK;
}
/* ============================== step ============================== */
/* RADIANCE_LING_DUMP=DIR: the residual stream after each layer's attention and feed-forward, every
* row of every step, as `<DIR>/s<step>.t<rows>.l<layer>.<attn|ffn>.r<rank>.bf16` ([rows, n_embd]
* bf16). A diagnostic for comparing against a reference model layer by layer; it synchronises the
* stream. */
static void dump(RadCtx* c, const RadBatch* batch, rad_buf x, int64_t E, int layer,
const char* site) {
static const char* dir = std::getenv("RADIANCE_LING_DUMP");
if (!dir || !*dir) return;
const int64_t T = batch->n_tok;
void* p = rad_buf_ptr(c, x);
if (!p) return;
std::vector<uint16_t> h((size_t)(T * E));
if (rad_memcpy_async(h.data(), p, T * E * 2, rad_stream(c)) < 0) return;
rad_stream_sync(rad_stream(c));
char path[512];
std::snprintf(path, sizeof path, "%s/s%d.t%lld.l%d.%s.r%d.bf16", dir, batch->step,
(long long)T, layer, site, rad_rank(c));
if (FILE* f = std::fopen(path, "wb")) {
std::fwrite(h.data(), 2, h.size(), f);
std::fclose(f);
}
}
/* A draft pass as GLM-5.3's (glm5next.cpp): the head's inputs, its MLA layer over every row (a
* history pass fills the draft layer's latent cache for all of them), then on the proposal rows the
* residual join, the routed feed-forward and the head. */
static void draft_pass(RadCtx* c, Model& m, const RadBatch* batch) {
if (!m.have_mtp || batch->draft_pass == 1) {
rad_step_fail(c, "bailing_hybrid MTP pass is not declared or has invalid round 1");
return;
}
const int64_t T = batch->n_tok;
m.mtp.step_inputs(c, batch);
auto& l = m.draft;
l.norm.step(c, T);
l.attn.step(c, batch);
if (batch->draft_pass < 0 && batch->n_draft_out <= 0) return;
m.mtp.step_join(c, batch, m.y);
l.moe.step_rows(c, GlmMtp::head_rows(batch));
m.mtp.step_head(c, batch);
}
static void step(RadCtx* c, const RadBatch* batch) {
Model& m = g_model[rad_rank(c)];
const int64_t T = batch->n_tok, E = m.g.n_embd;
if (batch->enc) {
rad_step_fail(c, "bailing_hybrid serves text");
return;
}
if (batch->draft_pass) {
draft_pass(c, m, batch);
return;
}
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 * E, brows(m.x, T), RAD_NONE);
for (size_t i = 0; i < m.layers.size(); ++i) {
const Layer& l = m.layers[i];
l.norm.step(c, T);
if (l.mla)
l.attn.step(c, batch);
else
l.kda.step(c, batch);
RAD_ISSUE_N(c, l.op_add, T, brows(m.x, T), brows(m.y, T), brows(m.x, T));
dump(c, batch, m.x, E, (int)i, "attn");
if (l.dense)
l.mlp.step(c, batch);
else
l.moe.step(c, batch);
dump(c, batch, m.x, E, (int)i, "ffn");
}
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) {
RAD_ISSUE_N(c, m.gather, batch->n_out, brows(m.final_hidden, T),
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.logit_input, batch->n_out));
RAD_ISSUE_N(c, m.head_op, batch->n_out, brows(m.logit_input, batch->n_out), RAD_W(m.head),
brows(m.logits, batch->n_out));
}
}
/* The default draft depth for `--num-speculative-tokens auto`: GlmMtp's operating point, when the
* checkpoint carries its one MTP layer. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
if (cfg(meta, "num_nextn_predict_layers", 0) == 1) out->draft_depth = GlmMtp::kDepth;
out->shape_probe_ok = 1; /* declare() writes scratch under shape_probe */
return RAD_OK;
}
} /* namespace bailing_hybrid */
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(bailing_hybrid)
RAD_ARCH_PLUGIN(bailing_hybrid, "bailinghybrid", "", "0.1.0",
"Ling-3.0 (bailing_hybrid): KDA and dense latent attention, group-routed experts")
#endif
+47 -3
View File
@@ -17,6 +17,7 @@
#include "rad_yarn.h" #include "rad_yarn.h"
#include "rad_abi_layout.h" #include "rad_abi_layout.h"
#include <cctype>
#include <cstdarg> #include <cstdarg>
#include <cstdio> #include <cstdio>
#include <cstring> #include <cstring>
@@ -123,6 +124,36 @@ inline const char* calib_dir() {
return d && *d ? d : nullptr; return d && *d ? d : nullptr;
} }
/* Whether layer `layer` taps (RADIANCE_CALIB_LAYERS: comma-separated layers and "lo-hi" ranges;
* unset, every layer). A model whose per-expert Hessians do not fit the host at once (Nemotron-3.5
* Bolt's are 169 GiB) calibrates in several runs over disjoint ranges; each run writes only its
* layers' files, so the runs share one directory. */
inline bool calib_layer_on(int layer) {
static const std::vector<std::pair<int, int>> ranges = [] {
std::vector<std::pair<int, int>> r;
const char* s = std::getenv("RADIANCE_CALIB_LAYERS");
while (s && *s) {
char* e = nullptr;
const long lo = std::strtol(s, &e, 10);
if (e == s) break;
long hi = lo;
if (*e == '-') {
const char* h = e + 1;
hi = std::strtol(h, &e, 10);
if (e == h) break;
}
r.emplace_back((int)lo, (int)hi);
s = *e == ',' ? e + 1 : e;
if (*s && *s != ',' && !std::isdigit((unsigned char)*s)) break;
}
return r;
}();
if (!std::getenv("RADIANCE_CALIB_LAYERS")) return true;
for (const auto& r : ranges)
if (layer >= r.first && layer <= r.second) return true;
return false;
}
/* Token count at which the tap dumps and switches itself off (RADIANCE_CALIB_TOKENS, default /* Token count at which the tap dumps and switches itself off (RADIANCE_CALIB_TOKENS, default
* 65536). Whether the tap runs at all is calib_dir()'s decision. */ * 65536). Whether the tap runs at all is calib_dir()'s decision. */
inline long long calib_target() { inline long long calib_target() {
@@ -980,7 +1011,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
g.wire_exact= c->tp_wire_lossy ? 0 : 1; g.wire_exact= c->tp_wire_lossy ? 0 : 1;
g.wire_min_bytes = c->tp_wire_min_bytes; g.wire_min_bytes = c->tp_wire_min_bytes;
g.attn_prefill_fp8 = c->attn_prefill_fp8; g.attn_prefill_fp8 = c->attn_prefill_fp8;
g.plain_norm = c->plain_norm; g.plain_norm = c->plain_norm != 0;
g.eps = m->rms_eps; g.eps = m->rms_eps;
g.theta = m->rope_theta; g.theta = m->rope_theta;
g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */ g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */
@@ -1504,7 +1535,12 @@ inline const char* drafter_layer_prefix(const RadModelMeta* meta) {
return "draft.transformer_layer_config."; return "draft.transformer_layer_config.";
return "draft."; return "draft.";
} }
inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what) { /* `kv_repl_ok`: the drafter block reads its k and v at Geom::kv_off (rad_block_dflash2.h does), so
* fewer KV heads than ranks are replicated as geom_from replicates the target's: world a multiple
* of the head count, one KV head a rank, `kv_off` its first row in the unsharded k/v projection.
* Otherwise such a world is refused, as before. */
inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what,
bool kv_repl_ok = false) {
dg = target; dg = target;
const char* pre = drafter_layer_prefix(meta); const char* pre = drafter_layer_prefix(meta);
char key[160]; char key[160];
@@ -1529,7 +1565,15 @@ inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta,
} }
RAD_ARCH_TRY(yarn_from(dg, meta, pre, dg.head_dim)); RAD_ARCH_TRY(yarn_from(dg, meta, pre, dg.head_dim));
RAD_ARCH_TRY(divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head)); RAD_ARCH_TRY(divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head));
RAD_ARCH_TRY(divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv)); /* The target's kv_off is the target's; the drafter's is set here or zero. */
dg.kv_off = 0;
if (kv_repl_ok && dg.world > dg.n_head_kv_all && dg.world % dg.n_head_kv_all == 0) {
dg.n_head_kv = 1; /* world / n_head_kv_all ranks share each KV head */
dg.kv_off = (dg.rank / (dg.world / dg.n_head_kv_all)) * dg.head_dim;
} else {
RAD_ARCH_TRY(divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads",
&dg.n_head_kv));
}
RAD_ARCH_TRY(divide_or_fail(dg.n_ff_all, dg.world, "draft intermediate_size", &dg.n_ff)); RAD_ARCH_TRY(divide_or_fail(dg.n_ff_all, dg.world, "draft intermediate_size", &dg.n_ff));
const long long dvocab = rad_meta_geti(meta, k("vocab_size"), dg.n_vocab_all); const long long dvocab = rad_meta_geti(meta, k("vocab_size"), dg.n_vocab_all);
if (dvocab != dg.n_vocab_all) { if (dvocab != dg.n_vocab_all) {
+24 -11
View File
@@ -9,6 +9,9 @@
* the GEMM output directly. * the GEMM output directly.
* - No output gate. The attention output goes straight into the out-projection. * - No output gate. The attention output goes straight into the out-projection.
* *
* `rotary_dim` 0 is attention without positions (NoPE, Nemotron-H's attention layers): no `rope`
* is declared, and position reaches the model through its recurrent layers alone.
*
* That allows a fused q|k|v, which the gated block cannot have (its query projection is [q|gate] * That allows a fused q|k|v, which the gated block cannot have (its query projection is [q|gate]
* interleaved per head). The three weights concatenate along dim 0 into one * interleaved per head). The three weights concatenate along dim 0 into one
* [q_dim + 2*kv_dim, n_embd], and `rope` takes that row as is: q heads, then k heads, v untouched * [q_dim + 2*kv_dim, n_embd], and `rope` takes that row as is: q heads, then k heads, v untouched
@@ -81,19 +84,21 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
const int64_t q_dim = g.q_dim(); const int64_t q_dim = g.q_dim();
const int64_t kv_dim = g.kv_dim(); const int64_t kv_dim = g.kv_dim();
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) { if (n_rot < 0 || n_rot > g.head_dim || (n_rot & 1)) {
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n", fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
(long long)n_rot, (long long)g.head_dim); (long long)n_rot, (long long)g.head_dim);
return RAD_E_INVAL; return RAD_E_INVAL;
} }
/* No KV-head replication: the fused [q|k|v] uses the plain even row shard, so above the KV head /* Above the KV head count geom_from replicates KV heads (rad_arch.h): each of the fused row's
* count a rank would read the wrong rows. rad_block_attn_gated_fp8.h is the block that uses * three parts takes its own span (as gemma4's q|k|v does), q this rank's heads and k and v the
* geom_from's `kv_off`. */ * shared head at `kv_off`, where the even shard would hand a rank part of a head. A smaller
if (g.world > g.n_head_kv_all) { * attention world (Geom::attn_world) is not served here. */
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d " const bool kv_repl = g.world > g.n_head_kv_all;
"with n_head_kv = %lld.\n", __func__, g.world, if (kv_repl && g.attn_world != g.world) {
(long long)g.n_head_kv_all); fprintf(stderr, "radiance: %s replicates KV heads but declares no attention-zero ranks; "
"world_size = %d must be a multiple of n_head_kv = %lld.\n", __func__,
g.world, (long long)g.n_head_kv_all);
return RAD_E_UNSUPPORTED; return RAD_E_UNSUPPORTED;
} }
@@ -107,9 +112,17 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
RAD_ARCH_TRY(qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, g.n_embd, RAD_ARCH_TRY(qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, g.n_embd,
RAD_SHARD_ROW, grp_layer(l), { src.q, src.k, src.v }, w.h, w.qkv, RAD_SHARD_ROW, grp_layer(l), { src.q, src.k, src.v }, w.h, w.qkv,
0, { q_dim, kv_dim, kv_dim })); 0, { q_dim, kv_dim, kv_dim }));
if (kv_repl) {
const int64_t lo[3] = { g.rank * q_dim, g.kv_off, g.kv_off };
const int64_t hi[3] = { lo[0] + q_dim, lo[1] + kv_dim, lo[2] + kv_dim };
const int64_t tot[3] = { g.n_head_all * g.head_dim, g.n_head_kv_all * g.head_dim,
g.n_head_kv_all * g.head_dim };
RAD_ARCH_TRY(qkv.span_parts(b, lo, hi, tot, 3));
}
op_rope = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, g.n_head_kv, n_rot, mode), if (n_rot > 0)
{w.qkv}, {w.qkv}); op_rope = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, g.n_head_kv, n_rot, mode),
{w.qkv}, {w.qkv});
/* Copies the query out of the fused row: libr4d's paged attention reads `q` as a dense /* Copies the query out of the fused row: libr4d's paged attention reads `q` as a dense
* [total_q, n_head, head_dim] block with no pitch argument (r4d_attn_args.h, fill_paged), so a * [total_q, n_head, head_dim] block with no pitch argument (r4d_attn_args.h, fill_paged), so a
@@ -179,7 +192,7 @@ inline void AttnFP8::step(RadCtx* c, const RadBatch* batch) const {
qkv.step(c, w.h, w.qkv, T); qkv.step(c, w.h, w.qkv, T);
/* In place over the fused row: rotates n_head query heads, then n_head_kv key heads, and /* In place over the fused row: rotates n_head query heads, then n_head_kv key heads, and
* leaves the value heads alone. */ * leaves the value heads alone. */
RAD_ISSUE(c, op_rope, brows(w.qkv, T), rope_posmc(g, batch, T)); if (op_rope) RAD_ISSUE(c, op_rope, brows(w.qkv, T), rope_posmc(g, batch, T));
/* k and v are column slices of the fused row, at q_dim and q_dim + kv_dim. */ /* k and v are column slices of the fused row, at q_dim and q_dim + kv_dim. */
RAD_ISSUE(c, op_kv_store, RAD_ISSUE(c, op_kv_store,
+5 -3
View File
@@ -458,8 +458,10 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
if (g.w_bf16) { if (g.w_bf16) {
RAD_ARCH_TRY(gate_pair(w.gate)); RAD_ARCH_TRY(gate_pair(w.gate));
} else { } else {
if (rad_op_declared(b, "gate_quant_fp8")) /* Rotated int8 codes (ActFP8::q8_rot): gate_had_quant_i8g, had_quant_act_i8g's codes. */
op_gq = rw(b, RAD_OP(b, "gate_quant_fp8", const char* gq = w.attn.q8_rot ? "gate_had_quant_i8g" : "gate_quant_fp8";
if (rad_op_declared(b, gq))
op_gq = rw(b, RAD_OP(b, gq,
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head), RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
RAD_INT("n", g.head_dim), RAD_INT("group", RAD_FP8_BLOCK), RAD_INT("n", g.head_dim), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", g.dtype), RAD_STR("act", "sigmoid")), RAD_STR("dtype", g.dtype), RAD_STR("act", "sigmoid")),
@@ -487,7 +489,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
* and quantiser read, so one op merges, gates, rounds and quantises (byte-identical to the * and quantiser read, so one op merges, gates, rounds and quantises (byte-identical to the
* pair). Declared only with a selection: the dense path also uses the prefill kernel, which * pair). Declared only with a selection: the dense path also uses the prefill kernel, which
* has no merge. */ * has no merge. */
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 && if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 && !w.attn.q8_rot &&
rad_op_declared(b, "attn_paged_gate_quant")) { rad_op_declared(b, "attn_paged_gate_quant")) {
op_attn_gq = RAD_OP(b, "attn_paged_gate_quant", op_attn_gq = RAD_OP(b, "attn_paged_gate_quant",
RAD_PARAMS(RAD_INT("q_len", 1), RAD_INT("head_dim", g.head_dim), RAD_PARAMS(RAD_INT("q_len", 1), RAD_INT("head_dim", g.head_dim),
+129 -58
View File
@@ -47,6 +47,13 @@
* hp = hidden_projection(x) the selector's query, rank 256 * hp = hidden_projection(x) the selector's query, rank 256
* tokens = dflash_select(cand, unary, hp, anchor, predecessor, successor) * tokens = dflash_select(cand, unary, hp, anchor, predecessor, successor)
* *
* ============================== LILICORR ==============================
*
* Config::lili is NVIDIA's LiLiCorr backbone (Nemotron-3.5-Bolt's drafter): the same layers with a
* learned sink logit a query head in the attention (attn_paged_sink, `attention_sink_bias`), and no
* selector or draft head here. The query pass ends with the gather into `sel_h`; the plugin then
* runs rad_block_lilicorr.h's correlator over those rows, which reads the target's own head.
*
* ============================== WHAT IS SHARED WITH THE TARGET ============================== * ============================== WHAT IS SHARED WITH THE TARGET ==============================
* *
* The embedding table and lm_head. The checkpoint (81 tensors) ships neither, and * The embedding table and lm_head. The checkpoint (81 tensors) ships neither, and
@@ -68,6 +75,8 @@
* *
* q/kv and gate_up shard by row, o and down by column with an all-reduce: ten collectives per * q/kv and gate_up shard by row, o and down by column with an all-reduce: ten collectives per
* draft pass, each 5120 * block * 2 bytes (80 KiB at block 8), below the lossy wire's floor. * draft pass, each 5120 * block * 2 bytes (80 KiB at block 8), below the lossy wire's floor.
* Fewer KV heads than ranks are replicated (drafter_geom's `kv_repl_ok`): each rank reads its
* head's k/v rows at `kv_off` and keeps that head in its cache.
* *
* fc [n_embd, n_taps*n_embd], 262 MiB in fp8 at Qwen3.8's width, read whole by the * fc [n_embd, n_taps*n_embd], 262 MiB in fp8 at Qwen3.8's width, read whole by the
* context pass every step. Split by rows over the ranks and all-gathered, and * context pass every step. Split by rows over the ranks and all-gathered, and
@@ -152,6 +161,9 @@ struct Dflash2 {
* acceptance, sum min(P, Q). */ * acceptance, sum min(P, Q). */
double q_temp = 1.0; double q_temp = 1.0;
int64_t short_rows = 0; int64_t short_rows = 0;
/* LiLiCorr's backbone (the LILICORR section above): sinks, and the head left to the
* plugin. sel_rank and sel_topk are then unused. */
int lili = 0;
int64_t steps() const { return block - 1; } int64_t steps() const { return block - 1; }
int64_t nodes() const { return tree && tree_nodes > 0 ? tree_nodes : steps(); } int64_t nodes() const { return tree && tree_nodes > 0 ? tree_nodes : steps(); }
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; } int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
@@ -294,6 +306,9 @@ struct Dflash2 {
int64_t block_lo = 0; int64_t block_lo = 0;
int64_t sel_lo_nodes = 0; /* a tree's nodes at the short block (op_sel_lo) */ int64_t sel_lo_nodes = 0; /* a tree's nodes at the short block (op_sel_lo) */
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0; rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
/* LiLiCorr: the attention with each layer's sinks, a weight, so one op a layer. */
rad_weight w_sink[MAX_LAYERS] = {};
rad_op op_attn_sink[MAX_LAYERS] = {};
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0; rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
/* The residual add folded into the norm after it (add_rmsnorm), issued in place of op_add and /* The residual add folded into the norm after it (add_rmsnorm), issued in place of op_add and
* that norm where it resolves: op_afn[i] after layer i's attention (its feed-forward norm), * that norm where it resolves: op_afn[i] after layer i's attention (its feed-forward norm),
@@ -353,7 +368,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
(long long)g.n_layer, MAX_LAYERS); (long long)g.n_layer, MAX_LAYERS);
return RAD_E_UNSUPPORTED; return RAD_E_UNSUPPORTED;
} }
if (cfg.block < 2 || cfg.n_taps <= 0 || cfg.sel_rank <= 0 || cfg.sel_topk <= 0) if (cfg.block < 2 || cfg.n_taps <= 0 || (!cfg.lili && (cfg.sel_rank <= 0 || cfg.sel_topk <= 0)))
return RAD_E_INVAL; return RAD_E_INVAL;
const int64_t NG = cfg.ng(g.n_embd); const int64_t NG = cfg.ng(g.n_embd);
@@ -401,23 +416,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
} }
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck))); RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck))); RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_proj.weight"),
nm.ckpt("%s.candidate_selector.hidden_projection.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_pred"),
nm.ckpt("%s.candidate_selector.predecessor_codebook", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_succ"),
nm.ckpt("%s.candidate_selector.successor_codebook", ck)));
w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd}, w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd}, w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
w_selp = decl_w(b, nm.f("dflash.sel_proj.weight"), RAD_BF16, {cfg.sel_rank, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
w_pred = decl_w(b, nm.f("dflash.sel_pred"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
w_succ = decl_w(b, nm.f("dflash.sel_succ"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
/* The 2-bit draft head, declared as the MTP head's is (rad_block_mtp_fp8.h): /* The 2-bit draft head, declared as the MTP head's is (rad_block_mtp_fp8.h):
* `dflash.draft_head.weight` is the target's lm_head under its own name, quantised by the * `dflash.draft_head.weight` is the target's lm_head under its own name, quantised by the
@@ -427,35 +429,53 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
* When sharded, each rank's `row_topk` reports global ids, an all_gather moves R pairs a row, * When sharded, each rank's `row_topk` reports global ids, an all_gather moves R pairs a row,
* and `row_topk_merge` reduces them to exactly the unsharded global top-R, ties included * and `row_topk_merge` reduces them to exactly the unsharded global top-R, ties included
* (docs/OPS.md). This runs before the selector, so every rank holds the same candidates for * (docs/OPS.md). This runs before the selector, so every rank holds the same candidates for
* the replicated codebooks. The all_gather is `world * R` pairs a row (2 KiB at R = 16). */ * the replicated codebooks. The all_gather is `world * R` pairs a row (2 KiB at R = 16).
*
* LiLiCorr has neither the selector nor this head (its correlator reads the target's). */
enum { DF_W2_GROUP = 128 }; enum { DF_W2_GROUP = 128 };
const bool dh_shard = head_sharded(g); const bool dh_shard = head_sharded(g);
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE; const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
const char* dhn = nm.f("dflash.draft_head.weight"); if (!cfg.lili) {
RAD_ARCH_TRY(map_copy(b, dhn, ck_lm)); RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_proj.weight"),
/* The 8-bit form: int8 codes, one f16 scale per (row, 128 of K), symmetric, which gemm_nt_q nm.ckpt("%s.candidate_selector.hidden_projection.weight", ck)));
* reads at w8a8 against the same quant_act_i8 activation (without its asum). */ RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_pred"),
{ nm.ckpt("%s.candidate_selector.predecessor_codebook", ck)));
RadEncoding e{}; RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_succ"),
const RadEncPlane* sc = nullptr; nm.ckpt("%s.candidate_selector.successor_codebook", ck)));
head_i8 = weight_enc(b, dhn, &e) && rad_enc_is(&e, "affine") && e.n_planes == 2 && w_selp = decl_w(b, nm.f("dflash.sel_proj.weight"), RAD_BF16, {cfg.sel_rank, g.n_embd},
!e.transform[0] && e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 && RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
(sc = rad_enc_plane(&e, "scale")) && sc->dtype == RAD_F16 && w_pred = decl_w(b, nm.f("dflash.sel_pred"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP; RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
w_succ = decl_w(b, nm.f("dflash.sel_succ"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
const char* dhn = nm.f("dflash.draft_head.weight");
RAD_ARCH_TRY(map_copy(b, dhn, ck_lm));
/* The 8-bit form: int8 codes, one f16 scale per (row, 128 of K), symmetric, which
* gemm_nt_q reads at w8a8 against the same quant_act_i8 activation (without its asum). */
{
RadEncoding e{};
const RadEncPlane* sc = nullptr;
head_i8 = weight_enc(b, dhn, &e) && rad_enc_is(&e, "affine") && e.n_planes == 2 &&
!e.transform[0] && e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 &&
(sc = rad_enc_plane(&e, "scale")) && sc->dtype == RAD_F16 &&
sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP;
}
if (head_i8) {
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_I8, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_F16,
{head_rows(g), g.n_embd / DF_W2_GROUP}, RAD_ACCESS_PER_TOKEN,
dh_split, grp_model());
} else {
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16,
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split,
grp_model());
}
if (!w_dh || !w_dhs) return RAD_E_INVAL;
} }
if (head_i8) {
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_I8, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_F16,
{head_rows(g), g.n_embd / DF_W2_GROUP}, RAD_ACCESS_PER_TOKEN, dh_split,
grp_model());
} else {
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16,
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
}
if (!w_dh || !w_dhs) return RAD_E_INVAL;
/* ---------------------------------------------------------------- per-layer weights */ /* ---------------------------------------------------------------- per-layer weights */
for (int64_t l = 0; l < g.n_layer; ++l) { for (int64_t l = 0; l < g.n_layer; ++l) {
@@ -492,6 +512,13 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd, RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i), RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i),
{ nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) })); { nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) }));
/* Fewer KV heads than ranks (drafter_geom's `kv_repl_ok`): k and v are this rank's
* replicated head, rows [kv_off, kv_off + kv_dim) of the unsharded projection, where the
* even shard would hand a rank part of a head. q stays an even share of the heads. */
if (g.world > g.n_head_kv_all) {
RAD_ARCH_TRY(w_k[i].span(b, g.kv_off, g.kv_off + kvd));
RAD_ARCH_TRY(w_v[i].span(b, g.kv_off, g.kv_off + kvd));
}
w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim}, w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(first_layer + i)); RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(first_layer + i));
w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim}, w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim},
@@ -520,6 +547,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
w_fcb[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_conv_base", i), RAD_BF16, w_fcb[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_conv_base", i), RAD_BF16,
{2, cfg.taps, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, {2, cfg.taps, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(first_layer + i)); grp_layer(first_layer + i));
/* LiLiCorr's sink logit a query head, split with the heads. */
if (cfg.lili) {
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_sinks", i),
nm.ckpt("%s.layers.%d.self_attn.attention_sink_bias", ck, i)));
w_sink[i] = decl_w(b, nm.f("dflash.blk.%d.attn_sinks", i), RAD_F32, {g.n_head},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i));
if (!w_sink[i]) return RAD_E_INVAL;
}
} }
@@ -529,15 +564,35 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
* *
* Declared before both kv_stores, which read the resolved `block_size` back with * Declared before both kv_stores, which read the resolved `block_size` back with
* rad_kv_block_size(); before this declaration it returns zero. */ * rad_kv_block_size(); before this declaration it returns zero. */
op_attn = rw(b, RAD_OP(b, "attn_paged", if (!cfg.lili) {
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim), op_attn = rw(b, RAD_OP(b, "attn_paged",
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal), RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
RAD_INT("window", cfg.window), RAD_INT("n_head", g.n_head), RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
RAD_INT("block_size", RAD_KV_BLOCK), RAD_INT("window", cfg.window), RAD_INT("n_head", g.n_head),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), RAD_INT("block_size", RAD_KV_BLOCK),
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_NOWEIGHTS), RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
{w.q}, {w.attn}); RAD_NOWEIGHTS),
{w.q}, {w.attn});
} else {
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_attn_sink[i] = rw(b, RAD_OP(b, "attn_paged_sink",
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block),
RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
RAD_INT("window", cfg.window),
RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs),
RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_WEIGHTS(w_sink[i])),
{w.q}, {w.attn});
if (!op_attn_sink[i]) return RAD_E_INVAL;
}
}
/* ---------------------------------------------------------------- the context pass */ /* ---------------------------------------------------------------- the context pass */
/* Every linear is `fp8a8` (or `mxfp4a8` for a 4-bit recipe; DenseFP8 reads which from the /* Every linear is `fp8a8` (or `mxfp4a8` for a 4-bit recipe; DenseFP8 reads which from the
@@ -555,12 +610,15 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
if (fc_rows) { if (fc_rows) {
/* The split (SHARDING above): this rank's block-aligned rows into `cpart`, its window of /* The split (SHARDING above): this rank's block-aligned rows into `cpart`, its window of
* them gathered into `c`. The GEMM takes its K split from the whole width. The gather * them gathered into `c`. The GEMM takes its K split from the whole width. The gather
* rides the trunk's all-reduce instance (the same numel bound, so the same instance). */ * rides the trunk's all-reduce instance (the same numel bound, so the same instance).
* The message is a range, as the all-reduce's: a fixed numel follows max_tok, and the
* arena's sizing declare (RadBuildCtx::shape_probe) refuses a fixed parameter that
* changes with the step size. */
op_cfc = w_fc.gemm(b, crows, fc_rows, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.cpart}, op_cfc = w_fc.gemm(b, crows, fc_rows, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.cpart},
g.n_embd); g.n_embd);
op_cgath = rw(b, RAD_OP(b, "all_gather", op_cgath = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", crows * g.n_embd), RAD_RANGE("numel", g.n_embd, crows * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("row", fc_share)), RAD_STR("dtype", g.dtype), RAD_INT("row", fc_share)),
RAD_NOWEIGHTS), RAD_NOWEIGHTS),
{w.cpart}, {w.c}); {w.cpart}, {w.c});
@@ -884,6 +942,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_STR("dtype", g.dtype)), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS), RAD_NOWEIGHTS),
{w.h}, {w.sel_h}); {w.h}, {w.sel_h});
/* LiLiCorr's head is the plugin's (rad_block_lilicorr.h), over sel_h. */
if (cfg.lili) return RAD_OK;
op_dquant = rw(b, RAD_OP(b, "quant_act_i8", op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd), RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)), RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)),
@@ -1090,7 +1150,8 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
if (fc_rows) { if (fc_rows) {
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s), RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
brows(w.cpart, T), RAD_NONE, w_fc.bref()); brows(w.cpart, T), RAD_NONE, w_fc.bref());
RAD_ISSUE_N(c, op_cgath, T, bcol(w.cpart, fc_off, fc_share, T), brows(w.c, T)); RAD_ISSUE_N(c, op_cgath, T * g.n_embd, bcol(w.cpart, fc_off, fc_share, T),
brows(w.c, T));
} else { } else {
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s), RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
brows(w.c, T), RAD_NONE, w_fc.bref()); brows(w.c, T), RAD_NONE, w_fc.bref());
@@ -1188,13 +1249,22 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T), RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T),
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i)); praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
} }
RAD_ISSUE_N(c, op_attn, batch->max_q_len, if (cfg.lili)
brows(w.q, T), kv_cache(kv, first_layer + i), RAD_ISSUE_N(c, op_attn_sink[i], batch->max_q_len,
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0), brows(w.q, T), kv_cache(kv, first_layer + i),
praw(used, RAD_I32, batch->n_seq), praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
RAD_NONE, RAD_NONE, praw(used, RAD_I32, batch->n_seq),
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), RAD_NONE, RAD_NONE,
brows(w.attn, T)); praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
RAD_W(w_sink[i]), brows(w.attn, T));
else
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
brows(w.q, T), kv_cache(kv, first_layer + i),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq),
RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(w.attn, T));
RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T)); RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T), RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref()); RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref());
@@ -1238,6 +1308,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
const int64_t S = batch->n_out; const int64_t S = batch->n_out;
if (S <= 0) return; if (S <= 0) return;
RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S)); RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S));
if (cfg.lili) return; /* the plugin's correlator takes sel_h from here */
/* `dsum` is group-major, [n_embd/group][ceil(M/16)*16], so it has no row slice; pass it /* `dsum` is group-major, [n_embd/group][ceil(M/16)*16], so it has no row slice; pass it
* whole. */ * whole. */
+958
View File
@@ -0,0 +1,958 @@
/* rad_block_dspark_bf16.h -- the DSpark drafter over bf16 weights, at the widths a Spark layer
* uses: a few plain attention layers that denoise a whole block of masked positions in one pass,
* conditioned on the trunk's residual stream at a handful of layers, with a rank-N Markov head
* over the target's own output table.
*
* ============================== WHY A SECOND DSPARK BLOCK ==============================
*
* rad_block_dspark.h is the same drafter shape for a block-fp8 release: its linears are DenseFP8
* behind `quant_act_fp8`, its feed-forward is `silu_mul`, its norms carry q/k gains, and its draft
* head is a 2-bit copy of the target's. The published Spark drafts (`dflash` GGUFs, and the HF
* Spark drafter releases behind them) ship the other way: bf16 linears, no q/k norms, one sigmoid
* gate a head on the attention output, exact-erf GELU, one RMS gain per tap, and a sliding window.
* Those are different ops, not different parameters, so this block declares its own graph and
* uses an explicit anchor-window attention op and a full-vocabulary Markov selector so neither
* semantic distinction is silently folded into the generic per-row window or candidate-lattice ops.
*
* Nothing here is quantised. The drafter is 624M parameters read whole a draft pass, so bf16 costs
* 1.2 GiB of residency and one extra weight pass a step; quantising it is a separate measurement
* (it can only move acceptance, since every draft is verified by the target).
*
* ============================== THE FORWARD PASS ==============================
*
* The reference is llama.cpp's `llama_model_dflash::graph<false>` (XHToken/llama.cpp
* 22c0ae1871b, the branch the Spark draft cards name), which mirrors the HF export:
*
* tap(l) = rmsnorm(residual after trunk layer l) * fc_norm[l] one gain row per tap
* ctx = rmsnorm(fc(concat_l tap(l))) hidden_norm
* per draft layer (x5):
* h_n = input_layernorm(h)
* q,k,v = q_proj/k_proj/v_proj(h_n); k_ctx, v_ctx = k_proj/v_proj(ctx)
* rope(q, k); attention over [the layer's context K/V, this block] non-causally,
* inside a `window` positions
* h += o_proj(sigmoid(g_proj(h)) * attn) one gate a head, no q/k norms
* h += mlp(post_attention_layernorm(h)) gelu(gate) * up, then down
* logits = target.lm_head(output_norm(h)) + markov_w2 @ markov_w1[prev]
*
* The two projections of `ctx` are the drafter's own k_proj and v_proj, one pair per layer, and
* they run over every committed token; the drafter's layers never see the context rows. That is
* the context pass below, and the block above is the query pass -- the same split
* rad_block_dspark.h makes, and the same `RAD_DRAFT_BLOCK` drive.
*
* ============================== THE TAPS ARE NORMED, NOT JUST READ ==================
*
* `fc_norm` is [n_taps, n_embd]: the residual entering each tap layer is normed with its own gain
* before the concatenation, so `fc` sees n_taps unit-scaled streams instead of one sum whose
* magnitudes the trunk happens to have. One `rmsnorm` per tap over that tap's column slice of the
* tap buffer, into the same slice layout of a normed copy; `fc` then reads one contiguous
* [n_taps * n_embd] row.
*
* ============================== THE SHARED ANCHOR WINDOW ==========================
*
* The pinned llama.cpp oracle increments the configured history from 512 to 513 and repeats the
* anchor row's mask for every row in the denoising block. `attn_paged_anchor_window` implements
* that exact predicate: every row sees keys through the end of the staged context whose absolute
* position is less than 513 behind the anchor. The query row does not move the lower cutoff. The
* same 513-token width is passed to the KV group and scheduler, so rollback, cache recycling and
* block staging all retain the exact history the drafter reads.
*
* ============================== ROW ALIGNMENT ==============================
*
* Every row predicts, the anchor included (`dflash.sample_from_anchor`, which the GGUF import
* refuses when false): row j of [anchor, MASK x (block-1)] proposes the token at the anchor's
* position plus j + 1, so `steps()` is `block` and the head runs over all the block's rows. The
* core stages the block against `RadDrafterDecl::block` and runs the head over the last `depth`
* rows, which covers this and Dflash2's shift-by-one convention (abi/rad_builder.h).
*
* ============================== THE MARKOV HEAD ==============================
*
* The draft logits get a learned bigram bias
*
* score[l, token] = logits[l, token] + markov_w2[token] . markov_w1[prev(l)]
* prev(0) = the anchor; prev(l) = the greedy token chosen at l - 1
*
* `dflash_markov_greedy` scans the full vocabulary at every position and greedily chooses the
* largest biased score, following the structure of the pinned reference's serial Markov walk.
* Base logits are F32; reduction order and tie behavior can still differ from the reference. It
* does not prune to the base head's top K, use a joint-path heap, or apply confidence to logits.
*
* The confidence head (`conf_proj`, one sigmoid a position predicting acceptance) is imported and
* ignored: it exists to let a serving loop cut the block short, this engine's depth is fixed at
* declare, and it changes nothing the drafter proposes.
*
* ============================== PRECISION ==============================
*
* bf16 for every weight and activation except the residual stream, which is f32 exactly as the
* Spark trunk keeps it (rad_block_dspark.h's fp8 graphs fold the residual into the norm; here the
* norms read the f32 stream and write bf16, and `add` keeps the sum in f32). The reference runs
* bf16 weights against an f32 residual, so rounding the drafter's stream to bf16 would be a third
* opinion on every layer's output for no saved bytes worth having at `block` rows.
*
* ============================== NOT DONE ==============================
*
* The head and full-vocabulary Markov scan are read replicated, so a vocab-sharded deployment
* cannot draft with them. The plugin refuses `world > 1` rather than scoring only one rank's
* slice of the vocabulary.
*
* The drafter's linears are four GEMMs and one attention a layer with no folding: the norms are
* plain `rmsnorm`, not a fused norm-add-quantise, because nothing here quantises. At seven rows
* a pass the launches, not the bytes, are the cost.
*/
#ifndef RAD_BLOCK_DSPARK_BF16_H
#define RAD_BLOCK_DSPARK_BF16_H
#include "rad_arch.h"
namespace rad {
namespace arch {
/* The builder refuses a declaration it cannot serve and says why in its own words; this names which
* handle did not come back, so that message reads against a line of this file. An op that resolves
* to no kernel is recorded and handed back null -- it is only an error if the block issues it -- so
* without this a missing kernel surfaces as a bare "invalid argument" at startup. */
#define DS_REFUSED(...) ::rad::arch::drafter_refused({ __VA_ARGS__ })
inline int drafter_refused(std::initializer_list<const char*> what) {
std::string list;
for (const char* w : what) { if (!list.empty()) list += ", "; list += w; }
std::fprintf(stderr, "DSpark drafter: the builder gave no handle for %s\n", list.c_str());
return RAD_E_INVAL;
}
struct DsparkBF16 {
enum { MAX_LAYERS = 8 };
/* The drafter's config beyond its geometry. Everything here comes from the container's
* `draft.` keys; nothing is defaulted quietly, because a silently ignored gate or window only
* moves acceptance, which is the one number the user cannot see. */
struct Config {
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
int64_t block = 0; /* noise rows a sequence, and drafts (one per row) */
int64_t rank = 0; /* markov_rank: the codebooks' width */
int64_t window = 0; /* reference's anchor-aligned n_swa (configured history + 1) */
int64_t rot = 0; /* rotary dimensions a head; 0 for all of head_dim */
int causal = 0;
int tap_norm = 0; /* `fc_norm`: one RMS gain a tap before the concatenation */
int qk_norm = 0; /* per-head q/k gains, and no output gate */
int gate = 0; /* one sigmoid gate a head on the attention output */
const char* act = "gelu"; /* the feed-forward's activation */
int64_t steps() const { return block; } /* every row predicts */
};
struct Wire {
/* ---- the context pass, one row per committed token */
rad_buf src = 0; /* [max_tok, n_taps * n_embd] the trunk's taps, read only */
rad_buf srcn = 0; /* [max_tok, n_taps * n_embd] each tap normed, same layout */
rad_buf c = 0, cn = 0; /* [max_tok, n_embd] fc output and separately normed context */
rad_buf ck = 0, ckn = 0; /* [max_tok, kv_dim] projected and optionally normed K */
rad_buf cv = 0; /* [max_tok, kv_dim] and its V */
/* ---- the query pass, `block` rows per sequence */
rad_buf x = 0; /* [qrows, n_embd] f32 the drafter's residual stream */
rad_buf delta = 0; /* [qrows, n_embd] f32 the block a projection just wrote */
rad_buf h = 0; /* [qrows, n_embd] bf16 the normed stream, and every linear's output */
rad_buf q = 0, k = 0, v = 0, qn = 0, kn = 0;
rad_buf gate = 0, gaten = 0; /* [qrows, n_head] projection and sigmoid */
rad_buf attn = 0, attng = 0; /* [qrows, q_dim] attention and gated attention */
rad_buf gate_up = 0; rad_buf ff = 0;
/* ---- the head and the walk, one row per draft position */
rad_buf dlog = 0; /* [srows, n_vocab] f32 full-vocabulary draft logits */
rad_buf best_score = 0; /* [max_seqs, ceil(n_vocab/64)] f32 partial argmax scores */
rad_buf best_token = 0; /* [max_seqs, ceil(n_vocab/64)] i32 partial argmax ids */
rad_buf tokens = 0; /* [max_seqs, steps] i32 the draft; the engine reads it by name */
};
Geom g{}; /* the drafter's geometry, not the trunk's */
Config cfg{};
Wire w{};
int first_layer = 0; /* absolute, for the KV group's layer_slot lookup */
int64_t qrows = 0, crows = 0, srows = 0;
rad_kvgroup kv = 0;
/* ---- model-scope weights */
rad_weight w_fc = 0, w_hnorm = 0, w_norm = 0;
rad_weight w_fcnorm[MAX_LAYERS] = {}; /* one row of `fc_norm` a tap */
rad_weight w_mk1 = 0, w_mk2 = 0; /* markov_w1 (pred), markov_w2 (succ) */
rad_weight w_tok = 0; /* the target's embedding table */
rad_weight w_head = 0; /* the target's output table */
/* ---- per-layer weights */
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
rad_weight w_q[MAX_LAYERS] = {}, w_k[MAX_LAYERS] = {}, w_v[MAX_LAYERS] = {}, w_o[MAX_LAYERS] = {};
rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {}, w_gate[MAX_LAYERS] = {};
rad_weight w_gu[MAX_LAYERS] = {}, w_dn[MAX_LAYERS] = {};
/* ---- the context pass */
rad_op op_tapn[MAX_LAYERS] = {}; /* one per tap, not per layer */
rad_op op_cfc = 0, op_cnorm = 0;
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
rad_op op_crope = 0, op_cstore = 0;
/* ---- the query pass. The weightless ops are declared once and issued per layer; the ones
* with weights are per layer, since a weight's prefetch interval and residency class come
* from the op that declares it. */
rad_op op_embed = 0, op_widen = 0, op_add = 0;
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}, op_outnorm = 0;
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
rad_op op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}, op_gp[MAX_LAYERS] = {};
rad_op op_op[MAX_LAYERS] = {}, op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
rad_op op_widen2 = 0, op_widen3 = 0;
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
rad_op op_sig = 0, op_gate_heads = 0, op_act = 0;
/* ---- the head and the walk */
rad_op op_dlogits = 0, op_markov = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
rad_kvgroup group, rad_weight tok_embd, const char* ck, const char* ck_head,
const Wire& wire);
/* The context pass, one row per committed token. */
void context(RadCtx* c, const RadBatch* batch) const;
/* The query pass, the head and the Markov walk, `block` rows per sequence. */
void step(RadCtx* c, const RadBatch* batch) const;
private:
int64_t q_dim() const { return g.n_head * g.head_dim; }
int64_t kv_dim() const { return g.n_head_kv * g.head_dim; }
};
/* ------------------------------------------------------------------------------ declare */
inline int DsparkBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
int base_layer, rad_kvgroup group, rad_weight tok_embd,
const char* ck, const char* ck_head, const Wire& wire) {
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
if (!ck || !ck_head || !w_tok) return DS_REFUSED("ck", "ck_head", "w_tok");
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
fprintf(stderr, "radiance: the bf16 DSpark drafter has %lld layers; this block carries at "
"most %d\n", (long long)g.n_layer, MAX_LAYERS);
return RAD_E_UNSUPPORTED;
}
if (cfg.n_taps <= 0 || cfg.n_taps > MAX_LAYERS || cfg.block < 2 || cfg.rank <= 0)
return RAD_E_INVAL;
if (cfg.qk_norm && cfg.gate) {
fprintf(stderr, "radiance: the drafter declares both per-head q/k norms and a per-head "
"output gate; no published drafter ships both, and this block would have "
"to guess which one the checkpoint trained with\n");
return RAD_E_UNSUPPORTED;
}
/* The full-vocabulary head and Markov scan are read replicated; partial-vocabulary drafting
* would need an exact distributed argmax and replicated codebook access. */
if (g.world > 1) {
fprintf(stderr, "radiance: the bf16 DSpark drafter reads the target's whole output table "
"and cannot draft at tp %d; run it at tp 1\n", g.world);
return RAD_E_UNSUPPORTED;
}
const int64_t qd = q_dim(), kvd = kv_dim(), E = g.n_embd;
crows = g.max_tok;
qrows = g.max_seqs * cfg.block;
if (qrows > g.max_tok) qrows = g.max_tok;
srows = g.max_seqs * cfg.steps(); /* every row predicts */
if (qrows <= 0 || srows <= 0 || cfg.rot < 0 || cfg.rot > g.head_dim || cfg.rot % 2)
return RAD_E_INVAL;
const int64_t rot = cfg.rot ? cfg.rot : g.head_dim;
/* One op declaration per kernel shape, shared by the layers: `rmsnorm`'s and `gemm_nt`'s
* parameters are geometry, and only the weights differ per layer. */
auto gemm = [&](int64_t rows, int64_t n, int64_t k, rad_weight wt, rad_buf x, rad_buf y) {
return rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", n),
RAD_INT("K", k), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(wt)),
{x}, {y});
};
/* ---------------------------------------------------------------- model-scope weights */
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.fc.weight"), nm.ckpt("%s.fc.weight", ck)));
w_fc = decl_w(b, nm.f("dspark.fc.weight"), RAD_BF16, {E, cfg.n_taps * E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.hidden_norm.weight"),
nm.ckpt("%s.hidden_norm.weight", ck)));
w_hnorm = decl_w(b, nm.f("dspark.hidden_norm.weight"), RAD_BF16, {E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
w_norm = decl_w(b, nm.f("dspark.norm.weight"), RAD_BF16, {E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
if (!w_fc || !w_hnorm || !w_norm) return DS_REFUSED("w_fc", "w_hnorm", "w_norm");
/* `fc_norm` is [n_taps, n_embd]: one gain row a tap, read as that tap's slice. */
if (cfg.tap_norm) {
const char* src = nm.ckpt("%s.fc_norm.weight", ck);
for (int64_t t = 0; t < cfg.n_taps; ++t) {
const int i = (int)t;
RAD_ARCH_TRY(map_rows(b, nm.f("dspark.fc_norm.%d.weight", i),
{ { src, (int)t, 1 } }));
w_fcnorm[i] = decl_w(b, nm.f("dspark.fc_norm.%d.weight", i), RAD_BF16, {E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
if (!w_fcnorm[i]) return DS_REFUSED("w_fcnorm[i]");
}
}
/* The Markov codebooks, bf16, replicated over the whole vocabulary: both are [vocab, rank], so
* `w2 @ w1[prev]` is `<w1[prev], w2[token]>`. RAD_ACCESS_VOCAB: each walk position reads one
* predecessor row and scans every successor row. */
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w1"),
nm.ckpt("%s.markov_head.markov_w1.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w2"),
nm.ckpt("%s.markov_head.markov_w2.weight", ck)));
w_mk1 = decl_w(b, nm.f("dspark.markov_w1"), RAD_BF16, {g.n_vocab_all, cfg.rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
w_mk2 = decl_w(b, nm.f("dspark.markov_w2"), RAD_BF16, {g.n_vocab_all, cfg.rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
if (!w_mk1 || !w_mk2) return DS_REFUSED("w_mk1", "w_mk2");
/* The target's output table under the drafter's own name: one stored tensor, two arch weights,
* as rad_block_dspark.h does for its 2-bit copy. bf16 and replicated here, since the drafter
* reads it as the head its full-vocabulary walk scores (see NOT DONE for sharding). */
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.head.weight"), ck_head));
w_head = decl_w(b, nm.f("dspark.head.weight"), RAD_BF16, {g.n_vocab_all, E},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
if (!w_head) return DS_REFUSED("w_head");
/* ---------------------------------------------------------------- per-layer weights
*
* One name map and one declaration a weight, spelled out: the list is the readable form of
* which checkpoint tensor feeds which matmul, and a drafter has few enough of them that a
* table would only hide it. */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
const RadWeightGroup grp = grp_layer(first_layer + i);
/* A norm gain: f32, read whole, never sharded. */
auto norm_w = [&](rad_weight* out, const char* suffix, const char* from,
std::initializer_list<int64_t> shape) -> int {
const char* name = nm.f("dspark.blk.%d.%s", i, suffix);
RAD_ARCH_TRY(map_copy(b, name, nm.ckpt("%s.layers.%d.%s", ck, i, from)));
*out = decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
return *out ? RAD_OK : RAD_E_INVAL;
};
/* A linear: bf16. More than one source is a concatenation, whose row parts say where each
* piece begins (RadWeightDecl::row_parts), so `act_mul` can read [gate | up] as one
* weight. */
auto lin_w = [&](rad_weight* out, const char* suffix,
std::initializer_list<const char*> srcs,
std::initializer_list<int64_t> shape,
std::initializer_list<int64_t> parts = {}) -> int {
const char* name = nm.f("dspark.blk.%d.%s", i, suffix);
if (srcs.size() > 1) RAD_ARCH_TRY(map_concat(b, name, srcs));
else RAD_ARCH_TRY(map_copy(b, name, *srcs.begin()));
*out = decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp, 0,
parts);
return *out ? RAD_OK : RAD_E_INVAL;
};
#define SRC(path) nm.ckpt("%s.layers.%d." path, ck, i)
RAD_ARCH_TRY(norm_w(&w_anorm[i], "attn_norm.weight", "input_layernorm.weight", {E}));
RAD_ARCH_TRY(norm_w(&w_fnorm[i], "ffn_norm.weight", "post_attention_layernorm.weight", {E}));
RAD_ARCH_TRY(lin_w(&w_q[i], "attn_q", { SRC("self_attn.q_proj.weight") }, {qd, E}));
RAD_ARCH_TRY(lin_w(&w_k[i], "attn_k", { SRC("self_attn.k_proj.weight") }, {kvd, E}));
RAD_ARCH_TRY(lin_w(&w_v[i], "attn_v", { SRC("self_attn.v_proj.weight") }, {kvd, E}));
RAD_ARCH_TRY(lin_w(&w_o[i], "attn_output", { SRC("self_attn.o_proj.weight") }, {E, qd}));
RAD_ARCH_TRY(lin_w(&w_gu[i], "ffn_gate_up",
{ SRC("mlp.gate_proj.weight"), SRC("mlp.up_proj.weight") },
{2 * g.n_ff, E}, { g.n_ff, g.n_ff }));
RAD_ARCH_TRY(lin_w(&w_dn[i], "ffn_down", { SRC("mlp.down_proj.weight") },
{E, g.n_ff}));
if (cfg.gate)
RAD_ARCH_TRY(lin_w(&w_gate[i], "attn_gate", { SRC("self_attn.g_proj.weight") },
{g.n_head, E}));
if (cfg.qk_norm) {
RAD_ARCH_TRY(norm_w(&w_qn[i], "attn_q_norm.weight", "self_attn.q_norm.weight",
{g.head_dim}));
RAD_ARCH_TRY(norm_w(&w_kn[i], "attn_k_norm.weight", "self_attn.k_norm.weight",
{g.head_dim}));
}
#undef SRC
}
/* Non-causal: every query row sees its whole block and the context the trunk committed
* (`causal` comes from `draft.is_causal`). Declared before both kv_stores, which read the
* resolved `block_size` back with rad_kv_block_size(); before it, that returns zero. */
op_attn = rw(b, RAD_OP(b, cfg.window > 0 ? "attn_paged_anchor_window" : "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
RAD_INT("window", cfg.window), RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{cfg.qk_norm ? w.qn : w.q}, {w.attn});
if (!op_attn) return DS_REFUSED("op_attn");
/* ---------------------------------------------------------------- the context pass
*
* One row per committed token, run once per trunk step: the taps become the drafter's own K
* and V. Nothing here is per query row, so its cost follows the trunk's token count, not the
* block's. */
for (int64_t t = 0; t < cfg.n_taps; ++t) {
const int i = (int)t;
op_tapn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_fcnorm[i])),
{w.src}, {w.srcn});
if (!op_tapn[i]) return DS_REFUSED("op_tapn[i]");
}
op_cfc = gemm(crows, E, cfg.n_taps * E, w_fc, w.srcn, w.c);
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_hnorm)),
{w.c}, {w.cn});
if (!op_cfc || !op_cnorm) return DS_REFUSED("op_cfc", "op_cnorm");
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
/* One op per weight: an op's declared weight list gives each weight its prefetch interval
* and residency class. */
op_ck[i] = gemm(crows, kvd, E, w_k[i], w.cn, w.ck);
op_cv[i] = gemm(crows, kvd, E, w_v[i], w.cn, w.cv);
if (!op_ck[i] || !op_cv[i]) return DS_REFUSED("op_ck[i]", "op_cv[i]");
if (cfg.qk_norm) {
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_kn[i])),
{w.ck}, {w.ckn});
if (!op_cknorm[i]) return DS_REFUSED("op_cknorm[i]");
}
}
/* K-only rope: `rope` rotates the first n_head + n_head_kv heads, so a K-only tensor is
* n_head = n_head_kv, n_head_kv = 0. Weightless, so one op serves every layer. Each context
* row is rotated by its own absolute position, as the reference's single concatenated rope
* does. */
op_crope = rw(b, decl_rope(b, g, crows, g.head_dim, g.n_head_kv, 0, rot, "neox"),
{cfg.qk_norm ? w.ckn : w.ck}, {cfg.qk_norm ? w.ckn : w.ck});
op_cstore = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{cfg.qk_norm ? w.ckn : w.ck, w.cv}, {});
if (!op_crope || !op_cstore) return DS_REFUSED("op_crope", "op_cstore");
/* ---------------------------------------------------------------- the query pass
*
* `block` rows per sequence, through the drafter's layers. The residual stream is f32 and the
* linears read bf16, exactly as the trunk keeps them: `rmsnorm` reads the stream and writes the
* activations, `cast` widens a projection's output, and `add` keeps the sum in f32. */
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", E),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w_tok)),
{}, {w.h});
op_widen = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
RAD_NOWEIGHTS),
{w.h}, {w.x});
/* One widen and one add serve both residual sites a layer: same shapes, same buffers. */
op_widen2 = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
RAD_NOWEIGHTS),
{w.h}, {w.delta});
op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{w.x, w.delta}, {w.x});
if (!op_embed || !op_widen || !op_widen2 || !op_add)
return DS_REFUSED("op_embed", "op_widen", "op_widen2", "op_add");
/* Invariant: the norms are declared where step() issues them. Declaration order is the buffer
* planner's liveness (core/build/rad_bufplan.cpp), and the stream `x` lives over the ops that
* touch it: each layer's two norms in the loop, the final one after everything the layers
* issue. Declared up front, the stream's lifetime would end before the layers and the planner
* could overlay a feed-forward temporary on it. */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_anorm[i])),
{w.x}, {w.h});
op_qp[i] = gemm(qrows, qd, E, w_q[i], w.h, w.q);
op_kp[i] = gemm(qrows, kvd, E, w_k[i], w.h, w.k);
op_vp[i] = gemm(qrows, kvd, E, w_v[i], w.h, w.v);
op_op[i] = gemm(qrows, E, qd, w_o[i], cfg.gate ? w.attng : w.attn, w.h);
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_fnorm[i])),
{w.x}, {w.h});
op_gu[i] = gemm(qrows, 2 * g.n_ff, E, w_gu[i], w.h, w.gate_up);
op_dn[i] = gemm(qrows, E, g.n_ff, w_dn[i], w.ff, w.h);
if (!op_anorm[i] || !op_qp[i] || !op_kp[i] || !op_vp[i] || !op_op[i] || !op_fnorm[i] ||
!op_gu[i] || !op_dn[i])
return RAD_E_INVAL;
if (cfg.qk_norm) {
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head),
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_qn[i])),
{w.q}, {w.qn});
op_kn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv),
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_kn[i])),
{w.k}, {w.kn});
if (!op_qn[i] || !op_kn[i]) return DS_REFUSED("op_qn[i]", "op_kn[i]");
}
if (cfg.gate) {
op_gp[i] = gemm(qrows, g.n_head, E, w_gate[i], w.h, w.gate);
if (!op_gp[i]) return DS_REFUSED("op_gp[i]");
}
}
op_qrope = rw(b, decl_rope(b, g, qrows, g.head_dim, g.n_head, 0, rot, "neox"),
{cfg.qk_norm ? w.qn : w.q}, {cfg.qk_norm ? w.qn : w.q});
op_krope = rw(b, decl_rope(b, g, qrows, g.head_dim, g.n_head_kv, 0, rot, "neox"),
{cfg.qk_norm ? w.kn : w.k}, {cfg.qk_norm ? w.kn : w.k});
op_store = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{cfg.qk_norm ? w.kn : w.k, w.v}, {});
/* The gate the trunk uses too: one sigmoid a head, then one scale a head's whole row. */
if (cfg.gate) {
op_sig = rw(b, RAD_OP(b, "sigmoid",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_head),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{w.gate}, {w.gaten});
op_gate_heads = rw(b, RAD_OP(b, "scale_rows",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head),
RAD_INT("n", g.head_dim), RAD_STR("act", "none"),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{w.attn, w.gaten}, {w.attng});
if (!op_sig || !op_gate_heads) return DS_REFUSED("op_sig", "op_gate_heads");
}
/* `act_mul` with the activation the drafter was trained with: exact-erf gelu for the Spark
* drafts (`hidden_activation: gelu`), silu for a Qwen3-shaped one. `gelu_mul` is the tanh
* approximation and is not what the reference runs. */
op_act = rw(b, RAD_OP(b, "act_mul",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_STR("act", cfg.act), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{w.gate_up}, {w.ff});
op_outnorm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h});
if (!op_qrope || !op_krope || !op_store || !op_act || !op_outnorm)
return DS_REFUSED("op_qrope", "op_krope", "op_store", "op_act", "op_outnorm");
/* ---------------------------------------------------------------- the head and full-vocabulary walk
*
* Every row predicts, so the head scores all `steps` rows, anchor included. The row order is
* sequence-major, which is the selector's [sequence, position, vocabulary] contract. The
* greedy Markov op scans all vocabulary entries at every position and feeds each winning id
* into the next position's bigram bias.
*/
op_dlogits = rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_head)),
{w.h}, {w.dlog});
op_markov = rw(b, RAD_OP(b, "dflash_markov_greedy_f32",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs),
RAD_INT("steps", cfg.steps()), RAD_INT("rank", cfg.rank),
RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("anchor_stride", cfg.block),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_mk1, w_mk2)),
{w.dlog}, {w.best_score, w.best_token, w.tokens});
if (!op_dlogits || !op_markov) return DS_REFUSED("op_dlogits", "op_markov");
return RAD_OK;
}
/* ------------------------------------------------------------------------------ the context pass */
inline void DsparkBF16::context(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (T <= 0) return;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int64_t E = g.n_embd;
/* Each tap's slice of the residual the trunk just tapped, normed with its own gain into the
* same slice layout of one row-per-token buffer. */
for (int64_t t = 0; t < cfg.n_taps; ++t) {
const int i = (int)t;
if (!cfg.tap_norm) continue;
RAD_ISSUE_N(c, op_tapn[i], T, bcol(w.src, t * E, E, T), RAD_W(w_fcnorm[i]),
bcol(w.srcn, t * E, E, T));
}
RAD_ISSUE_N(c, op_cfc, T, cfg.tap_norm ? brows(w.srcn, T) : brows(w.src, T), RAD_W(w_fc),
brows(w.c, T));
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.cn, T));
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cn, T), RAD_W(w_k[i]), brows(w.ck, T));
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cn, T), RAD_W(w_v[i]), brows(w.cv, T));
if (cfg.qk_norm)
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]),
brows(w.ckn, T));
RAD_ISSUE_N(c, op_crope, T, brows(cfg.qk_norm ? w.ckn : w.ck, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_cstore, T, brows(cfg.qk_norm ? w.ckn : w.ck, T), brows(w.cv, T),
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
}
}
/* ------------------------------------------------------------------------------ the query pass */
inline void DsparkBF16::step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (T <= 0) return;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int32_t* used = kvb ? kvb->seqused : nullptr;
const RadOperand pos = praw(batch->positions, RAD_I32, T);
/* The block the core staged: the token the sampler just chose, then the mask token in every
* unfilled slot. */
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.h, T));
RAD_ISSUE_N(c, op_widen, T, brows(w.h, T), brows(w.x, T));
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h, T), RAD_W(w_q[i]), brows(w.q, T));
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h, T), RAD_W(w_k[i]), brows(w.k, T));
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h, T), RAD_W(w_v[i]), brows(w.v, T));
if (cfg.qk_norm) {
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.qn, T));
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]),
brows(w.kn, T));
}
RAD_ISSUE_N(c, op_qrope, T, brows(cfg.qk_norm ? w.qn : w.q, T), pos);
RAD_ISSUE_N(c, op_krope, T, brows(cfg.qk_norm ? w.kn : w.k, T), pos);
/* The block's own K and V go into the cache past `seqused`, which is how every row of the
* block attends to every other; the next context pass overwrites them, which is the
* reference's `crop(start)`. */
RAD_ISSUE_N(c, op_store, T, brows(cfg.qk_norm ? w.kn : w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
kv_cache(kv, first_layer + i));
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(cfg.qk_norm ? w.qn : w.q, T), kv_cache(kv, first_layer + i),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn, T));
if (cfg.gate) {
/* One gate a head, applied to that head's whole row of the attention output, before
* o_proj. View [rows, heads * dim] and [rows, heads] as one row a head. */
RAD_ISSUE_N(c, op_gp[i], T, brows(w.h, T), RAD_W(w_gate[i]), brows(w.gate, T));
RAD_ISSUE_N(c, op_sig, T, brows(w.gate, T), brows(w.gaten, T));
const RadOperand heads = RAD_P_T2(rad_buf_ptr(c, w.attn), RAD_BF16, T * g.n_head,
g.head_dim);
const RadOperand gates = RAD_P_T2(rad_buf_ptr(c, w.gaten), RAD_BF16, T * g.n_head, 1);
const RadOperand gated = RAD_P_T2(rad_buf_ptr(c, w.attng), RAD_BF16, T * g.n_head,
g.head_dim);
RAD_ISSUE_N(c, op_gate_heads, T * g.n_head, heads, gates, RAD_NONE, gated);
}
RAD_ISSUE_N(c, op_op[i], T, brows(cfg.gate ? w.attng : w.attn, T), RAD_W(w_o[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_widen2, T, brows(w.h, T), brows(w.delta, T));
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.delta, T), brows(w.x, T));
RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h, T), RAD_W(w_gu[i]), brows(w.gate_up, T));
RAD_ISSUE_N(c, op_act, T, bcol(w.gate_up, 0, g.n_ff, T),
bcol(w.gate_up, g.n_ff, g.n_ff, T), brows(w.ff, T));
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ff, T), RAD_W(w_dn[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_widen2, T, brows(w.h, T), brows(w.delta, T));
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.delta, T), brows(w.x, T));
}
RAD_ISSUE_N(c, op_outnorm, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
/* The predicting rows, named by the scheduler through `out_ids`. */
const int64_t S = batch->n_out;
if (S <= 0) return;
RAD_ISSUE_N(c, op_dlogits, S, brows(w.h, S), RAD_W(w_head), brows(w.dlog, S));
RAD_ISSUE_N(c, op_markov, batch->n_seq, brows(w.dlog, S),
praw(batch->token_ids, RAD_I32, T), RAD_W(w_mk1), RAD_W(w_mk2),
brows(w.best_score, batch->n_seq), brows(w.best_token, batch->n_seq),
brows(w.tokens, batch->n_seq));
}
/* ================================================================== the trunk's side of it
*
* The taps, and one call a target plugin makes to put a drafter on. Both live here because both
* are the drafter's contract with the trunk: which residual streams it reads, where its blocks
* live, and how deep a proposal it makes. */
/* The residual streams a drafter reads, captured as the trunk passes them. */
struct DsparkTaps {
enum { MAX_TAPS = DsparkBF16::MAX_LAYERS };
int n = 0;
int layer[MAX_TAPS] = {}; /* the trunk layer whose OUTPUT is tapped */
rad_buf src = 0; /* [rows, n * n_embd] f32, one column slice a tap */
rad_op op = 0; /* the residual stream, copied into that slice */
/* Read `draft.target_layer_ids`, which names the layers whose output is tapped. Zero taps when
* the container carries no drafter, or one that reads no trunk stream. Out-of-range ids are
* dropped, not clamped: a drafter naming a layer this model lacks belongs to another target. */
int read(const RadModelMeta* meta, int64_t n_layer) {
n = 0;
const char* ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr);
if (!ids) ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr);
if (!ids) ids = rad_meta_gets(meta, "draft.gguf_target_layers", nullptr);
n = parse_layer_ids(ids, n_layer, layer, MAX_TAPS);
return n;
}
/* The copy that saves a tap. A drafter reads the trunk's own residual stream, which is f32
* here and stays f32: the widening the fp8 graphs do is theirs, not this one's. */
int declare(RadBuilder* b, Names& nm, const Geom& g, int64_t rows, rad_buf residual) {
if (n <= 0) return RAD_OK;
src = decl_b(b, nm.f("draft_src"), RAD_F32, {rows, (int64_t)n * g.n_embd});
if (!src) return DS_REFUSED("src");
/* Declared over the trunk's own residual buffer: the op's operand pair is the stream and a
* tap's slice, and every issue site passes the slice it is writing. */
op = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
RAD_STR("from", "f32"), RAD_STR("to", "f32")),
RAD_NOWEIGHTS),
{residual}, {src});
return op ? RAD_OK : RAD_E_INVAL;
}
/* The tap that follows trunk layer `l`, if any. Issued on prefill and decode alike: the
* drafter conditions on every committed token's residual stream. */
void step(RadCtx* c, rad_buf residual, int64_t rows, int64_t l, int64_t n_embd) const {
if (!op) return;
for (int t = 0; t < n; ++t)
if (layer[t] == l)
RAD_ISSUE(c, op, brows(residual, rows),
bcol(src, (int64_t)t * n_embd, n_embd, rows));
}
};
/* Put a DSpark drafter on a trunk: its config from the container's `draft.` keys, its own KV
* group, its graph, and the drafter declaration the core drives. `base_layer` is the absolute
* layer its first block takes, one past the trunk's last.
*
* Nothing is defaulted quietly. A `draft.` key that describes a drafter this file does not
* implement is refused by name, because a silently ignored gate, window or block length only moves
* acceptance -- the one number a user cannot see in the output.
*
* The plugin calls it last, after its own head and logits: a drafter's passes run after the whole
* trunk, and the buffer planner lays an op's lifetimes out in declaration order, so declaring it
* earlier would let a trunk temporary land on the stream the drafter is still reading. */
inline int declare_dspark(DsparkBF16* ds, DsparkBF16::Wire* w, rad_kvgroup* kv, RadBuilder* b,
Names& nm, const RadModelMeta* meta, const RadBuildCtx* ctx,
const Geom& target, const DsparkTaps& taps, int base_layer,
rad_weight tok_embd, const char* ck_head) {
Geom dg{};
RAD_ARCH_TRY(drafter_geom(dg, target, meta, "DSpark"));
/* The width the drafter concatenates and projects is the trunk's, and `drafter_geom` keeps the
* target's -- so a draft that disagrees is a draft for another model, and its `fc` would be
* read at a shape it was not trained at. */
const int64_t want_embd = rad_meta_geti(meta, "draft.hidden_size",
rad_meta_geti(meta, "draft.dflash_config.hidden_size",
dg.n_embd));
if (want_embd != dg.n_embd) {
fprintf(stderr, "radiance: the drafter reads a %lld-wide trunk and this target is %lld "
"wide; they are not the same model\n", (long long)want_embd,
(long long)dg.n_embd);
return RAD_E_UNSUPPORTED;
}
DsparkBF16::Config c{};
c.n_taps = taps.n;
c.rank = rad_meta_geti(meta, "draft.markov_rank", 0);
c.causal = rad_meta_geti(meta, "draft.is_causal", 0) ? 1 : 0;
c.tap_norm = rad_meta_geti(meta, "draft.fc_norm", 0) ? 1 : 0;
c.qk_norm = rad_meta_geti(meta, "draft.qk_norm", 0) ? 1 : 0;
c.gate = rad_meta_geti(meta, "draft.headwise_attn_output_gate", 0) ? 1 : 0;
const char* act = rad_meta_gets(meta, "draft.hidden_act", "silu");
c.act = (!std::strcmp(act, "gelu") || !std::strcmp(act, "none")) ? "gelu"
: (!std::strcmp(act, "silu")) ? "silu" : nullptr;
if (!c.act) {
fprintf(stderr, "radiance: the drafter's feed-forward is '%s'; this block runs exact-erf "
"gelu (what the Spark drafts train with) or silu, and the two are not the "
"same function\n", act);
return RAD_E_UNSUPPORTED;
}
const char* gate_mode = rad_meta_gets(meta, "draft.gate_attn_act_mode", "sigmoid");
if (c.gate && std::strcmp(gate_mode, "sigmoid")) {
fprintf(stderr, "radiance: the drafter gates its attention output with '%s'; this block "
"applies a sigmoid\n", gate_mode);
return RAD_E_UNSUPPORTED;
}
/* Every row predicts, the anchor included. Without it a block row's worth of proposals is
* missing and the head reads rows the drafter never filled. */
if (!rad_meta_geti(meta, "draft.sample_from_anchor", 1)) {
fprintf(stderr, "radiance: the drafter declares sample_from_anchor false, whose bonus "
"anchor slot this block has no rows for\n");
return RAD_E_UNSUPPORTED;
}
/* The reference applies the bigram bias to the full vocabulary before each greedy choice. */
if (c.rank <= 0 || c.rank % 32 || c.rank > 512) {
fprintf(stderr, "radiance: the drafter's Markov head has rank %lld; the walk that applies "
"the bigram bias takes a multiple of 32 up to 512\n", (long long)c.rank);
return RAD_E_UNSUPPORTED;
}
/* The block is both the number of noise rows and the number of drafts: every row, the anchor
* included, predicts the token after it, so the depth is `block_size` rather than the
* `block_size - 1` a DFlash2 container's is. A block-diffusion drafter is trained for one
* block length and has no partial block, so any other depth is refused. */
const int64_t trained = rad_meta_geti(meta, "draft.block_size", 0);
if (trained < 2) {
fprintf(stderr, "radiance: this drafter declares no draft.block_size; the number of masked "
"positions it denoises is not a number this engine may choose.\n");
return RAD_E_FORMAT;
}
if ((long long)ctx->max_spec != trained) {
fprintf(stderr, "radiance: the drafter was trained at block_size %lld, which is %lld draft "
"tokens, and this serve asks for %d. A block-diffusion drafter denoises a "
"fixed number of mask positions; run it at %lld.\n",
(long long)trained, (long long)trained, ctx->max_spec, (long long)trained);
return RAD_E_UNSUPPORTED;
}
c.block = trained;
/* The reference gives every row of the block the anchor's history. `window` is the configured
* number of preceding positions; llama.cpp sets n_swa to window + 1 and masks when
* anchor - key >= n_swa. Keep that exact width in attention, the KV group and scheduler. */
int64_t window = 0;
if (rad_meta_geti(meta, "draft.use_sliding_window", 0))
window = rad_meta_geti(meta, "draft.sliding_window", 0);
if (window < 0 || (window && window < c.block)) {
fprintf(stderr, "radiance: the drafter's %lld-token window does not cover the %lld-token "
"block it denoises\n", (long long)window, (long long)c.block);
return RAD_E_UNSUPPORTED;
}
if (window > 0 && window == INT64_MAX) return RAD_E_INVAL;
c.window = window > 0 ? window + 1 : 0; /* llama.cpp dflash: n_swa += 1 */
const double prf = rad_meta_getf(meta, "draft.partial_rotary_factor",
rad_meta_getf(meta,
"draft.rope_parameters.partial_rotary_factor", 1.0));
const double rot = (double)dg.head_dim * prf;
if (!(prf > 0.0) && prf != 0.0) {
fprintf(stderr, "radiance: the drafter's partial_rotary_factor is %g\n", prf);
return RAD_E_INVAL;
}
if (std::floor(rot) != rot || (int64_t)rot % 2 || rot > (double)dg.head_dim) {
fprintf(stderr, "radiance: the drafter rotates %g of %lld head dimensions\n", rot,
(long long)dg.head_dim);
return RAD_E_INVAL;
}
c.rot = (int64_t)rot ? (int64_t)rot : dg.head_dim;
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, c.window, base_layer, kv));
/* Activations: one row per committed token for the context pass, one row per block position
* for the query pass. Both are small; the drafter's cost is its weights. */
const int64_t qd = dg.n_head * dg.head_dim, kvd = dg.n_head_kv * dg.head_dim;
int64_t qr = dg.max_seqs * c.block;
if (qr > dg.max_tok) qr = dg.max_tok;
const int64_t sr = dg.max_seqs * c.steps();
DsparkBF16::Wire& dw = *w;
dw.src = taps.src;
dw.srcn = decl_b(b, nm.f("ds_srcn"), RAD_BF16, {dg.max_tok, c.n_taps * dg.n_embd});
dw.c = decl_b(b, nm.f("ds_c"), RAD_BF16, {dg.max_tok, dg.n_embd});
dw.cn = decl_b(b, nm.f("ds_cn"), RAD_BF16, {dg.max_tok, dg.n_embd});
dw.ck = decl_b(b, nm.f("ds_ck"), RAD_BF16, {dg.max_tok, kvd});
dw.cv = decl_b(b, nm.f("ds_cv"), RAD_BF16, {dg.max_tok, kvd});
if (c.qk_norm) dw.ckn = decl_b(b, nm.f("ds_ckn"), RAD_BF16, {dg.max_tok, kvd});
dw.x = decl_b(b, nm.f("ds_x"), RAD_F32, {qr, dg.n_embd});
dw.delta = decl_b(b, nm.f("ds_delta"), RAD_F32, {qr, dg.n_embd});
dw.h = decl_b(b, nm.f("ds_h"), RAD_BF16, {qr, dg.n_embd});
dw.q = decl_b(b, nm.f("ds_q"), RAD_BF16, {qr, qd});
dw.k = decl_b(b, nm.f("ds_k"), RAD_BF16, {qr, kvd});
dw.v = decl_b(b, nm.f("ds_v"), RAD_BF16, {qr, kvd});
if (c.qk_norm) {
dw.qn = decl_b(b, nm.f("ds_qn"), RAD_BF16, {qr, qd});
dw.kn = decl_b(b, nm.f("ds_kn"), RAD_BF16, {qr, kvd});
}
dw.gate = decl_b(b, nm.f("ds_gate"), RAD_BF16, {qr, dg.n_head});
dw.attn = decl_b(b, nm.f("ds_attn"), RAD_BF16, {qr, qd});
if (c.gate) {
dw.gaten = decl_b(b, nm.f("ds_gaten"), RAD_BF16, {qr, dg.n_head});
dw.attng = decl_b(b, nm.f("ds_attng"), RAD_BF16, {qr, qd});
}
dw.gate_up = decl_b(b, nm.f("ds_gate_up"), RAD_BF16, {qr, 2 * dg.n_ff});
dw.ff = decl_b(b, nm.f("ds_ff"), RAD_BF16, {qr, dg.n_ff});
dw.dlog = decl_b(b, nm.f("ds_dlog"), RAD_F32, {sr, dg.n_vocab});
const int64_t n_markov_tiles = (dg.n_vocab_all + 63) / 64;
dw.best_score = decl_b(b, nm.f("ds_markov_score"), RAD_F32,
{dg.max_seqs, n_markov_tiles});
dw.best_token = decl_b(b, nm.f("ds_markov_token"), RAD_I32,
{dg.max_seqs, n_markov_tiles});
/* The proposal buffer (RadDrafterDecl::proposal): a block pass proposes through the drafter's
* own walk, never through the sampler's token buffer. */
dw.tokens = decl_b(b, nm.f("ds_tokens"), RAD_I32, {dg.max_seqs, c.steps()});
if (!dw.srcn || !dw.c || !dw.cn || !dw.ck || !dw.cv ||
(c.qk_norm && (!dw.ckn || !dw.qn || !dw.kn)) ||
(c.gate && (!dw.gaten || !dw.attng)) || !dw.x || !dw.delta || !dw.h || !dw.q || !dw.k ||
!dw.v || !dw.gate || !dw.attn || !dw.gate_up || !dw.ff || !dw.dlog ||
!dw.best_score || !dw.best_token || !dw.tokens)
return RAD_E_INVAL;
RAD_ARCH_TRY(ds->declare(b, nm, dg, c, base_layer, *kv, tok_embd, "draft", ck_head, dw));
RadDrafterDecl drf{};
drf.name = "dspark";
drf.kind = RAD_DRAFT_BLOCK;
drf.depth = ctx->max_spec;
drf.block = c.block;
drf.proposal = dw.tokens;
drf.proposal_pitch = c.steps();
drf.window = c.window;
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.mask_token_id", -1);
if (drf.mask_token < 0)
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", -1);
if (drf.mask_token < 0) {
fprintf(stderr, "radiance: this drafter declares no mask_token_id, which every unfilled "
"block position embeds\n");
return RAD_E_FORMAT;
}
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
rad_note(b, "DSpark drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv x %lld, "
"ffn %lld, %s attention with a %lld-token anchor-aligned window (%lld configured "
"history + 1), %lld of %lld rotary dimensions, %s, %s a head, %d trunk tap(s); one "
"forward over %lld noise row(s), the anchor included, proposes %lld tokens",
(long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1,
(long long)dg.n_head, (long long)dg.n_head_kv, (long long)dg.head_dim,
(long long)dg.n_ff, c.causal ? "causal" : "non-causal", (long long)c.window,
(long long)window, (long long)c.rot, (long long)dg.head_dim, c.act,
c.gate ? "sigmoid gate" : "no gate", (int)c.n_taps, (long long)c.block,
(long long)c.steps());
rad_note(b, "the rank-%lld Markov bigram head greedily scans all %lld vocabulary tokens at "
"each draft position; confidence is not applied to logits%s",
(long long)c.rank, (long long)dg.n_vocab_all,
rad_meta_geti(meta, "draft.has_confidence_head", 0)
? " (its reference role is adaptive depth, which this fixed-depth graph does not use)"
: "");
return RAD_OK;
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_DSPARK_BF16_H */
+9 -5
View File
@@ -336,12 +336,14 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_WEIGHTS(w_a_log, w_dt_bias, w_out_norm)), RAD_WEIGHTS(w_a_log, w_dt_bias, w_out_norm)),
{w.q, w.k, w.v, w.ab, w.in.x}, {w.o.x}); {w.q, w.k, w.v, w.ab, w.in.x}, {w.o.x});
/* The epilogue's codes for an fp8 or int8 out-projection (int8 when ActFP8::q8_fed; the codes /* The epilogue's codes for an fp8 or int8 out-projection (int8 when ActFP8::q8_fed; the codes
* dtype picks the quantiser). A bf16 out-projection reads only `o.x` and these stay absent. */ * dtype picks the quantiser). A bf16 out-projection reads only `o.x` and these stay absent.
* Rotated int8 codes (ActFP8::q8_rot) only the conv fold writes (gdn_conv_recurrent_update_had);
* rows this update serves are quantised by q_o. */
if (g.plain_norm) { if (g.plain_norm) {
RAD_ARCH_TRY(out.probe(b, nm, g, nm.f("blk.%d.ssm_out", l), { s.out })); RAD_ARCH_TRY(out.probe(b, nm, g, nm.f("blk.%d.ssm_out", l), { s.out }));
o_plain = out.codes_free && out.reads_x; o_plain = out.codes_free && out.reads_x;
} }
if (op_recur && w.o.cq() && !o_plain) { if (op_recur && w.o.cq() && !o_plain && !w.o.q8_rot) {
const rad_buf oq[2] = { w.o.cq(), w.o.cs() }; const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
RAD_ARCH_TRY(rad_op_writes(b, op_recur, oq, 2)); RAD_ARCH_TRY(rad_op_writes(b, op_recur, oq, 2));
} }
@@ -349,7 +351,7 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
* tokens per sequence. Optional (no RAD_ARCH_TRY): without it the pair runs. */ * tokens per sequence. Optional (no RAD_ARCH_TRY): without it the pair runs. */
{ {
const int64_t hi = g.max_tok < 8 ? g.max_tok : 8; const int64_t hi = g.max_tok < 8 ? g.max_tok : 8;
op_cr = rw(b, RAD_OP(b, "gdn_conv_recurrent_update", op_cr = rw(b, RAD_OP(b, w.o.q8_rot ? "gdn_conv_recurrent_update_had" : "gdn_conv_recurrent_update",
RAD_PARAMS(RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k), RAD_PARAMS(RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k),
RAD_INT("head_v", cfg.head_v), RAD_INT("head_v", cfg.head_v),
RAD_INT("conv_width", cfg.conv_width), RAD_INT("conv_width", cfg.conv_width),
@@ -530,8 +532,10 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D), praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
praw(batch->cu_seqlens, RAD_I32, D + 1), praw(batch->cu_seqlens, RAD_I32, D + 1),
bcol(w.in.x, conv_dim, v_dim, DT), RAD_W(w_out_norm), brows(w.o.x, DT), bcol(w.in.x, conv_dim, v_dim, DT), RAD_W(w_out_norm), brows(w.o.x, DT),
w.o.cq() && !o_plain ? brows(w.o.cq(), DT) : RAD_NONE, w.o.cq() && !o_plain && !w.o.q8_rot ? brows(w.o.cq(), DT) : RAD_NONE,
w.o.cq() && !o_plain ? brows(w.o.cs(), DT) : RAD_NONE); w.o.cq() && !o_plain && !w.o.q8_rot ? brows(w.o.cs(), DT) : RAD_NONE);
/* Rotated codes come only from the fold; here the decode rows take the quantiser. */
if (w.o.q8_rot && !o_plain) q_o.step(c, T, 0, DT);
} }
/* The output a piece at a time where the caller takes the all-reduce that way (ArPieces): the /* The output a piece at a time where the caller takes the all-reduce that way (ArPieces): the
+263
View File
@@ -0,0 +1,263 @@
/* rad_block_gemma4_unified.h -- the media embedders of Gemma 4 12B ("unified", transformers'
* Gemma4UnifiedVisionEmbedder and the audio Gemma4UnifiedMultimodalEmbedder), served by gemma4_bf16.
* Neither has an encoder: the language model sees each patch or audio frame after a few norms and
* linears.
*
* image: a patch is 48 x 48 x 3 (3 x 3 of the processor's 16-pixel patches), staged by the core's
* Gemma 4 processor as u / 255 in bf16, (y, x, channel); a LayerNorm over the patch, a linear with
* a bias, a LayerNorm, plus a learned row for the patch's column and one for its row (the
* checkpoint's [npos, 2, width] table, read as its two taps of dimension 1), a LayerNorm, then the
* multimodal embedder: an RMS norm with no gain and a width -> n_embd linear. The LayerNorms are
* nn.LayerNorm's default eps 1e-5, which no config states. One patch is one row.
* audio: a frame is 640 samples at 16 kHz as they are, the last zero-padded, in bf16; an RMS norm
* with no gain and a 640 -> n_embd linear. One frame is one row.
*
* Their rows replace the placeholders' embeddings unscaled, as the vision tower's do. Every rank
* runs them whole (RAD_SHARD_NONE). */
#ifndef RAD_BLOCK_GEMMA4_UNIFIED_H
#define RAD_BLOCK_GEMMA4_UNIFIED_H
#include "rad_arch.h"
#include <cstdio>
#include <cstring>
namespace rad {
namespace arch {
struct Gemma4UnifiedVision {
bool on = false;
/* The language model reads a picture's rows both ways (RadEncoderDecl::bidirectional); the
* plugin sets it before declare. */
bool bidirectional = false;
int64_t P = 0, width = 0, patch_dim = 0, npos = 0, n_embd = 0;
rad_weight w_ln1 = 0, w_ln1b = 0, w_in = 0, w_inb = 0, w_ln2 = 0, w_ln2b = 0, w_px = 0, w_py = 0;
rad_weight w_pn = 0, w_pnb = 0, w_proj = 0;
rad_op op_ln1 = 0, op_in = 0, op_ln2 = 0, op_px = 0, op_py = 0, op_padd = 0, op_add = 0;
rad_op op_pn = 0, op_norm = 0, op_out = 0;
rad_buf b_n = 0, b_x = 0, b_h = 0, b_px = 0, b_py = 0, b_out = 0;
static bool present(const RadModelMeta* m) {
const char* t = rad_meta_gets(m, "vision_config.model_type", "");
return t && !std::strcmp(t, "gemma4_unified_vision");
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, const char* who) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
width = rad_meta_geti(m, "vision_config.mm_embed_dim", 0);
npos = rad_meta_geti(m, "vision_config.mm_posemb_size", 0);
const int64_t side = rad_meta_geti(m, "vision_config.model_patch_size", 0);
const int64_t outd = rad_meta_geti(m, "vision_config.output_proj_dims", width);
const double eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-6);
if (width <= 0 || npos <= 0 || side <= 0 || outd != width) {
fprintf(stderr, "radiance: %s: the container's vision_config is incomplete or not the "
"embedder this plugin serves (mm_embed_dim %lld, mm_posemb_size %lld, "
"model_patch_size %lld, output_proj_dims %lld)\n", who,
(long long)width, (long long)npos, (long long)side, (long long)outd);
return RAD_E_UNSUPPORTED;
}
n_embd = model_embd;
patch_dim = 3 * side * side;
P = ctx->max_enc_patches;
const int A = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
const char* V = "model.vision_embedder";
struct { const char* to; const char* from; } cp[] = {
{ "v.ln1.weight", "patch_ln1.weight" }, { "v.ln1.bias", "patch_ln1.bias" },
{ "v.in.weight", "patch_dense.weight" }, { "v.in.bias", "patch_dense.bias" },
{ "v.ln2.weight", "patch_ln2.weight" }, { "v.ln2.bias", "patch_ln2.bias" },
{ "v.pn.weight", "pos_norm.weight" }, { "v.pn.bias", "pos_norm.bias" } };
for (const auto& e : cp)
RAD_ARCH_TRY(map_copy(b, nm.f("%s", e.to), nm.ckpt("%s.%s", V, e.from)));
RAD_ARCH_TRY(map_tap(b, nm.f("v.pos_x.weight"), nm.ckpt("%s.pos_embedding", V), 1, 0));
RAD_ARCH_TRY(map_tap(b, nm.f("v.pos_y.weight"), nm.ckpt("%s.pos_embedding", V), 1, 1));
RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("model.embed_vision.embedding_projection.weight")));
w_ln1 = decl_w(b, nm.f("v.ln1.weight"), RAD_BF16, {patch_dim}, A, N, grp_model());
w_ln1b = decl_w(b, nm.f("v.ln1.bias"), RAD_BF16, {patch_dim}, A, N, grp_model());
w_in = decl_w(b, nm.f("v.in.weight"), RAD_BF16, {width, patch_dim}, A, N, grp_model());
w_inb = decl_w(b, nm.f("v.in.bias"), RAD_BF16, {width}, A, N, grp_model());
w_ln2 = decl_w(b, nm.f("v.ln2.weight"), RAD_BF16, {width}, A, N, grp_model());
w_ln2b = decl_w(b, nm.f("v.ln2.bias"), RAD_BF16, {width}, A, N, grp_model());
w_px = decl_w(b, nm.f("v.pos_x.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
w_py = decl_w(b, nm.f("v.pos_y.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
w_pn = decl_w(b, nm.f("v.pn.weight"), RAD_BF16, {width}, A, N, grp_model());
w_pnb = decl_w(b, nm.f("v.pn.bias"), RAD_BF16, {width}, A, N, grp_model());
w_proj = decl_w(b, nm.f("v.embed.weight"), RAD_BF16, {n_embd, width}, A, N, grp_model());
b_n = decl_b(b, nm.f("v.n"), RAD_BF16, {P, patch_dim});
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width});
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, {P, width});
b_px = decl_b(b, nm.f("v.px"), RAD_BF16, {P, width});
b_py = decl_b(b, nm.f("v.py"), RAD_BF16, {P, width});
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, {P, n_embd});
auto ln = [&](int64_t n, rad_weight w, rad_weight bias) {
return RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", n),
RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w, bias));
};
auto lookup = [&](rad_weight w) {
return RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_embd", width),
RAD_INT("n_vocab", npos), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
RAD_WEIGHTS(w));
};
auto add = [&]() {
return RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
op_ln1 = rw(b, ln(patch_dim, w_ln1, w_ln1b), {}, {b_n});
op_in = rw(b, RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", width),
RAD_INT("K", patch_dim), RAD_STR("dtype", "bf16"),
RAD_STR("act", "none")),
RAD_WEIGHTS(w_in, w_inb)),
{b_n}, {b_x});
op_ln2 = rw(b, ln(width, w_ln2, w_ln2b), {b_x}, {b_h});
op_px = rw(b, lookup(w_px), {}, {b_px});
op_py = rw(b, lookup(w_py), {}, {b_py});
op_padd = rw(b, add(), {b_px, b_py}, {b_px});
op_add = rw(b, add(), {b_h, b_px}, {b_h});
op_pn = rw(b, ln(width, w_pn, w_pnb), {b_h}, {b_x});
op_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{b_x}, {b_h});
op_out = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", n_embd),
RAD_INT("K", width), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_proj)),
{b_h}, {b_out});
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
e.patch_dim = patch_dim;
e.merge = 1;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
e.bidirectional = bidirectional ? 1 : 0;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "vision embedder (no tower): %lldx%lld patches of %lld values -> %lld, "
"positions %lld a side; %lld patches a pass -> %lld rows of %lld",
(long long)side, (long long)side, (long long)patch_dim, (long long)width,
(long long)npos, (long long)P, (long long)P, (long long)n_embd);
on = true;
return RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch;
if (!on || Pn <= 0 || Pn > P || batch->enc_n_seg <= 0) {
rad_step_fail(c, "an encoder pass this program's vision embedder cannot serve: none "
"declared, or more patches than it was declared for");
return;
}
const int32_t* crd = batch->enc_coord;
RAD_ISSUE_N(c, op_ln1, Pn, praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim), RAD_W(w_ln1),
RAD_W(w_ln1b), brows(b_n, Pn));
RAD_ISSUE_N(c, op_in, Pn, brows(b_n, Pn), RAD_W(w_in), RAD_W(w_inb), RAD_NONE, brows(b_x, Pn));
RAD_ISSUE_N(c, op_ln2, Pn, brows(b_x, Pn), RAD_W(w_ln2), RAD_W(w_ln2b), brows(b_h, Pn));
RAD_ISSUE_N(c, op_px, Pn, praw(crd + Pn, RAD_I32, Pn), RAD_W(w_px), brows(b_px, Pn));
RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn));
RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn));
RAD_ISSUE_N(c, op_add, Pn, brows(b_h, Pn), brows(b_px, Pn), brows(b_h, Pn));
RAD_ISSUE_N(c, op_pn, Pn, brows(b_h, Pn), RAD_W(w_pn), RAD_W(w_pnb), brows(b_x, Pn));
RAD_ISSUE_N(c, op_norm, Pn, brows(b_x, Pn), RAD_NONE, brows(b_h, Pn));
RAD_ISSUE_N(c, op_out, Pn, brows(b_h, Pn), RAD_W(w_proj), brows(b_out, Pn));
}
};
struct Gemma4UnifiedAudio {
bool on = false;
int64_t P = 0, frame = 0, n_embd = 0;
rad_weight w_proj = 0;
rad_op op_norm = 0, op_out = 0;
rad_buf b_n = 0, b_out = 0;
static bool present(const RadModelMeta* m) {
const char* t = rad_meta_gets(m, "audio_config.model_type", "");
return t && !std::strcmp(t, "gemma4_unified_audio");
}
/* Samples a frame: the extractor's audio_samples_per_token, else the embedder's input width. */
static int64_t frame_for(const RadModelMeta* m) {
return rad_meta_geti(m, "processor.feature_extractor.audio_samples_per_token",
rad_meta_geti(m, "audio_config.audio_embed_dim", 0));
}
/* The longest clip in frames: processor_config.json's audio_seq_length, else 30 s. */
static int64_t frames_for(const RadModelMeta* m) {
const int64_t f = frame_for(m);
const int64_t rate = rad_meta_geti(m, "processor.feature_extractor.sampling_rate", 16000);
if (f <= 0 || rate <= 0) return 0;
return rad_meta_geti(m, "processor.audio_seq_length", (30 * rate + f - 1) / f);
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, const char* who) {
on = false;
if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK;
frame = frame_for(m);
const int64_t width = rad_meta_geti(m, "audio_config.audio_embed_dim", 0);
const double eps = rad_meta_getf(m, "audio_config.rms_norm_eps", 1e-6);
if (frame <= 0 || width != frame) {
fprintf(stderr, "radiance: %s: the container's audio frame (%lld samples) is not the "
"embedder's input (audio_embed_dim %lld)\n", who, (long long)frame,
(long long)width);
return RAD_E_UNSUPPORTED;
}
n_embd = model_embd;
P = ctx->max_audio_frames;
RAD_ARCH_TRY(map_copy(b, nm.f("a.embed.weight"), nm.ckpt("model.embed_audio.embedding_projection.weight")));
w_proj = decl_w(b, nm.f("a.embed.weight"), RAD_BF16, {n_embd, frame}, RAD_ACCESS_PER_REQUEST,
RAD_SHARD_NONE, grp_model());
b_n = decl_b(b, nm.f("a.n"), RAD_BF16, {P, frame});
b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {P, n_embd});
op_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", frame),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{}, {b_n});
op_out = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", n_embd),
RAD_INT("K", frame), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_proj)),
{b_n}, {b_out});
RadEncoderDecl e{};
e.name = "audio";
e.modalities = RAD_MM_AUDIO;
e.patch_dim = frame;
e.merge = 1;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "audio embedder (no encoder): frames of %lld samples -> %lld; %lld frames a pass",
(long long)frame, (long long)n_embd, (long long)P);
on = true;
return RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch;
if (!on || Pn <= 0 || Pn > P || batch->enc_n_seg <= 0) {
rad_step_fail(c, "an audio pass this program's audio embedder cannot serve: none "
"declared, or more frames than it was declared for");
return;
}
RAD_ISSUE_N(c, op_norm, Pn, praw2(batch->enc_pixels, RAD_BF16, Pn, frame), RAD_NONE,
brows(b_n, Pn));
RAD_ISSUE_N(c, op_out, Pn, brows(b_n, Pn), RAD_W(w_proj), brows(b_out, Pn));
}
};
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_GEMMA4_UNIFIED_H */
+4
View File
@@ -56,6 +56,9 @@ struct Gemma4Vision {
rad_op op_c[C_N] = {}; rad_op op_c[C_N] = {};
}; };
bool on = false, standardize = false, clip = false; bool on = false, standardize = false, clip = false;
/* The language model reads a picture's rows both ways (RadEncoderDecl::bidirectional); the
* plugin sets it before declare. */
bool bidirectional = false;
int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0; int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0;
int64_t npos = 0, n_embd = 0; int64_t npos = 0, n_embd = 0;
rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0, w_sbias = 0, w_sscale = 0; rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0, w_sbias = 0, w_sscale = 0;
@@ -321,6 +324,7 @@ struct Gemma4Vision {
e.max_patches = P; e.max_patches = P;
e.n_embd = n_embd; e.n_embd = n_embd;
e.out = b_out; e.out = b_out;
e.bidirectional = bidirectional ? 1 : 0;
RAD_ARCH_TRY(rad_declare_encoder(b, &e)); RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, " rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
"pooled %lldx%lld%s%s; %lld patches a pass -> %lld rows of %lld", "pooled %lldx%lld%s%s; %lld patches a pass -> %lld rows of %lld",
+65 -16
View File
@@ -27,6 +27,9 @@ struct DsaCache {
rad_buf query = 0, codes = 0, scales = 0, gate = 0, kg = 0; rad_buf query = 0, codes = 0, scales = 0, gate = 0, kg = 0;
rad_buf stage = 0, page = 0, bpos = 0, nc = 0, pooled = 0, pool_scale = 0; rad_buf stage = 0, page = 0, bpos = 0, nc = 0, pooled = 0, pool_scale = 0;
rad_buf score = 0, selected = 0, nsel = 0, length = 0; rad_buf score = 0, selected = 0, nsel = 0, length = 0;
/* A taking-all step's zero scores, [max_tok, topk + 1]: such a step does not split, and
* the score plane holds only a run of rows when the step may. */
rad_buf unscored = 0;
/* TP only: a rank's rebased bounds, page tables and lengths before the gathers. */ /* TP only: a rank's rebased bounds, page tables and lengths before the gathers. */
rad_buf cu_part = 0, sel_part = 0, len_part = 0; rad_buf cu_part = 0, sel_part = 0, len_part = 0;
}; };
@@ -44,6 +47,7 @@ struct DsaCache {
rad_kvgroup index = 0, tail = 0, attention = 0; rad_kvgroup index = 0, tail = 0, attention = 0;
rad_weight ape = 0; rad_weight ape = 0;
rad_op op_query = 0, op_work = 0, op_pool = 0, op_tail = 0, op_score = 0, op_select = 0; rad_op op_query = 0, op_work = 0, op_pool = 0, op_tail = 0, op_score = 0, op_select = 0;
rad_op op_unscored = 0, op_select_all = 0;
rad_op op_score_part = 0, op_select_part = 0, op_gather_sel = 0, op_gather_len = 0; rad_op op_score_part = 0, op_select_part = 0, op_gather_sel = 0, op_gather_len = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg, int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
@@ -112,6 +116,15 @@ struct DsaCache {
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "bf16")), RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS), RAD_NOWEIGHTS),
{ w.kg }, {}); { w.kg }, {});
/* A step whose every row reaches topk or fewer blocks selects them all (takes_all), and
* qsa_select takes any finite scores in block order then: zeros serve as well as the
* scorer's. The fill spans topk + 1 columns, at least the live reach of such a step. */
op_unscored = rw(b,
RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("n", unscored_cols()), RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{}, { w.unscored });
op_score = rw(b, op_score = rw(b,
RAD_OP(b, "dsa_score", RAD_OP(b, "dsa_score",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128), RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
@@ -139,6 +152,14 @@ struct DsaCache {
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)), RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
RAD_NOWEIGHTS), RAD_NOWEIGHTS),
{ w.score, w.nc }, { w.selected, w.nsel, w.length }); { w.score, w.nc }, { w.selected, w.nsel, w.length });
op_select_all = rw(b,
RAD_OP(b, "qsa_select",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("blocks", unscored_cols()),
RAD_INT("topk", 512), RAD_INT("ratio", 4),
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
RAD_NOWEIGHTS),
{ w.unscored, w.nc }, { w.selected, w.nsel, w.length });
if (split) { if (split) {
op_select_part = rw( op_select_part = rw(
b, b,
@@ -165,8 +186,12 @@ struct DsaCache {
if (!op_score_part || !op_select_part || !op_gather_sel || !op_gather_len) if (!op_score_part || !op_select_part || !op_gather_sel || !op_gather_len)
return RAD_E_INVAL; return RAD_E_INVAL;
} }
return op_query && op_work && op_tail && op_score && op_select ? RAD_OK : RAD_E_INVAL; return op_query && op_work && op_tail && op_unscored && op_score && op_select &&
op_select_all
? RAD_OK
: RAD_E_INVAL;
} }
int64_t unscored_cols() const { return c.topk + 1 < c.blocks ? c.topk + 1 : c.blocks; }
/* The columns a step scores: the live reach the batch bounds on the host. */ /* The columns a step scores: the live reach the batch bounds on the host. */
int64_t live_blocks(const RadBatch* batch) const { int64_t live_blocks(const RadBatch* batch) const {
const auto* ib = kv_batch(batch, index); const auto* ib = kv_batch(batch, index);
@@ -179,13 +204,19 @@ struct DsaCache {
} }
/* The decision reads the same host bound as the score plane's width (max_ctx_len, rounded by /* The decision reads the same host bound as the score plane's width (max_ctx_len, rounded by
* the core), so every rank takes the same path and a recorded decode pass changes it only when * the core), so every rank takes the same path and a recorded decode pass changes it only when
* that bound moves. */ * that bound moves. A step that takes all its blocks never splits: with nothing to score, every
* rank selects the whole step itself, and the gathers have nothing to save. */
bool splits(const RadBatch* batch) const { bool splits(const RadBatch* batch) const {
const int64_t T = batch->n_tok; const int64_t T = batch->n_tok;
return op_score_part && (GlmTp::splits(T, g.world) || return op_score_part && live_blocks(batch) > c.topk &&
(T >= GlmTp::kSplitWorkRows && (GlmTp::splits(T, g.world) ||
T * live_blocks(batch) >= GlmTp::kSplitWork)); (T >= GlmTp::kSplitWorkRows && T * live_blocks(batch) >= GlmTp::kSplitWork));
} }
/* Every row's history fits the selection, so the query side (projection, head gates,
* quantiser, scorer) has nothing to decide: the selected table is every live block in order,
* bit for bit what scoring would select. Read from the same host bound as splits(), so every
* rank agrees. */
bool takes_all(const RadBatch* batch) const { return live_blocks(batch) <= c.topk; }
/* The query rows this rank runs: the whole step, or its run of a split step (GlmTp::run_of). /* The query rows this rank runs: the whole step, or its run of a split step (GlmTp::run_of).
* A rank whose run lies wholly past a small step runs the step's first R rows instead: no * A rank whose run lies wholly past a small step runs the step's first R rows instead: no
* sequence holds its run, so its scores are -inf, and its answers land past T. The caller's * sequence holds its run, so its scores are -inf, and its answers land past T. The caller's
@@ -210,11 +241,13 @@ struct DsaCache {
const int64_t T = batch->n_tok, S = batch->n_seq; const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t work = (T + 3) / 4 + S, const int64_t work = (T + 3) / 4 + S,
pitch = tb->state_index_pitch > 0 ? tb->state_index_pitch : 1; pitch = tb->state_index_pitch > 0 ? tb->state_index_pitch : 1;
const bool all = takes_all(batch);
int64_t q0 = 0, qn = T; int64_t q0 = 0, qn = T;
query_rows(batch, &q0, &qn); query_rows(batch, &q0, &qn);
RAD_ISSUE_N(ctx, op_query, qn * 32, brow_slice(w.query, q0 * 32, qn * 32, 128), if (!all)
brow_slice(w.codes, q0 * 32, qn * 32, 128), RAD_ISSUE_N(ctx, op_query, qn * 32, brow_slice(w.query, q0 * 32, qn * 32, 128),
brow_slice(w.scales, q0 * 32, qn * 32, 1)); brow_slice(w.codes, q0 * 32, qn * 32, 128),
brow_slice(w.scales, q0 * 32, qn * 32, 1));
RAD_ISSUE_N(ctx, op_work, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T), RAD_ISSUE_N(ctx, op_work, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer), praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer),
praw2(tb->state_index, RAD_I32, S, pitch), praw2(tb->state_index, RAD_I32, S, pitch),
@@ -232,6 +265,16 @@ struct DsaCache {
step_split(ctx, batch, live); step_split(ctx, batch, live);
return; return;
} }
if (all) {
const int64_t U = unscored_cols();
RAD_ISSUE_N(ctx, op_unscored, T, brows(w.unscored, T));
RAD_ISSUE_N(ctx, op_select_all, T, bcol_at(w.unscored, 0, U, 0, live, T),
praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch),
brows(w.nc, S), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.selected, T),
brows(w.nsel, T), brows(w.length, T));
return;
}
// dsa_score declares ten operands, cu_part the optional tenth; the engine counts them. // dsa_score declares ten operands, cu_part the optional tenth; the engine counts them.
RAD_ISSUE_N(ctx, op_score, T, brows(w.codes, T * 32), brows(w.scales, T * 32), RAD_ISSUE_N(ctx, op_score, T, brows(w.codes, T * 32), brows(w.scales, T * 32),
brows(w.gate, T), kv_cache(index, layer), RAD_NONE, brows(w.gate, T), kv_cache(index, layer), RAD_NONE,
@@ -348,23 +391,29 @@ struct GlmIndexer {
}; };
int64_t r0 = 0, rows = T; int64_t r0 = 0, rows = T;
cache.query_rows(batch, &r0, &rows); cache.query_rows(batch, &r0, &rows);
/* The key side runs on every step, since the index cache must stay current; the query
* side only where the selection is a choice (DsaCache::takes_all). */
const bool all = cache.takes_all(batch);
/* Every output row of these ops is independent of the others and of how many there are, /* Every output row of these ops is independent of the others and of how many there are,
* except the bf16 projection's at 64 rows and under, a band whose split count a tuned * except the bf16 projection's at 64 rows and under, a band whose split count a tuned
* configuration may set: it stays on the step's rows unless every run is wider. */ * configuration may set: it stays on the step's rows unless every run is wider. */
const bool runs = cache.splits(batch); const bool runs = cache.splits(batch);
if (runs && T - (g.world - 1) * DsaCache::part_rows(T, g.world) > 64) if (!all) {
query.step(ctx, act(w.q_low), w.q_wide, T, r0, rows); if (runs && T - (g.world - 1) * DsaCache::part_rows(T, g.world) > 64)
else query.step(ctx, act(w.q_low), w.q_wide, T, r0, rows);
query.step(ctx, act(w.q_low), w.q_wide, T); else
RAD_ISSUE_N(ctx, op_query_copy, rows * 32, brow_slice(w.q_wide, r0, rows, 4096), query.step(ctx, act(w.q_low), w.q_wide, T);
brow_slice(w.cache.query, r0 * 32, rows * 32, 128)); RAD_ISSUE_N(ctx, op_query_copy, rows * 32, brow_slice(w.q_wide, r0, rows, 4096),
brow_slice(w.cache.query, r0 * 32, rows * 32, 128));
}
key_gate.step(ctx, act(w.input), w.kg_raw, T); key_gate.step(ctx, act(w.input), w.kg_raw, T);
RAD_ISSUE_N(ctx, op_norm, T, bcol(w.kg_raw, 0, 128, T), RAD_W(gain), RAD_W(bias), RAD_ISSUE_N(ctx, op_norm, T, bcol(w.kg_raw, 0, 128, T), RAD_W(gain), RAD_W(bias),
bcol(w.cache.kg, 0, 128, T)); bcol(w.cache.kg, 0, 128, T));
RAD_ISSUE_N(ctx, op_gate_copy, T, bcol(w.kg_raw, 128, 128, T), RAD_ISSUE_N(ctx, op_gate_copy, T, bcol(w.kg_raw, 128, 128, T),
bcol(w.cache.kg, 128, 128, T)); bcol(w.cache.kg, 128, 128, T));
RAD_ISSUE_N(ctx, op_head, rows, brow_slice(w.input, r0, rows, 4096), RAD_W(head_weight), if (!all)
brow_slice(w.cache.gate, r0, rows, 32)); RAD_ISSUE_N(ctx, op_head, rows, brow_slice(w.input, r0, rows, 4096),
RAD_W(head_weight), brow_slice(w.cache.gate, r0, rows, 32));
cache.step(ctx, batch); cache.step(ctx, batch);
} }
}; };
+30 -22
View File
@@ -19,6 +19,7 @@
#include "rad_glm_tp.h" #include "rad_glm_tp.h"
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
#include <cstring>
#include <vector> #include <vector>
namespace rad { namespace rad {
@@ -27,6 +28,25 @@ struct MlaLatent {
struct Config { struct Config {
int64_t heads = 16, head_dim = 256, latent_dim = 512, blocks = 513; int64_t heads = 16, head_dim = 256, latent_dim = 512, blocks = 513;
}; };
/* The attention over the latent cache, `rows` rows of `heads` heads. The cache is Geom::kv_dtype
* (bf16, or fp8_e4m3 under --kv-cache-dtype fp8); `kv_dtype` is stated only for a cache that is
* not bf16, so a bf16 build declares the op it always did. */
static rad_op attn_op(RadBuilder* b, const Geom& g, int64_t rows, int64_t heads,
int64_t blocks, double scale) {
if (g.kv_dtype && std::strcmp(g.kv_dtype, "bf16"))
return RAD_OP(b, "mla_attn",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("latent_dim", 512),
RAD_INT("heads", heads), RAD_INT("blocks", blocks),
RAD_INT("block_size", 4), RAD_F64("scale", scale),
RAD_STR("dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS);
return RAD_OP(b, "mla_attn",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("latent_dim", 512),
RAD_INT("heads", heads), RAD_INT("blocks", blocks),
RAD_INT("block_size", 4), RAD_F64("scale", scale),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
}
struct Wire { struct Wire {
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0; rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0;
/* qsa_select's entry count (selected_count), one int a row: the streamed resolve's `nsel`. /* qsa_select's entry count (selected_count), one int a row: the streamed resolve's `nsel`.
@@ -68,16 +88,10 @@ struct MlaLatent {
RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16")), RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(projection)), RAD_WEIGHTS(projection)),
{ w.q }, { w.q_latent }); { w.q }, { w.q_latent });
op_attn = op_attn = rw(b,
rw(b, attn_op(b, g, g.max_tok, c.heads, c.blocks,
RAD_OP(b, "mla_attn", 1.0 / std::sqrt((double)c.head_dim)),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("latent_dim", c.latent_dim), { w.q_latent, w.selected, w.length }, { w.attn_latent });
RAD_INT("heads", c.heads), RAD_INT("blocks", c.blocks),
RAD_INT("block_size", 4),
RAD_F64("scale", 1.0 / std::sqrt((double)c.head_dim)),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.q_latent, w.selected, w.length }, { w.attn_latent });
if (!op_attn || rad_kv_block_size(b, group) != 4) return RAD_E_INVAL; if (!op_attn || rad_kv_block_size(b, group) != 4) return RAD_E_INVAL;
op_expand = rw( op_expand = rw(
b, b,
@@ -172,12 +186,13 @@ struct GlmMla {
RAD_ARCH_TRY(q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b", l), GlmTp::mla_width(g.world), RAD_ARCH_TRY(q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b", l), GlmTp::mla_width(g.world),
1536, RAD_SHARD_ROW, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) }, 1536, RAD_SHARD_ROW, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) },
w.q_low, w.core.q)); w.q_low, w.core.q));
// Cache stores contiguous halves of the normalized latent, with no duplicated K/V. /* Cache stores contiguous halves of the normalized latent, with no duplicated K/V. An E4M3
* cache (Geom::kv_dtype) stores at kv_store's default descale of 1, which mla_attn reads. */
op_store = rw(b, op_store = rw(b,
RAD_OP(b, "kv_store", RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", 256), RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", 256),
RAD_INT("n_head_kv", 1), RAD_INT("block_size", 4), RAD_INT("n_head_kv", 1), RAD_INT("block_size", 4),
RAD_STR("kv_dtype", "bf16")), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS), RAD_NOWEIGHTS),
{ w.latent }, {}); { w.latent }, {});
if (!op_store) return RAD_E_INVAL; if (!op_store) return RAD_E_INVAL;
@@ -200,7 +215,7 @@ struct GlmMla {
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("head_dim", 256), RAD_INT("n_head_kv", 1), RAD_INT("head_dim", 256), RAD_INT("n_head_kv", 1),
RAD_INT("block_size", 4), RAD_INT("block_size", 4),
RAD_STR("kv_dtype", "bf16")), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS), RAD_NOWEIGHTS),
{ w.latent }, {}); { w.latent }, {});
/* Issued in finish, after this layer's indexer selects and before the attention reads /* Issued in finish, after this layer's indexer selects and before the attention reads
@@ -239,15 +254,8 @@ struct GlmMla {
{ in }, { out }); { in }, { out });
}; };
op_rows_absorb = project("absorb", r.q, r.q_latent); op_rows_absorb = project("absorb", r.q, r.q_latent);
op_rows_attn = op_rows_attn = rw(b, MlaLatent::attn_op(b, g, R, 64, core.c.blocks, 1.0 / std::sqrt(256.0)),
rw(b, { r.q_latent, w.core.selected, w.core.length }, { r.attn_latent });
RAD_OP(b, "mla_attn",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("latent_dim", 512),
RAD_INT("heads", 64), RAD_INT("blocks", core.c.blocks),
RAD_INT("block_size", 4), RAD_F64("scale", 1.0 / std::sqrt(256.0)),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ r.q_latent, w.core.selected, w.core.length }, { r.attn_latent });
op_rows_expand = project("expand", r.attn_latent, r.attn.x); op_rows_expand = project("expand", r.attn_latent, r.attn.x);
RAD_ARCH_TRY(rows_quant.declare(b, g, r.attn, 16384)); RAD_ARCH_TRY(rows_quant.declare(b, g, r.attn, 16384));
rows_output.stored = nm.f("blk.%d.attn_output.weight", layer); rows_output.stored = nm.f("blk.%d.attn_output.weight", layer);
+34 -25
View File
@@ -16,7 +16,11 @@
* before the layer's attention, `join` (the residual add and the proposal rows' selection) between * before the layer's attention, `join` (the residual add and the proposal rows' selection) between
* its attention and its feed-forward, `head` after it. The embedding and lm_head are the trunk's. * its attention and its feed-forward, `head` after it. The embedding and lm_head are the trunk's.
* Its names live under the `mtp.` scope (Names), its weights in layer 45's group. eh_proj * Its names live under the `mtp.` scope (Names), its weights in layer 45's group. eh_proj
* (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass. */ * (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass.
*
* The same head serves another DeepSeek-style drafter by its checkpoint layout, set before
* declare_inputs: the residual width, the layer's checkpoint prefix and index, and the name of the
* head's final norm (Ling-3.0: 2560, `model.layers.42`, 42, `final_layernorm.weight`). */
#ifndef RAD_BLOCK_GLM_MTP_H #ifndef RAD_BLOCK_GLM_MTP_H
#define RAD_BLOCK_GLM_MTP_H #define RAD_BLOCK_GLM_MTP_H
#include "rad_glm_tp.h" #include "rad_glm_tp.h"
@@ -31,6 +35,10 @@ struct GlmMtp {
rad_weight token = 0, head = 0; rad_weight token = 0, head = 0;
}; };
static constexpr int kDepth = 3; /* --num-speculative-tokens auto */ static constexpr int kDepth = 3; /* --num-speculative-tokens auto */
int64_t width = 4096;
const char* prefix = "model.language_model.layers.45";
int layer = 45;
const char* norm_src = "shared_head.norm.weight";
Names nm{ "mtp" }; Names nm{ "mtp" };
Geom g{}; Geom g{};
Wire w{}; Wire w{};
@@ -50,47 +58,48 @@ struct GlmMtp {
w = wire; w = wire;
if (!b || !w.final_hidden || !w.logits || !w.token || !w.head || g.max_spec < 1) if (!b || !w.final_hidden || !w.logits || !w.token || !w.head || g.max_spec < 1)
return RAD_E_INVAL; return RAD_E_INVAL;
x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, 4096 }); const int64_t E = width;
hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, 4096 }, RAD_BUF_PERSIST); x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, E });
embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, 4096 }); hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, E }, RAD_BUF_PERSIST);
concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 8192 }); embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, E });
out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, 4096 }); concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 2 * E });
const char* pre = "model.language_model.layers.45"; out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, E });
const char* pre = prefix;
auto gain = [&](const char* n, const char* src) { auto gain = [&](const char* n, const char* src) {
const char* name = nm.f("%s", n); const char* name = nm.f("%s", n);
if (map_copy(b, name, nm.ckpt("%s.%s", pre, src)) < 0) return (rad_weight)0; if (map_copy(b, name, nm.ckpt("%s.%s", pre, src)) < 0) return (rad_weight)0;
return decl_w(b, name, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, return decl_w(b, name, RAD_F32, { E }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(45)); grp_layer(layer));
}; };
en = gain("enorm.weight", "enorm.weight"); en = gain("enorm.weight", "enorm.weight");
hn = gain("hnorm.weight", "hnorm.weight"); hn = gain("hnorm.weight", "hnorm.weight");
norm = gain("output_norm.weight", "shared_head.norm.weight"); norm = gain("output_norm.weight", norm_src);
RAD_ARCH_TRY(map_copy(b, nm.f("eh_proj.weight"), nm.ckpt("%s.eh_proj.weight", pre))); RAD_ARCH_TRY(map_copy(b, nm.f("eh_proj.weight"), nm.ckpt("%s.eh_proj.weight", pre)));
eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { 4096, 8192 }, RAD_ACCESS_PER_TOKEN, eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { E, 2 * E }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(45)); RAD_SHARD_NONE, grp_layer(layer));
if (!x || !hidden || !embedding || !concat || !out || !en || !hn || !norm || !eh) if (!x || !hidden || !embedding || !concat || !out || !en || !hn || !norm || !eh)
return RAD_E_INVAL; return RAD_E_INVAL;
op_prev = rw(b, op_prev = rw(b,
RAD_OP(b, "gather_rows", RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", E),
RAD_STR("dtype", "bf16")), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS), RAD_NOWEIGHTS),
{ w.final_hidden }, { hidden }); { w.final_hidden }, { hidden });
op_embed = rw(b, op_embed = rw(b,
RAD_OP(b, "embed_lookup", RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", 4096), RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", E),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"), RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)), RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w.token)), RAD_WEIGHTS(w.token)),
{}, { embedding }); {}, { embedding });
if (media) RAD_ARCH_TRY(mrows.declare(b, g.max_tok, 4096, embedding)); if (media) RAD_ARCH_TRY(mrows.declare(b, g.max_tok, E, embedding));
op_embed_ar = GlmTp::reduce(b, g, embedding, true); op_embed_ar = GlmTp::reduce(b, g, embedding, true);
op_en = rmsnorm(b, en, embedding, concat); op_en = rmsnorm(b, en, embedding, concat);
op_hn = rmsnorm(b, hn, hidden, concat); op_hn = rmsnorm(b, hn, hidden, concat);
op_eh = rw(b, op_eh = rw(b,
RAD_OP(b, "gemm_nt", RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 4096), RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", E),
RAD_INT("K", 8192), RAD_STR("dtype", "bf16")), RAD_INT("K", 2 * E), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(eh)), RAD_WEIGHTS(eh)),
{ concat }, { x }); { concat }, { x });
return op_prev && op_embed && op_en && op_hn && op_eh && (g.world == 1 || op_embed_ar) return op_prev && op_embed && op_en && op_hn && op_eh && (g.world == 1 || op_embed_ar)
@@ -102,14 +111,14 @@ struct GlmMtp {
int declare_join(RadBuilder* b, rad_buf y) { int declare_join(RadBuilder* b, rad_buf y) {
op_residual = rw(b, op_residual = rw(b,
RAD_OP(b, "add", RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
RAD_STR("dtype", "bf16")), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS), RAD_NOWEIGHTS),
{ x, y }, { x }); { x, y }, { x });
// All history rows fill the draft cache; only proposal rows need its FFN. // All history rows fill the draft cache; only proposal rows need its FFN.
op_select = rw(b, op_select = rw(b,
RAD_OP(b, "gather_rows", RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096), RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", width),
RAD_STR("dtype", "bf16")), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS), RAD_NOWEIGHTS),
{ x }, { hidden }); { x }, { hidden });
@@ -124,7 +133,7 @@ struct GlmMtp {
op_head = rw(b, op_head = rw(b,
RAD_OP(b, "logits_gemm", RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", 4096), RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", width),
RAD_STR("dtype", "bf16")), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w.head)), RAD_WEIGHTS(w.head)),
{ hidden }, { w.logits }); { hidden }, { w.logits });
@@ -150,9 +159,9 @@ struct GlmMtp {
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w.token), RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w.token),
brows(embedding, T)); brows(embedding, T));
mrows.step(c, batch, embedding, T); mrows.step(c, batch, embedding, T);
if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * 4096, brows(embedding, T), RAD_NONE); if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * width, brows(embedding, T), RAD_NONE);
RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, 4096, T)); RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, width, T));
RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, 4096, 4096, T)); RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, width, width, T));
RAD_ISSUE_N(c, op_eh, T, brows(concat, T), RAD_W(eh), brows(x, T)); RAD_ISSUE_N(c, op_eh, T, brows(concat, T), RAD_W(eh), brows(x, T));
} }
void step_join(RadCtx* c, const RadBatch* batch, rad_buf y) const { void step_join(RadCtx* c, const RadBatch* batch, rad_buf y) const {
@@ -175,7 +184,7 @@ private:
rad_op rmsnorm(RadBuilder* b, rad_weight gain, rad_buf in, rad_buf out) const { rad_op rmsnorm(RadBuilder* b, rad_weight gain, rad_buf in, rad_buf out) const {
return rw(b, return rw(b,
RAD_OP(b, "rmsnorm", RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")), RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(gain)), RAD_WEIGHTS(gain)),
{ in }, { out }); { in }, { out });
@@ -183,7 +192,7 @@ private:
rad_op cast(RadBuilder* b, rad_buf in, rad_buf out) const { rad_op cast(RadBuilder* b, rad_buf in, rad_buf out) const {
return rw(b, return rw(b,
RAD_OP(b, "cast", RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS), RAD_NOWEIGHTS),
{ in }, { out }); { in }, { out });
+25 -12
View File
@@ -1,5 +1,6 @@
/* GLM noaux_tc router. Correction bias changes selection only; mixture weights /* GLM noaux_tc router. Correction bias changes selection only; mixture weights
* come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. */ * come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. With `groups`
* above 1 the selection is group-limited (router_sigmoid_group_topk, Ling-3.0's 8 groups, 4 kept). */
#ifndef RAD_BLOCK_GLM_ROUTER_H #ifndef RAD_BLOCK_GLM_ROUTER_H
#define RAD_BLOCK_GLM_ROUTER_H #define RAD_BLOCK_GLM_ROUTER_H
#include "rad_glm_tp.h" #include "rad_glm_tp.h"
@@ -9,7 +10,7 @@ namespace rad {
namespace arch { namespace arch {
struct GlmRouter { struct GlmRouter {
struct Config { struct Config {
int64_t experts = 288, top_k = 8, rows = 32; int64_t experts = 288, top_k = 8, rows = 32, groups = 1, topk_groups = 1;
int norm = 1; int norm = 1;
double route_scale = 2.5; double route_scale = 2.5;
}; };
@@ -33,8 +34,9 @@ struct GlmRouter {
w = wire; w = wire;
if (!b || !name || !src.weight || !src.correction || g.n_embd < 1 || c.experts < 1 || if (!b || !name || !src.weight || !src.correction || g.n_embd < 1 || c.experts < 1 ||
c.experts > 512 || c.top_k < 1 || c.top_k > c.experts || c.rows < 1 || c.experts > 512 || c.top_k < 1 || c.top_k > c.experts || c.rows < 1 ||
c.rows > g.max_tok || !std::isfinite(c.route_scale) || c.route_scale <= 0 || !w.input || c.rows > g.max_tok || !std::isfinite(c.route_scale) || c.route_scale <= 0 ||
!w.logits || !w.ids || !w.weights || w.logits == w.weights) c.groups < 1 || c.experts % c.groups || c.topk_groups < 1 || c.topk_groups > c.groups ||
!w.input || !w.logits || !w.ids || !w.weights || w.logits == w.weights)
return RAD_E_INVAL; return RAD_E_INVAL;
const char *pn = nm.f("%s.weight", name), *cn = nm.f("%s.correction", name); const char *pn = nm.f("%s.weight", name), *cn = nm.f("%s.correction", name);
RAD_ARCH_TRY(map_copy(b, pn, src.weight)); RAD_ARCH_TRY(map_copy(b, pn, src.weight));
@@ -52,14 +54,25 @@ struct GlmRouter {
{ w.input }, { w.logits }); { w.input }, { w.logits });
RAD_ARCH_TRY(split.declare(b, nm, g, name, c.rows, c.experts, g.n_embd, projection, w.input, RAD_ARCH_TRY(split.declare(b, nm, g, name, c.rows, c.experts, g.n_embd, projection, w.input,
w.logits)); w.logits));
op_select = if (c.groups > 1)
rw(b, op_select =
RAD_OP(b, "router_sigmoid_topk", rw(b,
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts), RAD_OP(b, "router_sigmoid_group_topk",
RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm), RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")), RAD_INT("top_k", c.top_k), RAD_INT("n_group", c.groups),
RAD_WEIGHTS(correction)), RAD_INT("topk_group", c.topk_groups), RAD_INT("norm", c.norm),
{ w.logits }, { w.ids, w.weights }); RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
RAD_WEIGHTS(correction)),
{ w.logits }, { w.ids, w.weights });
else
op_select =
rw(b,
RAD_OP(b, "router_sigmoid_topk",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm),
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
RAD_WEIGHTS(correction)),
{ w.logits }, { w.ids, w.weights });
return op_project && op_select ? RAD_OK : RAD_E_INVAL; return op_project && op_select ? RAD_OK : RAD_E_INVAL;
} }
void project(RadCtx* ctx, int64_t first, int64_t rows, int64_t output_first = 0) const { void project(RadCtx* ctx, int64_t first, int64_t rows, int64_t output_first = 0) const {
+395
View File
@@ -0,0 +1,395 @@
/* rad_block_lilicorr.h -- LiLiCorr's head: the candidate correlator after a DFlash2 backbone.
*
* NVIDIA's drafter for Nemotron-3.5-Bolt (vLLM's model_executor/models/lilicorr.py). The backbone is
* rad_block_dflash2.h's, with attention sinks (Dflash2::Config::lili). Its final hidden states at
* the block's draft rows go here instead of to DFlash2's selector:
*
* candidates each draft position's top-k from the target's own lm_head (log-softmax values,
* vocab-parallel: each rank's shard, all-gathered, merged)
* lattice steps x k rows a sequence, row s * k + j:
* token_proj(embed(cand)) + pass_hidden_proj(h_s)
* + feature_mlp(layernorm(five rank features)) + slot[s] + rank[j]
* 2 layers rmsnorm, attention over the lattice with a learned slot bias (lili_attn), the
* in/out projections; rmsnorm, silu MLP with biases; residuals
* factor x = output_norm(lattice), a = anchor_norm(context_proj(the anchor's context row))
* f = silu(W [x | a | x * a] + b), [out | in] = edge heads of f
* walk normalised dot products, start from the anchor's own outgoing head, greedy
* (lili_walk)
*
* The anchor's context row is hidden_norm(fc(taps)) at the last committed position, which the
* context pass left in Dflash2's `c` (RadBatch::anchor_rows names the row). The head reads the
* target's embedding and lm_head, and its own 25 linears are bf16: ModelOpt ships them NVFP4,
* which no kernel serves, and the recipe decodes them (`cast dtype=bf16`).
*
* Every rank computes the whole lattice (vLLM: "candidate IDs and embeddings are replicated across
* TP ranks"); only the head's logits and the embedding lookup are per rank, with the merge in
* lili_cand and an exact all-reduce after the lookup.
*/
#ifndef RAD_BLOCK_LILICORR_H
#define RAD_BLOCK_LILICORR_H
#include "rad_arch.h"
namespace rad {
namespace arch {
struct LiliCorr {
enum { MAX_LAYERS = 4 };
struct Config {
int64_t steps = 0; /* draft positions a sequence: the block less the anchor */
int64_t k = 8; /* candidates a position (lilicorr_candidate_topk) */
int64_t hs = 1024; /* the lattice's width (lilicorr_hidden_size) */
int64_t n_head = 8;
int64_t mlp = 2048; /* hs * lilicorr_mlp_ratio */
int64_t fdim = 1024; /* lilicorr_factor_dim */
int64_t n_layer = 2;
double eps = 1e-6; /* rms_norm_eps, the lattice's RMS norms */
double vec_eps = 1e-4; /* lilicorr_vector_eps, F.normalize's floor */
double scale = 8.0; /* lilicorr_logit_scale */
};
/* row_k: the pairs a rank's logprob row carries, k rounded up so 2 + 2 row_k floats are whole
* 16-byte words (the all-gather's unit): 9 for k = 8. */
static int64_t row_k(int64_t k) { return (k % 2) ? k : k + 1; }
struct Wire {
/* Dflash2's */
rad_buf sel_h = 0; /* [srows, n_embd] the drafter's final hidden states, draft rows */
rad_buf c = 0; /* [max_tok, n_embd] hidden_norm(fc(taps)), the context pass's rows */
rad_buf tokens = 0; /* [max_seqs, steps] i32, the proposal */
/* the head's own */
rad_buf logits = 0; /* [srows, n_vocab] f32, this rank's shard */
rad_buf stats = 0; /* [srows, 2 + 2 row_k] f32 */
rad_buf sgath = 0; /* [srows, world * (2 + 2 row_k)] f32, world > 1 */
rad_buf pas = 0; /* [srows, hs] */
rad_buf cand = 0; /* [srows * k] i32 */
rad_buf feat = 0; /* [lrows, hs] */
rad_buf hh = 0; /* [lrows, hs] the lattice's residual stream; starts as lili_cand's base */
rad_buf emb = 0; /* [lrows, n_embd] the candidates' embeddings */
rad_buf y = 0; /* [lrows, hs] */
rad_buf qkv = 0; /* [lrows, 3 hs] */
rad_buf att = 0; /* [lrows, hs] */
rad_buf up = 0; /* [lrows, mlp] */
rad_buf ups = 0; /* [lrows, mlp] */
rad_buf cat = 0; /* [lrows, 3 hs] */
rad_buf fh = 0; /* [lrows, hs] */
rad_buf fhs = 0; /* [lrows, hs] */
rad_buf edges = 0; /* [lrows, 2 fdim] */
rad_buf anc = 0; /* [max_seqs, n_embd] */
rad_buf ast = 0; /* [max_seqs, hs] */
rad_buf an = 0; /* [max_seqs, hs] */
rad_buf aout = 0; /* [max_seqs, fdim] */
};
Geom g{};
Config cfg{};
Wire w{};
int64_t srows = 0, lrows = 0, rk = 0;
rad_weight w_lm = 0, w_tok = 0; /* the target's */
rad_weight w_tokp = 0, b_tokp = 0, w_pass = 0, b_pass = 0, w_ctx = 0, b_ctx = 0;
rad_weight w_fdn = 0, b_fdn = 0, ln_w = 0, ln_b = 0, up_w = 0, up_b = 0, w_slot = 0, w_rank = 0;
rad_weight w_anorm[MAX_LAYERS] = {}, w_in[MAX_LAYERS] = {}, b_in[MAX_LAYERS] = {};
rad_weight w_out[MAX_LAYERS] = {}, b_out[MAX_LAYERS] = {}, w_mnorm[MAX_LAYERS] = {};
rad_weight w_up[MAX_LAYERS] = {}, b_up[MAX_LAYERS] = {}, w_dn[MAX_LAYERS] = {};
rad_weight b_dn[MAX_LAYERS] = {};
rad_weight w_rel = 0, w_same = 0, w_onorm = 0, w_annorm = 0;
rad_weight w_fac = 0, b_fac = 0, w_edge = 0, b_edge = 0, w_aout = 0, b_aout = 0;
rad_op op_logits = 0, op_stats = 0, op_sgath = 0, op_pas = 0, op_cand = 0;
rad_op op_emb = 0, op_emb_ar = 0, op_tokp = 0, op_fdn = 0;
rad_op op_anorm[MAX_LAYERS] = {}, op_in[MAX_LAYERS] = {}, op_attn = 0;
rad_op op_out[MAX_LAYERS] = {}, op_mnorm[MAX_LAYERS] = {}, op_up[MAX_LAYERS] = {};
rad_op op_dn[MAX_LAYERS] = {}, op_silu_up = 0;
rad_op op_onorm = 0, op_anc = 0, op_ctx = 0, op_annorm = 0, op_factor = 0, op_fac = 0;
rad_op op_silu_f = 0, op_edge = 0, op_aout = 0, op_walk = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, rad_weight lm_head,
rad_weight tok_embd, const char* ck, const Wire& wire);
/* After Dflash2::step, on the same query batch: `sel_h` holds the draft rows. */
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int LiliCorr::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
rad_weight lm_head, rad_weight tok_embd, const char* ck,
const Wire& wire) {
g = geom; cfg = c; w = wire; w_lm = lm_head; w_tok = tok_embd;
if (!w_lm || !w_tok || !ck || cfg.steps < 1 || cfg.k < 2 || cfg.n_layer < 1 ||
cfg.n_layer > MAX_LAYERS || cfg.hs % cfg.n_head)
return RAD_E_INVAL;
const int64_t K = cfg.k, S = cfg.steps, hs = cfg.hs, fd = cfg.fdim, E = g.n_embd;
srows = g.max_seqs * S;
lrows = srows * K;
rk = row_k(K);
const int ACC = RAD_ACCESS_PER_TOKEN;
const RadWeightGroup grp = grp_model();
/* The head's weights, all replicated. Linears and tables bf16, biases, norms and the
* feature layer f32. */
auto wt = [&](const char* dn, const char* src, uint32_t dt,
std::initializer_list<int64_t> shp) -> rad_weight {
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, grp);
};
const char* L = nm.ckpt("%s.lilicorr", ck);
auto src = [&](const char* tail) { return nm.ckpt("%s.%s", L, tail); };
w_tokp = wt(nm.f("dflash.lili.token_proj.weight"), src("token_proj.weight"), RAD_BF16, { hs, E });
b_tokp = wt(nm.f("dflash.lili.token_proj.bias"), src("token_proj.bias"), RAD_F32, { hs });
w_pass = wt(nm.f("dflash.lili.pass_proj.weight"), src("pass_hidden_proj.weight"), RAD_BF16,
{ hs, E });
b_pass = wt(nm.f("dflash.lili.pass_proj.bias"), src("pass_hidden_proj.bias"), RAD_F32, { hs });
w_ctx = wt(nm.f("dflash.lili.context_proj.weight"), src("context_proj.weight"), RAD_BF16,
{ hs, E });
b_ctx = wt(nm.f("dflash.lili.context_proj.bias"), src("context_proj.bias"), RAD_F32, { hs });
ln_w = wt(nm.f("dflash.lili.feature_norm.weight"), src("feature_norm.weight"), RAD_F32, { 5 });
ln_b = wt(nm.f("dflash.lili.feature_norm.bias"), src("feature_norm.bias"), RAD_F32, { 5 });
up_w = wt(nm.f("dflash.lili.feature_up.weight"), src("feature_mlp.up_proj.weight"), RAD_F32,
{ hs, 5 });
up_b = wt(nm.f("dflash.lili.feature_up.bias"), src("feature_mlp.up_proj.bias"), RAD_F32,
{ hs });
w_fdn = wt(nm.f("dflash.lili.feature_down.weight"), src("feature_mlp.down_proj.weight"),
RAD_BF16, { hs, hs });
b_fdn = wt(nm.f("dflash.lili.feature_down.bias"), src("feature_mlp.down_proj.bias"), RAD_F32,
{ hs });
/* [1, 1, steps, 1, hs] and [1, 1, 1, k, hs], read as tables (a reshape of one whole plane). */
w_slot = wt(nm.f("dflash.lili.slot_embedding"), src("slot_embedding"), RAD_BF16, { S, hs });
w_rank = wt(nm.f("dflash.lili.rank_embedding"), src("rank_embedding"), RAD_BF16, { K, hs });
w_rel = wt(nm.f("dflash.lili.relative_slot_bias"), src("relative_slot_bias"), RAD_F32,
{ cfg.n_head, 2 * (S + 1) - 1 });
w_same = wt(nm.f("dflash.lili.same_slot_bias"), src("same_slot_bias"), RAD_F32, { cfg.n_head });
for (int64_t l = 0; l < cfg.n_layer; ++l) {
const int i = (int)l;
auto ls = [&](const char* tail) { return nm.ckpt("%s.layers.%d.%s", L, i, tail); };
w_anorm[i] = wt(nm.f("dflash.lili.blk.%d.attn_norm.weight", i), ls("attn_norm.weight"),
RAD_F32, { hs });
w_in[i] = wt(nm.f("dflash.lili.blk.%d.attn_in.weight", i), ls("attn.in_proj_weight"),
RAD_BF16, { 3 * hs, hs });
b_in[i] = wt(nm.f("dflash.lili.blk.%d.attn_in.bias", i), ls("attn.in_proj_bias"), RAD_F32,
{ 3 * hs });
w_out[i] = wt(nm.f("dflash.lili.blk.%d.attn_out.weight", i), ls("attn.out_proj.weight"),
RAD_BF16, { hs, hs });
b_out[i] = wt(nm.f("dflash.lili.blk.%d.attn_out.bias", i), ls("attn.out_proj.bias"),
RAD_F32, { hs });
w_mnorm[i] = wt(nm.f("dflash.lili.blk.%d.mlp_norm.weight", i), ls("mlp_norm.weight"),
RAD_F32, { hs });
w_up[i] = wt(nm.f("dflash.lili.blk.%d.mlp_up.weight", i), ls("mlp.up_proj.weight"),
RAD_BF16, { cfg.mlp, hs });
b_up[i] = wt(nm.f("dflash.lili.blk.%d.mlp_up.bias", i), ls("mlp.up_proj.bias"), RAD_F32,
{ cfg.mlp });
w_dn[i] = wt(nm.f("dflash.lili.blk.%d.mlp_down.weight", i), ls("mlp.down_proj.weight"),
RAD_BF16, { hs, cfg.mlp });
b_dn[i] = wt(nm.f("dflash.lili.blk.%d.mlp_down.bias", i), ls("mlp.down_proj.bias"),
RAD_F32, { hs });
if (!w_anorm[i] || !w_in[i] || !b_in[i] || !w_out[i] || !b_out[i] || !w_mnorm[i] ||
!w_up[i] || !b_up[i] || !w_dn[i] || !b_dn[i])
return RAD_E_INVAL;
}
w_onorm = wt(nm.f("dflash.lili.output_norm.weight"), src("output_norm.weight"), RAD_F32, { hs });
w_annorm = wt(nm.f("dflash.lili.anchor_norm.weight"), src("anchor_norm.weight"), RAD_F32, { hs });
w_fac = wt(nm.f("dflash.lili.factor_proj.weight"), src("factor_input_proj.weight"), RAD_BF16,
{ hs, 3 * hs });
b_fac = wt(nm.f("dflash.lili.factor_proj.bias"), src("factor_input_proj.bias"), RAD_F32,
{ hs });
/* [out_head | in_head] as one linear, as vLLM fuses them (`_fused_edge_weight`). */
RAD_ARCH_TRY(map_concat(b, nm.f("dflash.lili.edge.weight"),
{ src("out_head.weight"), src("in_head.weight") }, 0));
RAD_ARCH_TRY(map_concat(b, nm.f("dflash.lili.edge.bias"),
{ src("out_head.bias"), src("in_head.bias") }, 0));
w_edge = decl_w(b, nm.f("dflash.lili.edge.weight"), RAD_BF16, { 2 * fd, hs }, ACC,
RAD_SHARD_NONE, grp);
b_edge = decl_w(b, nm.f("dflash.lili.edge.bias"), RAD_F32, { 2 * fd }, ACC, RAD_SHARD_NONE,
grp);
w_aout = wt(nm.f("dflash.lili.anchor_out.weight"), src("anchor_out_head.weight"), RAD_BF16,
{ fd, hs });
b_aout = wt(nm.f("dflash.lili.anchor_out.bias"), src("anchor_out_head.bias"), RAD_F32, { fd });
if (!w_tokp || !b_tokp || !w_pass || !b_pass || !w_ctx || !b_ctx || !ln_w || !ln_b || !up_w ||
!up_b || !w_fdn || !b_fdn || !w_slot || !w_rank || !w_rel || !w_same || !w_onorm ||
!w_annorm || !w_fac || !b_fac || !w_edge || !b_edge || !w_aout || !b_aout)
return RAD_E_INVAL;
/* ---------------------------------------------------------------- ops */
auto gemm_b = [&](int64_t rows, int64_t N, int64_t Kd, rad_weight wgt, rad_weight bias)
-> rad_op {
return RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", Kd),
RAD_STR("dtype", "bf16"), RAD_STR("act", "none")),
RAD_WEIGHTS(wgt, bias));
};
auto rms = [&](int64_t rows, int64_t n, rad_weight gain) -> rad_op {
return RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", cfg.eps),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(gain));
};
auto silu = [&](int64_t rows, int64_t n) -> rad_op {
return RAD_OP(b, "silu",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
const int64_t sw = 2 + 2 * rk;
/* The candidates: this rank's shard of the target's logits, its logprob row, the exchange. */
op_logits = rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_lm)),
{ w.sel_h }, { w.logits });
/* Replicated, `vocab_off` is omitted: an optional parameter present at 0 is a different
* declaration from an absent one. */
op_stats = g.world > 1
? rw(b, RAD_OP(b, "sample_logprobs",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("k", rk), RAD_INT("vocab_off", g.vocab_off)),
RAD_NOWEIGHTS),
{ w.logits }, { w.stats })
: rw(b, RAD_OP(b, "sample_logprobs",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("k", rk)),
RAD_NOWEIGHTS),
{ w.logits }, { w.stats });
if (g.world > 1)
op_sgath = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", srows * sw), RAD_STR("dtype", "f32"),
RAD_INT("row", sw)),
RAD_NOWEIGHTS),
{ w.stats }, { w.sgath });
op_pas = rw(b, gemm_b(srows, hs, E, w_pass, b_pass), { w.sel_h }, { w.pas });
op_cand = rw(b, RAD_OP(b, "lili_cand",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("k", K),
RAD_INT("world", g.world), RAD_INT("steps", S),
RAD_INT("n", hs), RAD_STR("dtype", "bf16"),
RAD_F64("eps", 1e-5), RAD_INT("row_k", rk)),
RAD_WEIGHTS(ln_w, ln_b, up_w, up_b, w_slot, w_rank)),
{ g.world > 1 ? w.sgath : w.stats, w.pas }, { w.cand, w.feat, w.hh });
/* The lattice: candidates' embeddings (the trunk's vocab-sharded table, exact reduce), the
* token and feature projections added onto lili_cand's base in their GEMMs' residual. */
op_emb = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("n_embd", E),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w_tok)),
{ w.cand }, { w.emb });
if (g.world > 1)
op_emb_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", E, lrows * E),
RAD_STR("dtype", "bf16"), RAD_INT("exact", 1)),
RAD_NOWEIGHTS),
{ w.emb }, { w.emb });
op_tokp = rw(b, gemm_b(lrows, hs, E, w_tokp, b_tokp), { w.emb, w.hh }, { w.hh });
op_fdn = rw(b, gemm_b(lrows, hs, hs, w_fdn, b_fdn), { w.feat, w.hh }, { w.hh });
for (int64_t l = 0; l < cfg.n_layer; ++l) {
const int i = (int)l;
op_anorm[i] = rw(b, rms(lrows, hs, w_anorm[i]), { w.hh }, { w.y });
op_in[i] = rw(b, gemm_b(lrows, 3 * hs, hs, w_in[i], b_in[i]), { w.y }, { w.qkv });
op_out[i] = rw(b, gemm_b(lrows, hs, hs, w_out[i], b_out[i]), { w.att, w.hh }, { w.hh });
op_mnorm[i] = rw(b, rms(lrows, hs, w_mnorm[i]), { w.hh }, { w.y });
op_up[i] = rw(b, gemm_b(lrows, cfg.mlp, hs, w_up[i], b_up[i]), { w.y }, { w.up });
op_dn[i] = rw(b, gemm_b(lrows, hs, cfg.mlp, w_dn[i], b_dn[i]), { w.ups, w.hh }, { w.hh });
}
op_attn = rw(b, RAD_OP(b, "lili_attn",
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("steps", S), RAD_INT("k", K),
RAD_INT("n_head", cfg.n_head),
RAD_INT("head_dim", hs / cfg.n_head),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_rel, w_same)),
{ w.qkv }, { w.att });
op_silu_up = rw(b, silu(lrows, cfg.mlp), { w.up }, { w.ups });
op_onorm = rw(b, rms(lrows, hs, w_onorm), { w.hh }, { w.y });
/* The anchor: the context pass's row at each drafting sequence's last committed position. */
op_anc = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", E),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.c }, { w.anc });
op_ctx = rw(b, gemm_b(g.max_seqs, hs, E, w_ctx, b_ctx), { w.anc }, { w.ast });
op_annorm = rw(b, rms(g.max_seqs, hs, w_annorm), { w.ast }, { w.an });
op_factor = rw(b, RAD_OP(b, "lili_factor",
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("L", S * K),
RAD_INT("n", hs), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.y, w.an }, { w.cat });
op_fac = rw(b, gemm_b(lrows, hs, 3 * hs, w_fac, b_fac), { w.cat }, { w.fh });
op_silu_f = rw(b, silu(lrows, hs), { w.fh }, { w.fhs });
op_edge = rw(b, gemm_b(lrows, 2 * fd, hs, w_edge, b_edge), { w.fhs }, { w.edges });
op_aout = rw(b, gemm_b(g.max_seqs, fd, hs, w_aout, b_aout), { w.an }, { w.aout });
op_walk = rw(b, RAD_OP(b, "lili_walk",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", S),
RAD_INT("k", K), RAD_INT("n", fd), RAD_STR("dtype", "bf16"),
RAD_F64("eps", cfg.vec_eps), RAD_F64("scale", cfg.scale)),
RAD_NOWEIGHTS),
{ w.edges, w.aout, w.cand }, { w.tokens });
if (!op_logits || !op_stats || (g.world > 1 && (!op_sgath || !op_emb_ar)) || !op_pas ||
!op_cand || !op_emb || !op_tokp || !op_fdn || !op_attn || !op_silu_up || !op_onorm ||
!op_anc || !op_ctx || !op_annorm || !op_factor || !op_fac || !op_silu_f || !op_edge ||
!op_aout || !op_walk)
return RAD_E_INVAL;
return RAD_OK;
}
inline void LiliCorr::step(RadCtx* c, const RadBatch* batch) const {
const int64_t n = batch->n_seq, S = n * cfg.steps, Lr = S * cfg.k;
if (n <= 0) return;
if (!batch->anchor_rows) {
rad_step_fail(c, "lilicorr: the query pass carries no anchor rows (RadBatch::anchor_rows): "
"this engine does not position a block drafter's anchor");
return;
}
const int64_t E = g.n_embd, hs = cfg.hs, fd = cfg.fdim;
const int64_t sw = 2 + 2 * rk;
RAD_ISSUE_N(c, op_logits, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.logits, S));
RAD_ISSUE_N(c, op_stats, S, brows(w.logits, S), RAD_NONE, brows(w.stats, S));
if (op_sgath) RAD_ISSUE(c, op_sgath, brows(w.stats, S), brows(w.sgath, S));
RAD_ISSUE_N(c, op_pas, S, brows(w.sel_h, S), RAD_W(w_pass), RAD_W(b_pass), RAD_NONE,
brows(w.pas, S));
RAD_ISSUE_N(c, op_cand, S, op_sgath ? brows(w.sgath, S) : brows(w.stats, S), brows(w.pas, S),
RAD_W(ln_w), RAD_W(ln_b), RAD_W(up_w), RAD_W(up_b), RAD_W(w_slot), RAD_W(w_rank),
brow_slice(w.cand, 0, Lr, 1), brows(w.feat, Lr), brows(w.hh, Lr));
(void)sw;
RAD_ISSUE_N(c, op_emb, Lr, brow_slice(w.cand, 0, Lr, 1), RAD_W(w_tok), brows(w.emb, Lr));
if (op_emb_ar) RAD_ISSUE_N(c, op_emb_ar, Lr * E, brows(w.emb, Lr), RAD_NONE);
RAD_ISSUE_N(c, op_tokp, Lr, brows(w.emb, Lr), RAD_W(w_tokp), RAD_W(b_tokp), brows(w.hh, Lr),
brows(w.hh, Lr));
RAD_ISSUE_N(c, op_fdn, Lr, brows(w.feat, Lr), RAD_W(w_fdn), RAD_W(b_fdn), brows(w.hh, Lr),
brows(w.hh, Lr));
for (int64_t l = 0; l < cfg.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_anorm[i], Lr, brows(w.hh, Lr), RAD_W(w_anorm[i]), brows(w.y, Lr));
RAD_ISSUE_N(c, op_in[i], Lr, brows(w.y, Lr), RAD_W(w_in[i]), RAD_W(b_in[i]), RAD_NONE,
brows(w.qkv, Lr));
RAD_ISSUE_N(c, op_attn, Lr, brows(w.qkv, Lr), RAD_W(w_rel), RAD_W(w_same), brows(w.att, Lr));
RAD_ISSUE_N(c, op_out[i], Lr, brows(w.att, Lr), RAD_W(w_out[i]), RAD_W(b_out[i]),
brows(w.hh, Lr), brows(w.hh, Lr));
RAD_ISSUE_N(c, op_mnorm[i], Lr, brows(w.hh, Lr), RAD_W(w_mnorm[i]), brows(w.y, Lr));
RAD_ISSUE_N(c, op_up[i], Lr, brows(w.y, Lr), RAD_W(w_up[i]), RAD_W(b_up[i]), RAD_NONE,
brows(w.up, Lr));
RAD_ISSUE_N(c, op_silu_up, Lr, brows(w.up, Lr), brows(w.ups, Lr));
RAD_ISSUE_N(c, op_dn[i], Lr, brows(w.ups, Lr), RAD_W(w_dn[i]), RAD_W(b_dn[i]),
brows(w.hh, Lr), brows(w.hh, Lr));
}
RAD_ISSUE_N(c, op_onorm, Lr, brows(w.hh, Lr), RAD_W(w_onorm), brows(w.y, Lr));
RAD_ISSUE_N(c, op_anc, n, RAD_B(w.c), praw(batch->anchor_rows, RAD_I32, n), brows(w.anc, n));
RAD_ISSUE_N(c, op_ctx, n, brows(w.anc, n), RAD_W(w_ctx), RAD_W(b_ctx), RAD_NONE, brows(w.ast, n));
RAD_ISSUE_N(c, op_annorm, n, brows(w.ast, n), RAD_W(w_annorm), brows(w.an, n));
RAD_ISSUE_N(c, op_factor, Lr, brows(w.y, Lr), brows(w.an, n), brows(w.cat, Lr));
RAD_ISSUE_N(c, op_fac, Lr, brows(w.cat, Lr), RAD_W(w_fac), RAD_W(b_fac), RAD_NONE,
brows(w.fh, Lr));
RAD_ISSUE_N(c, op_silu_f, Lr, brows(w.fh, Lr), brows(w.fhs, Lr));
RAD_ISSUE_N(c, op_edge, Lr, brows(w.fhs, Lr), RAD_W(w_edge), RAD_W(b_edge), RAD_NONE,
brows(w.edges, Lr));
RAD_ISSUE_N(c, op_aout, n, brows(w.an, n), RAD_W(w_aout), RAD_W(b_aout), RAD_NONE,
brows(w.aout, n));
RAD_ISSUE_N(c, op_walk, n, brows(w.edges, Lr), brows(w.aout, n),
brow_slice(w.cand, 0, Lr, 1), brows(w.tokens, n), RAD_NONE);
(void)E; (void)hs; (void)fd;
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_LILICORR_H */
+16 -7
View File
@@ -132,9 +132,9 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
swiglu_limit)); swiglu_limit));
/* The fold: decl_gated_fold (an fp8a8 tile) for block-fp8 weights, decl_gated_fold_mx for plain /* The fold: decl_gated_fold (an fp8a8 tile) for block-fp8 weights, decl_gated_fold_mx for plain
* MXFP4 at one to 16 rows (eight where K is short). Other gate_up encodings (M2XFP4 included), * MXFP4 at one to 16 rows (eight where K is short), decl_gated_fold_iqr for an IQR weight
* and a clamped (swiglu_limit) product, take the pair. Over int8 codes only a host kernel would * whose input and output are the rotated int8 trunk's fed pairs, to 16 rows. Other gate_up
* take it, which would pin the layer's weights to the host. */ * encodings (M2XFP4 included), and a clamped (swiglu_limit) product, take the pair. */
const bool fold_ok = swiglu_limit <= 0 && !gate_up.f32_scale; const bool fold_ok = swiglu_limit <= 0 && !gate_up.f32_scale;
if (fold_ok && !gate_up.bf16 && !gate_up.mx && !gate_up.m2x && !gate_up.paro5 && !gate_up.w4 && if (fold_ok && !gate_up.bf16 && !gate_up.mx && !gate_up.m2x && !gate_up.paro5 && !gate_up.w4 &&
!gate_up.i8) !gate_up.i8)
@@ -144,6 +144,14 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s, w.ffn.x } ? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s, w.ffn.x }
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s }, : std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s },
&gated_rows, wide_fold); &gated_rows, wide_fold);
else if (fold_ok && gate_up.iqr && w.h.q8_fed && w.h.q8_rot && w.ffn.q8_fed && w.ffn.q8_rot)
op_gated = decl_gated_fold_iqr(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
{ w.h.q8, w.h.s8 },
gq_ffn.want_x
? std::initializer_list<rad_buf>{ w.ffn.q8, w.ffn.s8,
w.ffn.x }
: std::initializer_list<rad_buf>{ w.ffn.q8, w.ffn.s8 },
&gated_rows);
else if (fold_ok && gate_up.mx && !gate_up.paro) else if (fold_ok && gate_up.mx && !gate_up.paro)
op_gated = decl_gated_fold_mx(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws, op_gated = decl_gated_fold_mx(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
gate_up.wref, { w.h.q, w.h.s }, gate_up.wref, { w.h.q, w.h.s },
@@ -207,10 +215,11 @@ inline void MlpFP8::body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK), brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK),
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE); gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
} else if (op_gated && rows <= gated_rows) { } else if (op_gated && rows <= gated_rows) {
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd), /* The fp8a8 fold's E4M3 pairs, or the IQR fold's int8 ones (cq / cs: the fed pair). */
brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w), RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.cq(), r0, rows, g.n_embd),
RAD_W(gate_up.ws), brow_slice(w.ffn.q, r0, rows, g.n_ff), brow_slice(w.h.cs(), r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK), RAD_W(gate_up.ws), brow_slice(w.ffn.cq(), r0, rows, g.n_ff),
brow_slice(w.ffn.cs(), r0, rows, g.n_ff / RAD_FP8_BLOCK),
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE); gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
} else { } else {
gate_up.step(c, w.h, w.gate_up, T, r0, rows); gate_up.step(c, w.h, w.gate_up, T, r0, rows);
+85 -33
View File
@@ -182,8 +182,19 @@ struct MoeFP8 {
/* Block-fp8 experts whose scale plane is f32 (format 9, dtype fp8a8f32). */ /* Block-fp8 experts whose scale plane is f32 (format 9, dtype fp8a8f32). */
int expert_f32_scale = 0; int expert_f32_scale = 0;
double route_scale = 1.0; double route_scale = 1.0;
/* With `sigmoid_router`: group-limited selection over `n_group` groups, `topk_group` kept
* (router_sigmoid_group_topk; Ling-3.0). 1 is GLM's single group. The fused selection and
* sort is single-group, so a grouped router runs the separate pair. */
int64_t n_group = 1, topk_group = 1;
/* Clamp of the SwiGLU product (swiglu_clamped); 0 is none. */ /* Clamp of the SwiGLU product (swiglu_clamped); 0 is none. */
double swiglu_limit = 0.0; double swiglu_limit = 0.0;
/* The shared arm's clamp where it differs from the routed one (Ling-3.0 clamps its shared
* expert at 5 or 7 and its routed ones at 4, in different layers); negative: the routed
* arm's. */
double shared_swiglu_limit = -1.0;
/* Clip after the SiLU (`swiglu_step`) rather than before it (`swiglu_clamped`), for both
* arms. */
int swiglu_step = 0;
/* With `swiglu_limit`: the clamped product and its quantiser as one launch /* With `swiglu_limit`: the clamped product and its quantiser as one launch
* (GateQuantFP8::fuse_clamped), for the routed and the shared arm. */ * (GateQuantFP8::fuse_clamped), for the routed and the shared arm. */
int swiglu_quant = 0; int swiglu_quant = 0;
@@ -196,6 +207,19 @@ struct MoeFP8 {
* At TP1 the ungated gather preserves both roundings; TP>1 reduces each arm separately * At TP1 the ungated gather preserves both roundings; TP>1 reduces each arm separately
* before combining, so its gather cannot fold the shared output. */ * before combining, so its gather cannot fold the shared output. */
int shared_fp32_combine = 0; int shared_fp32_combine = 0;
/* Experts without a gate (Nemotron-H): one projection up (`up_proj`), relu(x)^2, and down,
* so the first GEMM is n_ff_exp wide rather than 2 * n_ff_exp and the quantiser between
* the GEMMs squares rather than gates (GateQuantFP8's "relu2"). The routed arm only: such a
* family's shared expert is the caller's. */
int ungated = 0;
/* The router's input width when it is not the experts' (Nemotron-H's latent experts: the
* router scores the full hidden state, the experts read a narrower projection of it, and
* this block's Geom is the experts'). 0 means n_embd. With it the router reads
* Wire::route. The sigmoid router only. */
int64_t router_k = 0;
/* The caller reduces the block's delta across ranks, because it applies more linear work
* to it first (Nemotron-H's latent up-projection); no all-reduce is declared. */
int no_reduce = 0;
/* 4-bit experts (`i4*bf16[1x128]`) rather than E4M3 (`fp8_e4m3*bf16[128x128]`); for /* 4-bit experts (`i4*bf16[1x128]`) rather than E4M3 (`fp8_e4m3*bf16[128x128]`); for
* Qwen3.8-Flash-Next this decides whether the model fits two cards (see the `moe_gemm_w4a8` * Qwen3.8-Flash-Next this decides whether the model fits two cards (see the `moe_gemm_w4a8`
* registry row). It is the stored encoding: probe() reads it from the first expert's * registry row). It is the stored encoding: probe() reads it from the first expert's
@@ -267,6 +291,8 @@ struct MoeFP8 {
struct Wire { struct Wire {
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */ rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
ActFP8 h{}; /* [max_tok, n_embd] normed input, then the block's delta */ ActFP8 h{}; /* [max_tok, n_embd] normed input, then the block's delta */
/* The router's input when Config::router_k is set; `h` otherwise. */
rad_buf route = 0; /* [max_tok, router_k] bf16 */
/* Rotated codes of the same input (only `q` and `s`; `x` is `h`'s). Declared only with /* Rotated codes of the same input (only `q` and `s`; `x` is `h`'s). Declared only with
* `expert_rot`: the routed gate_up reads them, the shared expert reads `h`'s. */ * `expert_rot`: the routed gate_up reads them, the shared expert reads `h`'s. */
ActFP8 hr{}; /* [max_tok, n_embd] q + scale only */ ActFP8 hr{}; /* [max_tok, n_embd] q + scale only */
@@ -547,17 +573,19 @@ inline int moe_expert_sources(RadBuilder* b, Names& nm, const char* tag, const c
/* The gate_up and down name maps of one expert: a dim-0 slice of the stacked tensors, or the /* The gate_up and down name maps of one expert: a dim-0 slice of the stacked tensors, or the
* checkpoint's per-expert gate and up joined along rows. `gate_up` false maps down alone. */ * checkpoint's per-expert gate and up joined along rows. `gate_up` false maps down alone. */
inline int moe_map_gate_up(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw, inline int moe_map_gate_up(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw,
long long ge) { long long ge, bool ungated = false) {
if (src.experts_gate_up) return map_slice(b, guw, src.experts_gate_up, (int)ge); if (src.experts_gate_up) return map_slice(b, guw, src.experts_gate_up, (int)ge);
if (src.experts_gate && src.experts_up) if (src.experts_gate && src.experts_up)
return map_slice_concat(b, guw, {src.experts_gate, src.experts_up}, (int)ge); return map_slice_concat(b, guw, {src.experts_gate, src.experts_up}, (int)ge);
/* Ungated experts (Nemotron-H) have no gate_proj: the first GEMM is up_proj alone. */
if (ungated) return map_copy(b, guw, nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge));
return map_concat(b, guw, {nm.ckpt("%s.%lld.gate_proj.weight", src.experts, ge), return map_concat(b, guw, {nm.ckpt("%s.%lld.gate_proj.weight", src.experts, ge),
nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge)}); nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge)});
} }
inline int moe_map_expert(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw, inline int moe_map_expert(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw,
const char* dnw, long long ge, bool gate_up) { const char* dnw, long long ge, bool gate_up) {
if (gate_up) RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge)); if (gate_up) RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge, src.cfg.ungated));
if (src.experts_gate_up || src.experts_gate) if (src.experts_gate_up || src.experts_gate)
return map_slice(b, dnw, src.experts_down, (int)ge); return map_slice(b, dnw, src.experts_down, (int)ge);
return map_copy(b, dnw, nm.ckpt("%s.%lld.down_proj.weight", src.experts, ge)); return map_copy(b, dnw, nm.ckpt("%s.%lld.down_proj.weight", src.experts, ge));
@@ -584,7 +612,7 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
int f = 0; int f = 0;
for (long long ge = g0; ge < gn && ge <= g0 + kMaxProtected; ++ge) { for (long long ge = g0; ge < gn && ge <= g0 + kMaxProtected; ++ge) {
const char* guw = nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, ge); const char* guw = nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, ge);
RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge)); RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge, cfg->ungated));
cfg->probed_count = ge - g0 + 1; cfg->probed_count = ge - g0 + 1;
RadEncoding e{}; RadEncoding e{};
f = 0; f = 0;
@@ -618,6 +646,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
int ar_in, bool ar_out_) { int ar_in, bool ar_out_) {
g = geom; c = src.cfg; w = wire; layer = l; g = geom; c = src.cfg; w = wire; layer = l;
ar_out = ar_out_; ar_out = ar_out_;
if (c.n_group > 1) c.router_fuse = 0;
const double sh_limit = c.shared_swiglu_limit < 0 ? c.swiglu_limit : c.shared_swiglu_limit;
/* 0 means not expert-parallel: this rank owns every expert. */ /* 0 means not expert-parallel: this rank owns every expert. */
if (c.n_expert_all <= 0) c.n_expert_all = c.n_expert; if (c.n_expert_all <= 0) c.n_expert_all = c.n_expert;
if (c.n_expert <= 0 || c.top_k <= 0 || c.top_k > c.n_expert_all || c.n_ff_exp <= 0) if (c.n_expert <= 0 || c.top_k <= 0 || c.top_k > c.n_expert_all || c.n_ff_exp <= 0)
@@ -639,6 +669,21 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
"BF16 shared arm and routed output\n", l); "BF16 shared arm and routed output\n", l);
return RAD_E_INVAL; return RAD_E_INVAL;
} }
/* 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";
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 "
"without a shared arm in this block\n");
return RAD_E_INVAL;
}
if (c.router_k && (!c.sigmoid_router || !w.route)) {
fprintf(stderr, "radiance: a router over another input than the experts' is the sigmoid "
"router reading Wire::route\n");
return RAD_E_INVAL;
}
/* Whether `w.sgate` is excluded from buffer sharing; set with the shared arm and required by /* Whether `w.sgate` is excluded from buffer sharing; set with the shared arm and required by
* the fused router's gate write (see there). */ * the fused router's gate write (see there). */
bool sgate_concurrent = false; bool sgate_concurrent = false;
@@ -764,9 +809,13 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
rc.rows = c.rows; rc.rows = c.rows;
rc.norm = c.norm_topk; rc.norm = c.norm_topk;
rc.route_scale = c.route_scale; rc.route_scale = c.route_scale;
const GlmRouter::Wire wire{ w.h.x, w.logits, w.ids, w.ew }; rc.groups = c.n_group;
rc.topk_groups = c.topk_group;
const GlmRouter::Wire wire{ c.router_k ? w.route : w.h.x, w.logits, w.ids, w.ew };
const GlmRouter::Src rs{ src.router, src.router_bias }; const GlmRouter::Src rs{ src.router, src.router_bias };
RAD_ARCH_TRY(glm_router.declare(b, nm, g, l, nm.f("blk.%d.glm_router", l), rc, wire, rs)); Geom rg = g;
if (c.router_k) rg.n_embd = c.router_k;
RAD_ARCH_TRY(glm_router.declare(b, nm, rg, l, nm.f("blk.%d.glm_router", l), rc, wire, rs));
w_router = glm_router.projection; w_router = glm_router.projection;
op_router = glm_router.op_project; op_router = glm_router.op_project;
op_topk = glm_router.op_select; op_topk = glm_router.op_select;
@@ -931,7 +980,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
} }
const int sh_row = ep ? RAD_SHARD_NONE : RAD_SHARD_ROW; const int sh_row = ep ? RAD_SHARD_NONE : RAD_SHARD_ROW;
const int sh_col = ep ? RAD_SHARD_NONE : RAD_SHARD_COL; const int sh_col = ep ? RAD_SHARD_NONE : RAD_SHARD_COL;
const int n_parts = ep ? 0 : 2; const int n_parts = ep ? 0 : (int)gu;
/* The scale grid: one per 128x128 tile for E4M3, one per row per 128 of K for 4-bit (per 32 /* The scale grid: one per 128x128 tile for E4M3, one per row per 128 of K for 4-bit (per 32
* for MXFP4). `sdiv` is how many weight rows or columns one scale covers along the split * for MXFP4). `sdiv` is how many weight rows or columns one scale covers along the split
* dimension. */ * dimension. */
@@ -969,10 +1018,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
return RAD_E_INVAL; return RAD_E_INVAL;
} }
for (int64_t e = 0; e < ne; ++e) { for (int64_t e = 0; e < ne; ++e) {
const int64_t parts[2] = { c.n_ff_exp, c.n_ff_exp }; 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, 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)), (long long)(c.expert_base + e)),
RAD_BF16, {2 * c.n_ff_exp, g.n_embd}, RAD_ACCESS_CONDITIONAL, RAD_BF16, {gu * c.n_ff_exp, g.n_embd}, RAD_ACCESS_CONDITIONAL,
sh_row, grp_expert_slot(l, (int)e, 0), 0, parts, n_parts); sh_row, grp_expert_slot(l, (int)e, 0), 0, parts, n_parts);
if (!w_gu[(size_t)e]) return RAD_E_INVAL; if (!w_gu[(size_t)e]) return RAD_E_INVAL;
} }
@@ -986,7 +1035,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* Row orders as for the quantised GEMMs (see `a_order` below): gate_up gathers token rows, /* Row orders as for the quantised GEMMs (see `a_order` below): gate_up gathers token rows,
* down reads sorted rows. */ * down reads sorted rows. */
op_gu = rw(b, rad_decl_op(b, "moe_gemm", op_gu = rw(b, rad_decl_op(b, "moe_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * c.n_ff_exp), RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * c.n_ff_exp),
RAD_INT("K", g.n_embd), RAD_INT("n_expert", ne), RAD_INT("K", g.n_embd), RAD_INT("n_expert", ne),
RAD_INT("top_k", c.top_k), RAD_STR("a_order", "token"), RAD_INT("top_k", c.top_k), RAD_STR("a_order", "token"),
RAD_STR("dtype", "bf16")), RAD_STR("dtype", "bf16")),
@@ -996,8 +1045,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* (rad_fp8.h: GateQuantFP8). */ * (rad_fp8.h: GateQuantFP8). */
Geom gx = g; Geom gx = g;
gx.w_bf16 = true; gx.w_bf16 = true;
RAD_ARCH_TRY(gq_exp.declare(b, gx, w.egu, w.eff, c.n_ff_exp, "silu", c.rows * c.top_k, RAD_ARCH_TRY(gq_exp.declare(b, gx, w.egu, w.eff, c.n_ff_exp, gact, c.rows * c.top_k,
true, false, c.swiglu_limit)); true, false, c.swiglu_limit, c.swiglu_step != 0));
op_dn = rw(b, rad_decl_op(b, "moe_gemm", op_dn = rw(b, rad_decl_op(b, "moe_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd), RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", c.n_ff_exp), RAD_INT("n_expert", ne), RAD_INT("K", c.n_ff_exp), RAD_INT("n_expert", ne),
@@ -1015,7 +1064,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
rad_weight& h = w_gu[(size_t)s]; rad_weight& h = w_gu[(size_t)s];
h = decl_view(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, h = decl_view(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
(long long)(c.expert_base + e)), (long long)(c.expert_base + e)),
nullptr, ecodes, edt[0], {2 * wq[q], g.n_embd}, nullptr, ecodes, edt[0], {gu * wq[q], g.n_embd},
RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0), RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0),
parts, n_parts); parts, n_parts);
if (!h) return RAD_E_INVAL; if (!h) return RAD_E_INVAL;
@@ -1031,7 +1080,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
(long long)(c.expert_base + e)), (long long)(c.expert_base + e)),
escale, sdt, escale, sdt,
{(c.expert_w4 || c.expert_mx) ? 2 * wq[q] : fp8_blocks(2 * wq[q]), {(c.expert_w4 || c.expert_mx) ? gu * wq[q] : fp8_blocks(gu * wq[q]),
(c.expert_w4 || c.expert_mx) ? g.n_embd / sgk : fp8_blocks(g.n_embd)}, (c.expert_w4 || c.expert_mx) ? g.n_embd / sgk : fp8_blocks(g.n_embd)},
RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0), RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0),
parts, n_parts); parts, n_parts);
@@ -1107,22 +1156,22 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const std::vector<rad_weight> tab = tables(w_gu, w_gus); const std::vector<rad_weight> tab = tables(w_gu, w_gus);
rad_op h = ncls == 4 rad_op h = ncls == 4
? rad_decl_op(b, "moe_gemm_q_mod4", ? rad_decl_op(b, "moe_gemm_q_mod4",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wq[0]), RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg), RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK), RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]), RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
RAD_INT("N_1", 2 * wq[1]), RAD_INT("K_1", g.n_embd), RAD_INT("N_1", gu * wq[1]), RAD_INT("K_1", g.n_embd),
RAD_INT("N_2", 2 * wq[2]), RAD_INT("K_2", g.n_embd), RAD_INT("N_2", gu * wq[2]), RAD_INT("K_2", g.n_embd),
RAD_INT("N_3", 2 * wq[3]), RAD_INT("K_3", g.n_embd), RAD_INT("N_3", gu * wq[3]), RAD_INT("K_3", g.n_embd),
RAD_INT("parts", 2)), RAD_INT("parts", gu)),
tab.data(), (int)tab.size()) tab.data(), (int)tab.size())
: rad_decl_op(b, "moe_gemm_q", : rad_decl_op(b, "moe_gemm_q",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wq[0]), RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg), RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK), RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]), RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
RAD_INT("N_odd", 2 * wq[1]), RAD_INT("K_odd", g.n_embd), RAD_INT("N_odd", gu * wq[1]), RAD_INT("K_odd", g.n_embd),
RAD_INT("parts", 2)), RAD_INT("parts", gu)),
tab.data(), (int)tab.size()); tab.data(), (int)tab.size());
op_gu = rw(b, h, {rot ? w.hr.q : w.h.q, rot ? w.hr.s : w.h.s, w.sorted, w.eoff}, {w.egu}); op_gu = rw(b, h, {rot ? w.hr.q : w.h.q, rot ? w.hr.s : w.h.s, w.sorted, w.eoff}, {w.egu});
} }
@@ -1130,8 +1179,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* which takes the codes alone (no bf16 product is written), so the gated quantiser resolves to * which takes the codes alone (no bf16 product is written), so the gated quantiser resolves to
* the rotated op at no extra launch. */ * the rotated op at no extra launch. */
gq_exp.fuse_clamped = c.swiglu_quant != 0; gq_exp.fuse_clamped = c.swiglu_quant != 0;
RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, w.eff, c.n_ff_exp, "silu", c.rows * c.top_k, RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, w.eff, c.n_ff_exp, gact, c.rows * c.top_k,
false, rot, c.swiglu_limit)); false, rot, c.swiglu_limit, c.swiglu_step != 0));
{ {
const std::vector<rad_weight> tab = tables(w_dn, w_dns); const std::vector<rad_weight> tab = tables(w_dn, w_dns);
rad_op h = ncls == 4 rad_op h = ncls == 4
@@ -1184,7 +1233,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* the plain even split with no span. */ * the plain even split with no span. */
psh_row = RAD_SHARD_ROW; psh_row = RAD_SHARD_ROW;
psh_col = RAD_SHARD_COL; psh_col = RAD_SHARD_COL;
pparts = 2; pparts = (int)gu;
if (full % g.world == 0 && (full / g.world) % 64 == 0) { if (full % g.world == 0 && (full / g.world) % 64 == 0) {
wp = full / g.world; wp = full / g.world;
} else if (full % 64 || full / 64 < g.world) { } else if (full % 64 || full / 64 < g.world) {
@@ -1206,7 +1255,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const int64_t parts[2] = { wp, wp }; 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, 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])), (long long)(c.expert_base + prot[(size_t)j])),
RAD_BF16, {2 * wp, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_BF16, {gu * wp, g.n_embd}, RAD_ACCESS_PER_TOKEN,
psh_row, grp_layer(l), 0, parts, pparts); psh_row, grp_layer(l), 0, parts, pparts);
if (!w_pgu[(size_t)j]) return RAD_E_INVAL; if (!w_pgu[(size_t)j]) return RAD_E_INVAL;
if (phi > 0) RAD_ARCH_TRY(rad_weight_shard_span(b, w_pgu[(size_t)j], plo, phi)); if (phi > 0) RAD_ARCH_TRY(rad_weight_shard_span(b, w_pgu[(size_t)j], plo, phi));
@@ -1221,11 +1270,11 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
} }
/* The gate_up and gate outputs, bf16, one sorted row each; regular experts' rows are /* The gate_up and gate outputs, bf16, one sorted row each; regular experts' rows are
* unused. */ * unused. */
b_pgu = decl_b(b, nm.f("blk.%d.moe_prot_gu", l), RAD_BF16, {c.rows * c.top_k, 2 * wp}); b_pgu = decl_b(b, nm.f("blk.%d.moe_prot_gu", l), RAD_BF16, {c.rows * c.top_k, gu * wp});
pff.x = decl_b(b, nm.f("blk.%d.moe_prot_ff", l), RAD_BF16, {c.rows * c.top_k, wp}); pff.x = decl_b(b, nm.f("blk.%d.moe_prot_ff", l), RAD_BF16, {c.rows * c.top_k, wp});
if (!b_pgu || !pff.x) return RAD_E_INVAL; if (!b_pgu || !pff.x) return RAD_E_INVAL;
op_pgu = rw(b, rad_decl_op(b, "moe_gemm", op_pgu = rw(b, rad_decl_op(b, "moe_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wp), RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wp),
RAD_INT("K", g.n_embd), RAD_INT("n_expert", np), RAD_INT("K", g.n_embd), RAD_INT("n_expert", np),
RAD_INT("top_k", c.top_k), RAD_STR("a_order", "token"), RAD_INT("top_k", c.top_k), RAD_STR("a_order", "token"),
RAD_STR("dtype", "bf16")), RAD_STR("dtype", "bf16")),
@@ -1233,8 +1282,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
{w.h.x, w.sorted, w.eoff}, {b_pgu}); {w.h.x, w.sorted, w.eoff}, {b_pgu});
Geom gx = g; Geom gx = g;
gx.w_bf16 = true; gx.w_bf16 = true;
RAD_ARCH_TRY(gq_prot.declare(b, gx, b_pgu, pff, wp, "silu", c.rows * c.top_k, true, RAD_ARCH_TRY(gq_prot.declare(b, gx, b_pgu, pff, wp, gact, c.rows * c.top_k, true,
false, c.swiglu_limit)); false, c.swiglu_limit, c.swiglu_step != 0));
op_pdn = rw(b, rad_decl_op(b, "moe_gemm", op_pdn = rw(b, rad_decl_op(b, "moe_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd), RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", wp), RAD_INT("n_expert", np), RAD_INT("K", wp), RAD_INT("n_expert", np),
@@ -1374,7 +1423,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.q8)); RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.q8));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.s8)); RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.s8));
} }
if (!w.sff.q || c.swiglu_limit>0 || (sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8))) if (!w.sff.q || sh_limit>0 || (sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8)))
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.x)); RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.x));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sout)); RAD_ARCH_TRY(rad_buf_concurrent(b, w.sout));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sgate)); RAD_ARCH_TRY(rad_buf_concurrent(b, w.sgate));
@@ -1391,7 +1440,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
gq_sh.fuse_clamped = c.swiglu_quant != 0; 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, 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_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8), false,
c.swiglu_limit)); sh_limit, c.swiglu_step != 0));
RAD_ARCH_TRY(sh_down.declare(b, nm, g, down_base, RAD_ARCH_TRY(sh_down.declare(b, nm, g, down_base,
g.n_embd, c.n_ff_shared, RAD_SHARD_COL, grp_layer(l), g.n_embd, c.n_ff_shared, RAD_SHARD_COL, grp_layer(l),
{ shared_down }, { shared_down },
@@ -1515,7 +1564,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
} }
} }
if (g.world > 1) { if (g.world > 1 && !c.no_reduce) {
const auto all_reduce = [&](const char* dtype, rad_buf buffer) { const auto all_reduce = [&](const char* dtype, rad_buf buffer) {
return rw(b, RAD_OP(b, "all_reduce", return rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -1536,7 +1585,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
} }
/* The same collective for a caller that runs it beside other work (issue_ar, a pipelined /* The same collective for a caller that runs it beside other work (issue_ar, a pipelined
* prefill): at `overlap` 1 it gets the rows that hold fewer CUs while waiting on the link. */ * prefill): at `overlap` 1 it gets the rows that hold fewer CUs while waiting on the link. */
if (g.world > 1 && ar_overlap > 0) if (g.world > 1 && !c.no_reduce && ar_overlap > 0)
op_ar_ov = rw(b, RAD_OP(b, "all_reduce", op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
@@ -1784,6 +1833,9 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
(!calib_dne_failed && (!calib_dne_failed &&
calib_dne.write(gram_dn_stem, c.expert_base, gram_domain, calib_dne.write(gram_dn_stem, c.expert_base, gram_domain,
rad_rank(c_))); rad_rank(c_)));
/* Written: the host sums are done with (a layer's can be gigabytes). */
calib_dne.acc = {};
calib_dne.rows = {};
calib_done = true; calib_done = true;
if (layer == 0) if (layer == 0)
std::fprintf(stderr, "radiance: calibration wrote layer Hessians after %lld " std::fprintf(stderr, "radiance: calibration wrote layer Hessians after %lld "
+42 -3
View File
@@ -25,7 +25,13 @@
* safetensors file per input, <dir>/<stem>.safetensors, holding `hessian_upper`, f32 * safetensors file per input, <dir>/<stem>.safetensors, holding `hessian_upper`, f32
* [k * (k + 1) / 2], row i's entries k2 = i .. k-1 after row i-1's, and metadata naming `k`, the * [k * (k + 1) / 2], row i's entries k2 = i .. k-1 after row i-1's, and metadata naming `k`, the
* rows summed and the checkpoint linears that read the input. H is the raw sum; divide by `rows` * rows summed and the checkpoint linears that read the input. H is the raw sum; divide by `rows`
* for the mean second moment. */ * for the mean second moment.
*
* An int8 trunk (site_i8, one rank only) is recorded from the codes and scales its GEMMs actually
* read, so H includes what the model's own quantisation did to the input -- the input a quantised
* model feeds each layer, for GPTQ against the error it inherits. Codes a rotating producer wrote
* are in the rotated domain; the file's metadata then names it (`domain`: the Hadamard width), as
* RADGRAM2's header does, and the reader converts. */
#pragma once #pragma once
#include <arch/rad_arch.h> #include <arch/rad_arch.h>
@@ -52,6 +58,8 @@ struct CalibFull {
rad_op op_gather = 0; /* the columns of every rank into `gathered`; 0 when replicated */ rad_op op_gather = 0; /* the columns of every rank into `gathered`; 0 when replicated */
rad_op op_gram = 0; /* declared on the owner only */ rad_op op_gram = 0; /* declared on the owner only */
bool owner = false; bool owner = false;
rad_buf q8 = 0, s8 = 0; /* site_i8: the int8 codes and their f32 (row, 128) scales */
uint32_t domain = 0; /* site_i8: the codes' rotation width, 0 for none */
std::vector<float> tri; /* the owner's accumulator, upper triangle packed */ std::vector<float> tri; /* the owner's accumulator, upper triangle packed */
}; };
@@ -156,6 +164,32 @@ struct CalibFull {
return RAD_OK; return RAD_OK;
} }
/* One input of layer `layer` from an int8 trunk's codes `q8` and scales `s8` (see the file
* comment): the whole input on one rank, `domain` the Hadamard width the codes were rotated by
* (0 for none). */
int site_i8(RadBuilder* b, const Geom& g, int64_t layer, std::string stem, std::string linears,
rad_buf q8, rad_buf s8, int64_t K, uint32_t domain) {
if (world > 1 || !q8 || !s8 || K > kmax) return RAD_E_INVAL;
Site s;
s.stem = std::move(stem);
s.linears = std::move(linears);
s.K = s.k_local = K;
s.owner = true;
s.q8 = q8;
s.s8 = s8;
s.domain = domain;
(void)layer;
s.op_gram = rw(b, RAD_OP(b, "gram_accum",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
RAD_INT("group", 128), RAD_STR("dtype", "i8a8"),
RAD_INT("upper", 1)),
RAD_NOWEIGHTS),
{ q8, s8, scratch }, { scratch });
if (!s.op_gram) return RAD_E_INVAL;
sites.push_back(std::move(s));
return RAD_OK;
}
/* Site `i` over a step's T rows: gather (every rank), then on the owner the Gram into the /* 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. */ * scratch, copied to a free square, the scratch zeroed, and the square handed to the worker. */
void tap(RadCtx* c, size_t i, int64_t T) { void tap(RadCtx* c, size_t i, int64_t T) {
@@ -186,7 +220,10 @@ struct CalibFull {
} }
} }
const int64_t K = s.K; const int64_t K = s.K;
RAD_ISSUE_N(c, s.op_gram, T, a, RAD_NONE, praw2(dev, RAD_F32, K, K)); if (s.q8)
RAD_ISSUE_N(c, s.op_gram, T, brows(s.q8, T), brows(s.s8, T), praw2(dev, RAD_F32, K, K));
else
RAD_ISSUE_N(c, s.op_gram, T, a, RAD_NONE, praw2(dev, RAD_F32, K, K));
/* `upper` 1 writes no entry below the diagonal, so only the upper triangle comes back: /* `upper` 1 writes no entry below the diagonal, so only the upper triangle comes back:
* band by band of kBand rows, each from its first row's diagonal on, about half the * band by band of kBand rows, each from its first row's diagonal on, about half the
* square's bytes. The link is what a step's taps wait on, 25 GB a step on each rank of * square's bytes. The link is what a step's taps wait on, 25 GB a step on each rank of
@@ -317,7 +354,9 @@ private:
const uint64_t bytes = (uint64_t)s.tri.size() * 4; const uint64_t bytes = (uint64_t)s.tri.size() * 4;
std::string hdr = "{\"__metadata__\":{\"k\":\"" + std::to_string(s.K) + "\",\"rows\":\"" + std::string hdr = "{\"__metadata__\":{\"k\":\"" + std::to_string(s.K) + "\",\"rows\":\"" +
std::to_string(seen) + "\",\"layout\":\"upper triangle, row-major, packed\"," std::to_string(seen) + "\",\"layout\":\"upper triangle, row-major, packed\","
"\"linears\":\"" + s.linears + "\"},\"hessian_upper\":{\"dtype\":\"F32\"," "\"linears\":\"" + s.linears + "\"" +
(s.domain ? ",\"domain\":\"" + std::to_string(s.domain) + "\"" : std::string()) +
"},\"hessian_upper\":{\"dtype\":\"F32\","
"\"shape\":[" + std::to_string(s.tri.size()) + "],\"data_offsets\":[0," + "\"shape\":[" + std::to_string(s.tri.size()) + "],\"data_offsets\":[0," +
std::to_string(bytes) + "]}}"; std::to_string(bytes) + "]}}";
while (hdr.size() % 8) hdr += ' '; while (hdr.size() % 8) hdr += ' ';
+92 -6
View File
@@ -141,8 +141,9 @@ inline int QuantFP8::declare(RadBuilder* b, const Geom& g, const ActFP8& act, in
if (g.w_bf16) { op = 0; return a.x ? RAD_OK : RAD_E_INVAL; } 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.x || !a.cq() || !a.cs() || n <= 0) return RAD_E_INVAL;
/* `dtype` is the input's (bf16); the op name gives the output format. An input fed at int8 /* `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. */ * codes is quantised by quant_act_i8g into its int8 pair, or by had_quant_act_i8g where they
op = rw(b, RAD_OP(b, a.q8_fed ? "quant_act_i8g" : "quant_act_fp8", * are rotated (ActFP8::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_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS), RAD_NOWEIGHTS),
@@ -580,14 +581,20 @@ struct GateQuantFP8 {
* not resolve: `silu_mul` into the bf16 plane (`op`), then `had_quant_act_fp8` over it into the * not resolve: `silu_mul` into the bf16 plane (`op`), then `had_quant_act_fp8` over it into the
* codes (`op_q`). */ * codes (`op_q`). */
rad_op op_q = 0; rad_op op_q = 0;
/* act "relu2" (Nemotron-H's ungated experts): `gate_up` is one part, n wide, and `op` is
* act_mul's relu over it twice, relu(x)^2 into the bf16 plane, which `op_q` quantises (rotated
* for a rotated weight). No fused form yet: the plane is written either way. */
bool ungated = false;
/* Set before declare: the product in bf16 alone, as for bf16 linears, for a consumer that /* Set before declare: the product in bf16 alone, as for bf16 linears, for a consumer that
* quantises its input itself (an int8 linear's op_q). */ * quantises its input itself (an int8 linear's op_q). */
bool silu_only = false; bool silu_only = false;
/* `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 ActFP8& act, int64_t n, int declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act, int64_t n,
const char* act_name = "silu", int64_t max_rows = 0, bool bf16_out = true, const char* act_name = "silu", int64_t max_rows = 0, bool bf16_out = true,
bool rot = false, double limit = 0); bool rot = false, double limit = 0, bool step = false);
void step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0 = 0, int64_t rows = 0) const; void step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0 = 0, int64_t rows = 0) const;
}; };
@@ -596,7 +603,7 @@ struct GateQuantFP8 {
* bf16 output is unrotated either way. */ * bf16 output is unrotated either way. */
inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act, inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act,
int64_t n, const char* act_name, int64_t max_rows, int64_t n, const char* act_name, int64_t max_rows,
bool bf16_out, bool rot, double limit) { bool bf16_out, bool rot, double limit, bool step) {
a = act; a = act;
want_x = bf16_out; want_x = bf16_out;
op_quant = 0; op_quant = 0;
@@ -607,6 +614,28 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
clipped = limit > 0; clipped = limit > 0;
clamped_fused = false; clamped_fused = false;
if (!std::isfinite(limit) || limit < 0) return RAD_E_INVAL; if (!std::isfinite(limit) || limit < 0) return RAD_E_INVAL;
ungated = std::strcmp(act_name, "relu2") == 0;
if (ungated) {
if (!gate_up || !a.x || n <= 0 || clipped || (!bf16 && (!a.cq() || !a.cs())) ||
(rot && a.q8_fed))
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, "act_mul",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("act", "relu"),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ gate_up }, { a.x });
if (!op) return RAD_E_INVAL;
if (bf16) return RAD_OK;
const char* qn = rot ? "had_quant_act_fp8" : a.q8_fed ? "quant_act_i8g" : "quant_act_fp8";
op_q = rw(b, RAD_OP(b, qn,
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ a.x }, { a.cq(), a.cs() });
return op_q ? RAD_OK : RAD_E_INVAL;
}
if (clipped) { if (clipped) {
/* No rotated int8 form: its quantiser would be quant_act_i8g, unrotated; and no clamp /* No rotated int8 form: its quantiser would be quant_act_i8g, unrotated; and no clamp
* with `silu_only`. */ * with `silu_only`. */
@@ -614,7 +643,7 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
std::strcmp(act_name, "silu")) std::strcmp(act_name, "silu"))
return RAD_E_INVAL; return RAD_E_INVAL;
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok; const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
if (fuse_clamped && !bf16 && !a.q8_fed && a.cq() && a.cs() && if (fuse_clamped && !step && !bf16 && !a.q8_fed && a.cq() && a.cs() &&
rad_op_declared(b, "swiglu_clamped_quant_fp8")) { rad_op_declared(b, "swiglu_clamped_quant_fp8")) {
op = op =
RAD_OP(b, "swiglu_clamped_quant_fp8", RAD_OP(b, "swiglu_clamped_quant_fp8",
@@ -631,7 +660,7 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
} }
want_x = true; want_x = true;
op = rw(b, op = rw(b,
RAD_OP(b, "swiglu_clamped", RAD_OP(b, step ? "swiglu_step" : "swiglu_clamped",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("limit", limit), RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("limit", limit),
RAD_STR("dtype", g.dtype)), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS), RAD_NOWEIGHTS),
@@ -701,6 +730,15 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0, inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0,
int64_t rows) const { int64_t rows) const {
if (rows <= 0) rows = T - r0; if (rows <= 0) rows = T - r0;
if (ungated) {
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, n), brow_slice(gate_up, r0, rows, n),
brow_slice(a.x, r0, rows, n));
if (op_q)
RAD_ISSUE_N(c, op_q, rows, brow_slice(a.x, r0, rows, n),
brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
return;
}
if (clamped_fused) { if (clamped_fused) {
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n), RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n),
brow_slice(a.cq(), r0, rows, n), brow_slice(a.cq(), r0, rows, n),
@@ -779,6 +817,13 @@ struct LinearFP8 {
* writes E4M3. Read from the weight's encoding. */ * writes E4M3. Read from the weight's encoding. */
bool i8 = false; bool i8 = false;
rad_op op_q = 0; rad_op op_q = 0;
/* An int8 weight stored rotated (i8a8h, or a rotated four- or five-bit one): its activation
* codes are in the 128-wide Hadamard domain, whoever wrote them (had_quant_act_i8g or a
* rotating producer). */
bool i8_rot = false;
/* With i8_rot: an IQR weight (libr4d's r4d_iqr.h), whose codes decode where they are read: a
* u6 code under a zero, a table, a grid or a trellis. Read from the weight's encoding. */
bool iqr = false;
/* OCP-MXFP4 weight read by `gemm_nt_q` at dtype mxfp4a8 against the usual E4M3 activation pair: /* OCP-MXFP4 weight read by `gemm_nt_q` at dtype mxfp4a8 against the usual E4M3 activation pair:
* e2m1 codes with one E8M0 exponent per 32 of K (libquant `codes=fp4_e2m1 group=32 * e2m1 codes with one E8M0 exponent per 32 of K (libquant `codes=fp4_e2m1 group=32
* scale=e8m0`). libr4d folds each block's exponent into the e4m3 operand against a per-row * scale=e8m0`). libr4d folds each block's exponent into the e4m3 operand against a per-row
@@ -1310,6 +1355,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
const bool asym = known && linear_is_wnh(enc); const bool asym = known && linear_is_wnh(enc);
const bool rot8 = known && (linear_is_w8h(enc) || asym); const bool rot8 = known && (linear_is_w8h(enc) || asym);
i8 = known && (linear_is_w8(enc) || rot8); i8 = known && (linear_is_w8(enc) || rot8);
i8_rot = i8 && rot8;
if (i8) { if (i8) {
if (stored) { if (stored) {
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
@@ -1340,6 +1386,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
const char* sn = nm.f("%s.scale", base); const char* sn = nm.f("%s.scale", base);
/* A narrower i8a8h weight's codes view takes the plane that decodes it too. */ /* A narrower i8a8h weight's codes view takes the plane that decodes it too. */
const W8hForm form = linear_w8h_form(enc); const W8hForm form = linear_w8h_form(enc);
iqr = rot8 && !asym && (form == W8hForm::Zero || form == W8hForm::Table ||
form == W8hForm::Grid || form == W8hForm::Trellis);
const RadEncPlane* tpl = rad_enc_plane(&enc, "trellis"); const RadEncPlane* tpl = rad_enc_plane(&enc, "trellis");
const bool trb = form == W8hForm::Trellis && tpl && tpl->block[1] > 1; const bool trb = form == W8hForm::Trellis && tpl && tpl->block[1] > 1;
const char* cv = form == W8hForm::Zero ? "codes,zero" const char* cv = form == W8hForm::Zero ? "codes,zero"
@@ -1829,6 +1877,23 @@ struct DenseFP8 {
RAD_ARCH_TRY(rad_weight_shard_span(b, w, lo, hi)); RAD_ARCH_TRY(rad_weight_shard_span(b, w, lo, hi));
return rad_weight_shard_span(b, s, lo / RAD_FP8_BLOCK, hi / RAD_FP8_BLOCK); return rad_weight_shard_span(b, s, lo / RAD_FP8_BLOCK, hi / RAD_FP8_BLOCK);
} }
/* This rank's rows [lo, hi) of a RAD_SHARD_ROW weight where the even shard is the wrong cut: a
* KV head replicated over ranks (Geom::kv_off), the same rows on every rank that shares it.
* Call after declare(), whose N is already hi - lo. The fp8 scale plane takes the span in its
* 128-row blocks; the MXFP4 and M2XFP4 planes are one row a weight row, as in LinearFP8. */
int span(RadBuilder* b, int64_t lo, int64_t hi) const {
RAD_ARCH_TRY(rad_weight_shard_span(b, w, lo, hi));
if (mx || m2x) {
RAD_ARCH_TRY(rad_weight_shard_span(b, s, lo, hi));
return rad_weight_shard_span(b, ref, lo, hi);
}
if (lo % RAD_FP8_BLOCK || hi % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: a row span [%lld, %lld) is not whole %d-row scale blocks\n",
(long long)lo, (long long)hi, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
return rad_weight_shard_span(b, s, lo / RAD_FP8_BLOCK, hi / RAD_FP8_BLOCK);
}
/* `gemm_nt_q` over this weight, `fp8a8`, `mxfp4a8` or `m2xfp4` as it was declared, ranged /* `gemm_nt_q` over this weight, `fp8a8`, `mxfp4a8` or `m2xfp4` as it was declared, ranged
* M 1..hi. `split_n`, when set, is the stored width a row slice takes its K split from * M 1..hi. `split_n`, when set, is the stored width a row slice takes its K split from
* (docs/OPS.md). */ * (docs/OPS.md). */
@@ -1968,6 +2033,27 @@ inline rad_op decl_gated_fold_mx(RadBuilder* b, int64_t rows, int64_t N, int64_t
return 0; return 0;
} }
/* The same fold over an IQR [2n, K] gate_up weight under the rotated int8 trunk (`gemm_nt_q_gated`
* at i8a8h: the codes and scale views gemm_nt_q reads, the input's and the output's int8 pairs, both
* in the Hadamard domain), declared for M up to min(rows, 16): libr4d's gemm_iqr_gated serves its
* GEMV and 16-token tile, each byte-identical to the GEMM row of its band followed by
* gated_had_quant_i8g. Optional like decl_gated_fold, and asked for only when a loaded library
* declares the op at that dtype: a CPU-only engine takes the pair. */
inline rad_op decl_gated_fold_iqr(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w,
rad_weight ws, std::initializer_list<rad_buf> reads,
std::initializer_list<rad_buf> writes, int64_t* gated_rows) {
if (rows <= 0 || N % 256 || K % 256) return 0;
const int64_t hi = rows < 16 ? rows : 16;
const rad_op op = rw(b, RAD_OP(b, "gemm_nt_q_gated",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "i8a8h"),
RAD_STR("act", "silu")),
RAD_WEIGHTS(w, ws)),
reads, writes);
if (op) *gated_rows = hi;
return op;
}
/* ================================================== a calibration tap */ /* ================================================== a calibration tap */
/* One tap of the GPTQ calibration (calib_dir): the Gram of a linear's bf16 input, summed over the /* 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. */
+134 -16
View File
@@ -1,5 +1,6 @@
/* gemma4_bf16.cpp -- Gemma 4 dense, bf16, with its vision tower (rad_block_gemma4_vision.h) and, /* gemma4_bf16.cpp -- Gemma 4 dense, bf16, with its vision tower (rad_block_gemma4_vision.h) and,
* for E2B/E4B, its audio encoder (rad_block_gemma4_audio.h). * for E2B/E4B, its audio encoder (rad_block_gemma4_audio.h); for the 12B ("unified"), its image and
* audio embedders in their place (rad_block_gemma4_unified.h).
* *
* Two attention classes over one residual stream, alternating by layer. A "sliding" layer is * Two attention classes over one residual stream, alternating by layer. A "sliding" layer is
* sliding-window attention over head_dim 256 with a v projection and standard RoPE; a "global" * sliding-window attention over head_dim 256 with a v projection and standard RoPE; a "global"
@@ -17,6 +18,7 @@
*/ */
#include <arch/rad_arch.h> #include <arch/rad_arch.h>
#include <arch/rad_block_gemma4_audio.h> #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_gemma4_vision.h>
#include <arch/rad_gemma4_chat.h> #include <arch/rad_gemma4_chat.h>
#include <arch/rad_gemma4_dflash.h> #include <arch/rad_gemma4_dflash.h>
@@ -454,6 +456,16 @@ struct Gemma4Attn {
* no library serves it, which the model reads as "no trees". */ * no library serves it, which the model reads as "no trees". */
bool tree = false; bool tree = false;
rad_op op_attn_tree = 0, op_tree_lift = 0; rad_op op_attn_tree = 0, op_tree_lift = 0;
/* Pictures read both ways (Model::bidi, set before declare; sliding layers only): attention
* again over a run's keys without the causal bound (RadBatch::n_bidi), reading q in the row
* (op_bidi_row) where the step's attention does, else in its own rows (op_bidi); 0 where no
* kernel serves it. */
bool want_bidi = false;
rad_op op_bidi = 0, op_bidi_row = 0;
/* The same where the window bounds the keys behind a row only: a run longer than the window
* (op_ahead_row where q is read in the row); 0 where no kernel serves it. */
rad_op op_ahead = 0, op_ahead_row = 0;
bool bidi_ok() const { return op_bidi || op_bidi_row; }
/* the feed-forward's gate_up read into the cache beside this block's all-reduce, or 0 (see /* the feed-forward's gate_up read into the cache beside this block's all-reduce, or 0 (see
* "Prefetch beside the reductions") */ * "Prefetch beside the reductions") */
rad_op op_pf = 0; rad_op op_pf = 0;
@@ -492,6 +504,9 @@ struct Gemma4Attn {
bool slicable() const { return op_qnr_kv && (op_attn_row || op_attn); } bool slicable() const { return op_qnr_kv && (op_attn_row || op_attn); }
void attend_rows(RadCtx* c, const RadBatch* batch, int64_t r0, int64_t n, void attend_rows(RadCtx* c, const RadBatch* batch, int64_t r0, int64_t n,
RadOperand used) const; RadOperand used) const;
/* The rows of each run read both ways, attended again (see op_bidi); `q_dense`: the step's
* attention left q in its own rows. */
void attend_bidi(RadCtx* c, const RadBatch* batch, bool q_dense) const;
}; };
int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo, int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo,
@@ -644,11 +659,12 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
/* Gemma 4 scores Q.K without the 1/sqrt(head_dim) factor (HF Gemma4TextAttention and vLLM /* Gemma 4 scores Q.K without the 1/sqrt(head_dim) factor (HF Gemma4TextAttention and vLLM
* use scaling = 1.0; the q/k norm gains absorb it). attn_paged defaults to 1/sqrt(head_dim), * use scaling = 1.0; the q/k norm gains absorb it). attn_paged defaults to 1/sqrt(head_dim),
* so 1.0 is passed explicitly. */ * so 1.0 is passed explicitly. */
auto attn = [&](const char* op, std::initializer_list<rad_buf> rd, int64_t q_hi = 0) { auto attn = [&](const char* op, std::initializer_list<rad_buf> rd, int64_t q_hi = 0,
int causal = 1) {
return rw(b, RAD_OP(b, op, return rw(b, RAD_OP(b, op,
RAD_PARAMS(RAD_RANGE("q_len", 1, q_hi > 0 ? q_hi : g.max_tok), RAD_PARAMS(RAD_RANGE("q_len", 1, q_hi > 0 ? q_hi : g.max_tok),
RAD_INT("head_dim", cls.head_dim), RAD_INT("head_dim", cls.head_dim),
RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 1), RAD_INT("gqa", cls.gqa()), RAD_INT("causal", causal),
RAD_INT("window", cls.window), RAD_INT("n_head", cls.n_head), RAD_INT("window", cls.window), RAD_INT("n_head", cls.n_head),
RAD_INT("block_size", RAD_KV_BLOCK), RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
@@ -729,6 +745,15 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
op_attn = attn("attn_paged", {w.q, w.qkv}); op_attn = attn("attn_paged", {w.q, w.qkv});
} }
} }
if (want_bidi) {
if (op_attn_row) {
op_bidi_row = attn("attn_paged_qrow", {w.qkv}, 0, 0);
op_ahead_row = attn("attn_paged_qrow_ahead", {w.qkv}, 0, 0);
} else {
op_bidi = attn("attn_paged", {w.q}, 0, 0);
op_ahead = attn("attn_paged_ahead", {w.q}, 0, 0);
}
}
/* The tree form over the decode rows: a verify block of 1 + n_spec rows a sequence, so the /* The tree form over the decode rows: a verify block of 1 + n_spec rows a sequence, so the
* split-KV band (q_len * gqa <= 64) covers it at every class here. In the row where the * split-KV band (q_len * gqa <= 64) covers it at every class here. In the row where the
@@ -855,6 +880,23 @@ int Gemma4Attn::declare_shared(RadBuilder* b, Names& nm, const char* pre) {
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS), RAD_NOWEIGHTS),
{w.q}, {w.attn}); {w.q}, {w.attn});
if (want_bidi) {
auto bidi = [&](const char* op) {
return rw(b, RAD_OP(b, op,
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
RAD_INT("head_dim", cls.head_dim),
RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 0),
RAD_INT("window", cls.window), RAD_INT("n_head", cls.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_F64("scale", 1.0),
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.q}, {w.attn});
};
op_bidi = bidi("attn_paged");
op_ahead = bidi("attn_paged_ahead");
}
if (g.world > 1) if (g.world > 1)
op_ar = rw(b, RAD_OP(b, "all_reduce", op_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
@@ -963,6 +1005,7 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
RAD_NONE, RAD_NONE, RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(w.attn, T)); brows(w.attn, T));
attend_bidi(c, batch, true);
return; return;
} }
/* q, k and v where the prologue works on them: their own buffers, or on a fused layer with the /* q, k and v where the prologue works on them: their own buffers, or on a fused layer with the
@@ -1001,6 +1044,7 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
* which come first (spec §8). */ * which come first (spec §8). */
const bool tree_step = op_attn_tree && batch->spec_parent && batch->draft_pass == 0 && const bool tree_step = op_attn_tree && batch->spec_parent && batch->draft_pass == 0 &&
batch->n_seq_decode > 0; batch->n_seq_decode > 0;
bool q_dense = true;
if (!tree_step || batch->n_seq_decode < batch->n_seq) { if (!tree_step || batch->n_seq_decode < batch->n_seq) {
/* attn_paged reads q dense: one row of the row's slice is, a taller step copies q out. */ /* attn_paged reads q dense: one row of the row's slice is, a taller step copies q out. */
rad_op a_op = op_attn; rad_op a_op = op_attn;
@@ -1011,8 +1055,9 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
} else if (op_attn_dec && batch->max_q_len <= dec_hi) { } else if (op_attn_dec && batch->max_q_len <= dec_hi) {
a_op = op_attn_dec; a_op = op_attn_dec;
a_q = Q; a_q = Q;
q_dense = false;
} else if (row) { } else if (row) {
if (T == 1) a_q = Q; if (T == 1) { a_q = Q; q_dense = false; }
else RAD_ISSUE_N(c, op_lift_q, T, Q, brows(w.q, T)); else RAD_ISSUE_N(c, op_lift_q, T, Q, brows(w.q, T));
} }
RAD_ISSUE_N(c, a_op, batch->max_q_len, RAD_ISSUE_N(c, a_op, batch->max_q_len,
@@ -1039,6 +1084,44 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
brows(w.attn, Td), brows(w.attn, Td),
praw(batch->spec_parent, RAD_I32, Td)); praw(batch->spec_parent, RAD_I32, Td));
} }
attend_bidi(c, batch, q_dense);
}
/* A run's rows (RadBatch::n_bidi) see every key of their run, later ones included: attention over
* their sequence's cache up to the run's end without the causal bound, written over what the
* causal pass left in their rows, on a sliding layer. Its window stays: (causal or the run) and
* the window, as transformers' mask has it. The window bounds the keys behind a row; within it a
* run's far end is in reach of every row up to the window's length, and a longer run is read with
* attn_paged_ahead, whose window bounds the keys behind only. The keys are all in the cache: the
* step stored its own, and a run's earlier rows are this step's or a prefix hit's. */
void Gemma4Attn::attend_bidi(RadCtx* c, const RadBatch* batch, bool q_dense) const {
if (batch->n_bidi <= 0 || !bidi_ok()) return;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int64_t pitch = kvb ? kvb->block_table_pitch : 0;
const int64_t qd = cls.q_dim(), kvd = cls.kv_dim();
const int64_t qkvd = qd + kvd + (cls.has_v ? kvd : 0);
for (int64_t i = 0; i < batch->n_bidi; ++i) {
const int64_t r0 = batch->bidi_row[i], n = batch->bidi_n[i], s = batch->bidi_seq[i];
const RadOperand tb = praw2(table ? table + s * pitch : nullptr, RAD_I32, 1, pitch);
const RadOperand used = praw(batch->bidi_used + i, RAD_I32, 1);
const RadOperand out = brow_slice(w.attn, r0, n, qd);
/* A run longer than the window has rows that miss its far end under a two-sided window;
* transformers' mask bounds only the keys behind. */
const bool ahead = n > cls.window;
const rad_op bidi_row = ahead && op_ahead_row ? op_ahead_row : op_bidi_row;
const rad_op bidi = ahead && op_ahead ? op_ahead : op_bidi;
if (op_bidi_row) {
RAD_ISSUE_N(c, bidi_row, n, bcol_at(w.qkv, r0, qkvd, 0, qd, n),
kv_cache(kv, kv_layer), tb, used, RAD_NONE, RAD_NONE, RAD_NONE, out);
continue;
}
if (!q_dense)
RAD_ISSUE_N(c, op_lift_q, n, bcol_at(w.qkv, r0, qkvd, 0, qd, n),
brow_slice(w.q, r0, n, qd));
RAD_ISSUE_N(c, bidi, n, brow_slice(w.q, r0, n, qd), kv_cache(kv, kv_layer), tb, used,
RAD_NONE, RAD_NONE, RAD_NONE, out);
}
} }
/* A slice's rows see exactly the keys they see in the whole step: the cache holds the step's /* A slice's rows see exactly the keys they see in the whole step: the cache holds the step's
@@ -1414,10 +1497,11 @@ struct Gemma4Head {
void step(RadCtx* c, const RadBatch* batch) const; void step(RadCtx* c, const RadBatch* batch) const;
}; };
/* Does the container carry an assistant head at all? */ /* Does the container carry an assistant head at all? The 12B's is the same head under another
* name (Gemma4UnifiedAssistantForCausalLM). */
static bool has_assistant(const RadModelMeta* m) { static bool has_assistant(const RadModelMeta* m) {
const char* a = rad_meta_gets(m, "draft.architectures", ""); const char* a = rad_meta_gets(m, "draft.architectures", "");
return a && std::strstr(a, "Gemma4Assistant") != nullptr; return a && (std::strstr(a, "Gemma4Assistant") || std::strstr(a, "Gemma4UnifiedAssistant"));
} }
int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, const Geom& trunk, int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, const Geom& trunk,
@@ -1459,16 +1543,17 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
} }
/* The head reads the trunk's cache, so everything the cache's shape depends on must agree: /* The head reads the trunk's cache, so everything the cache's shape depends on must agree:
* the two head widths, the two kv head counts and the window. A head that disagrees was trained * the two head widths, the two kv head counts and the window. A head that disagrees was trained
* with another trunk. */ * with another trunk. The counts are the model's, not a rank's: a replicated kv head (fewer
* than ranks) is one head on every rank. */
if (n_trunk != trunk.n_embd || vocab != trunk.n_vocab_all || head_s != cs.head_dim || if (n_trunk != trunk.n_embd || vocab != trunk.n_vocab_all || head_s != cs.head_dim ||
head_g != cg.head_dim || n_kv != cs.n_head_kv * trunk.world || head_g != cg.head_dim || n_kv != cs.n_head_kv_all || n_kv_g != cg.n_head_kv_all ||
n_kv_g != cg.n_head_kv * trunk.world || win != cs.window) { win != cs.window) {
fprintf(stderr, "radiance: gemma4 assistant: this head was not made for this trunk -- it " fprintf(stderr, "radiance: gemma4 assistant: this head was not made for this trunk -- it "
"states width %lld, vocabulary %lld, heads %lld/%lld x %lld/%lld kv over a " "states width %lld, vocabulary %lld, heads %lld/%lld x %lld/%lld kv over a "
"window of %lld; the trunk's cache is %lld/%lld kv heads of %lld/%lld over " "window of %lld; the trunk's cache is %lld/%lld kv heads of %lld/%lld over "
"%lld, at width %lld and vocabulary %lld\n", "%lld, at width %lld and vocabulary %lld\n",
(long long)n_trunk, vocab, n_kv, n_kv_g, head_s, head_g, win, (long long)n_trunk, vocab, n_kv, n_kv_g, head_s, head_g, win,
(long long)(cs.n_head_kv * trunk.world), (long long)(cg.n_head_kv * trunk.world), (long long)cs.n_head_kv_all, (long long)cg.n_head_kv_all,
(long long)cs.head_dim, (long long)cg.head_dim, (long long)cs.window, (long long)cs.head_dim, (long long)cg.head_dim, (long long)cs.window,
(long long)trunk.n_embd, (long long)trunk.n_vocab_all); (long long)trunk.n_embd, (long long)trunk.n_vocab_all);
return RAD_E_INVAL; return RAD_E_INVAL;
@@ -1888,7 +1973,13 @@ struct Model {
* embeddings. */ * embeddings. */
Gemma4Vision vis{}; Gemma4Vision vis{};
Gemma4Audio aud{}; Gemma4Audio aud{};
Gemma4UnifiedVision uvis{}; /* the 12B's embedders, in place of the tower and encoder */
Gemma4UnifiedAudio uaud{};
rad_op op_mm = 0; rad_op op_mm = 0;
/* A picture's or video frame's placeholders attend to each other both ways
* (use_bidirectional_attention "vision"): every sliding layer attends a run's rows again
* (Gemma4Attn::op_bidi), and the encoder says so (RadEncoderDecl::bidirectional). */
bool bidi = false;
G4Junction j0{}; /* the first block's entry: norm + quantiser of the embedding stream */ G4Junction j0{}; /* the first block's entry: norm + quantiser of the embedding stream */
bool fuse = false; bool fuse = false;
@@ -2404,8 +2495,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* the lookup and before its all-reduce (RadBatch::mm_embd: rank 0 holds the rows, every other * the lookup and before its all-reduce (RadBatch::mm_embd: rank 0 holds the rows, every other
* rank zeros). The reference scales token embeddings by sqrt(n_embd) and scatters the media * rank zeros). The reference scales token embeddings by sqrt(n_embd) and scatters the media
* features in unscaled. */ * features in unscaled. */
if ((Gemma4Vision::present(meta) && ctx->max_enc_patches > 0) || if (((Gemma4Vision::present(meta) || Gemma4UnifiedVision::present(meta)) &&
(Gemma4Audio::present(meta) && ctx->max_audio_frames > 0)) ctx->max_enc_patches > 0) ||
((Gemma4Audio::present(meta) || Gemma4UnifiedAudio::present(meta)) &&
ctx->max_audio_frames > 0))
m.op_mm = rw(b, RAD_OP(b, "scatter_rows", m.op_mm = rw(b, RAD_OP(b, "scatter_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", "bf16")), RAD_STR("dtype", "bf16")),
@@ -2508,10 +2601,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
kv_shared == 0 && ctx->draft_tree != 0; kv_shared == 0 && ctx->draft_tree != 0;
bool tree_all = tree_want; bool tree_all = tree_want;
/* Pictures read both ways where the model was trained so, on the sliding layers alone: the
* global layers stay causal (transformers' create_masks_for_vision_model, "Gemma 4 explicitly
* disables bidirectional attention on global attention layers"; KerasHub's Gemma 4 decoder
* block and vLLM agree). */
const char* bidi_cfg = meta_text_gets(meta, "use_bidirectional_attention", "");
const bool want_bidi = bidi_cfg && !std::strcmp(bidi_cfg, "vision") && ctx->max_enc_patches > 0 &&
(Gemma4Vision::present(meta) || Gemma4UnifiedVision::present(meta));
m.layers.resize((size_t)m.n_main); m.layers.resize((size_t)m.n_main);
for (int64_t l = 0; l < m.n_main; ++l) { for (int64_t l = 0; l < m.n_main; ++l) {
Layer& lay = m.layers[(size_t)l]; Layer& lay = m.layers[(size_t)l];
lay.global = (is_global[(size_t)l] == 1); lay.global = (is_global[(size_t)l] == 1);
lay.attn.want_bidi = want_bidi && !lay.global;
const ClassGeom& cgeo = lay.global ? m.cg : m.cs; const ClassGeom& cgeo = lay.global ? m.cg : m.cs;
const rad_kvgroup kg = lay.global ? m.kv_g : m.kv_s; const rad_kvgroup kg = lay.global ? m.kv_g : m.kv_s;
const Gemma4Attn::Wire& aw = lay.global ? gw : sw; const Gemma4Attn::Wire& aw = lay.global ? gw : sw;
@@ -2818,11 +2919,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
std::snprintf(k, sizeof k, "%snum_hidden_layers", drafter_layer_prefix(meta)); std::snprintf(k, sizeof k, "%snum_hidden_layers", drafter_layer_prefix(meta));
head_groups = rad_meta_geti(meta, k, 0); head_groups = rad_meta_geti(meta, k, 0);
} }
m.bidi = want_bidi;
for (const Layer& lay : m.layers) m.bidi = m.bidi && (lay.global || lay.attn.bidi_ok());
if (want_bidi && !m.bidi)
rad_note(b, "pictures are read causally: no kernel attends a run's rows without the "
"causal bound");
m.vis.bidirectional = m.uvis.bidirectional = m.bidi;
RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, g.n_embd, (int)(m.n_main + head_groups), RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, g.n_embd, (int)(m.n_main + head_groups),
"model.", "gemma4_bf16")); "model.", "gemma4_bf16"));
RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, g.n_embd, RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, g.n_embd,
(int)(m.n_main + head_groups) + (int)m.vis.L.size(), "model.", (int)(m.n_main + head_groups) + (int)m.vis.L.size(), "model.",
"gemma4_bf16")); "gemma4_bf16"));
RAD_ARCH_TRY(m.uvis.declare(b, meta, ctx, nm, g.n_embd, "gemma4_bf16"));
RAD_ARCH_TRY(m.uaud.declare(b, meta, ctx, nm, g.n_embd, "gemma4_bf16"));
} }
rad_note(b, "rank %d/%d: %lld layers (%lld global, %lld sliding), sliding window %lld, " rad_note(b, "rank %d/%d: %lld layers (%lld global, %lld sliding), sliding window %lld, "
@@ -2954,7 +3063,7 @@ static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int6
m.j0.step(c, T); m.j0.step(c, T);
const size_t L = m.layers.size(); const size_t L = m.layers.size();
if (m.slice_attn && batch->n_seq == 1) { if (m.slice_attn && batch->n_seq == 1 && batch->n_bidi == 0) {
/* Attention per slice (see Model::slice_attn): slice A's context end first, then each /* Attention per slice (see Model::slice_attn): slice A's context end first, then each
* layer as A's attention block, B's beside A's attention-side reduction, A's feed-forward * layer as A's attention block, B's beside A's attention-side reduction, A's feed-forward
* beside B's, B's feed-forward beside A's, and the next layer's A block beside B's. Each * beside B's, B's feed-forward beside A's, and the next layer's A block beside B's. Each
@@ -3050,8 +3159,14 @@ static void step(RadCtx* c, const RadBatch* batch) {
/* An encoder pass runs only its encoder. */ /* An encoder pass runs only its encoder. */
if (batch->enc) { if (batch->enc) {
if (batch->enc == RAD_MM_AUDIO) m.aud.step(c, batch); if (batch->enc == RAD_MM_AUDIO) {
else m.vis.step(c, batch); if (m.uaud.on) m.uaud.step(c, batch);
else m.aud.step(c, batch);
} else if (m.uvis.on) {
m.uvis.step(c, batch);
} else {
m.vis.step(c, batch);
}
return; return;
} }
/* A draft pass runs only the draft model. The trunk already left its final-normed hidden state /* A draft pass runs only the draft model. The trunk already left its final-normed hidden state
@@ -3192,12 +3307,15 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (k > 0) out->enc_merge = k * k; if (k > 0) out->enc_merge = k * k;
} }
if (Gemma4Audio::present(meta)) out->audio_frames = Gemma4Audio::frames_for(meta); if (Gemma4Audio::present(meta)) out->audio_frames = Gemma4Audio::frames_for(meta);
/* The 12B's embedders: a patch and an audio frame are a row each. */
if (Gemma4UnifiedVision::present(meta)) out->enc_merge = 1;
if (Gemma4UnifiedAudio::present(meta)) out->audio_frames = Gemma4UnifiedAudio::frames_for(meta);
return RAD_OK; return RAD_OK;
} }
#ifndef RAD_ARCH_NO_EXPORTS #ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0", RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0",
"Gemma 4 dense (text, images and E2B/E4B audio), w4a8 or w8a8 from its bf16 or its CT-INT4 (QAT) " "Gemma 4 dense (text, images, E2B/E4B/12B audio), w4a8 or w8a8 from its bf16 or its CT-INT4 (QAT) "
"release: sliding-window and proportional-RoPE global attention over a plain " "release: sliding-window and proportional-RoPE global attention over a plain "
"RMSNorm stream with GELU feed-forward, per-layer scalar scaling and soft-capped " "RMSNorm stream with GELU feed-forward, per-layer scalar scaling and soft-capped "
"logits; Google's assistant head, z-lab's DFlash drafter or a DFlash2 drafter") "logits; Google's assistant head, z-lab's DFlash drafter or a DFlash2 drafter")
+65 -24
View File
@@ -50,6 +50,12 @@ struct Model {
* form declares none of the row form's full-width weights (1.29 GiB a card at eight ranks); * form declares none of the row form's full-width weights (1.29 GiB a card at eight ranks);
* the row form is opt-in because it is not bit-identical to it (docs/ARCHITECTURES.md). */ * the row form is opt-in because it is not bit-identical to it (docs/ARCHITECTURES.md). */
GlmMla::Form form = GlmMla::Form::heads; GlmMla::Form form = GlmMla::Form::heads;
/* Routed experts whole on their rank (288/world of them) instead of split by width across
* every rank. Whole experts can be read from the drive, which two cards need; at four and
* eight the width split is the shape the MXFP4 kernels are tuned for (prefill runs about three
* times faster), so all-MXFP4 experts take it unless --weights-disk-tier asks for the drive.
* Anything else stays whole: a plain bf16 expert cannot be sliced at all. */
bool whole_experts = false;
std::vector<Layer> layers; std::vector<Layer> layers;
rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0; rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0;
/* The streams and the step's stream-wide buffers. */ /* The streams and the step's stream-wide buffers. */
@@ -76,6 +82,23 @@ struct Model {
static std::unique_ptr<Model> models[MAX_RANKS]; static std::unique_ptr<Model> models[MAX_RANKS];
static thread_local std::unique_ptr<Model> probe_model; static thread_local std::unique_ptr<Model> probe_model;
/* Whether every routed expert is MXFP4, asked before any buffer is sized and of the same experts on
* every rank, so all ranks reach the same layout. It reads the container's entries and declares no
* name map, so it leaves the graph as it was. One expert in another format settles it: a protected
* bf16 expert is served only whole. No answer means no container entry, and what is not known to
* be MXFP4 stays whole. */
static bool experts_are_mxfp4(RadBuilder* b, Names& nm) {
for (int l = 3; l < 45; ++l)
for (int ge = 0; ge < 288; ++ge)
for (const char* fmt : { "blk.%d.ffn_gate_up_exps.%d.weight",
"blk.%d.ffn_down_exps.%d.weight" }) {
RadEncoding e{};
if (!weight_enc(b, nm.f(fmt, l, ge), &e) || MoeFP8::format_of(e) != 8)
return false;
}
return true;
}
static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) { static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) {
char nested[160]; char nested[160];
std::snprintf(nested, sizeof nested, "text_config.%s", key); std::snprintf(nested, sizeof nested, "text_config.%s", key);
@@ -211,6 +234,7 @@ static int indexer_buffers(RadBuilder* b, Model& m) {
* at 64k of context the whole step's plane would be 256 MiB. */ * at 64k of context the whole step's plane would be 256 MiB. */
const int64_t scored = g.world > 1 ? std::min(T, std::max(part, GlmTp::kSplitRows)) : T; const int64_t scored = g.world > 1 ? std::min(T, std::max(part, GlmTp::kSplitRows)) : T;
c.score = decl_b(b, nm.f("index_scores"), RAD_F32, { scored, blocks }); c.score = decl_b(b, nm.f("index_scores"), RAD_F32, { scored, blocks });
c.unscored = decl_b(b, nm.f("index_unscored"), RAD_F32, { T, std::min<int64_t>(513, blocks) });
c.selected = m.aw.core.selected; c.selected = m.aw.core.selected;
c.length = m.aw.core.length; c.length = m.aw.core.length;
c.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T }); c.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T });
@@ -243,13 +267,18 @@ static int ffn_buffers(RadBuilder* b, Model& m) {
mw.ids = decl_b(b, nm.f("expert_ids"), RAD_I32, { T, 8 }); mw.ids = decl_b(b, nm.f("expert_ids"), RAD_I32, { T, 8 });
mw.ew = decl_b(b, nm.f("expert_weights"), RAD_F32, { T, 8 }); mw.ew = decl_b(b, nm.f("expert_weights"), RAD_F32, { T, 8 });
mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { 289 }); mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { 289 });
mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 }); /* PERSIST, as every other MoE here declares it: the router writes the counts and no declared
* op reads them (rad_route_report is a handoff), so as a transient a later buffer could share
* their bytes and an arena level would move them, while the core copies them at the block's
* end and the file stager reads them, through the address the last pass reported, at the
* layer's first expert op. */
mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 }, RAD_BUF_PERSIST);
mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { T * 8 }); mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { T * 8 });
mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { T * 8 }); mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { T * 8 });
// FE: the routed experts' WHOLE intermediate (2048). Under expert parallelism a rank owns // FE: the routed experts' intermediate. Under expert parallelism a rank owns whole experts,
// whole experts, so the routed arm's buffers are full-width at every world size; the SHARED // so the routed arm's buffers are full-width (2048); split by width they are F. The SHARED
// expert stays width-sharded (F). The two coincide at world 1. // expert stays width-sharded (F) either way. The two coincide at world 1.
const int64_t FE = 2048; const int64_t FE = m.whole_experts ? 2048 : F;
mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { T * 8, 2 * FE }); mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { T * 8, 2 * FE });
mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { T * 8, FE }); mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { T * 8, FE });
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", FE, T * 8)); RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", FE, T * 8));
@@ -266,7 +295,8 @@ static int kv_groups(RadBuilder* b, Model& m) {
auto& nm = m.nm; auto& nm = m.nm;
RadKVGroupDecl d{}; RadKVGroupDecl d{};
d.kind = RAD_KV_FULL; d.kind = RAD_KV_FULL;
d.dtype = RAD_BF16; // bf16, or E4M3 under --kv-cache-dtype fp8 (geometry); the other groups keep their own.
d.dtype = rad_dtype_parse(g.kv_dtype);
d.n_head_kv = 1; d.n_head_kv = 1;
d.head_dim = 256; d.head_dim = 256;
m.latent = rad_decl_kv_group(b, nm.f("kv_latent"), &d); m.latent = rad_decl_kv_group(b, nm.f("kv_latent"), &d);
@@ -373,14 +403,19 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
// degenerates to the old whole-model declaration (n_expert == n_expert_all, no spans). // degenerates to the old whole-model declaration (n_expert == n_expert_all, no spans).
s.cfg.n_expert_all = 288; s.cfg.n_expert_all = 288;
s.cfg.top_k = 8; s.cfg.top_k = 8;
s.cfg.n_expert = 288 / g.world; s.cfg.n_ff_shared = GlmTp::expert_width(g.world);
// A shape probe may pass rank >= world (arch_test's parallel declares reuse i % 4); if (m.whole_experts) {
// old code tolerated that because expert_base stayed 0, so clamp to rank 0's window. s.cfg.n_expert = 288 / g.world;
const int ep_rank = g.rank < g.world ? g.rank : 0; // A shape probe may pass rank >= world (arch_test's parallel declares reuse i % 4);
s.cfg.expert_base = ep_rank * (288 / g.world); // old code tolerated that because expert_base stayed 0, so clamp to rank 0's window.
s.cfg.probed_expert = s.cfg.expert_base; // probe this rank's first owned expert const int ep_rank = g.rank < g.world ? g.rank : 0;
s.cfg.n_ff_exp = 2048; // whole: whole experts' intermediate s.cfg.expert_base = ep_rank * (288 / g.world);
s.cfg.n_ff_shared = 2048 / g.world; s.cfg.probed_expert = s.cfg.expert_base; // probe this rank's first owned expert
s.cfg.n_ff_exp = 2048; // whole: whole experts' intermediate
} else {
s.cfg.n_expert = 288;
s.cfg.n_ff_exp = GlmTp::expert_width(g.world);
}
s.cfg.rows = g.max_tok; s.cfg.rows = g.max_tok;
s.cfg.sigmoid_router = 1; s.cfg.sigmoid_router = 1;
s.cfg.route_scale = 2.5; s.cfg.route_scale = 2.5;
@@ -389,12 +424,12 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
s.cfg.router_fuse = 1; s.cfg.router_fuse = 1;
s.cfg.swiglu_quant = 1; s.cfg.swiglu_quant = 1;
// At world 1 the width-slice declaration IS the whole model: keep the spans so the // At world 1 the width-slice declaration IS the whole model: keep the spans so the
// graph stays the pinned one. At world > 1 expert parallelism is in force and whole // graph stays the pinned one. Whole experts need no width spans (split && ep is refused
// experts need no width spans (split && ep is refused by the helper). // by the helper).
if (g.world == 1) { if (!m.whole_experts) {
for (int q = 0; q < 2; ++q) { for (int q = 0; q < 2; ++q) {
s.cfg.ff_lo[q] = g.rank * (2048 / g.world); s.cfg.ff_lo[q] = g.rank * GlmTp::expert_width(g.world);
s.cfg.ff_hi[q] = (g.rank + 1) * (2048 / g.world); s.cfg.ff_hi[q] = (g.rank + 1) * GlmTp::expert_width(g.world);
} }
} }
RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, s, &s.cfg)); RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, s, &s.cfg));
@@ -430,6 +465,9 @@ static int geometry(Geom& g, const RadModelMeta* meta, const RadBuildCtx* ctx, i
g.max_logit_rows = std::min<int64_t>(g.max_tok, g.max_seqs * (g.max_spec + 1)); 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; if (ctx->max_out_rows > g.max_logit_rows) g.max_logit_rows = ctx->max_out_rows;
g.eps = meta->rms_eps; g.eps = meta->rms_eps;
/* --kv-cache-dtype names the latent cache's dtype only (kv_groups); declare refuses all but
* bf16 and fp8. */
g.kv_dtype = rad_dtype_name(rad_kv_cache_dtype(ctx, RAD_BF16));
g.wire_exact = !ctx->tp_wire_lossy; g.wire_exact = !ctx->tp_wire_lossy;
g.wire_min_bytes = ctx->tp_wire_min_bytes; g.wire_min_bytes = ctx->tp_wire_min_bytes;
return g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1 || g.eps <= 0 ? RAD_E_INVAL : RAD_OK; return g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1 || g.eps <= 0 ? RAD_E_INVAL : RAD_OK;
@@ -468,11 +506,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
ctx->max_spec); ctx->max_spec);
return RAD_E_UNSUPPORTED; return RAD_E_UNSUPPORTED;
} }
if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16) { /* fp8 narrows the latent attention cache to E4M3 at a descale of 1 (kv_groups); the index
fprintf(stderr, "radiance: glm5next: --kv-cache-dtype %s; this plugin keeps its latent " * tail, the DSA index and the KDA caches keep their dtypes. */
"attention, index tail and KDA caches in bf16 and has no fp8 cache, so " if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_F8E4M3) {
"run it with --kv-cache-dtype bf16\n", fprintf(stderr, "radiance: glm5next: --kv-cache-dtype %s; this plugin serves its latent "
ctx->kv_dtype == RAD_F8E4M3 ? "fp8" : rad_dtype_name(ctx->kv_dtype)); "attention cache in bf16 or fp8 only\n",
rad_dtype_name(ctx->kv_dtype));
return RAD_E_UNSUPPORTED; return RAD_E_UNSUPPORTED;
} }
auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank]; auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank];
@@ -483,6 +522,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
auto& nm = m.nm; auto& nm = m.nm;
m.form = ctx->tp_attn_rows ? GlmMla::Form::rows : GlmMla::Form::heads; m.form = ctx->tp_attn_rows ? GlmMla::Form::rows : GlmMla::Form::heads;
RAD_ARCH_TRY(geometry(g, meta, ctx, world)); RAD_ARCH_TRY(geometry(g, meta, ctx, world));
m.whole_experts = world == 2 || (world > 2 && (ctx->expert_file_tier ||
!experts_are_mxfp4(b, nm)));
RAD_ARCH_TRY(stream_buffers(b, m)); RAD_ARCH_TRY(stream_buffers(b, m));
RAD_ARCH_TRY(kda_buffers(b, m)); RAD_ARCH_TRY(kda_buffers(b, m));
RAD_ARCH_TRY(mla_buffers(b, m)); RAD_ARCH_TRY(mla_buffers(b, m));
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/hunyuan3d2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(hunyuan3d2 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(hunyuan3d2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hunyuan3d2.cpp)
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(nemotronh LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(nemotronh architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/nemotronh.cpp)
File diff suppressed because it is too large. Load diff
+348
View File
@@ -0,0 +1,348 @@
/* radio.h -- Nemotron-H Omni's vision encoder: C-RADIO (v4-H) and the projector after it (mlp1).
*
* Per encoder pass (RadBatch::enc). The processor (core/mm, Family::Radio) gives every segment
* `n_prefix` zero rows ahead of its patches, with coordinate (-1, k):
*
* x = rows @ W^T one GEMM for both projections: a row is a
* tubelet's frames then a picture's patch, the part
* not in use zero, and W = [video_embedder |
* embedder] concatenated at convert; no bias
* x += CPE(table, row, col), or prefix[k] grid_embed_cpe: the 128 x 128 table resampled
* half-pixel bilinear onto a square of the grid's
* longer side and cropped to it; a prefix row takes
* the k-th class or register token
* depth times (pre-norm, LayerScale 1):
* x += proj(attn(qkv(LN1(x)))) full attention within a segment, no rotary
* x += fc2(gelu(fc1(LN2(x)))) exact GELU
* y = each segment's patch rows gather_rows: the prefix rows dropped
* out = l2(relu(l1(rms(y viewed [P/4, 4 * width])))^2)
*
* which is transformers' RadioModel (make_preprocessor_external) then NemotronH_Omni's vision
* projector with vision_final_layernorm off. The pixel shuffle (ps v2) is the view: the processor
* keeps a 2 x 2 block's patches consecutive, (dy, dx), the order the shuffle concatenates them;
* the tower is order-independent within a segment (attention is permutation-equivariant, every
* other layer is per row, the position term is sampled at each row's own coordinate).
*
* A pass is one grid (RadEncoderDecl::one_grid), so its segments are equally long and each
* segment's patch rows sit at a fixed offset, which `step` gathers with slices of one identity
* index. Replicated, per-request weights and pass-sized activations, as in
* arch/common/rad_block_vit.h's tower.
*/
#ifndef NEMOTRONH_RADIO_H
#define NEMOTRONH_RADIO_H
#include <arch/rad_arch.h>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace nemotronh {
using namespace rad::arch;
struct Radio {
int64_t depth = 0, width = 0, heads = 0, ff = 0, patch = 0, merge = 0, side = 0, npre = 0;
int64_t tubelet = 0, head_dim = 0, patch_dim = 0, proj_hidden = 0, n_embd = 0, P = 0, R = 0;
float eps = 1e-6f;
bool on = false;
struct Layer {
rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0;
rad_weight qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
rad_weight up_w = 0, up_b = 0, down_w = 0, down_b = 0;
rad_op ln1 = 0, qkv = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0;
};
std::vector<Layer> L;
rad_weight w_patch = 0, w_pos = 0, w_pre = 0, mn_w = 0, m1_w = 0, m2_w = 0;
rad_op op_patch = 0, op_pos = 0, op_seq = 0, op_gather = 0, op_mln = 0, op_m1 = 0;
rad_op op_act = 0, op_m2 = 0;
rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_seq = 0, b_g = 0, b_mn = 0;
rad_buf b_mf = 0, b_ma = 0, b_out = 0;
/* A tower to declare: the container is a Nemotron-H Omni one, whose vision_config is RADIO's. */
static bool present(const RadModelMeta* m) {
return !std::strcmp(rad_meta_gets(m, "vision_config.model_type", ""), "radio") &&
rad_meta_geti(m, "vision_config.num_hidden_layers", 0) > 0;
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, int first_group);
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int Radio::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, int first_group) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0);
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0);
ff = (int64_t)std::llround(rad_meta_getf(m, "vision_config.mlp_ratio", 0.0) * (double)width);
patch = rad_meta_geti(m, "vision_config.patch_size", 0);
eps = (float)rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-6);
side = rad_meta_geti(m, "vision_config.max_img_size", 0) / (patch > 0 ? patch : 1);
npre = rad_meta_geti(m, "vision_config.num_cls_tokens", 0) +
rad_meta_geti(m, "vision_config.num_registers", 0);
tubelet = rad_meta_geti(m, "vision_config.video_temporal_patch_size",
rad_meta_geti(m, "video_temporal_patch_size", 0));
const double ratio = rad_meta_getf(m, "downsample_ratio", 0.0);
merge = ratio > 0.0 ? (int64_t)std::llround(1.0 / ratio) : 0;
proj_hidden = rad_meta_geti(m, "projector_hidden_size", 0);
n_embd = model_embd;
const int64_t chans = rad_meta_geti(m, "vision_config.num_channels", 3);
if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || side <= 0 ||
npre <= 0 || tubelet <= 0 || merge <= 0 || proj_hidden <= 0 || width % heads ||
chans != 3) {
fprintf(stderr, "radiance: nemotronh: the container's RADIO vision_config is incomplete or "
"inconsistent (layers %lld, hidden %lld, heads %lld, ff %lld, patch %lld, "
"table %lld, prefix %lld, tubelet %lld, merge %lld, projector %lld)\n",
(long long)depth, (long long)width, (long long)heads, (long long)ff,
(long long)patch, (long long)side, (long long)npre, (long long)tubelet,
(long long)merge, (long long)proj_hidden);
return RAD_E_INVAL;
}
/* What this tower serves of RADIO's options: the plain GELU MLP, LayerScale 1 (no stored
* scales), q/k/v with biases, and no final layer norm before the projector. */
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu");
const bool swiglu = rad_meta_geti(m, "vision_config.use_swiglu_ffn", 0) != 0 ||
!std::strcmp(rad_meta_gets(m, "vision_config.use_swiglu_ffn", ""), "true");
const bool final_ln = rad_meta_geti(m, "vision_final_layernorm", 0) != 0 ||
!std::strcmp(rad_meta_gets(m, "vision_final_layernorm", ""), "true");
if (std::strcmp(act, "gelu") || swiglu || final_ln ||
rad_meta_getf(m, "vision_config.layerscale_value", 1.0) != 1.0) {
fprintf(stderr, "radiance: nemotronh: this RADIO tower (activation '%s'%s%s, layer scale "
"%g) is not the one served: GELU MLP, layer scale 1, no final layer norm\n",
act, swiglu ? ", SwiGLU" : "", final_ln ? ", final layer norm" : "",
rad_meta_getf(m, "vision_config.layerscale_value", 1.0));
return RAD_E_UNSUPPORTED;
}
head_dim = width / heads;
const int64_t pp = chans * patch * patch;
patch_dim = pp * (1 + tubelet);
const int64_t mm = merge * merge, mw = mm * width;
/* A pass's rows, prefix rows included; the output rows are at most a quarter of them. */
P = ctx->max_enc_patches;
const int64_t max_seg = P;
if (ctx->shape_probe) {
const int64_t r = std::min<int64_t>(P, ctx->max_tok);
P = std::max<int64_t>(mm, r / mm * mm);
}
R = P / mm;
if (R <= 0) return RAD_E_SHAPE;
const int ACC = RAD_ACCESS_PER_REQUEST;
auto bw = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
RadWeightGroup g) -> rad_weight {
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g);
};
const char* pg = "vision_model.radio_model.model.patch_generator.";
/* [video_embedder | embedder] along K: one GEMM for a row of either kind. */
if (map_concat(b, nm.f("v.patch.weight"),
{ nm.ckpt("%svideo_embedder.weight", pg), nm.ckpt("%sembedder.weight", pg) },
1) < 0)
return RAD_E_INVAL;
/* Whether the tower is here at all: its stem's encoding, which convert answers from the
* checkpoint and load from the container alike. A text-only cut (a few blocks for a host
* reference) or a container converted without it serves text; the map left behind is inert. */
{
RadEncoding enc;
if (rad_weight_encoding(b, nm.f("v.patch.weight"), &enc, nullptr, nullptr) != RAD_OK) {
rad_note(b, "nemotronh: vision_config names a RADIO tower its weights are not here "
"for; serving text");
return RAD_OK;
}
}
w_patch = decl_w(b, nm.f("v.patch.weight"), RAD_BF16, { width, patch_dim }, ACC,
RAD_SHARD_NONE, grp_model());
/* The checkpoint's [1, side * side, width] read as the [side * side, width] table. */
w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("%spos_embed", pg), { side * side, width }, grp_model());
w_pre = bw(nm.f("v.prefix.weight"), nm.ckpt("%scls_token.token", pg), { npre, width },
grp_model());
L.assign((size_t)depth, Layer{});
for (int64_t i = 0; i < depth; ++i) {
Layer& l = L[(size_t)i];
const RadWeightGroup g = grp_layer(first_group + (int)i);
const int li = (int)i;
const char* e = "vision_model.radio_model.model.blocks.%d.%s";
l.n1w = bw(nm.f("v.blk.%d.norm1.weight", li), nm.ckpt(e, li, "norm1.weight"), { width }, g);
l.n1b = bw(nm.f("v.blk.%d.norm1.bias", li), nm.ckpt(e, li, "norm1.bias"), { width }, g);
l.qkv_w = bw(nm.f("v.blk.%d.qkv.weight", li), nm.ckpt(e, li, "attn.qkv.weight"), { 3 * width, width }, g);
l.qkv_b = bw(nm.f("v.blk.%d.qkv.bias", li), nm.ckpt(e, li, "attn.qkv.bias"), { 3 * width }, g);
l.out_w = bw(nm.f("v.blk.%d.proj.weight", li), nm.ckpt(e, li, "attn.proj.weight"), { width, width }, g);
l.out_b = bw(nm.f("v.blk.%d.proj.bias", li), nm.ckpt(e, li, "attn.proj.bias"), { width }, g);
l.n2w = bw(nm.f("v.blk.%d.norm2.weight", li), nm.ckpt(e, li, "norm2.weight"), { width }, g);
l.n2b = bw(nm.f("v.blk.%d.norm2.bias", li), nm.ckpt(e, li, "norm2.bias"), { width }, g);
l.up_w = bw(nm.f("v.blk.%d.fc1.weight", li), nm.ckpt(e, li, "mlp.fc1.weight"), { ff, width }, g);
l.up_b = bw(nm.f("v.blk.%d.fc1.bias", li), nm.ckpt(e, li, "mlp.fc1.bias"), { ff }, g);
l.down_w = bw(nm.f("v.blk.%d.fc2.weight", li), nm.ckpt(e, li, "mlp.fc2.weight"), { width, ff }, g);
l.down_b = bw(nm.f("v.blk.%d.fc2.bias", li), nm.ckpt(e, li, "mlp.fc2.bias"), { width }, g);
if (!l.n1w || !l.n1b || !l.n2w || !l.n2b || !l.qkv_w || !l.qkv_b || !l.out_w ||
!l.out_b || !l.up_w || !l.up_b || !l.down_w || !l.down_b)
return RAD_E_INVAL;
}
mn_w = bw(nm.f("v.proj.norm.weight"), nm.ckpt("mlp1.0.weight"), { mw }, grp_model());
m1_w = bw(nm.f("v.proj.fc1.weight"), nm.ckpt("mlp1.1.weight"), { proj_hidden, mw }, grp_model());
m2_w = bw(nm.f("v.proj.fc2.weight"), nm.ckpt("mlp1.3.weight"), { n_embd, proj_hidden }, grp_model());
if (!w_patch || !w_pos || !w_pre || !mn_w || !m1_w || !m2_w) return RAD_E_INVAL;
/* ---- activations. `g` holds the gathered patch rows at `width` and is read by the norm as
* R rows of mm * width (the pixel shuffle's view, no copy). */
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, { P, width });
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, { P, width });
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width });
b_att = decl_b(b, nm.f("v.att"), RAD_BF16, { P, width });
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff });
b_seq = decl_b(b, nm.f("v.seq"), RAD_I32, { P });
b_g = decl_b(b, nm.f("v.g"), RAD_BF16, { R, mw });
b_mn = decl_b(b, nm.f("v.mn"), RAD_BF16, { R, mw });
b_mf = decl_b(b, nm.f("v.mf"), RAD_BF16, { R, proj_hidden });
b_ma = decl_b(b, nm.f("v.ma"), RAD_BF16, { R, proj_hidden });
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
if (!b_x || !b_h || !b_qkv || !b_att || !b_ff || !b_seq || !b_g || !b_mn || !b_mf || !b_ma ||
!b_out)
return RAD_E_INVAL;
auto gemm_b = [&](int64_t rows, int64_t N, int64_t K, const char* a, rad_weight w,
rad_weight bias) -> rad_op {
return RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", "bf16"), RAD_STR("act", a)),
RAD_WEIGHTS(w, bias));
};
auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) -> rad_op {
return RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto lnorm = [&](int64_t rows, rad_weight w, rad_weight bias) -> rad_op {
return RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w, bias));
};
op_patch = rw(b, gemm(P, width, patch_dim, w_patch), {}, { b_x });
op_pos = rw(b, RAD_OP(b, "grid_embed_cpe",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_INT("side", side), RAD_INT("n_prefix", npre),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_pos, w_pre)),
{ b_x }, { b_x });
op_seq = rw(b, RAD_OP(b, "iota",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("start", 0), RAD_INT("step", 1)),
RAD_NOWEIGHTS),
{}, { b_seq });
for (Layer& l : L) {
l.ln1 = rw(b, lnorm(P, l.n1w, l.n1b), { b_x }, { b_h });
l.qkv = rw(b, gemm_b(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
l.attn = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)head_dim)),
RAD_INT("max_seqlen", max_seg)),
RAD_NOWEIGHTS),
{ b_qkv }, { b_att });
l.proj = rw(b, gemm_b(P, width, width, "none", l.out_w, l.out_b), { b_att, b_x }, { b_x });
l.ln2 = rw(b, lnorm(P, l.n2w, l.n2b), { b_x }, { b_h });
l.up = rw(b, gemm_b(P, ff, width, "gelu", l.up_w, l.up_b), { b_h }, { b_ff });
l.down = rw(b, gemm_b(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_x }, { b_x });
}
op_gather = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_x, b_seq }, { b_g });
op_mln = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", mw), RAD_F64("eps", 1e-5),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(mn_w)),
{ b_g }, { b_mn });
op_m1 = rw(b, gemm(R, proj_hidden, mw, m1_w), { b_mn }, { b_mf });
/* relu(x)^2: act_mul's "relu" with the one tensor in both operands. */
op_act = rw(b, RAD_OP(b, "act_mul",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_hidden),
RAD_STR("act", "relu"), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_mf }, { b_ma });
op_m2 = rw(b, gemm(R, n_embd, proj_hidden, m2_w), { b_ma }, { b_out });
if (!ctx->shape_probe) {
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
e.patch_dim = patch_dim;
e.merge = mm;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
e.one_grid = 1;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "RADIO tower: %lld blocks of %lld (%lld heads x %lld), ff %lld, patch %lld "
"(tubelet %lld), %lld x %lld position table, %lld prefix rows; projector %lld "
"-> %lld -> %lld; %lld rows a pass",
(long long)depth, (long long)width, (long long)heads, (long long)head_dim,
(long long)ff, (long long)patch, (long long)tubelet, (long long)side,
(long long)side, (long long)npre, (long long)mw, (long long)proj_hidden,
(long long)n_embd, (long long)P);
}
on = true;
return RAD_OK;
}
inline void Radio::step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
const int64_t mm = merge * merge;
const int64_t gh = S > 0 && batch->enc_seg_h ? batch->enc_seg_h[0] : 0;
const int64_t gw = S > 0 && batch->enc_seg_w ? batch->enc_seg_w[0] : 0;
const int64_t seg = npre + gh * gw, Rn = S * gh * gw / (mm > 0 ? mm : 1);
if (!on || Pn <= 0 || Pn > P || S <= 0 || gh <= 0 || gw <= 0 || (gh * gw) % mm ||
S * seg != Pn || Rn > R) {
rad_step_fail(c, "nemotronh: an encoder pass this program's RADIO tower cannot serve: no "
"tower, more rows than it was declared for, or segments that are not one "
"grid of whole merged rows behind their prefix rows");
return;
}
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, Pn);
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), brows(b_x, Pn));
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd, RAD_W(w_pre));
RAD_ISSUE_N(c, op_seq, Pn, brows(b_seq, Pn));
for (const Layer& l : L) {
RAD_ISSUE_N(c, l.ln1, Pn, brows(b_x, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn));
RAD_ISSUE_N(c, l.qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
brows(b_qkv, Pn));
RAD_ISSUE_N(c, l.attn, Pn,
bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
RAD_ISSUE_N(c, l.proj, Pn, brows(b_att, Pn), RAD_W(l.out_w), RAD_W(l.out_b),
brows(b_x, Pn), brows(b_x, Pn));
RAD_ISSUE_N(c, l.ln2, Pn, brows(b_x, Pn), RAD_W(l.n2w), RAD_W(l.n2b), brows(b_h, Pn));
RAD_ISSUE_N(c, l.up, Pn, brows(b_h, Pn), RAD_W(l.up_w), RAD_W(l.up_b), RAD_NONE,
brows(b_ff, Pn));
RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
brows(b_x, Pn), brows(b_x, Pn));
}
/* Each segment's patch rows, behind its prefix rows, into `g` at width: segment s's are rows
* [s * seg + npre, (s + 1) * seg) of x, which the identity index names by a slice. */
const int64_t hw = gh * gw;
for (int64_t s = 0; s < S; ++s)
RAD_ISSUE_N(c, op_gather, hw, brows(b_x, Pn), brow_slice(b_seq, s * seg + npre, hw, 1),
brow_slice(b_g, s * hw / mm, hw / mm, mm * width));
RAD_ISSUE_N(c, op_mln, Rn, brows(b_g, Rn), RAD_W(mn_w), brows(b_mn, Rn));
RAD_ISSUE_N(c, op_m1, Rn, brows(b_mn, Rn), RAD_W(m1_w), brows(b_mf, Rn));
RAD_ISSUE_N(c, op_act, Rn, brows(b_mf, Rn), brows(b_mf, Rn), brows(b_ma, Rn));
RAD_ISSUE_N(c, op_m2, Rn, brows(b_ma, Rn), RAD_W(m2_w), brows(b_out, Rn));
}
} /* namespace nemotronh */
#endif /* NEMOTRONH_RADIO_H */
+137 -17
View File
@@ -80,6 +80,7 @@
#include <arch/rad_arch.h> #include <arch/rad_arch.h>
#include <arch/rad_block_attn_gated_fp8.h> #include <arch/rad_block_attn_gated_fp8.h>
#include <arch/rad_block_gdn_fp8.h> #include <arch/rad_block_gdn_fp8.h>
#include <arch/rad_calib_full.h>
#include <arch/rad_block_mlp_fp8.h> #include <arch/rad_block_mlp_fp8.h>
#if QWEN35_MOE #if QWEN35_MOE
#include <arch/rad_block_moe_fp8.h> #include <arch/rad_block_moe_fp8.h>
@@ -134,6 +135,9 @@ struct Layer {
* beside the feed-forward's; 0 where none is declared. */ * beside the feed-forward's; 0 where none is declared. */
rad_op op_pf_gu = 0, op_pf_next = 0; rad_op op_pf_gu = 0, op_pf_next = 0;
rad_weight pf_gu_w = 0, pf_next_w = 0; rad_weight pf_gu_w = 0, pf_next_w = 0;
/* The layer's calibration inputs (rad_calib_full.h, site_i8), -1 where this run does not record
* it: the mixer's input and its output projection's, the feed-forward's and its down's. */
int cs_in = -1, cs_o = -1, cs_mlp = -1, cs_down = -1;
}; };
struct Model { struct Model {
@@ -208,6 +212,12 @@ struct Model {
rad_op op_tap = 0; rad_op op_tap = 0;
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0; rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
/* A vocabulary-weighted head (logits_gemm_vocab): its width classes' codes, scales and rows'
* vocabulary ids, and this rank's rows of each. */
enum { MAX_VCLS = 4 };
int n_vcls = 0;
rad_weight w_vw[MAX_VCLS] = {}, w_vs[MAX_VCLS] = {}, w_vi[MAX_VCLS] = {}, w_vrow = 0;
int64_t vcls_rows[MAX_VCLS] = {};
rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_gather = 0, op_logits = 0; rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_gather = 0, op_logits = 0;
/* Set by a plugin built over this one whose head answers a request from its words /* Set by a plugin built over this one whose head answers a request from its words
* (RadBatch::plugin_words): a `fill` of the logits rows that plugin declared. A step every * (RadBatch::plugin_words): a `fill` of the logits rows that plugin declared. A step every
@@ -224,6 +234,7 @@ struct Model {
MediaRows mrows{}; MediaRows mrows{};
std::vector<Layer> layers; std::vector<Layer> layers;
CalibFull calib; /* --calib-dir over an int8 trunk (rad_calib_full.h) */
/* The pipelined prefill (step_pipelined): on where declare allowed it; the bounds buffer it /* The pipelined prefill (step_pipelined): on where declare allowed it; the bounds buffer it
* cuts a step by, rewritten by every pipelined step from the pinned table `pipe_tbl` of * cuts a step by, rewritten by every pipelined step from the pinned table `pipe_tbl` of
@@ -871,6 +882,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
(g.world != 2 || rad_op_declared(b, "ar_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; 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, "gated_had_quant_i8g")) m.a_ffn.q8_fed = m.a_ffn.q8_rot = true;
/* The delta net's output likewise, from the decode conv fold's epilogue
* (gdn_conv_recurrent_update_had) and had_quant_act_i8g on the other rows (GdnFP8::q_o). */
if (rad_op_declared(b, "gdn_conv_recurrent_update_had") && rad_op_declared(b, "had_quant_act_i8g"))
m.a_go.q8_fed = m.a_go.q8_rot = true;
/* And the gated attention's output, from its gate (gate_had_quant_i8g). */
if (rad_op_declared(b, "gate_had_quant_i8g") && rad_op_declared(b, "had_quant_act_i8g"))
m.a_attn.q8_fed = m.a_attn.q8_rot = true;
#endif #endif
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd}); m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
@@ -929,10 +947,45 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
} }
m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd}, 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()); RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
/* Row-sharded with the vocabulary: g.n_vocab is this rank's share (rad_arch.h). */ /* A vocabulary-weighted head, where the model holds one in place of output.weight: the rows
m.w_lm_head = decl_w(b, nm.f("output.weight"), * sorted by their token's probability into classes of one computed-trellis width each,
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16), * `output.k<B>.weight`, with `output.k<B>.ids` [rows, 1] each row's vocabulary id, and
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model()); * `output.vrow` [n_vocab, 1] the inverse (each id's class width and row). Each class is
* row-sharded like any lm_head, the converter keeping an id's row among its rank's rows
* (libr4d's logits_gemm_vocab). */
for (int B = 7; B >= 2; --B) {
const char* wn = nm.f("output.k%d.weight", B);
RAD_ARCH_TRY(map_copy(b, wn, nm.ckpt("lm_head.k%d.weight", B)));
RadEncoding e{};
int64_t shp[RAD_MAX_RANK] = {};
if (rad_weight_encoding(b, wn, &e, shp, nullptr) != RAD_OK) continue;
if (m.n_vcls == Model::MAX_VCLS || shp[0] % (256 * g.world) || shp[1] != g.n_embd) {
fprintf(stderr, "radiance: '%s' is not a head class this build reads (at most %d "
"classes, rows a multiple of 256 a rank)\n", wn, (int)Model::MAX_VCLS);
return RAD_E_SHAPE;
}
const int64_t n = shp[0] / g.world;
const int k = m.n_vcls++;
m.w_vw[k] = decl_view(b, wn, nullptr, "codes,trellis,trellis.mad", e.plane[0].dtype,
{n, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
m.w_vs[k] = decl_view(b, nm.f("output.k%d.scale", B), wn,
rad_enc_plane(&e, "scale.col") ? "scale,scale.col" : "scale",
RAD_F32, {n, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
const char* in = nm.f("output.k%d.ids", B);
RAD_ARCH_TRY(map_copy(b, in, nm.ckpt("lm_head.k%d.ids", B)));
m.w_vi[k] = decl_w(b, in, RAD_I32, {n, 1}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
m.vcls_rows[k] = n;
}
if (m.n_vcls) {
RAD_ARCH_TRY(map_copy(b, nm.f("output.vrow"), nm.ckpt("lm_head.vrow")));
m.w_vrow = decl_w(b, nm.f("output.vrow"), RAD_I32, {g.n_vocab, 1}, RAD_ACCESS_VOCAB,
RAD_SHARD_ROW, grp_model());
} else {
/* Row-sharded with the vocabulary: g.n_vocab is this rank's share (rad_arch.h). */
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", 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_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
@@ -1028,6 +1081,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* unfolded: it is a separate chain over its own residual buffer and saves only two launches a * unfolded: it is a separate chain over its own residual buffer and saves only two launches a
* step. */ * step. */
m.layers.resize((size_t)m.n_main); m.layers.resize((size_t)m.n_main);
#if !QWEN35_MOE
/* GPTQ calibration over the trunk's own int8 codes (rad_calib_full.h, site_i8): one rank, the
* serial step. The scratch is the widest input's square, the feed-forward's. */
if (ctx->calib_dir && *ctx->calib_dir && g.world > 1) {
fprintf(stderr, "radiance: qwen35: --calib-dir records an int8 trunk at --tp 1 only\n");
return RAD_E_INVAL;
}
RAD_ARCH_TRY(m.calib.begin(b, nm, g, ctx, m.n_main, 0, std::max<int64_t>(g.n_ff, g.n_embd)));
#endif
for (int64_t l = 0; l < m.n_main; ++l) { for (int64_t l = 0; l < m.n_main; ++l) {
Layer& lay = m.layers[(size_t)l]; Layer& lay = m.layers[(size_t)l];
lay.full = is_full_attention(l, interval) ? 1 : 0; lay.full = is_full_attention(l, interval) ? 1 : 0;
@@ -1093,6 +1155,36 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
#endif #endif
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, true, f.mlp_add, 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)); f.mlp_ar_in, f.mlp_ar_out));
#if !QWEN35_MOE
if (m.calib.records(l)) {
/* The codes each int8 GEMM reads, in the domain its weight is stored in (i8_rot). */
const ActFP8& ao = lay.full ? m.a_attn : m.a_go;
const LinearFP8& li = lay.full ? lay.attn.qg : lay.gdn.in;
const LinearFP8& lo = lay.full ? lay.attn.o : lay.gdn.out;
if (!m.a_h.q8 || !ao.q8 || !m.a_ffn.q8 || !lay.mlp.gate_up.i8 || !lo.i8) {
fprintf(stderr, "radiance: qwen35: --calib-dir records an int8 trunk; layer %lld "
"is not one\n", (long long)l);
return RAD_E_INVAL;
}
auto dom = [](const LinearFP8& w) { return w.i8_rot ? (uint32_t)RAD_FP8_BLOCK : 0u; };
const std::string L = "model.language_model.layers." + std::to_string(l);
const std::string mix = L + (lay.full ? ".self_attn" : ".linear_attn");
const std::string op = lay.full ? ".o_proj" : ".out_proj";
lay.cs_in = (int)m.calib.sites.size();
RAD_ARCH_TRY(m.calib.site_i8(b, g, l, L + ".input", mix, m.a_h.q8, m.a_h.s8, g.n_embd,
dom(li)));
lay.cs_o = (int)m.calib.sites.size();
RAD_ARCH_TRY(m.calib.site_i8(b, g, l, mix + op + ".input", mix + op, ao.q8, ao.s8, lo.K,
dom(lo)));
lay.cs_mlp = (int)m.calib.sites.size();
RAD_ARCH_TRY(m.calib.site_i8(b, g, l, L + ".post_attention.input",
L + ".mlp.gate_proj," + L + ".mlp.up_proj", m.a_h.q8,
m.a_h.s8, g.n_embd, dom(lay.mlp.gate_up)));
lay.cs_down = (int)m.calib.sites.size();
RAD_ARCH_TRY(m.calib.site_i8(b, g, l, L + ".mlp.down_proj.input", L + ".mlp.down_proj",
m.a_ffn.q8, m.a_ffn.s8, g.n_ff, dom(lay.mlp.down)));
}
#endif
} }
#if QWEN35_MOE #if QWEN35_MOE
/* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */ /* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */
@@ -1136,12 +1228,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_NOWEIGHTS), RAD_NOWEIGHTS),
{m.a_h.x}, {m.b_hout}); {m.a_h.x}, {m.b_hout});
m.op_logits = rw(b, RAD_OP(b, "logits_gemm", m.op_logits = m.n_vcls
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), ? rw(b, RAD_OP(b, "logits_gemm_vocab",
RAD_INT("n_vocab", g.n_vocab), 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_INT("n_embd", g.n_embd), RAD_STR("dtype", g.dtype),
RAD_WEIGHTS(m.w_lm_head)), RAD_INT("vocab_offset", g.vocab_off),
{m.b_hout}, {m.b_logits}); RAD_INT("rows0", m.vcls_rows[0]), RAD_INT("rows1", m.vcls_rows[1]),
RAD_INT("rows2", m.vcls_rows[2]), RAD_INT("rows3", m.vcls_rows[3])),
RAD_WEIGHTS(m.w_vw[0], m.w_vs[0], m.w_vi[0], m.w_vw[1], m.w_vs[1], m.w_vi[1],
m.w_vw[2], m.w_vs[2], m.w_vi[2], m.w_vw[3], m.w_vs[3], m.w_vi[3],
m.w_vrow)),
{m.b_hout}, {m.b_logits})
: rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("n_embd", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(m.w_lm_head)),
{m.b_hout}, {m.b_logits});
/* ---- the multi-token-prediction head (rad_block_mtp_fp8.h). /* ---- the multi-token-prediction head (rad_block_mtp_fp8.h).
* *
@@ -1151,7 +1253,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* *
* Also only when there is no DFlash2 drafter (`n_taps` == 0): a deployment drafts with one, * Also only when there is no DFlash2 drafter (`n_taps` == 0): a deployment drafts with one,
* and DFlash2 (one forward per block rather than one per token) is the better one here. */ * and DFlash2 (one forward per block rather than one per token) is the better one here. */
if (nextn > 0 && g.max_spec > 0 && m.n_taps == 0) { /* (A vocabulary-weighted head has no output.weight for the draft head to read.) */
if (nextn > 0 && g.max_spec > 0 && m.n_taps == 0 && !m.n_vcls) {
/* Sized at max_tok, not max_logit_rows: a draft round is one row per sequence, but the /* Sized at max_tok, not max_logit_rows: a draft round is one row per sequence, but the
* history pass that fills the head's own K and V is one row per token over a whole prefill * history pass that fills the head's own K and V is one row per token over a whole prefill
* chunk (26 MiB at a 512-token chunk, beside 477 MiB of head weights). */ * chunk (26 MiB at a 512-token chunk, beside 477 MiB of head weights). */
@@ -1321,6 +1424,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
return RAD_OK; return RAD_OK;
} }
/* The lm_head over the gathered rows: the one weight, or a vocabulary-weighted head's classes. */
static void issue_logits(RadCtx* c, const Model& m, int n) {
if (!m.n_vcls) {
RAD_ISSUE_N(c, m.op_logits, n, brows(m.b_hout, n), RAD_W(m.w_lm_head),
brows(m.b_logits, n));
return;
}
auto w = [](rad_weight h) { return h ? RAD_W(h) : RAD_NONE; };
RAD_ISSUE_N(c, m.op_logits, n, brows(m.b_hout, n), w(m.w_vw[0]), w(m.w_vs[0]), w(m.w_vi[0]),
w(m.w_vw[1]), w(m.w_vs[1]), w(m.w_vi[1]), w(m.w_vw[2]), w(m.w_vs[2]), w(m.w_vi[2]),
w(m.w_vw[3]), w(m.w_vs[3]), w(m.w_vi[3]), RAD_W(m.w_vrow), brows(m.b_logits, n));
}
#if !QWEN35_MOE #if !QWEN35_MOE
/* ============================== A prefill step in two pieces ============================== /* ============================== A prefill step in two pieces ==============================
* *
@@ -1547,9 +1663,7 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
RAD_ISSUE_N(c, m.op_gather, batch->n_out, RAD_ISSUE_N(c, m.op_gather, batch->n_out,
brows(m.a_h.x, T), praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.a_h.x, T), praw(batch->out_ids, RAD_I32, batch->n_out),
brows(m.b_hout, batch->n_out)); brows(m.b_hout, batch->n_out));
RAD_ISSUE_N(c, m.op_logits, batch->n_out, issue_logits(c, m, batch->n_out);
brows(m.b_hout, batch->n_out), RAD_W(m.w_lm_head),
brows(m.b_logits, batch->n_out));
} }
} }
#endif #endif
@@ -1628,9 +1742,15 @@ static void step(RadCtx* c, const RadBatch* batch) {
const Layer& l = m.layers[(size_t)li]; const Layer& l = m.layers[(size_t)li];
if (l.full) l.attn.step(c, batch); if (l.full) l.attn.step(c, batch);
else l.gdn.step(c, batch); else l.gdn.step(c, batch);
/* The calibration taps read the codes the block's GEMMs just read, before the next block's
* norm rewrites the shared input planes. */
if (l.cs_in >= 0) m.calib.tap(c, (size_t)l.cs_in, batch->n_tok);
if (l.cs_o >= 0) m.calib.tap(c, (size_t)l.cs_o, batch->n_tok);
prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h); prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h);
dbg_resid(c, (int)li, "mix", m.g.n_embd, m.b_x, m.a_h.x); dbg_resid(c, (int)li, "mix", m.g.n_embd, m.b_x, m.a_h.x);
l.mlp.step(c, batch); l.mlp.step(c, batch);
if (l.cs_mlp >= 0) m.calib.tap(c, (size_t)l.cs_mlp, batch->n_tok);
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); 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); dbg_resid(c, (int)li, "ffn", m.g.n_embd, m.b_x, m.a_h.x);
@@ -1643,6 +1763,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
} }
} }
m.calib.after_step(c, batch->n_tok);
RAD_ISSUE(c, m.op_final_norm, RAD_ISSUE(c, m.op_final_norm,
brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.a_h.x, batch->n_tok)); brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.a_h.x, batch->n_tok));
@@ -1655,9 +1777,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
brows(m.a_h.x, batch->n_tok), brows(m.a_h.x, batch->n_tok),
praw(batch->out_ids, RAD_I32, batch->n_out), praw(batch->out_ids, RAD_I32, batch->n_out),
brows(m.b_hout, batch->n_out)); brows(m.b_hout, batch->n_out));
RAD_ISSUE_N(c, m.op_logits, batch->n_out, issue_logits(c, m, batch->n_out);
brows(m.b_hout, batch->n_out), RAD_W(m.w_lm_head),
brows(m.b_logits, batch->n_out));
} }
} }
+76
View File
@@ -88,6 +88,7 @@
#include <vector> #include <vector>
#include <arch/rad_arch.h> #include <arch/rad_arch.h>
#include <rad_prefill_split.h>
#include <arch/rad_block_attn_gated_fp8.h> #include <arch/rad_block_attn_gated_fp8.h>
#include <arch/rad_block_gdn_fp8.h> #include <arch/rad_block_gdn_fp8.h>
#include <arch/rad_block_hc.h> #include <arch/rad_block_hc.h>
@@ -1696,6 +1697,72 @@ static void step(RadCtx* c, const RadBatch* batch) {
* acceptance stays high at every depth, but each extra verify row costs real time because the * acceptance stays high at every depth, but each extra verify row costs real time because the
* weights do not fit device memory (more experts streamed, more n-gram rows faulted from the * weights do not fit device memory (more experts streamed, more n-gram rows faulted from the
* mapped table). */ * mapped table). */
uint64_t pass_key(RadCtx* c, const RadBatch* batch, const int32_t* used_max_h) {
if (!c || !batch) return 0;
if (batch->enc) return 1;
/* Mixed batches split the query rows into decode and prefill subsets before attention; the
* whole-batch host summary cannot key those subset geometries exactly. */
if (batch->phase == RAD_PHASE_MIXED) return 0;
Model& m = g_model[rad_rank(c)];
/* Decode, verify and draft passes (the MTP head attends over the same KV group): every
* attention launch covers all the pass's sequences, and the shape fields the core keys (n_tok,
* n_seq, max_q_len, n_spec, draft_pass) fix each launch's q_len band and units. The live KV
* length enters a split launcher's count only through the cap of eight 48-key tiles a split
* (rad_prefill_splits_law; every head_dim 256 launcher has P_TILE 48), and from 64 splits up
* the cap no longer binds. Keying that cap level lets these passes be recorded while each launch
* still splits by its exact live length: answering 0 left them unrecorded (issue #402), and the
* core's keyed bound for a plugin without the callback rounds the length up a bucket, which split
* a short single-stream verify into several partials with a merge (x1 203 against 219 tok/s). */
if (batch->phase != RAD_PHASE_PREFILL || batch->draft_pass != 0 || batch->n_spec > 0) {
if (!m.kv_full || !used_max_h || !batch->kv) return 0;
int group = -1;
for (int i = 0; i < batch->n_kv_groups; ++i)
if (batch->kv[i].group == m.kv_full) { group = i; break; }
if (group < 0) return 2; // no full-attention KV in this pass: nothing splits by length
const int used = used_max_h[group];
if (used <= 0) return 0; // Missing host summary is not the same as an empty KV cache.
constexpr int tile = 48;
const int ctx = (m.g.max_ctx > 0 && used >= m.g.max_ctx) ? (int)m.g.max_ctx : used;
const int cap = std::min(((ctx + tile - 1) / tile) / 8, 64);
return 3 + (uint64_t)cap;
}
bool has_full_attention = false;
for (const Layer& layer : m.layers) {
if (!layer.full) continue;
if (layer.attn.kv_block != 4) return 0;
has_full_attention = true;
}
if (!has_full_attention) return 1;
if (m.g.head_dim != 256 || (m.g.gqa() != 6 && m.g.gqa() != 12) || !m.kv_full ||
!used_max_h || !batch->kv || batch->n_kv_groups <= 0)
return 0;
int group = -1;
for (int i = 0; i < batch->n_kv_groups; ++i)
if (batch->kv[i].group == m.kv_full) { group = i; break; }
if (group < 0) return 0;
/* Qwen always passes cu_seqlens, so fill_paged takes q_len = min(band, total_q). That equals
* n_tok only for one sequence; a ragged or multi-sequence launch's band is not the host group
* max, and mixed decode-prefix / prefill-suffix launches use the suffix's own KV lengths. */
if (batch->n_seq != 1 || batch->n_tok <= 0 || m.g.max_ctx <= 0) return 0;
const int q_len = (int)batch->n_tok;
const int total_q = (int)batch->n_tok;
const int num_seqs = 1;
const int kv_heads = (int)m.g.n_head_kv;
const int used = used_max_h[group];
if (used <= 0) return 0; // Missing host summary is not the same as an empty KV cache.
const int wgps = rad_ctx_wgp_count(c);
if (wgps <= 0) return 0;
constexpr int tile = 48, nwarps = 24;
const int bq = nwarps * 16 / m.g.gqa();
const int splits = rad_prefill_splits_for_live(bq, tile, q_len, total_q, num_seqs,
kv_heads, m.g.max_ctx, used, wgps);
return rad_prefill_grid_key(q_len, bq, splits, kv_heads, num_seqs, nwarps * 32);
}
static int probe(const RadModelMeta* meta, RadArchProbe* out) { static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL; if (!meta || !out) return RAD_E_INVAL;
/* The gated attention block declares the streamed store and the resolve /* The gated attention block declares the streamed store and the resolve
@@ -1717,6 +1784,11 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
} }
/* The gated residual applies a control vector after every block's write (HcProject). */ /* The gated residual applies a control vector after every block's write (HcProject). */
out->control_vector_ok = 1; out->control_vector_ok = 1;
/* Chained launches pay with the MTP drafter: the speculative step's small kernels wait on the
* previous one on the card instead of behind a queue barrier (libr4d/r4d_chain.h). On 2x R9700,
* sampled at temperature 1 with a 25k prompt, MTP depth 3, with the chained hc_read forms:
* 1/2/4/8/16 streams 174/291/458/657/851 -> 207/339/493/647/843 tok/s. */
out->chain_pays = 1;
return RAD_OK; return RAD_OK;
} }
@@ -1728,4 +1800,8 @@ RAD_ARCH_PLUGIN(qwen4exp_fp8, "qwen4exp", "", "0.1.0",
"Qwen4-Exp (Qwen3.8-Flash-Next): hybrid Gated DeltaNet / gated attention, a gated " "Qwen4-Exp (Qwen3.8-Flash-Next): hybrid Gated DeltaNet / gated attention, a gated "
"residual four streams wide and 512 routed experts, from a dense bf16 checkpoint " "residual four streams wide and 512 routed experts, from a dense bf16 checkpoint "
"quantised ahead of time by a recipe") "quantised ahead of time by a recipe")
extern "C" uint64_t rad_arch_pass_key(RadCtx* c, const RadBatch* batch,
const int32_t* used_max_h) {
return qwen4exp_fp8::pass_key(c, batch, used_max_h);
}
#endif #endif
+9
View File
@@ -0,0 +1,9 @@
# Built in tree or against an installed radiance.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(spark25_bf16 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(spark25_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/spark25_bf16.cpp)
+35
View File
@@ -0,0 +1,35 @@
/* Spark's reply format: the checkpoint's template writes these tags around each call. */
#pragma once
#include "rad_builder.h"
namespace spark25_bf16 {
inline const RadChatFormat* spark_chat_format() {
static const char* const breaks[] = {"<tool_call>"};
static const char* const triggers[] = {"<tool_call>"};
static const RadChatFormat f = [] {
RadChatFormat x{};
x.struct_size = sizeof(x);
x.name = "plugin:spark25";
x.reasoning_open = "<think>";
x.reasoning_close = "</think>";
x.reasoning_breaks = breaks;
x.n_reasoning_breaks = 1;
x.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT;
/* There is no delimiter between the call opener and the function name. */
x.name_prefix = "<tool_call>";
x.call_end = "</tool_call>";
x.arg_prefix = "<arg_key>";
x.arg_name_suffix = "</arg_key>";
x.arg_value_prefix = "<arg_value>";
x.arg_value_suffix = "</arg_value>";
x.string_value = RAD_CHAT_VALUE_RAW;
x.other_value = RAD_CHAT_VALUE_JSON;
x.triggers = triggers;
x.n_triggers = 1;
return x;
}();
return &f;
}
} /* namespace spark25_bf16 */
+626
View File
@@ -0,0 +1,626 @@
/* Spark X2.6 (Spark2_5ForCausalLM), BF16 weights and activations.
*
* The checkpoint has one [q | k | v] projection per layer. Conversion splits its rows into
* contiguous matrices because paged attention needs a contiguous query. The MLP's two matrices
* are concatenated as [gate | up]; act_mul with exact erf GELU matches the reference, unlike
* gelu_mul (which is the tanh approximation). The attention gate is one sigmoid per head, not
* per channel. Local and full layers have different NeoX rotary dimensions and theta values.
*
* Tensor parallelism splits attention by whole KV groups, replicating KV heads when ranks
* outnumber them. As in the HF reference, residuals accumulate in f32; rmsnorm reads that stream
* and writes bf16 for the linear projections.
*
* A container built with `--draft-model` also carries a DSpark drafter, which reads the residual
* stream after the trunk layers its config names and denoises a block of masked positions in one
* pass. The trunk's part of that is the taps and the drafter pass dispatch (see
* arch/rad_block_dspark_bf16.h for the drafter itself).
*/
#include <arch/rad_arch.h>
#include <arch/rad_fp8.h>
#include <arch/rad_block_dspark_bf16.h>
#include "chat.h"
#include "spark25_prefill_pass_key.h"
#include <algorithm>
#include <cmath>
#include <sstream>
#include <string>
#include <vector>
namespace spark25_bf16 {
using namespace rad::arch;
struct Layer {
rad_kvgroup kv = 0;
rad_weight an = 0, q = 0, k = 0, v = 0, gate = 0, o = 0, fn = 0, gu = 0, down = 0;
rad_op anorm = 0, qp = 0, kp = 0, vp = 0, gp = 0, rq = 0, rk = 0, store = 0, attn = 0;
rad_op sigmoid = 0, gate_heads = 0, op = 0, widen_attn = 0, reduce_attn = 0, add_attn = 0;
rad_op fnorm = 0, gup = 0, act = 0, dp = 0, widen_ffn = 0, reduce_ffn = 0, add_ffn = 0;
CalibTap tap_in{}, tap_o{}, tap_gu{}, tap_down{};
};
struct Model {
Names nm{""};
Geom g{};
rad_kvgroup kv = 0;
rad_buf x = 0, delta = 0, h = 0, q = 0, k = 0, v = 0, gate = 0, attn = 0, gu = 0, ff = 0;
rad_buf hout = 0, logits = 0;
rad_weight tok = 0, norm = 0, head = 0;
rad_op embed = 0, widen = 0, reduce_embed = 0, final_norm = 0, gather = 0, logits_op = 0;
std::vector<Layer> layers;
bool tap_live = false;
long long calib_rows = 0;
int64_t calib_lo = 0, calib_hi = 0;
/* The drafter, declared only when the container carries one and this serve speculates. Its own
* KV group holds the context it derived from the trunk's taps. */
DsparkBF16 ds{};
DsparkBF16::Wire dsw{};
DsparkTaps taps{};
rad_kvgroup kv_draft = 0;
bool have_ds = false;
};
static Model models[MAX_RANKS];
/* Whether the container carries a drafter at all (`--draft-model` merged one under `draft.`), and
* whether this file implements it. A drafter this plugin cannot run is refused at declare rather
* than left unused: the container would serve at the speed of a model with no drafter, and the
* user would have no way to find out that the flag they passed did nothing. */
static int drafter_kind(const RadModelMeta* meta, bool* present) {
*present = false;
const char* da = rad_meta_gets(meta, "draft.architectures", "");
if (!da || !*da) {
/* A drafter's config.json flattened, or a GGUF import, either of which names it. */
if (rad_meta_geti(meta, "draft.num_hidden_layers", 0) <= 0) return RAD_OK;
da = rad_meta_gets(meta, "draft.model_type", "");
}
if (std::strstr(da, "DSpark") || std::strcmp(da, "dspark") == 0) {
*present = true;
return RAD_OK;
}
*present = true;
fprintf(stderr, "radiance: spark25: this container carries a '%s' drafter. Spark's drafts are "
"DSpark, with a rank-N Markov head over the target's own table; this "
"architecture implements that and nothing else\n", da);
return RAD_E_UNSUPPORTED;
}
/* The HF config names every layer. Do not infer a periodic schedule: it changes the mask and
* rotary of a layer and would silently produce a different model. */
static int schedule(const RadModelMeta* meta, int64_t n, std::vector<bool>& local) {
const char* s = rad_meta_gets(meta, "layer_types", nullptr);
if (!s) {
fprintf(stderr, "radiance: spark25: layer_types is required\n");
return RAD_E_INVAL;
}
std::istringstream in(s);
std::string word;
while (in >> word) {
if (word != "sliding_attention" && word != "full_attention") {
fprintf(stderr, "radiance: spark25: unknown layer type '%s'\n", word.c_str());
return RAD_E_UNSUPPORTED;
}
local.push_back(word == "sliding_attention");
}
if ((int64_t)local.size() != n) {
fprintf(stderr, "radiance: spark25: layer_types has %zu entries for %lld layers\n",
local.size(), (long long)n);
return RAD_E_INVAL;
}
return RAD_OK;
}
struct Span {
int64_t first = 0, count = 0;
};
/* Remainder-first contiguous slices, in whole units. */
static Span split(int64_t n, int parts, int rank) {
const int64_t base = n / parts, rem = n % parts;
return {base * rank + std::min<int64_t>(rank, rem), base + (rank < rem ? 1 : 0)};
}
struct Shards {
Span q, kv, ff; /* q and kv in heads; ff in channels */
};
/* A rank's attention heads must describe whole GQA groups, or a slice of a single group with
* that group's KV head replicated. This also covers non-divisible worlds such as 3 ranks over
* the checkpoint's 4 KV heads. Projection and FFN spans below give the loader those exact cuts. */
static int shard_geometry(Geom& g, const RadBuildCtx* ctx, Shards& s) {
g.world = ctx->world_size > 0 ? ctx->world_size : 1;
g.rank = ctx->rank;
if (g.rank >= g.world || g.world > g.n_head_all || g.n_head_kv_all <= 0 ||
g.n_head_all % g.n_head_kv_all || g.world > g.n_ff_all) {
fprintf(stderr, "radiance: spark25: cannot shard %lld query heads, %lld KV heads and "
"%lld FFN channels over %d ranks\n", (long long)g.n_head_all,
(long long)g.n_head_kv_all, (long long)g.n_ff_all, g.world);
return RAD_E_INVAL;
}
const int64_t group = g.n_head_all / g.n_head_kv_all;
if (g.world <= g.n_head_kv_all) {
s.kv = split(g.n_head_kv_all, g.world, g.rank);
s.q = {s.kv.first * group, s.kv.count * group};
} else {
int first_rank = 0;
for (int64_t k = 0; k < g.n_head_kv_all; ++k) {
const int n = (int)split(g.world, (int)g.n_head_kv_all, (int)k).count;
if (g.rank < first_rank + n) {
const Span q = split(group, n, g.rank - first_rank);
s.kv = {k, 1};
s.q = {k * group + q.first, q.count};
break;
}
first_rank += n;
}
}
/* Prefer whole 128-channel blocks for a ragged split, keeping device GEMMs aligned. */
const int64_t unit = g.n_ff_all % 128 == 0 && g.n_ff_all / 128 >= g.world ? 128 : 1;
s.ff = split(g.n_ff_all / unit, g.world, g.rank);
s.ff.first *= unit;
s.ff.count *= unit;
g.n_head = s.q.count;
g.n_head_kv = s.kv.count;
g.n_ff = s.ff.count;
g.n_vocab = shard_extent(g.n_vocab_all, g.world, g.rank);
g.vocab_off = shard_begin(g.n_vocab_all, g.world, g.rank);
return g.n_head > 0 && g.n_head_kv > 0 && g.n_ff > 0 && g.n_vocab > 0 ? RAD_OK : RAD_E_INVAL;
}
static bool needs_span(const Span& s, int64_t total, const Geom& g) {
return total % g.world != 0 || s.first != g.rank * (total / g.world) ||
s.count != total / g.world;
}
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
Model& m = models[ctx->rank];
m = Model{};
m.nm = Names(ctx->scope);
/* geom_from's even-only split cannot express a ragged GQA/FFN world. Read the whole geometry,
* then give each rank a group-preserving shard and state its spans on the weights. */
RadBuildCtx whole = *ctx;
whole.rank = 0;
whole.world_size = 1;
RAD_ARCH_TRY(geom_from(m.g, meta, &whole, "bf16", RAD_BF16));
Geom& g = m.g;
Shards shards;
RAD_ARCH_TRY(shard_geometry(g, ctx, shards));
Names& nm = m.nm;
if (g.n_head_kv <= 0 || g.n_head % g.n_head_kv || g.head_dim % 2 || meta->n_expert ||
rad_meta_geti(meta, "attention_bias", 0) || rad_meta_geti(meta, "mlp_bias", 0) ||
!rad_meta_geti(meta, "tie_word_embeddings", 0) ||
!rad_meta_geti(meta, "headwise_attn_output_gate", 0) ||
std::strcmp(rad_meta_gets(meta, "gate_attn_act_mode", "sigmoid"), "sigmoid") ||
std::strcmp(rad_meta_gets(meta, "hidden_act", "gelu"), "gelu")) {
fprintf(stderr, "radiance: spark25: requires a dense, bias-free, tied model with headwise "
"sigmoid gates, exact GELU and divisible attention heads\n");
return RAD_E_UNSUPPORTED;
}
/* A single global override cannot describe this model's two rotary ladders. */
RAD_ARCH_TRY(yarn_from(g, meta, "", g.head_dim));
if (g.yarn.factor != 0.0f || g.rope_scale != 1.0f || g.rope_mc) {
fprintf(stderr, "radiance: spark25: rotary scaling overrides are not supported\n");
return RAD_E_UNSUPPORTED;
}
std::vector<bool> local;
RAD_ARCH_TRY(schedule(meta, g.n_layer, local));
if (calib_dir()) {
if (g.world != 1) {
fprintf(stderr, "radiance: spark25 calibration requires one rank so column-split "
"Grams retain their cross terms\n");
return RAD_E_UNSUPPORTED;
}
RAD_ARCH_TRY(calib_layers("spark25", "RADIANCE_SPARK_CALIB_LAYERS", g.n_layer,
&m.calib_lo, &m.calib_hi));
m.tap_live = true;
}
const int64_t window = rad_meta_geti(meta, "sliding_window", 0);
if (window <= 0) {
fprintf(stderr, "radiance: spark25: a positive sliding_window is required\n");
return RAD_E_INVAL;
}
double theta[2]{};
int64_t rot[2]{};
const char* kinds[] = {"full_attention", "sliding_attention"};
for (int j = 0; j < 2; ++j) {
theta[j] = rad_meta_getf(meta, nm.f("rope_parameters.%s.rope_theta", kinds[j]), 10000.0);
const double factor = rad_meta_getf(meta,
nm.f("rope_parameters.%s.partial_rotary_factor", kinds[j]), 1.0);
const char* type = rad_meta_gets(meta, nm.f("rope_parameters.%s.rope_type", kinds[j]), "default");
if (std::strcmp(type, "default")) {
fprintf(stderr, "radiance: spark25: %s rotary type '%s' is not supported\n", kinds[j], type);
return RAD_E_UNSUPPORTED;
}
const double r = g.head_dim * factor;
if (!std::isfinite(theta[j]) || !(theta[j] > 0) || !(factor > 0 && factor <= 1) || !std::isfinite(r) ||
std::floor(r) != r || (int64_t)r % 2) {
fprintf(stderr, "radiance: spark25: invalid %s rotary theta %g or factor %g\n",
kinds[j], theta[j], factor);
return RAD_E_INVAL;
}
rot[j] = (int64_t)r;
}
/* A full cache for both kinds keeps prefix caching valid. The local attention op enforces
* its own window (q - k < window); the full layers read all past positions. */
RadKVGroupDecl kd{};
kd.kind = RAD_KV_FULL;
kd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
kd.n_head_kv = g.n_head_kv;
kd.head_dim = g.head_dim;
m.kv = rad_decl_kv_group(b, nm.f("kv_attn"), &kd);
if (!m.kv) return RAD_E_INVAL;
g.kv_dtype = rad_dtype_name(kd.dtype);
const int64_t T = g.max_tok, 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_F32, {T, E});
m.delta = decl_b(b, nm.f("delta"), RAD_F32, {T, E});
m.h = decl_b(b, nm.f("h"), RAD_BF16, {T, E});
m.q = decl_b(b, nm.f("q"), RAD_BF16, {T, Q});
m.k = decl_b(b, nm.f("k"), RAD_BF16, {T, K});
m.v = decl_b(b, nm.f("v"), RAD_BF16, {T, K});
m.gate = decl_b(b, nm.f("gate"), RAD_BF16, {T, g.n_head});
m.attn = decl_b(b, nm.f("attn"), RAD_BF16, {T, Q});
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.hout = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, E});
m.logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
if (!m.x || !m.delta || !m.h || !m.q || !m.k || !m.v || !m.gate || !m.attn || !m.gu || !m.ff ||
!m.hout || !m.logits) return RAD_E_INVAL;
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
/* ---- the drafter's taps, when the container carries a drafter and this serve speculates.
* Declared before the layer loop because the stream outlives it: the drafter's context pass
* runs after the trunk's, on the residual streams the trunk saved here. */
bool drafter = false;
RAD_ARCH_TRY(drafter_kind(meta, &drafter));
if (drafter && ctx->max_spec > 0) {
m.taps.read(meta, g.n_layer);
if (m.taps.n <= 0) {
fprintf(stderr, "radiance: spark25: the drafter names no trunk layer to read, or names "
"only layers past this target's last (`draft.target_layer_ids`)\n");
return RAD_E_FORMAT;
}
RAD_ARCH_TRY(m.taps.declare(b, nm, g, g.max_tok, m.x));
}
auto weight = [&](const char* name, const char* src, uint32_t dt,
std::initializer_list<int64_t> shape, RadWeightGroup group,
int access = RAD_ACCESS_PER_TOKEN, int shard = RAD_SHARD_NONE) {
if (map_copy(b, name, src) != RAD_OK) return (rad_weight)0;
return decl_w(b, name, dt, shape, access, shard, group);
};
m.tok = weight(nm.f("token_embd.weight"), nm.ckpt("model.embedding.weight"), RAD_BF16,
{g.n_vocab, E}, grp_model(), RAD_ACCESS_VOCAB, RAD_SHARD_ROW);
m.head = weight(nm.f("output.weight"), nm.ckpt("model.embedding.weight"), RAD_BF16,
{g.n_vocab, E}, grp_model(), RAD_ACCESS_VOCAB, RAD_SHARD_ROW);
m.norm = weight(nm.f("output_norm.weight"), nm.ckpt("model.norm.weight"), RAD_F32,
{E}, grp_model());
if (!m.tok || !m.head || !m.norm) return RAD_E_INVAL;
if (g.world > 1 && g.n_vocab_all % g.world) {
RAD_ARCH_TRY(rad_weight_shard_span(b, m.tok, g.vocab_off, g.vocab_off + g.n_vocab));
RAD_ARCH_TRY(rad_weight_shard_span(b, m.head, g.vocab_off, g.vocab_off + g.n_vocab));
}
auto norm = [&](rad_weight w, rad_buf x, rad_buf y) {
return rw(b, RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w)), {x}, {y});
};
auto gemm = [&](int64_t n, int64_t k, rad_weight w, rad_buf x, rad_buf y) {
return rw(b, RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("N", n),
RAD_INT("K", k), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(w)), {x}, {y});
};
auto add = [&]() {
return rw(b, RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
RAD_STR("dtype", "f32")), RAD_NOWEIGHTS), {m.x, m.delta}, {m.x});
};
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_INT("vocab_offset", g.vocab_off)), RAD_WEIGHTS(m.tok)), {}, {m.h});
auto widen = [&](rad_buf output) {
return rw(b, RAD_OP(b, "cast", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
RAD_STR("from", "bf16"), RAD_STR("to", "f32")), RAD_NOWEIGHTS), {m.h}, {output});
};
m.widen = widen(m.x);
/* Embedding shards contribute disjoint rows, so their widened sum is exact. Projection
* shards must instead reduce in bf16, rounding the merged output before it is widened and
* added to the f32 residual, as in the reference's BF16 linear layers. */
auto reduce = [&](rad_buf x, const char* dtype) {
if (g.world <= 1) return (rad_op)0;
return rw(b, RAD_OP(b, "all_reduce", RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", E, T * E), RAD_STR("dtype", dtype), RAD_INT("exact", 1)),
RAD_NOWEIGHTS), {x}, {x});
};
m.reduce_embed = reduce(m.x, "fp32");
if (g.world > 1 && !m.reduce_embed) {
fprintf(stderr, "radiance: spark25 requires an exact fp32 all-reduce for TP=%d\n", g.world);
return RAD_E_UNSUPPORTED;
}
m.layers.resize((size_t)g.n_layer);
for (int l = 0; l < g.n_layer; ++l) {
Layer& a = m.layers[(size_t)l];
auto src = [&](const char* suffix) { return nm.ckpt("model.layers.%d.%s", l, suffix); };
auto w = [&](const char* suffix, const char* s, uint32_t dt,
std::initializer_list<int64_t> shape, int shard = RAD_SHARD_NONE) {
return weight(nm.f("blk.%d.%s", l, suffix), src(s), dt, shape, grp_layer(l),
RAD_ACCESS_PER_TOKEN, shard);
};
a.an = w("attn_norm.weight", "input_layernorm.weight", RAD_F32, {E});
a.gate = w("attn_gate.weight", "self_attn.g_proj.weight", RAD_BF16, {g.n_head, E}, RAD_SHARD_ROW);
a.o = w("attn_output.weight", "self_attn.out_proj.weight", RAD_BF16, {E, Q}, RAD_SHARD_COL);
a.fn = w("ffn_norm.weight", "post_attention_layernorm.weight", RAD_F32, {E});
a.down = w("ffn_down.weight", "mlp.down_proj.weight", RAD_BF16, {E, F}, RAD_SHARD_COL);
const char* qkv = src("self_attn.q_k_v_proj.weight");
auto part = [&](const char* name, int first, int64_t all_rows, int64_t rows) {
const char* target = nm.f("blk.%d.attn_%s.weight", l, name);
if (map_rows(b, target, {{qkv, first, all_rows}}) != RAD_OK) return (rad_weight)0;
return decl_w(b, target, RAD_BF16, {rows, E}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,
grp_layer(l));
};
const int64_t qall = g.n_head_all * g.head_dim, kall = g.n_head_kv_all * g.head_dim;
a.q = part("q", 0, qall, Q);
a.k = part("k", (int)qall, kall, K);
a.v = part("v", (int)(qall + kall), kall, K);
const char* gu = nm.f("blk.%d.ffn_gate_up.weight", l);
RAD_ARCH_TRY(map_concat(b, gu, {src("mlp.gate_proj.weight"), src("mlp.up_proj.weight")}));
a.gu = decl_w(b, gu, RAD_BF16, {2 * F, E}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,
grp_layer(l), 0, {F, F});
if (!a.an || !a.q || !a.k || !a.v || !a.gate || !a.o || !a.fn || !a.gu || !a.down)
return RAD_E_INVAL;
if (g.world > 1 && needs_span(shards.q, g.n_head_all, g)) {
RAD_ARCH_TRY(rad_weight_shard_span(b, a.q, shards.q.first * g.head_dim,
(shards.q.first + shards.q.count) * g.head_dim));
RAD_ARCH_TRY(rad_weight_shard_span(b, a.gate, shards.q.first,
shards.q.first + shards.q.count));
RAD_ARCH_TRY(rad_weight_shard_span(b, a.o, shards.q.first * g.head_dim,
(shards.q.first + shards.q.count) * g.head_dim));
}
if (g.world > 1 && needs_span(shards.kv, g.n_head_kv_all, g)) {
for (rad_weight h : {a.k, a.v})
RAD_ARCH_TRY(rad_weight_shard_span(b, h, shards.kv.first * g.head_dim,
(shards.kv.first + shards.kv.count) * g.head_dim));
}
if (g.world > 1 && needs_span(shards.ff, g.n_ff_all, g)) {
for (rad_weight h : {a.gu, a.down})
RAD_ARCH_TRY(rad_weight_shard_span(b, h, shards.ff.first,
shards.ff.first + shards.ff.count));
}
a.kv = m.kv;
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, a.kv));
a.anorm = norm(a.an, m.x, m.h);
a.qp = gemm(Q, E, a.q, m.h, m.q);
a.kp = gemm(K, E, a.k, m.h, m.k);
a.vp = gemm(K, E, a.v, m.h, m.v);
a.gp = gemm(g.n_head, E, a.gate, m.h, m.gate);
Geom rope = g;
const int kind = local[(size_t)l] ? 1 : 0;
rope.theta = (float)theta[kind];
a.rq = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head, 0, rot[kind], "neox"), {m.q}, {m.q});
a.rk = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head_kv, 0, rot[kind], "neox"), {m.k}, {m.k});
a.attn = rw(b, decl_attn(b, g, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, T), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), RAD_INT("window", kind ? window : 0),
RAD_INT("n_head", g.n_head), RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)), RAD_NOWEIGHTS),
{m.q}, {m.attn});
a.store = rw(b, RAD_OP(b, "kv_store", RAD_PARAMS(RAD_RANGE("M", 1, T),
RAD_INT("head_dim", g.head_dim), RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, a.kv)), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS), {m.k, m.v}, {});
a.sigmoid = rw(b, RAD_OP(b, "sigmoid", RAD_PARAMS(RAD_RANGE("M", 1, T),
RAD_INT("n", g.n_head), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.gate}, {m.gate});
/* View dense [tokens, heads * dim] and [tokens, heads] as one row per head. */
a.gate_heads = rw(b, RAD_OP(b, "scale_rows", RAD_PARAMS(RAD_RANGE("M", 1, T * g.n_head),
RAD_INT("n", g.head_dim), RAD_STR("act", "none"), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS), {m.attn, m.gate}, {m.attn});
a.op = gemm(E, Q, a.o, m.attn, m.h);
a.reduce_attn = reduce(m.h, "bf16");
a.widen_attn = widen(m.delta);
a.add_attn = add();
a.fnorm = norm(a.fn, m.x, m.h);
a.gup = gemm(2 * F, E, a.gu, m.h, m.gu);
a.act = rw(b, RAD_OP(b, "act_mul", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", F),
RAD_STR("act", "gelu"), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.gu}, {m.ff});
a.dp = gemm(E, F, a.down, m.ff, m.h);
a.reduce_ffn = reduce(m.h, "bf16");
if (g.world > 1 && (!a.reduce_attn || !a.reduce_ffn)) {
fprintf(stderr, "radiance: spark25 requires exact bf16 all-reduces for TP=%d\n", g.world);
return RAD_E_UNSUPPORTED;
}
a.widen_ffn = widen(m.delta);
a.add_ffn = add();
if (m.tap_live && l >= m.calib_lo && l < m.calib_hi) {
RAD_ARCH_TRY(a.tap_in.declare(b, nm, T, nm.f("blk.%d.attn_in", l), m.h, E));
RAD_ARCH_TRY(a.tap_o.declare(b, nm, T, nm.f("blk.%d.attn_o", l), m.attn, Q));
RAD_ARCH_TRY(a.tap_gu.declare(b, nm, T, nm.f("blk.%d.ffn_in", l), m.h, E));
RAD_ARCH_TRY(a.tap_down.declare(b, nm, T, nm.f("blk.%d.ffn_down_in", l), m.ff, F));
}
}
m.final_norm = norm(m.norm, m.x, m.h);
m.gather = rw(b, RAD_OP(b, "gather_rows", RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n", E), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.h}, {m.hout});
m.logits_op = rw(b, RAD_OP(b, "logits_gemm", RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(m.head)), {m.hout}, {m.logits});
char ids[128] = "";
/* The drafter is declared last, after the head. The buffer planner takes lifetimes in
* declaration order, and a drafter's passes run after the whole trunk's, so declaring it in the
* middle would let a trunk temporary be planned onto bytes the drafter is still reading. */
if (m.taps.n > 0) {
RAD_ARCH_TRY(declare_dspark(&m.ds, &m.dsw, &m.kv_draft, b, nm, meta, ctx, g, m.taps,
(int)g.n_layer, m.tok, nm.ckpt("model.embedding.weight")));
m.have_ds = true;
for (int t = 0, off = 0; t < m.taps.n && off < (int)sizeof(ids) - 8; ++t)
off += std::snprintf(ids + off, sizeof ids - off, "%s%d", t ? ", " : "",
m.taps.layer[t]);
rad_note(b, "the drafter reads the residual stream after layer(s) %s", ids);
}
rad_note(b, "spark25 rank %d/%d: %lld layers, %lld query / %lld KV heads x %lld, "
"FFN %lld, vocab [%lld, %lld), local window %lld", g.rank, g.world,
(long long)g.n_layer, (long long)g.n_head, (long long)g.n_head_kv,
(long long)g.head_dim, (long long)g.n_ff, (long long)g.vocab_off,
(long long)(g.vocab_off + g.n_vocab), (long long)window);
return RAD_OK;
}
static void step(RadCtx* c, const RadBatch* batch) {
Model& m = models[rad_rank(c)];
const Geom& g = m.g;
/* A drafter pass; the sign gives the kind. Positive is the query pass, which denoises the whole
* block and proposes from it; negative is the context pass, which turns the tokens the trunk
* just committed into the drafter's own K and V. Zero is a trunk step. */
if (batch->draft_pass != 0) {
if (!m.have_ds) {
rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the "
"container carries no `draft.` block, or declare ran at max_spec 0");
return;
}
if (batch->draft_pass > 0) m.ds.step(c, batch);
else m.ds.context(c, batch);
return;
}
const int64_t T = batch->n_tok;
const RadOperand pos = praw(batch->positions, RAD_I32, T);
RAD_ISSUE(c, m.embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.tok), brows(m.h, T));
RAD_ISSUE(c, m.widen, brows(m.h, T), brows(m.x, T));
if (m.reduce_embed) RAD_ISSUE_N(c, m.reduce_embed, T * g.n_embd, brows(m.x, T), RAD_NONE);
for (size_t i = 0; i < m.layers.size(); ++i) {
const Layer& a = m.layers[i];
const RadKVGroupBatch* kvb = kv_batch(batch, a.kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int32_t* used = kvb ? kvb->seqused : nullptr;
RAD_ISSUE(c, a.anorm, brows(m.x, T), RAD_W(a.an), brows(m.h, T));
RAD_ISSUE(c, a.qp, brows(m.h, T), RAD_W(a.q), brows(m.q, T));
RAD_ISSUE(c, a.kp, brows(m.h, T), RAD_W(a.k), brows(m.k, T));
RAD_ISSUE(c, a.vp, brows(m.h, T), RAD_W(a.v), brows(m.v, T));
RAD_ISSUE(c, a.gp, brows(m.h, T), RAD_W(a.gate), brows(m.gate, T));
a.tap_in.step(c, m.h, T, m.tap_live);
RAD_ISSUE(c, a.rq, brows(m.q, T), pos);
RAD_ISSUE(c, a.rk, brows(m.k, T), pos);
RAD_ISSUE(c, a.store, brows(m.k, T), brows(m.v, T), praw(slot, RAD_I32, T),
kv_cache(a.kv, (int)i));
RAD_ISSUE_N(c, a.attn, batch->max_q_len, brows(m.q, T), kv_cache(a.kv, (int)i),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(m.attn, T));
RAD_ISSUE(c, a.sigmoid, brows(m.gate, T), brows(m.gate, T));
const RadOperand heads = RAD_P_T2(rad_buf_ptr(c, m.attn), RAD_BF16, T * g.n_head, g.head_dim);
const RadOperand gates = RAD_P_T2(rad_buf_ptr(c, m.gate), RAD_BF16, T * g.n_head, 1);
RAD_ISSUE_N(c, a.gate_heads, T * g.n_head, heads, gates, RAD_NONE, heads);
a.tap_o.step(c, m.attn, T, m.tap_live);
RAD_ISSUE(c, a.op, brows(m.attn, T), RAD_W(a.o), brows(m.h, T));
if (a.reduce_attn) RAD_ISSUE_N(c, a.reduce_attn, T * g.n_embd, brows(m.h, T), RAD_NONE);
RAD_ISSUE(c, a.widen_attn, brows(m.h, T), brows(m.delta, T));
RAD_ISSUE(c, a.add_attn, brows(m.x, T), brows(m.delta, T), brows(m.x, T));
RAD_ISSUE(c, a.fnorm, brows(m.x, T), RAD_W(a.fn), brows(m.h, T));
RAD_ISSUE(c, a.gup, brows(m.h, T), RAD_W(a.gu), brows(m.gu, T));
a.tap_gu.step(c, m.h, T, m.tap_live);
RAD_ISSUE(c, a.act, bcol(m.gu, 0, g.n_ff, T), bcol(m.gu, g.n_ff, g.n_ff, T), brows(m.ff, T));
a.tap_down.step(c, m.ff, T, m.tap_live);
RAD_ISSUE(c, a.dp, brows(m.ff, T), RAD_W(a.down), brows(m.h, T));
if (a.reduce_ffn) RAD_ISSUE_N(c, a.reduce_ffn, T * g.n_embd, brows(m.h, T), RAD_NONE);
RAD_ISSUE(c, a.widen_ffn, brows(m.h, T), brows(m.delta, T));
RAD_ISSUE(c, a.add_ffn, brows(m.x, T), brows(m.delta, T), brows(m.x, T));
/* The tap after this layer, on prefill and decode alike: the drafter conditions on every
* committed token's residual stream, not only on prefill's. */
m.taps.step(c, m.x, T, (int64_t)i, g.n_embd);
}
RAD_ISSUE(c, m.final_norm, brows(m.x, T), RAD_W(m.norm), brows(m.h, T));
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.gather, batch->n_out, brows(m.h, T),
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.hout, batch->n_out));
RAD_ISSUE_N(c, m.logits_op, batch->n_out, brows(m.hout, batch->n_out), RAD_W(m.head),
brows(m.logits, batch->n_out));
}
if (m.tap_live) {
m.calib_rows += T;
if (m.calib_rows >= calib_target()) {
bool ok = true;
for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) {
const Layer& a = m.layers[(size_t)l];
char stem[96];
for (const char* proj : {"attn_q", "attn_k", "attn_v"}) {
std::snprintf(stem, sizeof stem, "blk.%lld.%s", (long long)l, proj);
ok = calib_write(c, a.tap_in.h, a.tap_in.K, m.calib_rows, stem, 0) && ok;
}
std::snprintf(stem, sizeof stem, "blk.%lld.attn_output", (long long)l);
ok = calib_write(c, a.tap_o.h, a.tap_o.K, m.calib_rows, stem, 0) && ok;
std::snprintf(stem, sizeof stem, "blk.%lld.ffn_gate_up", (long long)l);
ok = calib_write(c, a.tap_gu.h, a.tap_gu.K, m.calib_rows, stem, 0) && ok;
std::snprintf(stem, sizeof stem, "blk.%lld.ffn_down", (long long)l);
ok = calib_write(c, a.tap_down.h, a.tap_down.K, m.calib_rows, stem, 0) && ok;
}
m.tap_live = false;
std::fprintf(stderr, "radiance: spark25 rank %d wrote calibration Grams for layers "
"%lld:%lld after %lld tokens to %s%s\n", rad_rank(c),
(long long)m.calib_lo, (long long)m.calib_hi, m.calib_rows, calib_dir(),
ok ? "" : ", with errors");
}
}
}
#ifdef SPARK25_HAVE_PREFILL_SPLIT
static uint64_t pass_key(RadCtx* c, const RadBatch* batch, const int32_t* used_max_h) {
if (!c || !batch) return 0;
Model& m = models[rad_rank(c)];
int group = -1;
if (batch->kv) for (int i = 0; i < batch->n_kv_groups; ++i)
if (batch->kv[i].group == m.kv) { group = i; break; }
spark25_prefill_key::Request r;
r.phase = batch->phase;
r.n_tok = batch->n_tok;
r.n_seq = batch->n_seq;
r.max_q_len = batch->max_q_len;
r.max_ctx = m.g.max_ctx;
r.n_spec = batch->n_spec;
r.draft_pass = batch->draft_pass;
r.enc = batch->enc != 0;
r.head_dim = m.g.head_dim;
r.gqa = m.g.gqa();
r.kv_heads = m.g.n_head_kv;
r.kv_group_found = group >= 0;
r.used = used_max_h && group >= 0 ? used_max_h[group] : 0;
r.wgps = rad_ctx_wgp_count(c);
return spark25_prefill_key::pass_key(r);
}
#endif
/* The speculation depth this container supports: zero without a drafter, or the block length a
* DSpark drafter was trained at. `draft_depth_fixed` because a block-diffusion drafter denoises
* exactly that many mask positions, and `declare` refuses to run it at any other depth. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
out->draft_depth = 0;
out->draft_depth_fixed = 0;
bool present = false;
if (drafter_kind(meta, &present) != RAD_OK) return RAD_E_UNSUPPORTED;
if (!present) return RAD_OK;
const long long bs = rad_meta_geti(meta, "draft.block_size", 0);
if (bs < 2) {
fprintf(stderr, "radiance: spark25: the container carries a drafter with no "
"draft.block_size\n");
return RAD_E_FORMAT;
}
out->draft_depth = (int)bs;
out->draft_depth_fixed = 1;
return RAD_OK;
}
static const RadChatFormat* chat_format(const RadModelMeta*) { return spark_chat_format(); }
}
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(spark25_bf16)
RAD_ARCH_PLUGIN(spark25_bf16, "spark25", "", "0.1.0", "Spark X2.6 BF16")
RAD_ARCH_CHAT_FORMAT(spark25_bf16)
#ifdef SPARK25_HAVE_PREFILL_SPLIT
extern "C" uint64_t rad_arch_pass_key(RadCtx* c, const RadBatch* batch,
const int32_t* used_max_h) {
return spark25_bf16::pass_key(c, batch, used_max_h);
}
#endif
#endif
@@ -0,0 +1,67 @@
/* Spark's prefill pass-key geometry. Keep this host-pure and mirror the h256/GQA4
* R4D launcher exactly; unsupported batches fail closed. */
#pragma once
#include <cstdint>
#if defined(__has_include)
# if __has_include(<rad_prefill_split.h>)
# include <rad_prefill_split.h>
# define SPARK25_HAVE_PREFILL_SPLIT 1
# endif
#endif
namespace spark25_prefill_key {
constexpr int kNwarps = 24;
constexpr int kTile = 48;
constexpr int kGqa = 4;
constexpr int kHeadDim = 256;
constexpr int kBq = kNwarps * 16 / kGqa;
constexpr int kThreads = kNwarps * 32;
constexpr int kDecodeRowCap = 64;
constexpr int kPhasePrefill = 0;
constexpr int kPhaseDecode = 1;
constexpr int kPhaseMixed = 2;
static_assert(kBq == 96, "Spark GQA4 prefill BQ must match the R4D launcher");
static_assert(kThreads == 768, "Spark prefill launcher uses 768 threads");
struct Request {
int phase = kPhasePrefill;
int64_t n_tok = 0, n_seq = 0, max_q_len = 0, max_ctx = 0;
int64_t n_spec = 0, draft_pass = 0;
int enc = 0;
int64_t head_dim = 0, gqa = 0, kv_heads = 0;
int kv_group_found = 0, used = 0, wgps = 0;
};
#ifdef SPARK25_HAVE_PREFILL_SPLIT
inline uint64_t pass_key(const Request& r) {
if (r.enc) return 1;
if (r.draft_pass != 0) return 0;
/* Mixed and speculative passes can launch attention on sub-batches whose exact geometry
* is not represented by the whole-batch summary. */
if (r.phase == kPhaseMixed || r.n_spec > 0) return 0;
if (r.phase != kPhasePrefill) return 1;
if (r.head_dim != kHeadDim || r.gqa != kGqa || r.kv_heads <= 0 || !r.kv_group_found)
return 0;
/* For a singleton, these equalities prove the R4D q_len band and total_q used by its launch.
* Do not infer geometry for multi-sequence/ragged batches. */
if (r.n_seq != 1 || r.n_tok <= 0 || r.max_q_len != r.n_tok || r.max_ctx <= 0 ||
r.used <= 0 || r.wgps <= 0)
return 0;
/* The short-query path resolves to the decode launcher, with a different split law. */
if (r.max_q_len * r.gqa <= kDecodeRowCap) return 0;
const int q_len = (int)r.max_q_len;
const int splits = rad_prefill_splits_for_live(kBq, kTile, q_len, (int)r.n_tok, 1,
(int)r.kv_heads, (int)r.max_ctx, r.used,
r.wgps);
return rad_prefill_grid_key(q_len, kBq, splits, (int)r.kv_heads, 1, kThreads);
}
#else
inline uint64_t pass_key(const Request&) { return 0; }
#endif
} // namespace spark25_prefill_key
+9
View File
@@ -0,0 +1,9 @@
# Built in tree or against an installed radiance.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(spark25_w8a8 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(spark25_w8a8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/spark25_w8a8.cpp)
+682
View File
@@ -0,0 +1,682 @@
/* Spark X2.6 (Spark2_5ForCausalLM), rotated int8 weights and activations.
*
* The checkpoint has one [q | k | v] projection per layer. Conversion splits its rows into
* contiguous matrices because paged attention needs a contiguous query. The MLP's two matrices
* are concatenated as [gate | up]; act_mul with exact erf GELU matches the reference, unlike
* gelu_mul (which is the tanh approximation). The attention gate is one sigmoid per head, not
* per channel. Local and full layers have different NeoX rotary dimensions and theta values.
*
* Tensor parallelism splits attention by whole KV groups, replicating KV heads when ranks
* outnumber them. As in the HF reference, residuals accumulate in f32; rmsnorm reads that stream
* and writes bf16 for the linear projections.
*
* A container built with `--draft-model` also carries a DSpark drafter, which reads the residual
* stream after the trunk layers its config names and denoises a block of masked positions in one
* pass. The drafter itself is bf16 whatever the trunk's quantisation (arch/rad_block_dspark_bf16.h
* says why); the trunk's part is the taps and the drafter pass dispatch below.
*/
#include <arch/rad_arch.h>
#include <arch/rad_fp8.h>
#include <arch/rad_block_dspark_bf16.h>
#include "../spark25_bf16/chat.h"
#include "../spark25_bf16/spark25_prefill_pass_key.h"
#include <algorithm>
#include <cmath>
#include <sstream>
#include <string>
#include <vector>
namespace spark25_w8a8 {
using namespace rad::arch;
struct Layer {
rad_kvgroup kv = 0;
rad_weight an = 0, gate = 0, fn = 0;
LinearFP8 q{}, k{}, v{}, o{}, gu{}, down{};
rad_op anorm = 0, gp = 0, rq = 0, rk = 0, store = 0, attn = 0;
rad_op sigmoid = 0, gate_heads = 0, widen_attn = 0, reduce_attn = 0, add_attn = 0;
rad_op fnorm = 0, act = 0, widen_ffn = 0, reduce_ffn = 0, add_ffn = 0;
CalibTap tap_in{}, tap_o{}, tap_gu{}, tap_down{};
};
struct Model {
Names nm{""};
Geom g{};
rad_kvgroup kv = 0;
rad_buf x = 0, delta = 0, h = 0, q = 0, k = 0, v = 0, gate = 0, attn = 0, gu = 0, ff = 0;
rad_buf hout = 0, logits = 0;
ActFP8 a_h{}, a_attn{}, a_ff{};
rad_weight tok = 0, norm = 0, head = 0;
rad_op embed = 0, widen = 0, reduce_embed = 0, had = 0, final_norm = 0, gather = 0, logits_op = 0;
std::vector<Layer> layers;
bool tap_live = false;
long long calib_rows = 0;
int64_t calib_lo = 0, calib_hi = 0;
/* The drafter, declared only when the container carries one and this serve speculates. Its own
* KV group holds the context it derived from the trunk's taps. */
DsparkBF16 ds{};
DsparkBF16::Wire dsw{};
DsparkTaps taps{};
rad_kvgroup kv_draft = 0;
bool have_ds = false;
};
static Model models[MAX_RANKS];
/* Whether the container carries a drafter at all (`--draft-model` merged one under `draft.`), and
* whether this file implements it. A drafter this plugin cannot run is refused at declare rather
* than left unused: the container would serve at the speed of a model with no drafter, and the
* user would have no way to find out that the flag they passed did nothing. */
static int drafter_kind(const RadModelMeta* meta, bool* present) {
*present = false;
const char* da = rad_meta_gets(meta, "draft.architectures", "");
if (!da || !*da) {
/* A drafter's config.json flattened, or a GGUF import, either of which names it. */
if (rad_meta_geti(meta, "draft.num_hidden_layers", 0) <= 0) return RAD_OK;
da = rad_meta_gets(meta, "draft.model_type", "");
}
if (std::strstr(da, "DSpark") || std::strcmp(da, "dspark") == 0) {
*present = true;
return RAD_OK;
}
*present = true;
fprintf(stderr, "radiance: spark25: this container carries a '%s' drafter. Spark's drafts are "
"DSpark, with a rank-N Markov head over the target's own table; this "
"architecture implements that and nothing else\n", da);
return RAD_E_UNSUPPORTED;
}
/* The HF config names every layer. Do not infer a periodic schedule: it changes the mask and
* rotary of a layer and would silently produce a different model. */
static int schedule(const RadModelMeta* meta, int64_t n, std::vector<bool>& local) {
const char* s = rad_meta_gets(meta, "layer_types", nullptr);
if (!s) {
fprintf(stderr, "radiance: spark25: layer_types is required\n");
return RAD_E_INVAL;
}
std::istringstream in(s);
std::string word;
while (in >> word) {
if (word != "sliding_attention" && word != "full_attention") {
fprintf(stderr, "radiance: spark25: unknown layer type '%s'\n", word.c_str());
return RAD_E_UNSUPPORTED;
}
local.push_back(word == "sliding_attention");
}
if ((int64_t)local.size() != n) {
fprintf(stderr, "radiance: spark25: layer_types has %zu entries for %lld layers\n",
local.size(), (long long)n);
return RAD_E_INVAL;
}
return RAD_OK;
}
struct Span {
int64_t first = 0, count = 0;
};
/* Remainder-first contiguous slices, in whole units. */
static Span split(int64_t n, int parts, int rank) {
const int64_t base = n / parts, rem = n % parts;
return {base * rank + std::min<int64_t>(rank, rem), base + (rank < rem ? 1 : 0)};
}
struct Shards {
Span q, kv, ff; /* q and kv in heads; ff in channels */
};
/* A rank's attention heads must describe whole GQA groups, or a slice of a single group with
* that group's KV head replicated. This also covers non-divisible worlds such as 3 ranks over
* the checkpoint's 4 KV heads. Projection and FFN spans below give the loader those exact cuts. */
static int shard_geometry(Geom& g, const RadBuildCtx* ctx, Shards& s) {
g.world = ctx->world_size > 0 ? ctx->world_size : 1;
g.rank = ctx->rank;
if (g.rank >= g.world || g.world > g.n_head_all || g.n_head_kv_all <= 0 ||
g.n_head_all % g.n_head_kv_all || g.world > g.n_ff_all) {
fprintf(stderr, "radiance: spark25: cannot shard %lld query heads, %lld KV heads and "
"%lld FFN channels over %d ranks\n", (long long)g.n_head_all,
(long long)g.n_head_kv_all, (long long)g.n_ff_all, g.world);
return RAD_E_INVAL;
}
const int64_t group = g.n_head_all / g.n_head_kv_all;
if (g.world <= g.n_head_kv_all) {
s.kv = split(g.n_head_kv_all, g.world, g.rank);
s.q = {s.kv.first * group, s.kv.count * group};
} else {
int first_rank = 0;
for (int64_t k = 0; k < g.n_head_kv_all; ++k) {
const int n = (int)split(g.world, (int)g.n_head_kv_all, (int)k).count;
if (g.rank < first_rank + n) {
const Span q = split(group, n, g.rank - first_rank);
s.kv = {k, 1};
s.q = {k * group + q.first, q.count};
break;
}
first_rank += n;
}
}
/* Prefer whole 128-channel blocks for a ragged split, keeping device GEMMs aligned. */
const int64_t unit = g.n_ff_all % 128 == 0 && g.n_ff_all / 128 >= g.world ? 128 : 1;
s.ff = split(g.n_ff_all / unit, g.world, g.rank);
s.ff.first *= unit;
s.ff.count *= unit;
g.n_head = s.q.count;
g.n_head_kv = s.kv.count;
g.n_ff = s.ff.count;
g.n_vocab = shard_extent(g.n_vocab_all, g.world, g.rank);
g.vocab_off = shard_begin(g.n_vocab_all, g.world, g.rank);
return g.n_head > 0 && g.n_head_kv > 0 && g.n_ff > 0 && g.n_vocab > 0 ? RAD_OK : RAD_E_INVAL;
}
static bool needs_span(const Span& s, int64_t total, const Geom& g) {
return total % g.world != 0 || s.first != g.rank * (total / g.world) ||
s.count != total / g.world;
}
static int check_format(const RadModelMeta* meta) {
const char* method = rad_meta_gets(meta, "quantization_config.quant_method", nullptr);
const char* fmt = rad_meta_gets(meta, "quantization_config.fmt", nullptr);
if (!method || std::strcmp(method, "w8a8") != 0 || !fmt || std::strcmp(fmt, "fwht128") != 0) {
fprintf(stderr, "radiance: spark25_w8a8 serves a rotated int8 trunk (quant_method "
"'w8a8', fmt 'fwht128'); this container says '%s' / '%s'\n",
method ? method : "(none)", fmt ? fmt : "(none)");
return RAD_E_UNSUPPORTED;
}
return RAD_OK;
}
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
RAD_ARCH_TRY(check_format(meta));
Model& m = models[ctx->rank];
m = Model{};
m.nm = Names(ctx->scope);
/* geom_from's even-only split cannot express a ragged GQA/FFN world. Read the whole geometry,
* then give each rank a group-preserving shard and state its spans on the weights. */
RadBuildCtx whole = *ctx;
whole.rank = 0;
whole.world_size = 1;
RAD_ARCH_TRY(geom_from(m.g, meta, &whole, "bf16", RAD_BF16));
Geom& g = m.g;
Shards shards;
RAD_ARCH_TRY(shard_geometry(g, ctx, shards));
/* A column-sharded int8 linear slices its input's scale groups, so every rank's
* feed-forward span must be whole 128-column groups. shard_geometry prefers whole blocks
* even for ragged worlds such as TP=3; refuse a geometry that cannot be split that way. */
if (g.world > 1 && shards.ff.count % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: spark25_w8a8 cannot shard %lld FFN channels over %d ranks: a "
"rank's %lld are not whole %d-column scale groups. An int8 down projection "
"sliced inside a group would read its scale plane at the wrong width\n",
(long long)g.n_ff_all, g.world, (long long)shards.ff.count, RAD_FP8_BLOCK);
return RAD_E_UNSUPPORTED;
}
Names& nm = m.nm;
if (g.n_head_kv <= 0 || g.n_head % g.n_head_kv || g.head_dim % 2 || meta->n_expert ||
rad_meta_geti(meta, "attention_bias", 0) || rad_meta_geti(meta, "mlp_bias", 0) ||
!rad_meta_geti(meta, "tie_word_embeddings", 0) ||
!rad_meta_geti(meta, "headwise_attn_output_gate", 0) ||
std::strcmp(rad_meta_gets(meta, "gate_attn_act_mode", "sigmoid"), "sigmoid") ||
std::strcmp(rad_meta_gets(meta, "hidden_act", "gelu"), "gelu")) {
fprintf(stderr, "radiance: spark25: requires a dense, bias-free, tied model with headwise "
"sigmoid gates, exact GELU and divisible attention heads\n");
return RAD_E_UNSUPPORTED;
}
/* A single global override cannot describe this model's two rotary ladders. */
RAD_ARCH_TRY(yarn_from(g, meta, "", g.head_dim));
if (g.yarn.factor != 0.0f || g.rope_scale != 1.0f || g.rope_mc) {
fprintf(stderr, "radiance: spark25: rotary scaling overrides are not supported\n");
return RAD_E_UNSUPPORTED;
}
std::vector<bool> local;
RAD_ARCH_TRY(schedule(meta, g.n_layer, local));
if (calib_dir()) {
if (g.world != 1) {
fprintf(stderr, "radiance: spark25 calibration requires one rank so column-split "
"Grams retain their cross terms\n");
return RAD_E_UNSUPPORTED;
}
RAD_ARCH_TRY(calib_layers("spark25", "RADIANCE_SPARK_CALIB_LAYERS", g.n_layer,
&m.calib_lo, &m.calib_hi));
m.tap_live = true;
}
const int64_t window = rad_meta_geti(meta, "sliding_window", 0);
if (window <= 0) {
fprintf(stderr, "radiance: spark25: a positive sliding_window is required\n");
return RAD_E_INVAL;
}
double theta[2]{};
int64_t rot[2]{};
const char* kinds[] = {"full_attention", "sliding_attention"};
for (int j = 0; j < 2; ++j) {
theta[j] = rad_meta_getf(meta, nm.f("rope_parameters.%s.rope_theta", kinds[j]), 10000.0);
const double factor = rad_meta_getf(meta,
nm.f("rope_parameters.%s.partial_rotary_factor", kinds[j]), 1.0);
const char* type = rad_meta_gets(meta, nm.f("rope_parameters.%s.rope_type", kinds[j]), "default");
if (std::strcmp(type, "default")) {
fprintf(stderr, "radiance: spark25: %s rotary type '%s' is not supported\n", kinds[j], type);
return RAD_E_UNSUPPORTED;
}
const double r = g.head_dim * factor;
if (!std::isfinite(theta[j]) || !(theta[j] > 0) || !(factor > 0 && factor <= 1) || !std::isfinite(r) ||
std::floor(r) != r || (int64_t)r % 2) {
fprintf(stderr, "radiance: spark25: invalid %s rotary theta %g or factor %g\n",
kinds[j], theta[j], factor);
return RAD_E_INVAL;
}
rot[j] = (int64_t)r;
}
/* A full cache for both kinds keeps prefix caching valid. The local attention op enforces
* its own window (q - k < window); the full layers read all past positions. */
RadKVGroupDecl kd{};
kd.kind = RAD_KV_FULL;
kd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
kd.n_head_kv = g.n_head_kv;
kd.head_dim = g.head_dim;
m.kv = rad_decl_kv_group(b, nm.f("kv_attn"), &kd);
if (!m.kv) return RAD_E_INVAL;
g.kv_dtype = rad_dtype_name(kd.dtype);
const int64_t T = g.max_tok, 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_F32, {T, E});
m.delta = decl_b(b, nm.f("delta"), RAD_F32, {T, E});
m.h = decl_b(b, nm.f("h"), RAD_BF16, {T, E});
m.q = decl_b(b, nm.f("q"), RAD_BF16, {T, Q});
m.k = decl_b(b, nm.f("k"), RAD_BF16, {T, K});
m.v = decl_b(b, nm.f("v"), RAD_BF16, {T, K});
m.gate = decl_b(b, nm.f("gate"), RAD_BF16, {T, g.n_head});
m.attn = decl_b(b, nm.f("attn"), RAD_BF16, {T, Q});
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.hout = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, E});
m.logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
if (!m.x || !m.delta || !m.h || !m.q || !m.k || !m.v || !m.gate || !m.attn || !m.gu || !m.ff ||
!m.hout || !m.logits) return RAD_E_INVAL;
m.a_h.x = m.h;
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", E, 0, true, false));
m.a_h.q8_fed = true;
m.a_h.q8_rot = true;
m.a_attn.x = m.attn;
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", Q, 0, true, false));
m.a_ff.x = m.ff;
RAD_ARCH_TRY(m.a_ff.declare_qs(b, nm, g, "ff", F, 0, true, false));
m.had = rw(b, RAD_OP(b, "had_quant_act_i8g",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS),
{m.h}, {m.a_h.q8, m.a_h.s8});
if (!m.had) return RAD_E_INVAL;
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
/* ---- the drafter's taps, when the container carries a drafter and this serve speculates.
* Declared before the layer loop because the stream outlives it: the drafter's context pass
* runs after the trunk's, on the residual streams the trunk saved here. */
bool drafter = false;
RAD_ARCH_TRY(drafter_kind(meta, &drafter));
if (drafter && ctx->max_spec > 0) {
m.taps.read(meta, g.n_layer);
if (m.taps.n <= 0) {
fprintf(stderr, "radiance: spark25: the drafter names no trunk layer to read, or names "
"only layers past this target's last (`draft.target_layer_ids`)\n");
return RAD_E_FORMAT;
}
RAD_ARCH_TRY(m.taps.declare(b, nm, g, g.max_tok, m.x));
}
auto weight = [&](const char* name, const char* src, uint32_t dt,
std::initializer_list<int64_t> shape, RadWeightGroup group,
int access = RAD_ACCESS_PER_TOKEN, int shard = RAD_SHARD_NONE) {
if (map_copy(b, name, src) != RAD_OK) return (rad_weight)0;
return decl_w(b, name, dt, shape, access, shard, group);
};
m.tok = weight(nm.f("token_embd.weight"), nm.ckpt("model.embedding.weight"), RAD_BF16,
{g.n_vocab, E}, grp_model(), RAD_ACCESS_VOCAB, RAD_SHARD_ROW);
/* The head is the tied table again, at whatever the container holds it: bf16 as shipped, or
* the int8 grid where the recipe quantised it, which is the widest GEMM a decode step runs. */
if (map_copy(b, nm.f("output.weight"), nm.ckpt("model.embedding.weight")) != RAD_OK)
return RAD_E_INVAL;
m.head = decl_w(b, nm.f("output.weight"),
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
{g.n_vocab, E}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
m.norm = weight(nm.f("output_norm.weight"), nm.ckpt("model.norm.weight"), RAD_F32,
{E}, grp_model());
if (!m.tok || !m.head || !m.norm) return RAD_E_INVAL;
if (g.world > 1 && g.n_vocab_all % g.world) {
RAD_ARCH_TRY(rad_weight_shard_span(b, m.tok, g.vocab_off, g.vocab_off + g.n_vocab));
RAD_ARCH_TRY(rad_weight_shard_span(b, m.head, g.vocab_off, g.vocab_off + g.n_vocab));
}
auto norm = [&](rad_weight w, rad_buf x, rad_buf y) {
return rw(b, RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w)), {x}, {y});
};
auto gemm = [&](int64_t n, int64_t k, rad_weight w, rad_buf x, rad_buf y) {
return rw(b, RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("N", n),
RAD_INT("K", k), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(w)), {x}, {y});
};
auto add = [&]() {
return rw(b, RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
RAD_STR("dtype", "f32")), RAD_NOWEIGHTS), {m.x, m.delta}, {m.x});
};
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_INT("vocab_offset", g.vocab_off)), RAD_WEIGHTS(m.tok)), {}, {m.h});
auto widen = [&](rad_buf output) {
return rw(b, RAD_OP(b, "cast", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
RAD_STR("from", "bf16"), RAD_STR("to", "f32")), RAD_NOWEIGHTS), {m.h}, {output});
};
m.widen = widen(m.x);
/* Embedding shards contribute disjoint rows, so their widened sum is exact. Projection
* shards must instead reduce in bf16, rounding the merged output before it is widened and
* added to the f32 residual, as in the reference's BF16 linear layers. */
auto reduce = [&](rad_buf x, const char* dtype) {
if (g.world <= 1) return (rad_op)0;
return rw(b, RAD_OP(b, "all_reduce", RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", E, T * E), RAD_STR("dtype", dtype), RAD_INT("exact", 1)),
RAD_NOWEIGHTS), {x}, {x});
};
m.reduce_embed = reduce(m.x, "fp32");
if (g.world > 1 && !m.reduce_embed) {
fprintf(stderr, "radiance: spark25_w8a8 requires an exact fp32 all-reduce for TP=%d\n", g.world);
return RAD_E_UNSUPPORTED;
}
m.layers.resize((size_t)g.n_layer);
for (int l = 0; l < g.n_layer; ++l) {
Layer& a = m.layers[(size_t)l];
auto src = [&](const char* suffix) { return nm.ckpt("model.layers.%d.%s", l, suffix); };
auto w = [&](const char* suffix, const char* s, uint32_t dt,
std::initializer_list<int64_t> shape, int shard = RAD_SHARD_NONE) {
return weight(nm.f("blk.%d.%s", l, suffix), src(s), dt, shape, grp_layer(l),
RAD_ACCESS_PER_TOKEN, shard);
};
a.an = w("attn_norm.weight", "input_layernorm.weight", RAD_F32, {E});
a.gate = w("attn_gate.weight", "self_attn.g_proj.weight", RAD_BF16, {g.n_head, E}, RAD_SHARD_ROW);
a.fn = w("ffn_norm.weight", "post_attention_layernorm.weight", RAD_F32, {E});
const char* qkv = src("self_attn.q_k_v_proj.weight");
const int64_t qall = g.n_head_all * g.head_dim, kall = g.n_head_kv_all * g.head_dim;
const int64_t qlo = needs_span(shards.q, g.n_head_all, g) ? shards.q.first * g.head_dim : 0;
const int64_t qhi = needs_span(shards.q, g.n_head_all, g)
? (shards.q.first + shards.q.count) * g.head_dim : 0;
const int64_t kvlo = needs_span(shards.kv, g.n_head_kv_all, g)
? shards.kv.first * g.head_dim : 0;
const int64_t kvhi = needs_span(shards.kv, g.n_head_kv_all, g)
? (shards.kv.first + shards.kv.count) * g.head_dim : 0;
auto map_part = [&](const char* name, int64_t first, int64_t rows) {
const char* target = nm.f("blk.%d.attn_%s.weight", l, name);
return map_rows(b, target, {{qkv, (int)first, rows}});
};
const char* qb = nm.f("blk.%d.attn_q", l);
const char* kb = nm.f("blk.%d.attn_k", l);
const char* vb = nm.f("blk.%d.attn_v", l);
RAD_ARCH_TRY(map_part("q", 0, qall));
RAD_ARCH_TRY(map_part("k", qall, kall));
RAD_ARCH_TRY(map_part("v", qall + kall, kall));
a.q.mapped = a.k.mapped = a.v.mapped = true;
RAD_ARCH_TRY(a.q.declare(b, nm, g, qb, Q, E, RAD_SHARD_ROW, grp_layer(l), {qkv},
m.a_h, m.q, 0, {}, qlo, qhi));
RAD_ARCH_TRY(a.k.declare(b, nm, g, kb, K, E, RAD_SHARD_ROW, grp_layer(l), {qkv},
m.a_h, m.k, 0, {}, kvlo, kvhi));
RAD_ARCH_TRY(a.v.declare(b, nm, g, vb, K, E, RAD_SHARD_ROW, grp_layer(l), {qkv},
m.a_h, m.v, 0, {}, kvlo, kvhi));
const int64_t olo = qlo, ohi = qhi;
RAD_ARCH_TRY(a.o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), E, Q,
RAD_SHARD_COL, grp_layer(l), {src("self_attn.out_proj.weight")},
m.a_attn, m.h, 0, {}, olo, ohi));
RAD_ARCH_TRY(a.gu.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up", l), 2 * F, E,
RAD_SHARD_ROW, grp_layer(l),
{src("mlp.gate_proj.weight"), src("mlp.up_proj.weight")},
m.a_h, m.gu, 0, {F, F}));
const int64_t flo = needs_span(shards.ff, g.n_ff_all, g) ? shards.ff.first : 0;
const int64_t fhi = needs_span(shards.ff, g.n_ff_all, g)
? shards.ff.first + shards.ff.count : 0;
if (needs_span(shards.ff, g.n_ff_all, g)) {
const int64_t lo[2] = {shards.ff.first, shards.ff.first};
const int64_t hi[2] = {shards.ff.first + shards.ff.count,
shards.ff.first + shards.ff.count};
const int64_t total[2] = {g.n_ff_all, g.n_ff_all};
RAD_ARCH_TRY(a.gu.span_parts(b, lo, hi, total, 2));
}
RAD_ARCH_TRY(a.down.declare(b, nm, g, nm.f("blk.%d.ffn_down", l), E, F,
RAD_SHARD_COL, grp_layer(l), {src("mlp.down_proj.weight")},
m.a_ff, m.h, 0, {}, flo, fhi));
if (!a.an || !a.gate || !a.fn || !a.q.w || !a.k.w || !a.v.w || !a.o.w ||
!a.gu.w || !a.down.w) return RAD_E_INVAL;
if (g.world > 1 && needs_span(shards.q, g.n_head_all, g))
RAD_ARCH_TRY(rad_weight_shard_span(b, a.gate, shards.q.first,
shards.q.first + shards.q.count));
a.kv = m.kv;
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, a.kv));
a.anorm = norm(a.an, m.x, m.h);
a.gp = gemm(g.n_head, E, a.gate, m.h, m.gate);
Geom rope = g;
const int kind = local[(size_t)l] ? 1 : 0;
rope.theta = (float)theta[kind];
a.rq = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head, 0, rot[kind], "neox"), {m.q}, {m.q});
a.rk = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head_kv, 0, rot[kind], "neox"), {m.k}, {m.k});
a.attn = rw(b, decl_attn(b, g, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, T), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), RAD_INT("window", kind ? window : 0),
RAD_INT("n_head", g.n_head), RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)), RAD_NOWEIGHTS),
{m.q}, {m.attn});
a.store = rw(b, RAD_OP(b, "kv_store", RAD_PARAMS(RAD_RANGE("M", 1, T),
RAD_INT("head_dim", g.head_dim), RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, a.kv)), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS), {m.k, m.v}, {});
a.sigmoid = rw(b, RAD_OP(b, "sigmoid", RAD_PARAMS(RAD_RANGE("M", 1, T),
RAD_INT("n", g.n_head), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.gate}, {m.gate});
/* View dense [tokens, heads * dim] and [tokens, heads] as one row per head. */
a.gate_heads = rw(b, RAD_OP(b, "scale_rows", RAD_PARAMS(RAD_RANGE("M", 1, T * g.n_head),
RAD_INT("n", g.head_dim), RAD_STR("act", "none"), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS), {m.attn, m.gate}, {m.attn});
a.reduce_attn = reduce(m.h, "bf16");
a.widen_attn = widen(m.delta);
a.add_attn = add();
a.fnorm = norm(a.fn, m.x, m.h);
a.act = rw(b, RAD_OP(b, "act_mul", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", F),
RAD_STR("act", "gelu"), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.gu}, {m.ff});
a.reduce_ffn = reduce(m.h, "bf16");
if (g.world > 1 && (!a.reduce_attn || !a.reduce_ffn)) {
fprintf(stderr, "radiance: spark25_w8a8 requires exact bf16 all-reduces for TP=%d\n", g.world);
return RAD_E_UNSUPPORTED;
}
a.widen_ffn = widen(m.delta);
a.add_ffn = add();
if (m.tap_live && l >= m.calib_lo && l < m.calib_hi) {
RAD_ARCH_TRY(a.tap_in.declare(b, nm, T, nm.f("blk.%d.attn_in", l), m.h, E));
RAD_ARCH_TRY(a.tap_o.declare(b, nm, T, nm.f("blk.%d.attn_o", l), m.attn, Q));
RAD_ARCH_TRY(a.tap_gu.declare(b, nm, T, nm.f("blk.%d.ffn_in", l), m.h, E));
RAD_ARCH_TRY(a.tap_down.declare(b, nm, T, nm.f("blk.%d.ffn_down_in", l), m.ff, F));
}
}
m.final_norm = norm(m.norm, m.x, m.h);
m.gather = rw(b, RAD_OP(b, "gather_rows", RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n", E), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.h}, {m.hout});
m.logits_op = rw(b, RAD_OP(b, "logits_gemm", RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(m.head)), {m.hout}, {m.logits});
char ids[128] = "";
/* The drafter is declared last, after the head. The buffer planner takes lifetimes in
* declaration order, and a drafter's passes run after the whole trunk's, so declaring it in the
* middle would let a trunk temporary be planned onto bytes the drafter is still reading. */
if (m.taps.n > 0) {
RAD_ARCH_TRY(declare_dspark(&m.ds, &m.dsw, &m.kv_draft, b, nm, meta, ctx, g, m.taps,
(int)g.n_layer, m.tok, nm.ckpt("model.embedding.weight")));
m.have_ds = true;
for (int t = 0, off = 0; t < m.taps.n && off < (int)sizeof(ids) - 8; ++t)
off += std::snprintf(ids + off, sizeof ids - off, "%s%d", t ? ", " : "",
m.taps.layer[t]);
rad_note(b, "the drafter reads the residual stream after layer(s) %s", ids);
}
rad_note(b, "spark25 rank %d/%d: %lld layers, %lld query / %lld KV heads x %lld, "
"FFN %lld, vocab [%lld, %lld), local window %lld", g.rank, g.world,
(long long)g.n_layer, (long long)g.n_head, (long long)g.n_head_kv,
(long long)g.head_dim, (long long)g.n_ff, (long long)g.vocab_off,
(long long)(g.vocab_off + g.n_vocab), (long long)window);
return RAD_OK;
}
static void step(RadCtx* c, const RadBatch* batch) {
Model& m = models[rad_rank(c)];
const Geom& g = m.g;
/* A drafter pass; the sign gives the kind. Positive is the query pass, which denoises the whole
* block and proposes from it; negative is the context pass, which turns the tokens the trunk
* just committed into the drafter's own K and V. Zero is a trunk step. */
if (batch->draft_pass != 0) {
if (!m.have_ds) {
rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the "
"container carries no `draft.` block, or declare ran at max_spec 0");
return;
}
if (batch->draft_pass > 0) m.ds.step(c, batch);
else m.ds.context(c, batch);
return;
}
const int64_t T = batch->n_tok;
const RadOperand pos = praw(batch->positions, RAD_I32, T);
RAD_ISSUE(c, m.embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.tok), brows(m.h, T));
RAD_ISSUE(c, m.widen, brows(m.h, T), brows(m.x, T));
if (m.reduce_embed) RAD_ISSUE_N(c, m.reduce_embed, T * g.n_embd, brows(m.x, T), RAD_NONE);
for (size_t i = 0; i < m.layers.size(); ++i) {
const Layer& a = m.layers[i];
const RadKVGroupBatch* kvb = kv_batch(batch, a.kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int32_t* used = kvb ? kvb->seqused : nullptr;
RAD_ISSUE(c, a.anorm, brows(m.x, T), RAD_W(a.an), brows(m.h, T));
a.tap_in.step(c, m.h, T, m.tap_live);
RAD_ISSUE(c, m.had, brows(m.h, T), brows(m.a_h.q8, T), brows(m.a_h.s8, T));
a.q.step(c, m.a_h, m.q, T);
a.k.step(c, m.a_h, m.k, T);
a.v.step(c, m.a_h, m.v, T);
RAD_ISSUE(c, a.gp, brows(m.h, T), RAD_W(a.gate), brows(m.gate, T));
RAD_ISSUE(c, a.rq, brows(m.q, T), pos);
RAD_ISSUE(c, a.rk, brows(m.k, T), pos);
RAD_ISSUE(c, a.store, brows(m.k, T), brows(m.v, T), praw(slot, RAD_I32, T),
kv_cache(a.kv, (int)i));
RAD_ISSUE_N(c, a.attn, batch->max_q_len, brows(m.q, T), kv_cache(a.kv, (int)i),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(m.attn, T));
RAD_ISSUE(c, a.sigmoid, brows(m.gate, T), brows(m.gate, T));
const RadOperand heads = RAD_P_T2(rad_buf_ptr(c, m.attn), RAD_BF16, T * g.n_head, g.head_dim);
const RadOperand gates = RAD_P_T2(rad_buf_ptr(c, m.gate), RAD_BF16, T * g.n_head, 1);
RAD_ISSUE_N(c, a.gate_heads, T * g.n_head, heads, gates, RAD_NONE, heads);
a.tap_o.step(c, m.attn, T, m.tap_live);
a.o.step(c, m.a_attn, m.h, T);
if (a.reduce_attn) RAD_ISSUE_N(c, a.reduce_attn, T * g.n_embd, brows(m.h, T), RAD_NONE);
RAD_ISSUE(c, a.widen_attn, brows(m.h, T), brows(m.delta, T));
RAD_ISSUE(c, a.add_attn, brows(m.x, T), brows(m.delta, T), brows(m.x, T));
RAD_ISSUE(c, a.fnorm, brows(m.x, T), RAD_W(a.fn), brows(m.h, T));
a.tap_gu.step(c, m.h, T, m.tap_live);
RAD_ISSUE(c, m.had, brows(m.h, T), brows(m.a_h.q8, T), brows(m.a_h.s8, T));
a.gu.step(c, m.a_h, m.gu, T);
RAD_ISSUE(c, a.act, bcol(m.gu, 0, g.n_ff, T), bcol(m.gu, g.n_ff, g.n_ff, T), brows(m.ff, T));
a.tap_down.step(c, m.ff, T, m.tap_live);
a.down.step(c, m.a_ff, m.h, T);
if (a.reduce_ffn) RAD_ISSUE_N(c, a.reduce_ffn, T * g.n_embd, brows(m.h, T), RAD_NONE);
RAD_ISSUE(c, a.widen_ffn, brows(m.h, T), brows(m.delta, T));
RAD_ISSUE(c, a.add_ffn, brows(m.x, T), brows(m.delta, T), brows(m.x, T));
/* The tap after this layer, on prefill and decode alike: the drafter conditions on every
* committed token's residual stream, not only on prefill's. */
m.taps.step(c, m.x, T, (int64_t)i, g.n_embd);
}
RAD_ISSUE(c, m.final_norm, brows(m.x, T), RAD_W(m.norm), brows(m.h, T));
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.gather, batch->n_out, brows(m.h, T),
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.hout, batch->n_out));
RAD_ISSUE_N(c, m.logits_op, batch->n_out, brows(m.hout, batch->n_out), RAD_W(m.head),
brows(m.logits, batch->n_out));
}
if (m.tap_live) {
m.calib_rows += T;
if (m.calib_rows >= calib_target()) {
bool ok = true;
for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) {
const Layer& a = m.layers[(size_t)l];
char stem[96];
for (const char* proj : {"attn_q", "attn_k", "attn_v"}) {
std::snprintf(stem, sizeof stem, "blk.%lld.%s", (long long)l, proj);
ok = calib_write(c, a.tap_in.h, a.tap_in.K, m.calib_rows, stem, 0) && ok;
}
std::snprintf(stem, sizeof stem, "blk.%lld.attn_output", (long long)l);
ok = calib_write(c, a.tap_o.h, a.tap_o.K, m.calib_rows, stem, 0) && ok;
std::snprintf(stem, sizeof stem, "blk.%lld.ffn_gate_up", (long long)l);
ok = calib_write(c, a.tap_gu.h, a.tap_gu.K, m.calib_rows, stem, 0) && ok;
std::snprintf(stem, sizeof stem, "blk.%lld.ffn_down", (long long)l);
ok = calib_write(c, a.tap_down.h, a.tap_down.K, m.calib_rows, stem, 0) && ok;
}
m.tap_live = false;
std::fprintf(stderr, "radiance: spark25 rank %d wrote calibration Grams for layers "
"%lld:%lld after %lld tokens to %s%s\n", rad_rank(c),
(long long)m.calib_lo, (long long)m.calib_hi, m.calib_rows, calib_dir(),
ok ? "" : ", with errors");
}
}
}
#ifdef SPARK25_HAVE_PREFILL_SPLIT
static uint64_t pass_key(RadCtx* c, const RadBatch* batch, const int32_t* used_max_h) {
if (!c || !batch) return 0;
Model& m = models[rad_rank(c)];
int group = -1;
if (batch->kv) for (int i = 0; i < batch->n_kv_groups; ++i)
if (batch->kv[i].group == m.kv) { group = i; break; }
spark25_prefill_key::Request r;
r.phase = batch->phase;
r.n_tok = batch->n_tok;
r.n_seq = batch->n_seq;
r.max_q_len = batch->max_q_len;
r.max_ctx = m.g.max_ctx;
r.n_spec = batch->n_spec;
r.draft_pass = batch->draft_pass;
r.enc = batch->enc != 0;
r.head_dim = m.g.head_dim;
r.gqa = m.g.gqa();
r.kv_heads = m.g.n_head_kv;
r.kv_group_found = group >= 0;
r.used = used_max_h && group >= 0 ? used_max_h[group] : 0;
r.wgps = rad_ctx_wgp_count(c);
return spark25_prefill_key::pass_key(r);
}
#endif
/* The speculation depth this container supports: zero without a drafter, or the block length a
* DSpark drafter was trained at. `draft_depth_fixed` because a block-diffusion drafter denoises
* exactly that many mask positions, and `declare` refuses to run it at any other depth. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
out->draft_depth = 0;
out->draft_depth_fixed = 0;
bool present = false;
if (drafter_kind(meta, &present) != RAD_OK) return RAD_E_UNSUPPORTED;
if (!present) return RAD_OK;
const long long bs = rad_meta_geti(meta, "draft.block_size", 0);
if (bs < 2) {
fprintf(stderr, "radiance: spark25: the container carries a drafter with no "
"draft.block_size\n");
return RAD_E_FORMAT;
}
out->draft_depth = (int)bs;
out->draft_depth_fixed = 1;
return RAD_OK;
}
static const RadChatFormat* chat_format(const RadModelMeta*) { return spark25_bf16::spark_chat_format(); }
}
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(spark25_w8a8)
RAD_ARCH_PLUGIN(spark25_w8a8, "spark25", "w8a8_fwht128", "0.1.0",
"Spark X2.6 with an int8 trunk: i8 weights with a bf16 scale a 128 of K, rotated "
"by a 128-wide Hadamard, against int8 activations the same rotation quantises")
RAD_ARCH_CHAT_FORMAT(spark25_w8a8)
#ifdef SPARK25_HAVE_PREFILL_SPLIT
extern "C" uint64_t rad_arch_pass_key(RadCtx* c, const RadBatch* batch,
const int32_t* used_max_h) {
return spark25_w8a8::pass_key(c, batch, used_max_h);
}
#endif
#endif
+5
View File
@@ -23,6 +23,11 @@ list(APPEND RAD_CORE_SRC ${_top})
add_library(rad_core STATIC ${RAD_CORE_SRC}) add_library(rad_core STATIC ${RAD_CORE_SRC})
target_link_libraries(rad_core PUBLIC rad_abi ${CMAKE_DL_LIBS} Threads::Threads) target_link_libraries(rad_core PUBLIC rad_abi ${CMAKE_DL_LIBS} Threads::Threads)
target_compile_definitions(rad_core PUBLIC RAD_VERSION="${PROJECT_VERSION}") target_compile_definitions(rad_core PUBLIC RAD_VERSION="${PROJECT_VERSION}")
if(RAD_ENABLE_KV_ROLLBACK_TEST_HOOK)
# Scheduler is embedded in Engine and its test-only callback changes its class layout.
# Propagate the definition to every consumer to keep all translation units ABI-consistent.
target_compile_definitions(rad_core PUBLIC RAD_ENABLE_KV_ROLLBACK_TEST_HOOK=1)
endif()
target_include_directories(rad_core PUBLIC target_include_directories(rad_core PUBLIC
${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/abi ${CMAKE_SOURCE_DIR}/abi
+1
View File
@@ -137,6 +137,7 @@ public:
int declare_generator(const RadGeneratorDecl* d); int declare_generator(const RadGeneratorDecl* d);
int declare_audio_generator(const RadAudioGenDecl* d); int declare_audio_generator(const RadAudioGenDecl* d);
int declare_video_generator(const RadVideoGenDecl* d); int declare_video_generator(const RadVideoGenDecl* d);
int declare_shape_generator(const RadShapeGenDecl* d);
void note_v (const char* f, va_list ap); void note_v (const char* f, va_list ap);
/* An op's buffer operands (rad_op_reads/rad_op_writes in rad_builder.h), which give the /* An op's buffer operands (rad_op_reads/rad_op_writes in rad_builder.h), which give the
+137 -12
View File
@@ -1201,6 +1201,11 @@ int Builder::declare_logits(rad_buf b) {
prog_.vgen_str.name.c_str()); prog_.vgen_str.name.c_str());
return RAD_E_STATE; return RAD_E_STATE;
} }
if (prog_.is_shape_generator()) {
err(RAD_E_STATE, "declare_logits: this program already declared the shape generator '%s'",
prog_.sgen_name.c_str());
return RAD_E_STATE;
}
prog_.logits_buf = b; prog_.logits_buf = b;
return RAD_OK; return RAD_OK;
} }
@@ -1241,6 +1246,11 @@ int Builder::declare_pooled(rad_buf b) {
prog_.vgen_str.name.c_str()); prog_.vgen_str.name.c_str());
return RAD_E_STATE; return RAD_E_STATE;
} }
if (prog_.is_shape_generator()) {
err(RAD_E_STATE, "declare_pooled: this program already declared the shape generator '%s'",
prog_.sgen_name.c_str());
return RAD_E_STATE;
}
const RadBufDecl& d = prog_.buffers[b].decl; const RadBufDecl& d = prog_.buffers[b].decl;
if (d.dtype != RAD_F32 || d.domain != RAD_DOMAIN_DEVICE || d.rank != 2 || if (d.dtype != RAD_F32 || d.domain != RAD_DOMAIN_DEVICE || d.rank != 2 ||
d.shape[0] < prog_.ctx.max_seqs || d.shape[1] <= 0) { d.shape[0] < prog_.ctx.max_seqs || d.shape[1] <= 0) {
@@ -1329,6 +1339,11 @@ int Builder::declare_encoder(const RadEncoderDecl* d) {
(int)d->one_grid); (int)d->one_grid);
return RAD_E_INVAL; return RAD_E_INVAL;
} }
if (d->bidirectional != 0 && (d->bidirectional != 1 || audio)) {
err(RAD_E_INVAL, "declare_encoder '%s': bidirectional %d -- 0, or 1 for a picture and video "
"encoder", nm, (int)d->bidirectional);
return RAD_E_INVAL;
}
slot = *d; slot = *d;
slot_name = nm; slot_name = nm;
slot.name = nullptr; /* the plugin's storage; the name is the copy */ slot.name = nullptr; /* the plugin's storage; the name is the copy */
@@ -1348,12 +1363,13 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
return RAD_E_STATE; return RAD_E_STATE;
} }
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE || if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
prog_.is_audio_generator() || prog_.is_video_generator()) { prog_.is_audio_generator() || prog_.is_video_generator() || prog_.is_shape_generator()) {
err(RAD_E_STATE, "declare_generator '%s': this program already declared %s; a program " err(RAD_E_STATE, "declare_generator '%s': this program already declared %s; a program "
"generates text, embeds, makes images, audio or video -- one of the five", "generates text, embeds, makes images, audio, video or shapes -- one of "
nm, prog_.logits_buf != RAD_NULL_HANDLE ? "logits" "the six", nm, prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output" : prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
: prog_.is_audio_generator() ? "an audio generator" : "a video generator"); : prog_.is_audio_generator() ? "an audio generator"
: prog_.is_video_generator() ? "a video generator" : "a shape generator");
return RAD_E_STATE; return RAD_E_STATE;
} }
if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID && d->layout != RAD_GEN_LAYOUT_JOINT_STEP) { if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID && d->layout != RAD_GEN_LAYOUT_JOINT_STEP) {
@@ -1505,13 +1521,14 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
return RAD_E_STATE; return RAD_E_STATE;
} }
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE || if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
prog_.generator.layout != 0 || prog_.is_video_generator()) { prog_.generator.layout != 0 || prog_.is_video_generator() || prog_.is_shape_generator()) {
err(RAD_E_STATE, "declare_audio_generator '%s': this program already declared %s; a " err(RAD_E_STATE, "declare_audio_generator '%s': this program already declared %s; a "
"program generates text, embeds, makes images, audio or video -- one of " "program generates text, embeds, makes images, audio, video or shapes -- "
"the five", nm, "one of the six", nm,
prog_.logits_buf != RAD_NULL_HANDLE ? "logits" prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output" : prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
: prog_.generator.layout != 0 ? "an image generator" : "a video generator"); : prog_.generator.layout != 0 ? "an image generator"
: prog_.is_video_generator() ? "a video generator" : "a shape generator");
return RAD_E_STATE; return RAD_E_STATE;
} }
if (!d->tmpl && !d->tmpl_plain) { if (!d->tmpl && !d->tmpl_plain) {
@@ -1682,13 +1699,14 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) {
return RAD_E_STATE; return RAD_E_STATE;
} }
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE || if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
prog_.generator.layout != 0 || prog_.is_audio_generator()) { prog_.generator.layout != 0 || prog_.is_audio_generator() || prog_.is_shape_generator()) {
err(RAD_E_STATE, "declare_video_generator '%s': this program already declared %s; a " err(RAD_E_STATE, "declare_video_generator '%s': this program already declared %s; a "
"program generates text, embeds, makes images, audio or video -- one of " "program generates text, embeds, makes images, audio, video or shapes -- "
"the five", nm, "one of the six", nm,
prog_.logits_buf != RAD_NULL_HANDLE ? "logits" prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output" : prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
: prog_.generator.layout != 0 ? "an image generator" : "an audio generator"); : prog_.generator.layout != 0 ? "an image generator"
: prog_.is_audio_generator() ? "an audio generator" : "a shape generator");
return RAD_E_STATE; return RAD_E_STATE;
} }
if (!d->tmpl || !std::strstr(d->tmpl, "{prompt}") || d->max_text <= 0) { if (!d->tmpl || !std::strstr(d->tmpl, "{prompt}") || d->max_text <= 0) {
@@ -1903,6 +1921,108 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) {
return RAD_OK; return RAD_OK;
} }
/* The shape generator (rad_declare_shape_generator). Checked here rather than at the first request:
* the picture's geometry, the sampler, the grid and the field's buffer, which the core reads back
* after every query pass. */
int Builder::declare_shape_generator(const RadShapeGenDecl* d) {
if (finished_) {
err(RAD_E_STATE, "declare_shape_generator after declare finished");
return RAD_E_STATE;
}
if (!d) { err(RAD_E_INVAL, "declare_shape_generator: null declaration"); return RAD_E_INVAL; }
const char* nm = d->name && *d->name ? d->name : "(unnamed)";
if (prog_.is_shape_generator()) {
err(RAD_E_STATE, "declare_shape_generator: '%s' was already declared; '%s' is a second one",
prog_.sgen_name.c_str(), nm);
return RAD_E_STATE;
}
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
prog_.generator.layout != 0 || prog_.is_audio_generator() || prog_.is_video_generator()) {
err(RAD_E_STATE, "declare_shape_generator '%s': this program already declared %s; a "
"program generates text, embeds, makes images, audio, video or shapes -- "
"one of the six", nm,
prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
: prog_.generator.layout != 0 ? "an image generator"
: prog_.is_audio_generator() ? "an audio generator" : "a video generator");
return RAD_E_STATE;
}
if (d->canvas < 1 || d->canvas > 4096 || !(d->border_ratio >= 0.0 && d->border_ratio < 1.0) ||
d->enc_patch < 1 || d->enc_size < d->enc_patch || d->enc_size > 4096 ||
d->enc_size % d->enc_patch != 0) {
err(RAD_E_INVAL, "declare_shape_generator '%s': the picture is out of range (canvas %lld, "
"border %g, encoder %lld in patches of %lld): the canvas 1..4096, the "
"border in [0, 1), the encoder's side 1..4096 and a whole number of "
"patches", nm, (long long)d->canvas, d->border_ratio,
(long long)d->enc_size, (long long)d->enc_patch);
return RAD_E_INVAL;
}
for (int c = 0; c < 3; ++c)
if (!std::isfinite(d->pix_mean[c]) || !(d->pix_std[c] > 0.0) ||
!std::isfinite(d->pix_std[c])) {
err(RAD_E_INVAL, "declare_shape_generator '%s': channel %d's mean %g and deviation %g "
"must be finite and the deviation positive", nm, c, d->pix_mean[c],
d->pix_std[c]);
return RAD_E_INVAL;
}
if (d->latent_rows < 1 || d->latent_channels < 1 || d->step_rows < 2 * d->latent_rows) {
err(RAD_E_INVAL, "declare_shape_generator '%s': a latent of %lld rows of %lld channels "
"and a step of %lld rows; a step holds both branches' latents", nm,
(long long)d->latent_rows, (long long)d->latent_channels, (long long)d->step_rows);
return RAD_E_INVAL;
}
if (d->default_steps < 2 || d->max_steps < d->default_steps || d->max_steps > 1000 ||
!(d->default_guidance >= 0.0) || !std::isfinite(d->default_guidance)) {
err(RAD_E_INVAL, "declare_shape_generator '%s': the sampler is out of range (%lld steps "
"by default, %lld at most, guidance %g): at least 2 grid points, at most "
"1000, the guidance finite and not negative", nm,
(long long)d->default_steps, (long long)d->max_steps, d->default_guidance);
return RAD_E_INVAL;
}
if (!(d->bounds > 0.0) || !std::isfinite(d->bounds) || !std::isfinite(d->level) ||
d->min_resolution < 2 || d->default_resolution < d->min_resolution ||
d->max_resolution < d->default_resolution || d->max_resolution > 2048) {
err(RAD_E_INVAL, "declare_shape_generator '%s': the field is out of range (bounds %g, "
"level %g, resolution %lld in %lld..%lld): the bounds positive, the level "
"finite, the resolutions in order from 2 to 2048", nm, d->bounds,
d->level, (long long)d->default_resolution, (long long)d->min_resolution,
(long long)d->max_resolution);
return RAD_E_INVAL;
}
if (d->max_lanes < 1 || d->max_query < 1) {
err(RAD_E_INVAL, "declare_shape_generator '%s': %lld lanes and %lld points a query pass; "
"both at least 1", nm, (long long)d->max_lanes, (long long)d->max_query);
return RAD_E_INVAL;
}
const int64_t n_patch = (d->enc_size / d->enc_patch) * (d->enc_size / d->enc_patch);
const int64_t rows = std::max({ d->step_rows, d->max_query, n_patch, d->latent_rows });
if (prog_.ctx.max_tok < rows) {
err(RAD_E_INVAL, "declare_shape_generator '%s': a pass carries %lld rows and this one's "
"largest is %lld", nm, (long long)prog_.ctx.max_tok, (long long)rows);
return RAD_E_INVAL;
}
const rad_buf h = d->field_out;
if (h == RAD_NULL_HANDLE || (size_t)h >= prog_.buffers.size()) {
err(RAD_E_INVAL, "declare_shape_generator '%s': field_out %u is not a declared buffer", nm,
(unsigned)h);
return RAD_E_INVAL;
}
const RadBufDecl& ob = prog_.buffers[h].decl;
if (ob.dtype != RAD_F32 || ob.domain != RAD_DOMAIN_DEVICE ||
decl_numel(ob.rank, ob.shape) < d->max_query) {
err(RAD_E_INVAL, "declare_shape_generator '%s': field_out '%s' must be a device f32 "
"buffer of at least %lld elements", nm, prog_.buffers[h].name.c_str(),
(long long)d->max_query);
return RAD_E_INVAL;
}
prog_.sgen_name = nm;
prog_.shape_gen = *d;
/* As for the other generators: the Program is moved after declare; the name lives in
* sgen_name. */
prog_.shape_gen.name = nullptr;
return RAD_OK;
}
/* Validates the draft head at declare rather than at the first draft pass, where a bad decl would /* Validates the draft head at declare rather than at the first draft pass, where a bad decl would
* only show as zero acceptance. `depth` must equal RadBuildCtx::max_spec, which the plugin sized * only show as zero acceptance. `depth` must equal RadBuildCtx::max_spec, which the plugin sized
* its buffers with. */ * its buffers with. */
@@ -2745,6 +2865,11 @@ int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d) {
return B(b)->declare_video_generator(d); return B(b)->declare_video_generator(d);
} }
int rad_declare_shape_generator(RadBuilder* b, const RadShapeGenDecl* d) {
if (!b) return RAD_E_INVAL;
return B(b)->declare_shape_generator(d);
}
void rad_note(RadBuilder* b, const char* f, ...) { void rad_note(RadBuilder* b, const char* f, ...) {
if (!b) return; if (!b) return;
va_list ap; va_list ap;
+58 -12
View File
@@ -76,8 +76,10 @@ static const Flag g_flags[] = {
"(default) leaves decode rows and new requests their room,\n" "(default) leaves decode rows and new requests their room,\n"
"off takes the whole step, N holds the chunk to N tokens" }, "off takes the whole step, N holds the chunk to N tokens" },
{ "--prefill-interleave", "N", "decode-only steps after each prefill chunk while other\n" { "--prefill-interleave", "N", "decode-only steps after each prefill chunk while other\n"
"sequences decode, at most 64; 0 (default) lets every step\n" "sequences decode, at most 64; auto fits them in a quarter\n"
"carry a chunk" }, "of the chunk step's time, auto:SHARE in SHARE of it (0-4];\n"
"0 lets every step carry a chunk; served default auto:1\n"
"(0 under --deterministic, KL mode, generators)" },
{ "--preempt-wait-ms", "N", "how long a preempted prefill may wait for the whole-\n" { "--preempt-wait-ms", "N", "how long a preempted prefill may wait for the whole-\n"
"recompute gate before reclaiming cache blocks and\n" "recompute gate before reclaiming cache blocks and\n"
"preempting the lowest-priority running request; 0\n" "preempting the lowest-priority running request; 0\n"
@@ -87,7 +89,10 @@ static const Flag g_flags[] = {
{ "--rope-scaling", "SPEC", "yarn:FACTOR[:ORIG]: static YaRN over the container's own rotary\n" { "--rope-scaling", "SPEC", "yarn:FACTOR[:ORIG]: static YaRN over the container's own rotary\n"
"keys, no reconvert (docs/YARN.md); none: off" }, "keys, no reconvert (docs/YARN.md); none: off" },
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" }, { "--gpu-memory-mib", "N", "VRAM claimed on every card; the rest is left unclaimed.\n"
"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 | fp8 | fp8_v4 | k6_v4 -- fp8 halves what a token of\n" { "--kv-cache-dtype", "T", "bf16 | fp8 | fp8_v4 | k6_v4 -- fp8 halves what a token of\n"
"context costs; fp8_v4 keeps V in 4 bits (0.78 of fp8), k6_v4\n" "context costs; fp8_v4 keeps V in 4 bits (0.78 of fp8), k6_v4\n"
"also K in 6 (0.69); both Qwen3.8-27B and -Flash-Next" }, "also K in 6 (0.69); both Qwen3.8-27B and -Flash-Next" },
@@ -568,7 +573,22 @@ int config_parse(int argc, char** argv, Config* c) {
else if (!std::strcmp(v, "off")) c->busy_prefill_chunk = 0; else if (!std::strcmp(v, "off")) c->busy_prefill_chunk = 0;
else if (!parse_int(a.c_str(), v, 1, INT64_MAX, &c->busy_prefill_chunk)) return RAD_E_INVAL; else if (!parse_int(a.c_str(), v, 1, INT64_MAX, &c->busy_prefill_chunk)) return RAD_E_INVAL;
} }
else if (S("--prefill-interleave")) { if (!num(0, 64, &c->prefill_interleave)) return RAD_E_INVAL; } else if (S("--prefill-interleave")) {
if (!(v = need(i))) return RAD_E_INVAL;
c->prefill_interleave_set = true;
if (!std::strcmp(v, "auto")) { c->prefill_interleave = -1; c->prefill_interleave_share = 0.25; }
else if (!std::strncmp(v, "auto:", 5)) {
/* auto:SHARE -- decode-only steps for up to SHARE x a chunk step's time, 0 < SHARE <= 4 */
char* e = nullptr;
const double sh = std::strtod(v + 5, &e);
if (e == v + 5 || *e || !(sh > 0.0 && sh <= 4.0)) {
RAD_ERR("--prefill-interleave %s: auto:SHARE takes a share in (0, 4]", v);
return RAD_E_INVAL;
}
c->prefill_interleave = -1; c->prefill_interleave_share = sh;
}
else if (!parse_int(a.c_str(), v, 0, 64, &c->prefill_interleave)) return RAD_E_INVAL;
}
else if (S("--preempt-wait-ms")) { if (!num(0, INT64_MAX, &c->preempt_wait_ms)) return RAD_E_INVAL; } else if (S("--preempt-wait-ms")) { if (!num(0, INT64_MAX, &c->preempt_wait_ms)) return RAD_E_INVAL; }
else if (S("--max-num-seqs")) { if (!num(1, INT64_MAX, &c->max_seqs)) return RAD_E_INVAL; } else if (S("--max-num-seqs")) { if (!num(1, INT64_MAX, &c->max_seqs)) return RAD_E_INVAL; }
else if (S("--max-model-len")) { if (!num(0, INT64_MAX, &c->max_ctx)) return RAD_E_INVAL; } else if (S("--max-model-len")) { if (!num(0, INT64_MAX, &c->max_ctx)) return RAD_E_INVAL; }
@@ -587,14 +607,15 @@ int config_parse(int argc, char** argv, Config* c) {
* old launch lines at the flags that move the split. */ * old launch lines at the flags that move the split. */
else if (S("--vram-weights-mib") || S("--vram-kv-mib")) { else if (S("--vram-weights-mib") || S("--vram-kv-mib")) {
RAD_ERR("%s was removed: the card is split between the weights and the cache from what " RAD_ERR("%s was removed: the card is split between the weights and the cache from what "
"the model needs. --gpu-headroom-mib takes card space away, --max-model-len and " "the model needs. --gpu-headroom-mib or --gpu-memory-mib take card space away, "
"--max-num-seqs bound the cache, and --host-pool-mib decides which experts stay " "--max-model-len and --max-num-seqs bound the cache, and --host-pool-mib "
"on the card", a.c_str()); "decides which experts stay on the card", a.c_str());
return RAD_E_INVAL; return RAD_E_INVAL;
} }
/* --gpu-headroom is accepted as an alias of --gpu-headroom-mib. */ /* --gpu-headroom is accepted as an alias of --gpu-headroom-mib. */
else if (S("--gpu-headroom-mib") || S("--gpu-headroom")) else if (S("--gpu-headroom-mib") || S("--gpu-headroom"))
{ if (!num(0, INT64_MAX, &c->gpu_headroom_mib)) return RAD_E_INVAL; } { if (!num(0, INT64_MAX, &c->gpu_headroom_mib)) return RAD_E_INVAL; }
else if (S("--gpu-memory-mib")) { if (!num(1, INT64_MAX, &c->gpu_memory_mib)) return RAD_E_INVAL; }
else if (S("--host-headroom-mib")) { if (!num(0, INT64_MAX, &c->host_headroom_mib)) return RAD_E_INVAL; } else if (S("--host-headroom-mib")) { if (!num(0, INT64_MAX, &c->host_headroom_mib)) return RAD_E_INVAL; }
else if (S("--kv-cache-dtype")) { else if (S("--kv-cache-dtype")) {
if (!(v = need(i))) return RAD_E_INVAL; if (!(v = need(i))) return RAD_E_INVAL;
@@ -641,7 +662,7 @@ int config_parse(int argc, char** argv, Config* c) {
RAD_ERR("--embedding-placement takes ram or vram, not '%s'", v); RAD_ERR("--embedding-placement takes ram or vram, not '%s'", v);
return RAD_E_INVAL; return RAD_E_INVAL;
} }
std::string share_dir; std::string share_dir, disk_dir;
if (!emb && !std::strncmp(v, "ram=", 4)) { if (!emb && !std::strncmp(v, "ram=", 4)) {
share_dir = v + 4; share_dir = v + 4;
if (share_dir.empty()) { if (share_dir.empty()) {
@@ -650,11 +671,23 @@ int config_parse(int argc, char** argv, Config* c) {
return RAD_E_INVAL; return RAD_E_INVAL;
} }
p = TablePlacement::Ram; p = TablePlacement::Ram;
} else if (!emb && !std::strncmp(v, "disk=", 5)) {
disk_dir = v + 5;
if (disk_dir.empty()) {
RAD_ERR("--ngram-placement disk= needs a directory: disk=DIR, where the table "
"is read from its own file");
return RAD_E_INVAL;
}
p = TablePlacement::Disk;
} else if (!emb && !parse_table_placement(v, &p)) { } else if (!emb && !parse_table_placement(v, &p)) {
RAD_ERR("%s takes auto, vram, ram, ram=DIR or disk, not '%s'", a.c_str(), v); RAD_ERR("%s takes auto, vram, ram, ram=DIR, disk or disk=DIR, not '%s'", a.c_str(),
v);
return RAD_E_INVAL; return RAD_E_INVAL;
} }
if (!emb) c->ngram_share_dir = share_dir; if (!emb) {
c->ngram_share_dir = share_dir;
c->ngram_disk_dir = disk_dir;
}
(emb ? c->embedding_placement : c->ngram_placement) = p; (emb ? c->embedding_placement : c->ngram_placement) = p;
if (emb) c->embedding_placement_given = true; if (emb) c->embedding_placement_given = true;
} }
@@ -1130,6 +1163,14 @@ int config_parse(int argc, char** argv, Config* c) {
return RAD_E_INVAL; return RAD_E_INVAL;
} }
/* --gpu-memory-mib claims the card; --gpu-headroom-mib leaves it unclaimed. The alias
* --gpu-headroom is recorded as --gpu-headroom-mib, so it is covered. */
if (c->given.count("--gpu-memory-mib") && c->given.count("--gpu-headroom-mib")) {
RAD_ERR("--gpu-memory-mib claims the card and --gpu-headroom-mib leaves it unclaimed; "
"give one");
return RAD_E_INVAL;
}
/* Prompt lookup alone: the window is its K, stated once. */ /* Prompt lookup alone: the window is its K, stated once. */
if (c->spec_ngram_min > c->spec_ngram_max) { if (c->spec_ngram_min > c->spec_ngram_max) {
RAD_ERR("--spec-ngram-min %d is longer than --spec-ngram-max %d", c->spec_ngram_min, RAD_ERR("--spec-ngram-min %d is longer than --spec-ngram-max %d", c->spec_ngram_min,
@@ -1322,12 +1363,16 @@ const ShowRow kShow[] = {
return c.busy_prefill_chunk < 0 ? std::string("auto") return c.busy_prefill_chunk < 0 ? std::string("auto")
: c.busy_prefill_chunk == 0 ? std::string("off") : num(c.busy_prefill_chunk); } }, : c.busy_prefill_chunk == 0 ? std::string("off") : num(c.busy_prefill_chunk); } },
{ "--prefill-interleave", [](const Config& c) { { "--prefill-interleave", [](const Config& c) {
return c.prefill_interleave > 0 ? num(c.prefill_interleave) : std::string("off"); } }, return c.prefill_interleave > 0 ? num(c.prefill_interleave)
: c.prefill_interleave < 0 ? "auto:" + std::to_string(c.prefill_interleave_share)
: std::string("off"); } },
{ "--preempt-wait-ms", [](const Config& c) { return num(c.preempt_wait_ms); } }, { "--preempt-wait-ms", [](const Config& c) { return num(c.preempt_wait_ms); } },
{ "--max-num-seqs", [](const Config& c) { return num(c.max_seqs); } }, { "--max-num-seqs", [](const Config& c) { return num(c.max_seqs); } },
{ "--max-model-len", [](const Config& c) { { "--max-model-len", [](const Config& c) {
return c.max_ctx ? num(c.max_ctx) : std::string("0 (the model's training context)"); } }, return c.max_ctx ? num(c.max_ctx) : std::string("0 (the model's training context)"); } },
{ "--rope-scaling", [](const Config& c) { return or_none(c.rope_scaling, "the checkpoint's own"); } }, { "--rope-scaling", [](const Config& c) { return or_none(c.rope_scaling, "the checkpoint's own"); } },
{ "--gpu-memory-mib", [](const Config& c) {
return c.gpu_memory_mib ? num(c.gpu_memory_mib) : std::string("0 (use --gpu-headroom-mib)"); } },
{ "--gpu-headroom-mib", [](const Config& c) { return num(c.gpu_headroom_mib); } }, { "--gpu-headroom-mib", [](const Config& c) { return num(c.gpu_headroom_mib); } },
{ "--kv-cache-dtype", [](const Config& c) { return c.kv_cache_dtype; } }, { "--kv-cache-dtype", [](const Config& c) { return c.kv_cache_dtype; } },
{ "--state-cache-dtype", [](const Config& c) { return c.state_cache_dtype; } }, { "--state-cache-dtype", [](const Config& c) { return c.state_cache_dtype; } },
@@ -1340,7 +1385,8 @@ const ShowRow kShow[] = {
{ "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } }, { "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } },
{ "--ngram-placement", [](const Config& c) { { "--ngram-placement", [](const Config& c) {
std::string v = table_placement_name(c.ngram_placement); std::string v = table_placement_name(c.ngram_placement);
return c.ngram_share_dir.empty() ? v : v + "=" + c.ngram_share_dir; } }, const std::string& dir = c.ngram_share_dir.empty() ? c.ngram_disk_dir : c.ngram_share_dir;
return dir.empty() ? v : v + "=" + dir; } },
{ "--vision-tower-placement", [](const Config& c) { return std::string(table_placement_name(c.tower_placement)); } }, { "--vision-tower-placement", [](const Config& c) { return std::string(table_placement_name(c.tower_placement)); } },
{ "--weights-disk-tier", [](const Config& c) { return onoff(c.weights_disk_tier); } }, { "--weights-disk-tier", [](const Config& c) { return onoff(c.weights_disk_tier); } },
{ "--prefix-cache-mib", [](const Config& c) { { "--prefix-cache-mib", [](const Config& c) {
+61 -16
View File
@@ -589,7 +589,7 @@ KernelRec* kernel_for(const void* stub, int ord, std::string* why) {
struct Stream { struct Stream {
uint64_t magic = kStreamMagic; uint64_t magic = kStreamMagic;
int ord = 0; int ord = 0;
uint32_t id = 0; /* index into g_queue_by_id, never reused */ uint32_t id = 0; /* queue_of's key, never reused (see there) */
hsa_agent_t agent{}; hsa_agent_t agent{};
hsa_queue_t* q = nullptr; hsa_queue_t* q = nullptr;
uint64_t mask = 0; uint64_t mask = 0;
@@ -623,12 +623,27 @@ struct Stream {
void unlock() { busy.store(false, std::memory_order_release); } void unlock() { busy.store(false, std::memory_order_release); }
}; };
/* Every queue this process has made, by an id that is never reused, so "packet i of queue n" /* Every live queue, by an id that is never reused, so "packet i of queue n" stays meaningful after
* stays meaningful after the queue is destroyed. A destroyed queue's entry is null; everything * the queue is destroyed: queue_of answers null for a destroyed queue's id, and everything it held
* it held has been consumed. */ * has been consumed. At most kMaxQueues are live at once; a destroyed queue's slot is taken again
* under a new generation, id = generation * kMaxQueues + slot, so a stale id never names the
* slot's next queue. */
constexpr uint32_t kMaxQueues = 1024; constexpr uint32_t kMaxQueues = 1024;
std::atomic<hsa_queue_t*> g_queue_by_id[kMaxQueues]; std::atomic<hsa_queue_t*> g_queue_by_id[kMaxQueues];
std::atomic<uint32_t> g_next_queue_id{0}; std::atomic<uint32_t> g_queue_id_at[kMaxQueues]; /* the id holding each slot now */
std::mutex g_queue_slot_mu;
std::vector<uint32_t> g_queue_free; /* destroyed queues' slots */
uint32_t g_queue_next_slot = 0;
uint32_t g_queue_gen[kMaxQueues];
/* The queue an id names, or null once it is destroyed. The slot's id is stored before its queue
* (release), so a queue read here that belongs to a later generation is seen with that
* generation's id and refused. */
inline hsa_queue_t* queue_of(uint32_t id) {
const uint32_t slot = id % kMaxQueues;
hsa_queue_t* q = g_queue_by_id[slot].load(std::memory_order_acquire);
return g_queue_id_at[slot].load(std::memory_order_acquire) == id ? q : nullptr;
}
inline Stream* ours(const void* s) { inline Stream* ours(const void* s) {
if ((uintptr_t)s < 4096) return nullptr; if ((uintptr_t)s < 4096) return nullptr;
@@ -1127,6 +1142,9 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t
if (!gx || !gy || !gz) return RAD_OK; if (!gx || !gy || !gz) return RAD_OK;
if (gx > UINT32_MAX || gy > UINT32_MAX || gz > UINT32_MAX) return RAD_E_INVAL; if (gx > UINT32_MAX || gy > UINT32_MAX || gz > UINT32_MAX) return RAD_E_INVAL;
if ((uint64_t)k->group_size + shm > 65536) return RAD_E_INVAL; if ((uint64_t)k->group_size + shm > 65536) return RAD_E_INVAL;
/* The packet's fields are 16 bits wide and the card runs at most 1024 work-items a group;
* HIP refuses a larger block, and so does this. */
if ((uint64_t)b.x * b.y * b.z > 1024) return RAD_E_INVAL;
alignas(64) unsigned char ka[kKargMax]; alignas(64) unsigned char ka[kKargMax];
const uint32_t n = (k->kernarg_size + 15u) & ~15u; const uint32_t n = (k->kernarg_size + 15u) & ~15u;
@@ -1562,6 +1580,7 @@ int a_stream_create(RadStream* out, int high_priority) {
if (hsa_amd_memory_pool_allocate(kpool, (size_t)(s->mask + 2) * kKargSlot, 0, &ka) != if (hsa_amd_memory_pool_allocate(kpool, (size_t)(s->mask + 2) * kKargSlot, 0, &ka) !=
HSA_STATUS_SUCCESS || HSA_STATUS_SUCCESS ||
hsa_amd_agents_allow_access(1, &kpeer, nullptr, ka) != HSA_STATUS_SUCCESS) { hsa_amd_agents_allow_access(1, &kpeer, nullptr, ka) != HSA_STATUS_SUCCESS) {
if (ka) hsa_amd_memory_pool_free(ka); /* allocated, then refused access */
hsa_queue_destroy(s->q); hsa_queue_destroy(s->q);
device_set_error("rad_stream_create: the kernel argument ring could not be placed in %s", device_set_error("rad_stream_create: the kernel argument ring could not be placed in %s",
d.host_kargs ? "pinned host memory" : "VRAM the host can write"); d.host_kargs ? "pinned host memory" : "VRAM the host can write");
@@ -1582,17 +1601,28 @@ int a_stream_create(RadStream* out, int high_priority) {
s->bounce = static_cast<char*>(bb); s->bounce = static_cast<char*>(bb);
note_alloc(ka, (int64_t)(s->mask + 2) * kKargSlot, -1); note_alloc(ka, (int64_t)(s->mask + 2) * kKargSlot, -1);
note_alloc(bb, kBounceBytes, -1); note_alloc(bb, kBounceBytes, -1);
s->id = g_next_queue_id.fetch_add(1, std::memory_order_relaxed); uint32_t slot = kMaxQueues;
if (s->id >= kMaxQueues) { {
std::lock_guard<std::mutex> lk(g_queue_slot_mu);
if (!g_queue_free.empty()) {
slot = g_queue_free.back();
g_queue_free.pop_back();
} else if (g_queue_next_slot < kMaxQueues) {
slot = g_queue_next_slot++;
}
if (slot < kMaxQueues) s->id = g_queue_gen[slot]++ * kMaxQueues + slot;
}
if (slot >= kMaxQueues) {
note_free(bb); note_free(bb);
note_free(ka); note_free(ka);
hsa_amd_memory_pool_free(bb); hsa_amd_memory_pool_free(bb);
hsa_amd_memory_pool_free(ka); hsa_amd_memory_pool_free(ka);
hsa_queue_destroy(s->q); hsa_queue_destroy(s->q);
device_set_error("rad_stream_create: more than %u streams in one process", kMaxQueues); device_set_error("rad_stream_create: more than %u streams live at once", kMaxQueues);
return RAD_E_NOMEM; return RAD_E_NOMEM;
} }
g_queue_by_id[s->id].store(s->q, std::memory_order_release); g_queue_id_at[slot].store(s->id, std::memory_order_release);
g_queue_by_id[slot].store(s->q, std::memory_order_release);
{ {
std::lock_guard<std::mutex> lk(G().streams_mu); std::lock_guard<std::mutex> lk(G().streams_mu);
G().streams.push_back(s.get()); G().streams.push_back(s.get());
@@ -1604,14 +1634,24 @@ int a_stream_create(RadStream* out, int high_priority) {
void a_stream_destroy(RadStream rs) { void a_stream_destroy(RadStream rs) {
Stream* s = ours(rs); Stream* s = ours(rs);
if (!s) return; if (!s) return;
(void)stream_drain(s); /* Undrained (a closed gate, a fault), the queue may still be read by the card, and so may its
* kernel argument ring: both are left allocated rather than freed under it. */
if (const int rc = stream_drain(s); rc < 0) {
RAD_WARN("device: a stream was destroyed with work it could not drain (%s); its queue and "
"argument ring stay allocated", rad_strerror(rc));
return;
}
{ {
std::lock_guard<std::mutex> lk(G().streams_mu); std::lock_guard<std::mutex> lk(G().streams_mu);
auto& v = G().streams; auto& v = G().streams;
for (size_t i = 0; i < v.size(); ++i) if (v[i] == s) { v.erase(v.begin() + (long)i); break; } for (size_t i = 0; i < v.size(); ++i) if (v[i] == s) { v.erase(v.begin() + (long)i); break; }
} }
g_queue_by_id[s->id].store(nullptr, std::memory_order_release); g_queue_by_id[s->id % kMaxQueues].store(nullptr, std::memory_order_release);
hsa_queue_destroy(s->q); hsa_queue_destroy(s->q);
{
std::lock_guard<std::mutex> lk(g_queue_slot_mu);
g_queue_free.push_back(s->id % kMaxQueues);
}
note_free(s->karg); note_free(s->karg);
note_free(s->bounce); note_free(s->bounce);
hsa_amd_memory_pool_free(s->karg); hsa_amd_memory_pool_free(s->karg);
@@ -1676,7 +1716,7 @@ bool xp_list_finished(int ord, uint32_t k);
bool reusable(const Sig* g) { bool reusable(const Sig* g) {
if (g->stamped || hsa_signal_load_relaxed(g->h) != 0) return false; if (g->stamped || hsa_signal_load_relaxed(g->h) != 0) return false;
for (const auto& w : g->waiters) { for (const auto& w : g->waiters) {
hsa_queue_t* q = g_queue_by_id[w.first].load(std::memory_order_acquire); hsa_queue_t* q = queue_of(w.first);
if (q && hsa_queue_load_read_index_relaxed(q) <= w.second) return false; if (q && hsa_queue_load_read_index_relaxed(q) <= w.second) return false;
} }
const int32_t xd = g->xp_dev.load(std::memory_order_acquire); const int32_t xd = g->xp_dev.load(std::memory_order_acquire);
@@ -1902,7 +1942,7 @@ std::vector<Tape*> g_tape_retired;
* kReserveMargin past it has launched, which proves it as in reserve(). */ * kReserveMargin past it has launched, which proves it as in reserve(). */
bool tape_idle(const Tape* t) { bool tape_idle(const Tape* t) {
for (const auto& l : t->last) { for (const auto& l : t->last) {
hsa_queue_t* q = g_queue_by_id[l.first].load(std::memory_order_acquire); hsa_queue_t* q = queue_of(l.first);
if (q && hsa_queue_load_read_index_scacquire(q) < l.second + kReserveMargin) return false; if (q && hsa_queue_load_read_index_scacquire(q) < l.second + kReserveMargin) return false;
} }
return true; return true;
@@ -2574,6 +2614,7 @@ struct DmaQueue {
* a queue while the engine runs on, and a ring the host thinks full would wait forever. */ * a queue while the engine runs on, and a ring the host thinks full would wait forever. */
volatile uint32_t* fin = nullptr; volatile uint32_t* fin = nullptr;
uint32_t lists = 0; /* lists handed over; list k ends at ends[k % kDmaEnds] */ uint32_t lists = 0; /* lists handed over; list k ends at ends[k % kDmaEnds] */
uint64_t seen = 0; /* the most the room check has known read, under the lock */
std::unique_ptr<uint64_t[]> ends; std::unique_ptr<uint64_t[]> ends;
}; };
constexpr uint32_t kDmaEnds = 4096; constexpr uint32_t kDmaEnds = 4096;
@@ -2818,22 +2859,26 @@ inline uint64_t dma_read(const DmaQueue* q) {
uint64_t r = *q->rptr; uint64_t r = *q->rptr;
if (q->fin) { if (q->fin) {
const uint32_t k = *q->fin; const uint32_t k = *q->fin;
if (k) r = std::max(r, q->ends[k % kDmaEnds]); /* ends[k % kDmaEnds] is list k's only while fewer than kDmaEnds lists are behind it. */
if (k && q->lists - k < kDmaEnds) r = std::max(r, q->ends[k % kDmaEnds]);
} }
return r; return std::max(r, q->seen);
} }
/* Writes `n` dwords to the ring; queue lock held. A packet never straddles the ring end: the tail /* Writes `n` dwords to the ring; queue lock held. A packet never straddles the ring end: the tail
* is padded with single-dword NOPs. The ring holds a few hundred layers' lists, so waiting for * is padded with single-dword NOPs. The ring holds a few hundred layers' lists, so waiting for
* room means the host is that far ahead of a stalled engine. */ * room means the host is that far ahead of a stalled engine. */
int dma_put(DmaQueue* q, const uint32_t* dw, uint64_t n) { int dma_put(DmaQueue* q, const uint32_t* dw, uint64_t n) {
/* What was once known read stays read: a list number whose ends slot a later list has taken
* cannot be used any more, and the read pointer alone may be behind it. */
q->seen = dma_read(q);
const uint64_t cap = kDmaRingBytes / 4; const uint64_t cap = kDmaRingBytes / 4;
uint64_t at = (q->w / 4) & (cap - 1); uint64_t at = (q->w / 4) & (cap - 1);
const uint64_t pad = at + n > cap ? cap - at : 0; const uint64_t pad = at + n > cap ? cap - at : 0;
const uint64_t need = (pad + n) * 4; const uint64_t need = (pad + n) * 4;
if (q->w + need - dma_read(q) > kDmaRingBytes) { if (q->w + need - dma_read(q) > kDmaRingBytes) {
Stall st("a full DMA ring"); Stall st("a full DMA ring");
while (q->w + need - dma_read(q) > kDmaRingBytes) { while (q->w + need - (q->seen = dma_read(q)) > kDmaRingBytes) {
if (G().faulted.load(std::memory_order_relaxed)) { if (G().faulted.load(std::memory_order_relaxed)) {
device_set_error("rad_memcpy_list_async: a queue faulted while the DMA ring was full"); device_set_error("rad_memcpy_list_async: a queue faulted while the DMA ring was full");
return RAD_E_DEVICE; return RAD_E_DEVICE;
+2 -1
View File
@@ -406,7 +406,8 @@ int64_t dev_stuck_ms();
constexpr int kTapeOverlapRun = 6; constexpr int kTapeOverlapRun = 6;
/* ------------------------------------------------------------------ the allocation ledger /* ------------------------------------------------------------------ the allocation ledger
* What rad_dev_alloc has handed out since process start, by RAD_MEM_* kind. It does not see a * By RAD_MEM_* kind: the bytes rad_dev_alloc has handed out and rad_dev_free has not taken back,
* and the number of allocations since process start. It does not see a
* kernel plugin that calls hipMalloc directly; see the ledger in dispatch.cpp. */ * kernel plugin that calls hipMalloc directly; see the ledger in dispatch.cpp. */
void rad_dev_alloc_totals(int kind, int64_t* bytes, int64_t* count); void rad_dev_alloc_totals(int kind, int64_t* bytes, int64_t* count);
+24 -4
View File
@@ -21,6 +21,7 @@
#include <iterator> #include <iterator>
#include <map> #include <map>
#include <mutex> #include <mutex>
#include <unordered_map>
#include <string> #include <string>
#include <utility> #include <utility>
#include <cstdint> #include <cstdint>
@@ -172,6 +173,26 @@ struct Ledger {
std::atomic<int64_t> count{0}; std::atomic<int64_t> count{0};
}; };
Ledger g_ledger[4]; /* indexed by RAD_MEM_*; rad_dev_alloc bounds the kind */ Ledger g_ledger[4]; /* indexed by RAD_MEM_*; rad_dev_alloc bounds the kind */
/* Each live allocation's size, so rad_dev_free (which has none) takes it back off the ledger's
* bytes: pinned ranges are freed and taken again during bring-up, and the pin-cap check reads the
* ledger as what the process holds. Allocations are rare, never per step. */
struct LiveAlloc { int64_t bytes; int kind; };
std::mutex g_ledger_mu;
std::unordered_map<void*, LiveAlloc> g_ledger_live;
void ledger_add(void* p, int64_t bytes, int kind) {
g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed);
std::lock_guard<std::mutex> lk(g_ledger_mu);
g_ledger_live[p] = LiveAlloc{ bytes, kind };
}
void ledger_drop(void* p) {
if (!p) return;
std::lock_guard<std::mutex> lk(g_ledger_mu);
const auto it = g_ledger_live.find(p);
if (it == g_ledger_live.end()) return;
g_ledger[it->second.kind].bytes.fetch_sub(it->second.bytes, std::memory_order_relaxed);
g_ledger_live.erase(it);
}
/* Live event handles, counted here so the number is backend-independent; the only place an /* Live event handles, counted here so the number is backend-independent; the only place an
* event leaked at teardown shows. */ * event leaked at teardown shows. */
@@ -450,7 +471,7 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
thread_local int64_t t_device_ordinal = 0; thread_local int64_t t_device_ordinal = 0;
void* p = dev()->alloc(bytes, kind); void* p = dev()->alloc(bytes, kind);
if (p && kind >= 0 && kind < (int)std::size(rad::g_ledger)) { if (p && kind >= 0 && kind < (int)std::size(rad::g_ledger)) {
rad::g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed); rad::ledger_add(p, bytes, kind);
const int64_t total = rad::g_ledger[kind].count.fetch_add(1, std::memory_order_relaxed) + 1; const int64_t total = rad::g_ledger[kind].count.fetch_add(1, std::memory_order_relaxed) + 1;
const int64_t ordinal = kind == RAD_MEM_DEVICE ? ++t_device_ordinal : total; const int64_t ordinal = kind == RAD_MEM_DEVICE ? ++t_device_ordinal : total;
const int64_t floor_ = rad::trace_floor(); const int64_t floor_ = rad::trace_floor();
@@ -476,8 +497,7 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
return p; return p;
} }
void rad_dev_free(void* p, int kind) { void rad_dev_free(void* p, int kind) {
/* The ledger counts allocations, not live bytes: rad_dev_free has no size. The engine frees rad::ledger_drop(p);
* only at teardown, so the two agree while running. */
dev()->free(p, kind); dev()->free(p, kind);
} }
void* rad_dev_host_ptr(void* p) { return dev()->host_ptr(p); } void* rad_dev_host_ptr(void* p) { return dev()->host_ptr(p); }
@@ -694,7 +714,7 @@ void* rad_dev_map_file(int fd, int64_t foff, int64_t bytes) {
} }
void* p = f(fd, foff, bytes); void* p = f(fd, foff, bytes);
if (p) { if (p) {
rad::g_ledger[RAD_MEM_HOST_MAPPED].bytes.fetch_add(bytes, std::memory_order_relaxed); rad::ledger_add(p, bytes, RAD_MEM_HOST_MAPPED);
rad::g_ledger[RAD_MEM_HOST_MAPPED].count.fetch_add(1, std::memory_order_relaxed); rad::g_ledger[RAD_MEM_HOST_MAPPED].count.fetch_add(1, std::memory_order_relaxed);
} }
return p; return p;
+28 -3
View File
@@ -20,6 +20,7 @@
#include <condition_variable> #include <condition_variable>
#include <cstdlib> #include <cstdlib>
#include <cstring> #include <cstring>
#include <map>
#include <mutex> #include <mutex>
#include <thread> #include <thread>
#include <unordered_map> #include <unordered_map>
@@ -723,6 +724,21 @@ constexpr int64_t kVmemGranule = RAD_ALIGN_POOL;
int64_t h_vmem_granularity(void) { return kVmemGranule; } int64_t h_vmem_granularity(void) { return kVmemGranule; }
/* Each reservation's card, recorded at reserve: the thread that later commits into a pool, or
* releases it at teardown, may have selected another card, and the pages count against the card
* the range was reserved for (as the AQL backend's VRes does). Keyed by base. */
struct VRange { char* end; int device; };
std::mutex g_vres_mu;
std::map<const char*, VRange> g_vres;
int vmem_device_of(const void* addr) {
std::lock_guard<std::mutex> lk(g_vres_mu);
auto it = g_vres.upper_bound((const char*)addr);
if (it == g_vres.begin()) return t_device;
--it;
return (const char*)addr < it->second.end ? it->second.device : t_device;
}
void* h_vmem_reserve(int64_t bytes, int64_t align) { void* h_vmem_reserve(int64_t bytes, int64_t align) {
if (bytes <= 0) return nullptr; if (bytes <= 0) return nullptr;
if (align < kVmemGranule) align = kVmemGranule; if (align < kVmemGranule) align = kVmemGranule;
@@ -740,11 +756,20 @@ void* h_vmem_reserve(int64_t bytes, int64_t align) {
if (head) ::munmap(raw, head); if (head) ::munmap(raw, head);
const size_t tail = raw_len - head - (size_t)bytes; const size_t tail = raw_len - head - (size_t)bytes;
if (tail) ::munmap(base + bytes, tail); if (tail) ::munmap(base + bytes, tail);
{
std::lock_guard<std::mutex> lk(g_vres_mu);
g_vres[base] = VRange{ base + bytes, t_device };
}
return base; return base;
} }
void h_vmem_release(void* base, int64_t bytes) { void h_vmem_release(void* base, int64_t bytes) {
if (base && bytes > 0) ::munmap(base, (size_t)bytes); if (!base || bytes <= 0) return;
{
std::lock_guard<std::mutex> lk(g_vres_mu);
g_vres.erase((const char*)base);
}
::munmap(base, (size_t)bytes);
} }
int h_vmem_commit(void* addr, int64_t bytes) { int h_vmem_commit(void* addr, int64_t bytes) {
@@ -755,7 +780,7 @@ int h_vmem_commit(void* addr, int64_t bytes) {
device_set_error("vmem_commit(%p, %lld): mmap failed", addr, (long long)bytes); device_set_error("vmem_commit(%p, %lld): mmap failed", addr, (long long)bytes);
return RAD_E_NOMEM; return RAD_E_NOMEM;
} }
g_used[t_device].fetch_add(bytes, std::memory_order_relaxed); g_used[vmem_device_of(addr)].fetch_add(bytes, std::memory_order_relaxed);
return RAD_OK; return RAD_OK;
} }
@@ -769,7 +794,7 @@ int h_vmem_decommit(void* addr, int64_t bytes) {
device_set_error("vmem_decommit(%p, %lld): mmap failed", addr, (long long)bytes); device_set_error("vmem_decommit(%p, %lld): mmap failed", addr, (long long)bytes);
return RAD_E_INVAL; return RAD_E_INVAL;
} }
g_used[t_device].fetch_sub(bytes, std::memory_order_relaxed); g_used[vmem_device_of(addr)].fetch_sub(bytes, std::memory_order_relaxed);
return RAD_OK; return RAD_OK;
} }
+315 -7
View File
@@ -6,6 +6,7 @@
#include "gen/driver.h" #include "gen/driver.h"
#include "gen/audio_driver.h" #include "gen/audio_driver.h"
#include "gen/video_driver.h" #include "gen/video_driver.h"
#include "gen/shape_driver.h"
#include "kld.h" #include "kld.h"
#include "mm/processor.h" #include "mm/processor.h"
#include "mm/media.h" #include "mm/media.h"
@@ -41,10 +42,220 @@
#include <utility> #include <utility>
#include <vector> #include <vector>
#include <thread> #include <thread>
#include <sys/mman.h>
#include <unistd.h> #include <unistd.h>
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
#include <string>
#endif
namespace rad { namespace rad {
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
namespace {
struct KVRollbackTestEvidence {
bool waiting_for_greedy = false;
std::string report_path;
uint64_t seq = 0;
int step = -1;
int proposals = 0;
int accepted = -1;
int32_t group = -1;
int64_t prefix_before = 0;
int64_t rollback_tokens_before = 0;
int64_t rollback_to_tokens = 0;
int64_t prefix_after_rollback = -1;
int64_t first_block_pos = 0;
int64_t block_size = 0;
int64_t n_layers = 0;
int64_t bytes_per_layer = 0;
std::vector<int32_t> logical_blocks;
std::vector<int32_t> physical_slots;
std::vector<uint8_t> before;
uint64_t after_hash = 0;
bool bytes_equal = false;
bool mapping_equal = false;
bool negative_control_detected = false;
};
uint64_t kv_test_hash(const std::vector<uint8_t>& bytes) {
uint64_t h = 14695981039346656037ull;
for (uint8_t b : bytes) h = (h ^ b) * 1099511628211ull;
return h;
}
bool kv_test_bytes_equal(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b) {
return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin());
}
template<class RankT>
bool kv_test_snapshot(RankT& rank, uint64_t seq, int32_t group, int64_t prefix_tokens,
int64_t* first_block_pos, std::vector<int32_t>* logical,
std::vector<int32_t>* physical, std::vector<uint8_t>* bytes) {
const KVGroupPlan* p = rank.kv.plan(group);
if (!p || p->zero || !p->paged() || p->kind != RAD_KV_FULL || p->streamed() ||
p->n_layers <= 0 || p->block_size <= 0 || !p->base) return false;
const auto& table = rank.kv.block_table(seq, group);
const int64_t first_pos = rank.kv.first_block_pos(seq, group);
if (first_pos < 0 || prefix_tokens < first_pos) return false;
const int64_t complete = (prefix_tokens - first_pos) / p->block_size;
if (complete <= 0 || complete > (int64_t)table.size()) return false;
if (first_block_pos) *first_block_pos = first_pos;
/* Snapshot every complete block in the retained pre-verify prefix. The trailing partial
* block is omitted because accepted verify tokens may legitimately fill its unused slots. */
const int64_t nblocks = complete;
const int64_t layer_bytes = p->layer_bytes_per_block();
const int64_t block_bytes = p->n_layers * layer_bytes;
if (nblocks <= 0 || layer_bytes <= 0 || p->bytes_per_block != block_bytes) return false;
if (rad_dev_set(rank.device) < 0 || rad_stream_sync(rank.ctx.stream()) < 0) return false;
logical->clear();
physical->clear();
logical->reserve((size_t)nblocks);
physical->reserve((size_t)nblocks);
bytes->resize((size_t)nblocks * (size_t)block_bytes);
for (int64_t b = 0; b < nblocks; ++b) {
const int32_t id = table[(size_t)b];
if (id < 0 || id >= p->pool_blocks()) return false;
logical->push_back((int32_t)(first_pos / p->block_size + b));
physical->push_back(id);
for (int64_t layer = 0; layer < p->n_layers; ++layer) {
const auto* src = static_cast<const uint8_t*>(p->base) +
layer * p->layer_stride() + (int64_t)id * layer_bytes;
auto* dst = bytes->data() + b * block_bytes + layer * layer_bytes;
if (rad_memcpy_async(dst, src, layer_bytes, rank.ctx.stream()) < 0) return false;
}
}
return rad_stream_sync(rank.ctx.stream()) >= 0;
}
void kv_test_write_report(const KVRollbackTestEvidence& e, bool greedy, int greedy_token,
int64_t tokens_at_greedy) {
if (e.report_path.empty()) return;
std::ofstream f(e.report_path, std::ios::trunc);
if (!f) return;
f << "{\"partial_rejection_observed\":true,\"step\":" << e.step
<< ",\"sequence\":" << e.seq << ",\"proposals\":" << e.proposals
<< ",\"accepted\":" << e.accepted << ",\"group\":" << e.group
<< ",\"prefix_tokens_before_verify\":" << e.prefix_before
<< ",\"rollback_tokens_before\":" << e.rollback_tokens_before
<< ",\"rollback_to_tokens\":" << e.rollback_to_tokens
<< ",\"prefix_tokens_after\":" << e.prefix_after_rollback
<< ",\"first_block_pos\":" << e.first_block_pos
<< ",\"block_size\":" << e.block_size << ",\"layers\":" << e.n_layers
<< ",\"bytes_per_layer\":" << e.bytes_per_layer << ",\"logical_blocks\":[";
for (size_t i = 0; i < e.logical_blocks.size(); ++i) f << (i ? "," : "") << e.logical_blocks[i];
f << "],\"physical_slots\":[";
for (size_t i = 0; i < e.physical_slots.size(); ++i) f << (i ? "," : "") << e.physical_slots[i];
f << "],\"committed_prefix_bytes\":" << e.before.size()
<< ",\"before_hash\":" << kv_test_hash(e.before)
<< ",\"after_hash\":" << e.after_hash
<< ",\"bytes_equal\":" << (e.bytes_equal ? "true" : "false")
<< ",\"mapping_equal\":" << (e.mapping_equal ? "true" : "false")
<< ",\"negative_control_detected\":" << (e.negative_control_detected ? "true" : "false")
<< ",\"next_greedy_decode_observed\":" << (greedy ? "true" : "false")
<< ",\"tokens_at_next_greedy_decode\":" << (greedy ? tokens_at_greedy : -1)
<< ",\"next_greedy_token\":" << (greedy ? greedy_token : -1) << "}\n";
}
KVRollbackTestEvidence& kv_test_evidence() {
static KVRollbackTestEvidence e;
return e;
}
template<class Output, class Ranks>
void kv_test_before_commit(const StepPlan& plan, const Output& so, int step, Ranks& ranks) {
auto& e = kv_test_evidence();
if (!e.waiting_for_greedy && !e.report_path.empty() && e.accepted < 0) {
for (size_t i = 0; i < plan.e.size(); ++i) {
const StepEntry& entry = plan.e[i];
if (entry.seq == e.seq && step == e.step && entry.n_spec == e.proposals &&
(so.accepted[i] <= 0 || so.accepted[i] >= e.proposals)) {
e = KVRollbackTestEvidence{};
return;
}
}
}
if (!e.waiting_for_greedy) return;
for (size_t i = 0; i < plan.e.size(); ++i) {
const StepEntry& entry = plan.e[i];
if (entry.seq == e.seq && entry.req && entry.req->sp.greedy() &&
so.first_row[i] >= 0) {
kv_test_write_report(e, true, so.token[i], ranks[0]->kv.seq_tokens(e.seq));
e.waiting_for_greedy = false;
break;
}
}
}
template<class Ranks>
void kv_test_prepare(const StepPlan& plan, int step, Ranks& ranks) {
auto& e = kv_test_evidence();
if (!e.report_path.empty() || e.waiting_for_greedy) return;
const char* path = std::getenv("RADIANCE_TEST_KV_ROLLBACK_REPORT");
if (!path || !*path) return;
for (const StepEntry& entry : plan.e) {
if (!entry.req || entry.n_spec != 7) continue;
const int64_t prefix = entry.ctx_len;
for (int32_t g = 0; g < ranks[0]->kv.n_groups(); ++g) {
const KVGroupPlan* p = ranks[0]->kv.plan(g);
if (!p || p->kind != RAD_KV_FULL || p->zero || p->streamed() ||
prefix < p->block_size) continue;
KVRollbackTestEvidence candidate;
candidate.report_path = path;
candidate.seq = entry.seq;
candidate.step = step;
candidate.proposals = entry.n_spec;
candidate.group = g;
candidate.prefix_before = prefix;
candidate.block_size = p->block_size;
candidate.n_layers = p->n_layers;
candidate.bytes_per_layer = p->layer_bytes_per_block();
if (!kv_test_snapshot(*ranks[0], entry.seq, g, prefix, &candidate.first_block_pos,
&candidate.logical_blocks, &candidate.physical_slots,
&candidate.before)) continue;
e = std::move(candidate);
return;
}
}
}
template<class RankT>
void kv_test_rollback(uint64_t seq, int proposals, int accepted, int64_t valid,
bool before, RankT& rank) {
auto& e = kv_test_evidence();
if (e.report_path.empty() || e.waiting_for_greedy || seq != e.seq ||
proposals != e.proposals || proposals != 7 || accepted <= 0 || accepted >= proposals)
return;
if (before) {
e.accepted = accepted;
e.rollback_tokens_before = rank.kv.seq_tokens(seq);
e.rollback_to_tokens = valid;
return;
}
std::vector<int32_t> logical, physical;
std::vector<uint8_t> after;
int64_t first_block_pos = -1;
const bool copied = kv_test_snapshot(rank, seq, e.group, std::min(e.prefix_before, valid),
&first_block_pos, &logical, &physical, &after);
bool mapping_equal = copied && first_block_pos == e.first_block_pos &&
logical == e.logical_blocks && physical == e.physical_slots;
const bool bytes_equal = copied && kv_test_bytes_equal(after, e.before);
e.after_hash = copied ? kv_test_hash(after) : 0;
e.bytes_equal = bytes_equal;
std::vector<uint8_t> mutated = e.before;
if (!mutated.empty()) mutated[0] ^= 1;
e.negative_control_detected = !mutated.empty() && !kv_test_bytes_equal(e.before, mutated);
const int64_t after_tokens = rank.kv.seq_tokens(seq);
mapping_equal = mapping_equal && after_tokens == e.rollback_to_tokens;
e.mapping_equal = mapping_equal;
e.prefix_after_rollback = after_tokens;
kv_test_write_report(e, false, -1, -1);
e.waiting_for_greedy = true;
(void)valid; // rollback's requested length is emitted by the manager as after_tokens
}
} // namespace
#endif
/* The operator's RADIANCE_* names, captured at construction for the diagnostics report. */ /* The operator's RADIANCE_* names, captured at construction for the diagnostics report. */
Engine::Engine(Config cfg) Engine::Engine(Config cfg)
: cfg_(std::move(cfg)), env_set_(diag::env_names(environ, "RADIANCE_")) {} : cfg_(std::move(cfg)), env_set_(diag::env_names(environ, "RADIANCE_")) {}
@@ -108,6 +319,8 @@ Engine::~Engine() {
ranks_.clear(); ranks_.clear();
for (TableCopy& c : table_copies_) table_copy_free(&c); for (TableCopy& c : table_copies_) table_copy_free(&c);
table_copies_.clear(); table_copies_.clear();
for (TableCopy& c : table_files_) ::munmap(c.base, c.bytes);
table_files_.clear();
for (void* p : card_copies_) rad_dev_free(p, RAD_MEM_HOST_MAPPED); for (void* p : card_copies_) rad_dev_free(p, RAD_MEM_HOST_MAPPED);
card_copies_.clear(); card_copies_.clear();
for (TableShare& t : table_shares_) table_share_close(&t); for (TableShare& t : table_shares_) table_share_close(&t);
@@ -164,6 +377,10 @@ int Engine::declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool
} }
sc.max_seqs = cfg_.max_seqs; sc.max_seqs = cfg_.max_seqs;
sc.max_spec = cfg_.n_spec; sc.max_spec = cfg_.n_spec;
/* The real step bound, not the sizing declare's level: the sampler's planes must be the same
* buffers in every declare of the program (plan_level compares them), and a step can sample
* no more rows than the real bound lets it carry tokens. */
sc.max_tok = cfg_.max_tok;
sc.rank = rank; sc.rank = rank;
sc.world_size = cfg_.tp; sc.world_size = cfg_.tp;
sc.draft_coupling = cfg_.draft_coupling; sc.draft_coupling = cfg_.draft_coupling;
@@ -171,11 +388,14 @@ int Engine::declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool
/* Where the chain writes the sampled ids. The engine declares it because rad-kbench drives the /* Where the chain writes the sampled ids. The engine declares it because rad-kbench drives the
* same chain against its own buffer. PERSIST, since the step loop copies it back after the * same chain against its own buffer. PERSIST, since the step loop copies it back after the
* step, when a transient's storage may belong to another buffer. */ * step, when a transient's storage may belong to another buffer. One id per sampler row,
* capped as the rows are (SamplerConfig::max_tok). */
RadBufDecl d{}; RadBufDecl d{};
d.dtype = RAD_I32; d.dtype = RAD_I32;
d.rank = 1; d.rank = 1;
d.shape[0] = cfg_.max_seqs * (cfg_.n_spec > 0 ? cfg_.n_spec + 1 : 1); d.shape[0] = cfg_.max_seqs * (cfg_.n_spec > 0 ? cfg_.n_spec + 1 : 1);
if (cfg_.max_tok > 0)
d.shape[0] = std::min<int64_t>(d.shape[0], std::max<int64_t>(cfg_.max_tok, cfg_.max_seqs));
d.kind = RAD_BUF_PERSIST; d.kind = RAD_BUF_PERSIST;
tok = rad_decl_buffer(b, "sampler.tokens", &d); tok = rad_decl_buffer(b, "sampler.tokens", &d);
return tok ? RAD_OK : RAD_E_STATE; return tok ? RAD_OK : RAD_E_STATE;
@@ -506,6 +726,9 @@ int Engine::issue_ahead(const RadBatch** out) {
sched_.expect_draft(block_row_[(size_t)i].seq, block_steps_); sched_.expect_draft(block_row_[(size_t)i].seq, block_steps_);
const RadBatch* nb = sched_.step_next(); const RadBatch* nb = sched_.step_next();
if (!nb) return RAD_OK; if (!nb) return RAD_OK;
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
kv_test_prepare(sched_.plan(), nb->step, ranks_);
#endif
/* Its rows' tokens, positions and slots, advanced on the card behind this step's acceptance /* Its rows' tokens, positions and slots, advanced on the card behind this step's acceptance
* and drafts. */ * and drafts. */
RAD_TRY(advance_all(ADV_TRUNK, 0, false)); RAD_TRY(advance_all(ADV_TRUNK, 0, false));
@@ -567,6 +790,15 @@ int Engine::step_loop() {
return fail_loop(RAD_E_UNSUPPORTED); return fail_loop(RAD_E_UNSUPPORTED);
} }
const bool t_on = (int)log_level() >= (int)Log::Debug; const bool t_on = (int)log_level() >= (int)Log::Debug;
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
if (std::getenv("RADIANCE_TEST_KV_ROLLBACK_REPORT")) {
sched_.set_kv_rollback_test_hook([this](uint64_t seq, int proposals, int accepted,
int64_t valid, bool before) {
if (!ranks_.empty()) kv_test_rollback(seq, proposals, accepted, valid, before,
*ranks_[0]);
});
}
#endif
/* The next step's forward pass when already issued behind the previous step, before its /* The next step's forward pass when already issued behind the previous step, before its
* readback (Scheduler::step_next). */ * readback (Scheduler::step_next). */
const RadBatch* ahead = nullptr; const RadBatch* ahead = nullptr;
@@ -620,6 +852,9 @@ int Engine::step_loop() {
* produces_token, 1 + n_spec rows each. Row and sequence indices differ (a mid-prompt * produces_token, 1 + n_spec rows each. Row and sequence indices differ (a mid-prompt
* chunk produces no row). */ * chunk produces no row). */
const StepPlan& plan = sched_.plan(); const StepPlan& plan = sched_.plan();
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
kv_test_prepare(plan, b->step, ranks_);
#endif
/* One entry per request; Sampler::build_step expands each into 1 + n_draft rows itself /* One entry per request; Sampler::build_step expands each into 1 + n_draft rows itself
* (giving each position its RNG coordinate), so one push per row would stage (1+n)^2 rows. * (giving each position its RNG coordinate), so one push per row would stage (1+n)^2 rows.
* `first_row` indexes sampled tokens, so it counts rows. */ * `first_row` indexes sampled tokens, so it counts rows. */
@@ -883,6 +1118,9 @@ int Engine::step_loop() {
res.first_row = so.first_row.data(); res.first_row = so.first_row.data();
} }
res.path = so.path.empty() ? nullptr : so.path.data(); res.path = so.path.empty() ? nullptr : so.path.data();
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
kv_test_before_commit(plan, so, b->step, ranks_);
#endif
st = sched_.commit(res); st = sched_.commit(res);
if (t_on) phase_mark(PH_COMMIT); if (t_on) phase_mark(PH_COMMIT);
if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); } if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); }
@@ -1809,17 +2047,20 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
embedding_ = ranks_[0]->program.pooled_buf != RAD_NULL_HANDLE; embedding_ = ranks_[0]->program.pooled_buf != RAD_NULL_HANDLE;
const bool audio_gen = ranks_[0]->program.is_audio_generator(); const bool audio_gen = ranks_[0]->program.is_audio_generator();
const bool video_gen = ranks_[0]->program.is_video_generator(); const bool video_gen = ranks_[0]->program.is_video_generator();
const bool shape_gen = ranks_[0]->program.is_shape_generator();
const bool generator = ranks_[0]->program.is_pass_driven(); const bool generator = ranks_[0]->program.is_pass_driven();
if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE && !embedding_ && !generator) { if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE && !embedding_ && !generator) {
RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits), no pooled output " RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits), no pooled output "
"(rad_declare_pooled) and no generator (rad_declare_generator, " "(rad_declare_pooled) and no generator (rad_declare_generator, "
"rad_declare_audio_generator, rad_declare_video_generator), so a step produces " "rad_declare_audio_generator, rad_declare_video_generator, "
"rad_declare_shape_generator), so a step produces "
"nothing anyone can read. An encoder-only plugin cannot serve.", "nothing anyone can read. An encoder-only plugin cannot serve.",
plugins_.arch_plugin.c_str()); plugins_.arch_plugin.c_str());
return RAD_E_UNSUPPORTED; return RAD_E_UNSUPPORTED;
} }
if (generator) { if (generator) {
const char* const what = audio_gen ? "audio" : video_gen ? "video" : "images"; const char* const what = audio_gen ? "audio" : video_gen ? "video"
: shape_gen ? "shapes" : "images";
if (cfg_.kld() || cfg_.n_spec > 0) { if (cfg_.kld() || cfg_.n_spec > 0) {
RAD_ERR("the '%s' plugin makes %s: --kld and speculative decoding have no tokens to " RAD_ERR("the '%s' plugin makes %s: --kld and speculative decoding have no tokens to "
"work on", plugins_.arch_plugin.c_str(), what); "work on", plugins_.arch_plugin.c_str(), what);
@@ -1828,6 +2069,7 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
for (size_t i = 1; i < ranks_.size(); ++i) for (size_t i = 1; i < ranks_.size(); ++i)
if (ranks_[i]->program.is_audio_generator() != audio_gen || if (ranks_[i]->program.is_audio_generator() != audio_gen ||
ranks_[i]->program.is_video_generator() != video_gen || ranks_[i]->program.is_video_generator() != video_gen ||
ranks_[i]->program.is_shape_generator() != shape_gen ||
!ranks_[i]->program.is_pass_driven()) { !ranks_[i]->program.is_pass_driven()) {
RAD_ERR("rank %zu declared a different generator from rank 0's", i); RAD_ERR("rank %zu declared a different generator from rank 0's", i);
return RAD_E_STATE; return RAD_E_STATE;
@@ -1838,6 +2080,8 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
"after them" "after them"
: video_gen : video_gen
? "a video generator: a prompt is read by its own request's steps and keeps no KV" ? "a video generator: a prompt is read by its own request's steps and keeps no KV"
: shape_gen
? "a shape generator: a picture is read by its own request's steps and keeps no KV"
: "an image generator: a conditioning is read by its own request's images and by " : "an image generator: a conditioning is read by its own request's images and by "
"nothing after them"; "nothing after them";
decide("--no-prefix-cache", "prefix caching off", prefix_off_why_); decide("--no-prefix-cache", "prefix caching off", prefix_off_why_);
@@ -1994,7 +2238,16 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
rio.push_back({ rk->device, rk->ctx.stream(), &rk->program, rk->pools.kv().base(), rio.push_back({ rk->device, rk->ctx.stream(), &rk->program, rk->pools.kv().base(),
rank_stream_views_[r].data() }); rank_stream_views_[r].data() });
} }
if (video_gen) { if (shape_gen) {
/* As for the image generator below. */
std::vector<gen::ShapeDriver::RankIO> gio;
for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
auto d = std::make_unique<gen::ShapeDriver>();
RAD_TRY(d->init(ranks_[0]->program, gio));
shp_gen_ = d.get();
gen_ = std::move(d);
RAD_TRY(rad_dev_set(ranks_[0]->device));
} else if (video_gen) {
/* As for the image generator below; the plugin lays out each request's rows. */ /* As for the image generator below; the plugin lays out each request's rows. */
std::vector<gen::VideoDriver::RankIO> gio; std::vector<gen::VideoDriver::RankIO> gio;
for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() }); for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
@@ -2596,6 +2849,7 @@ int Engine::run_server() {
o.image_model = img_gen_ != nullptr; o.image_model = img_gen_ != nullptr;
o.audio_model = aud_gen_ != nullptr; o.audio_model = aud_gen_ != nullptr;
o.video_model = vid_gen_ != nullptr; o.video_model = vid_gen_ != nullptr;
o.shape_model = shp_gen_ != nullptr;
o.decision_type = rad_meta_gets(&meta_, "decision.type", ""); o.decision_type = rad_meta_gets(&meta_, "decision.type", "");
/* clef's learned scalars, which the server applies to what the head returns (server/clef.h); /* clef's learned scalars, which the server applies to what the head returns (server/clef.h);
* rad-convert writes them beside decision.type. */ * rad-convert writes them beside decision.type. */
@@ -2792,6 +3046,18 @@ int Engine::run_server() {
return RAD_E_INVAL; return RAD_E_INVAL;
} }
if (cfg_.image_tokens) vc.max_image_tokens = *cfg_.image_tokens; if (cfg_.image_tokens) vc.max_image_tokens = *cfg_.image_tokens;
} else if (vc.family == mm::Family::Radio) {
/* NVIDIA's processor sizes a picture and a video frame by patch budgets
* (min_num_patches..max_num_patches, video_target_num_patches), not pixel bands. */
if (cfg_.image_min_pixels || cfg_.image_max_pixels || cfg_.image_tokens ||
cfg_.video_min_pixels || cfg_.video_max_pixels || cfg_.video_max_frame_tokens) {
RAD_ERR("media: this model's processor sizes images and video frames by its patch "
"budgets (min_num_patches, max_num_patches, video_target_num_patches), so "
"--image-min/max-pixels, --image-tokens, --video-min/max-pixels and "
"--video-max-frame-tokens do nothing on it");
return RAD_E_INVAL;
}
if (cfg_.video_min_frames) vc.min_frames = *cfg_.video_min_frames;
} else { } else {
if (cfg_.image_tokens) { if (cfg_.image_tokens) {
RAD_ERR("media: --image-tokens is a token budget, and this model's processor " RAD_ERR("media: --image-tokens is a token budget, and this model's processor "
@@ -2892,6 +3158,16 @@ int Engine::run_server() {
ranks_[0]->program.encoder_name.c_str(), mm_proc->config().image_soft_tokens, ranks_[0]->program.encoder_name.c_str(), mm_proc->config().image_soft_tokens,
mm_proc->config().video_soft_tokens, mm_proc->config().fps, mm_proc->config().video_soft_tokens, mm_proc->config().fps,
mm_proc->config().max_frames, (long long)encd.max_patches); mm_proc->config().max_frames, (long long)encd.max_patches);
else if (mm_proc->config().family == mm::Family::Radio)
RAD_INFO("media: %s%s through '%s'; an image becomes one tile of %d..%d patches "
"(a quarter as many tokens), a video frame about %d patches, %d frames a "
"tubelet at %.3g frames a second, at most %d frames, no pruning; %lld "
"patches a pass", o.allow_image ? "images" : "",
o.allow_video ? " and video" : "", ranks_[0]->program.encoder_name.c_str(),
mm_proc->config().radio_min_patches, mm_proc->config().radio_max_patches,
mm_proc->config().radio_video_patches, mm_proc->config().radio_tubelet,
mm_proc->config().fps, mm_proc->config().max_frames,
(long long)encd.max_patches);
else else
RAD_INFO("media: %s%s through '%s'; an image resizes to at most %lld pixels (%lld " RAD_INFO("media: %s%s through '%s'; an image resizes to at most %lld pixels (%lld "
"patches a pass), a video to %lld pixels over all its frames", "patches a pass), a video to %lld pixels over all its frames",
@@ -2961,7 +3237,13 @@ int Engine::run_server() {
return rc; return rc;
} }
o.allow_audio = true; o.allow_audio = true;
if (mm::decoder_available()) if (mm::decoder_available() && ac.family == mm::AudioFamily::Gemma4Unified)
RAD_INFO("media: audio through '%s'; a clip is cut at %.3g s, a token is a frame of %d "
"samples (%d ms); %lld frames a pass",
ranks_[0]->program.audio_encoder_name.c_str(),
(double)mm_proc->audio_config().max_samples / (double)ac.rate, ac.frame_length,
ac.frame_length * 1000 / ac.rate, (long long)aend.max_patches);
else if (mm::decoder_available())
RAD_INFO("media: audio through '%s'; a clip is cut at %.3g s, %d mel bins a %d ms frame, " RAD_INFO("media: audio through '%s'; a clip is cut at %.3g s, %d mel bins a %d ms frame, "
"%d frames a token; %lld frames a pass", "%d frames a token; %lld frames a pass",
ranks_[0]->program.audio_encoder_name.c_str(), ranks_[0]->program.audio_encoder_name.c_str(),
@@ -3159,6 +3441,29 @@ int Engine::run_server() {
/* A video generator's endpoints: the driver's queue and the declared prompt, sizes and /* A video generator's endpoints: the driver's queue and the declared prompt, sizes and
* lengths. */ * lengths. */
struct ShapeBridge final : server::IShapeGen {
gen::ShapeDriver* drv = nullptr;
const gen::ShapeGenInfo& info() const override { return drv->info(); }
int submit(std::unique_ptr<gen::ShapeRequest> r, std::string* why) override {
return drv->submit(std::move(r), why);
}
int64_t queued() const override { return drv->queued(); }
int64_t running() const override { return drv->running(); }
} shape_bridge;
if (shp_gen_) {
shape_bridge.drv = shp_gen_;
d.shapes = &shape_bridge;
const gen::ShapeGenInfo& in = shp_gen_->info();
if (cfg_.served_model_name.empty() && !in.name.empty()) {
o.model_id = in.name;
decide("--served-model-name", o.model_id, "a shape generator: its own name");
}
RAD_INFO("shape: '%s', a %lldx%lld picture to a field sampled at %lld cells a side by "
"default (%lld..%lld), %lld steps by default at guidance %g",
in.name.c_str(), (long long)in.canvas, (long long)in.canvas,
(long long)in.default_resolution, (long long)in.min_resolution,
(long long)in.max_resolution, (long long)in.default_steps, in.default_guidance);
}
struct VideoBridge final : server::IVideoGen { struct VideoBridge final : server::IVideoGen {
gen::VideoDriver* drv = nullptr; gen::VideoDriver* drv = nullptr;
server::VideoGenInfo inf; server::VideoGenInfo inf;
@@ -3209,8 +3514,8 @@ int Engine::run_server() {
in.decoder_max_area = pg.vgen_str.decoder_max_area; in.decoder_max_area = pg.vgen_str.decoder_max_area;
if (in.image_cond && in.image_crf > 0 && !mm::h264_roundtrip_available()) if (in.image_cond && in.image_crf > 0 && !mm::h264_roundtrip_available())
RAD_WARN("video: '%s' prepares a first frame with an H.264 round trip at crf %d, which " RAD_WARN("video: '%s' prepares a first frame with an H.264 round trip at crf %d, which "
"needs libx264; this build's libavcodec has none, so input_reference is " "needs an H.264 encoder and decoder; this build's libavcodec lacks one, so "
"refused", in.name.c_str(), (int)in.image_crf); "input_reference is refused", in.name.c_str(), (int)in.image_crf);
in.max_lanes = vd.max_lanes; in.max_lanes = vd.max_lanes;
in.max_ref_images = vd.max_ref_images; in.max_ref_images = vd.max_ref_images;
in.max_ref_videos = vd.max_ref_videos; in.max_ref_videos = vd.max_ref_videos;
@@ -3308,6 +3613,9 @@ int Engine::run_server() {
else if (vid_gen_) else if (vid_gen_)
RAD_INFO("serving on http://%s:%d (/v1/videos; completions and chat are 501%s)", RAD_INFO("serving on http://%s:%d (/v1/videos; completions and chat are 501%s)",
o.host.c_str(), o.port, keyed); o.host.c_str(), o.port, keyed);
else if (shp_gen_)
RAD_INFO("serving on http://%s:%d (/generate, /send and /status/{uid}; completions and "
"chat are 501%s)", o.host.c_str(), o.port, keyed);
else if (gen_) else if (gen_)
RAD_INFO("serving on http://%s:%d (/v1/images/generations%s; completions and chat are " RAD_INFO("serving on http://%s:%d (/v1/images/generations%s; completions and chat are "
"501%s)", o.host.c_str(), o.port, "501%s)", o.host.c_str(), o.port,
+13 -5
View File
@@ -50,7 +50,7 @@ namespace rad {
class Kld; class Kld;
class StallWatch; class StallWatch;
namespace gen { class Driver; class AudioDriver; class VideoDriver; struct IPassDriver; } namespace gen { class Driver; class AudioDriver; class VideoDriver; class ShapeDriver; struct IPassDriver; }
namespace server { class Sink; } namespace server { class Sink; }
struct TierPump; struct TierPump;
struct TierJob; struct TierJob;
@@ -169,6 +169,7 @@ private:
std::vector<const char*> meta_kv_kp_, meta_kv_vp_; std::vector<const char*> meta_kv_kp_, meta_kv_vp_;
void (*arch_step_)(RadCtx*, const RadBatch*) = nullptr; void (*arch_step_)(RadCtx*, const RadBatch*) = nullptr;
uint64_t (*arch_pass_key_)(RadCtx*, const RadBatch*, const int32_t*) = nullptr;
int load_plugins(); int load_plugins();
int read_metadata(); int read_metadata();
@@ -254,6 +255,11 @@ private:
* copies are freed, because the holder that leaves last deletes the file. */ * copies are freed, because the holder that leaves last deletes the file. */
std::vector<TableShare> table_shares_; std::vector<TableShare> table_shares_;
std::vector<std::pair<const void*, void*>> table_copy_of_; std::vector<std::pair<const void*, void*>> table_copy_of_;
/* --ngram-placement disk=DIR: the table's own file, mapped read-only in place of the
* container's range (table_file_map); unmapped in ~Engine. */
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 /* --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. */ * rank's planner in place of the container's activation profile. */
std::vector<RadFileProfile> expert_profile_; std::vector<RadFileProfile> expert_profile_;
@@ -431,14 +437,16 @@ private:
int collect_pooled_issue(const RadBatch* b, StepOut& so); int collect_pooled_issue(const RadBatch* b, StepOut& so);
int collect_pooled(const RadBatch* b, StepOut& so); int collect_pooled(const RadBatch* b, StepOut& so);
/* A generator (rad_declare_generator, rad_declare_audio_generator, /* A generator (rad_declare_generator, rad_declare_audio_generator,
* rad_declare_video_generator): the driver that turns requests into passes and the loop that * rad_declare_video_generator, rad_declare_shape_generator): the driver that turns requests
* runs them, replacing the scheduler and step loop (engine_gen.cpp). Null for every other * into passes and the loop that runs them, replacing the scheduler and step loop
* program. `img_gen_`, `aud_gen_` and `vid_gen_` are the same driver by its kind, for the * (engine_gen.cpp). Null for every other program. `img_gen_`, `aud_gen_`, `vid_gen_` and
* endpoints; one of them is set when `gen_` is. */ * `shp_gen_` are the same driver by its kind, for the endpoints; one of them is set when
* `gen_` is. */
std::unique_ptr<gen::IPassDriver> gen_; std::unique_ptr<gen::IPassDriver> gen_;
gen::Driver* img_gen_ = nullptr; gen::Driver* img_gen_ = nullptr;
gen::AudioDriver* aud_gen_ = nullptr; gen::AudioDriver* aud_gen_ = nullptr;
gen::VideoDriver* vid_gen_ = nullptr; gen::VideoDriver* vid_gen_ = nullptr;
gen::ShapeDriver* shp_gen_ = nullptr;
int gen_loop(); int gen_loop();
/* Zeroes the state slots the KV manager granted since the last step, on every rank's stream, /* Zeroes the state slots the KV manager granted since the last step, on every rank's stream,
* before the step or pass that first reads them. */ * before the step or pass that first reads them. */
+114 -7
View File
@@ -11,6 +11,7 @@
#include "gen/driver.h" #include "gen/driver.h"
#include "gen/audio_driver.h" #include "gen/audio_driver.h"
#include "gen/video_driver.h" #include "gen/video_driver.h"
#include "gen/shape_driver.h"
#include "build/startup.h" #include "build/startup.h"
#include "build/rad_build.h" #include "build/rad_build.h"
@@ -481,6 +482,35 @@ int Engine::copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, v
return RAD_OK; return RAD_OK;
} }
/* --ngram-placement disk=DIR: the container's [src, src + n) at file offset `foff` read from its own
* file, DIR/ngram-<id>.bin (the table's bytes and nothing else, the id table_share_id's: the
* container's path, size and mtime and the table's place in it). The first start fills it from the
* container through a temporary name and renames it, so a file under the real name is complete; a
* later start checks samples of it against the container. Mapped read-only in place of the
* container's range, which is all the disk gather needs: it finds the file behind the mapping and
* reads it directly (libavx avx_ngram.cpp, table_file). */
int Engine::table_file_map(const uint8_t* src, int64_t n, int64_t foff, void** out,
std::string* why) {
const auto t0 = std::chrono::steady_clock::now();
const std::string id = table_share_id(file_->path(), foff, n);
if (id.empty()) {
*why = fmt("the container %s cannot be stat'ed, which names the table's file", file_->path());
return RAD_E_IO;
}
const std::string& dir = cfg_.ngram_disk_dir;
const std::string path = dir + (dir.back() == '/' ? "" : "/") + "ngram-" + id + ".bin";
TableCopy c;
bool filled = false;
const int rc = table_file_open(*file_, src, n, foff, path, &c, &filled, why);
if (rc != RAD_OK) return rc;
table_files_.push_back(c);
RAD_INFO("placement: n-gram table read from %s (%s%s, %.1f s)", path.c_str(), humanb(n).c_str(),
filled ? ", filled from the container" : "",
std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count());
*out = c.base;
return RAD_OK;
}
/* When --ngram-placement auto chose a pinned copy for a card and it could not be made, move the /* When --ngram-placement auto chose a pinned copy for a card and it could not be made, move the
* gather to the host. Every rank's n-gram weights take the host site, in both the WeightInfo * gather to the host. Every rank's n-gram weights take the host site, in both the WeightInfo
* Ctx::init reads and the plan, so the gather and its scale move together; a copy already * Ctx::init reads and the plan, so the gather and its scale move together; a copy already
@@ -967,6 +997,7 @@ int Engine::load_plugins() {
const Plugin* ap = rad_tools_registry().plugin(plugins_.arch_plugin); const Plugin* ap = rad_tools_registry().plugin(plugins_.arch_plugin);
arch_step_ = ap ? ap->arch_step : nullptr; arch_step_ = ap ? ap->arch_step : nullptr;
arch_pass_key_ = ap ? ap->arch_pass_key : nullptr;
return RAD_OK; return RAD_OK;
} }
@@ -1000,6 +1031,7 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
* fast row (RadBuildCtx::plain_norm). */ * fast row (RadBuildCtx::plain_norm). */
bc.plain_norm = std::strcmp(device_backend_name(), "sycl") == 0 ? 1 : 0; bc.plain_norm = std::strcmp(device_backend_name(), "sycl") == 0 ? 1 : 0;
bc.tp_wire_min_bytes = cfg_.tp_wire_min_kb * 1024; bc.tp_wire_min_bytes = cfg_.tp_wire_min_kb * 1024;
bc.expert_file_tier = cfg_.weights_disk_tier ? 1 : 0;
bc.scope = ""; bc.scope = "";
bc.max_enc_patches = cfg_.mm_max_patches > 0 ? cfg_.mm_max_patches : 0; bc.max_enc_patches = cfg_.mm_max_patches > 0 ? cfg_.mm_max_patches : 0;
bc.max_audio_frames = cfg_.mm_audio_frames > 0 ? cfg_.mm_audio_frames : 0; bc.max_audio_frames = cfg_.mm_audio_frames > 0 ? cfg_.mm_audio_frames : 0;
@@ -1113,6 +1145,25 @@ int Engine::declare() {
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0; if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
if (cfg_.n_spec < 0) cfg_.n_spec = 0; if (cfg_.n_spec < 0) cfg_.n_spec = 0;
cfg_.prefix_cache = false; cfg_.prefix_cache = false;
} else if (pb.gen_rows > 0 && pb.gen_shape) {
if (!cfg_.given.count("--max-num-batched-tokens")) {
cfg_.max_tok = pb.gen_rows;
decide("--max-num-batched-tokens", std::to_string(cfg_.max_tok),
"a shape generator: a denoising step's two branches or a query pass's "
"points, whichever is more");
}
if (!cfg_.given.count("--max-num-seqs")) {
cfg_.max_seqs = 1;
decide("--max-num-seqs", "1", "a shape generator: a pass is one request's");
}
if (!cfg_.given.count("--max-model-len") && cfg_.max_ctx == 0) {
cfg_.max_ctx = pb.gen_rows;
decide("--max-model-len", std::to_string(cfg_.max_ctx),
"a shape generator: a pass's rows");
}
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
if (cfg_.n_spec < 0) cfg_.n_spec = 0;
cfg_.prefix_cache = false;
} else if (pb.gen_rows > 0 && pb.gen_video) { } else if (pb.gen_rows > 0 && pb.gen_video) {
if (!cfg_.given.count("--max-num-batched-tokens")) { if (!cfg_.given.count("--max-num-batched-tokens")) {
cfg_.max_tok = pb.gen_rows; cfg_.max_tok = pb.gen_rows;
@@ -1302,6 +1353,27 @@ int Engine::declare() {
: "the model carries no vision tower"); : "the model carries no vision tower");
} }
/* --prefill-interleave not given: auto:1, decode-only steps for as long as a chunk step took,
* so decoders keep about half their rate while prompts prefill (measured on Flash-Next: 8
* decoders beside a 64K prefill, 12 -> 41 tokens/s each). Not where the schedule must not
* follow timing (--deterministic) or nothing decodes beside a prefill (a generator's passes,
* KL mode's scoring); an explicit N or auto[:SHARE] is kept as given. */
if (!cfg_.prefill_interleave_set) {
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
const char* none = pb.gen_rows > 0 ? "a generator: its passes carry no decode rows"
: cfg_.kld() ? "KL mode scores documents and decodes nothing" : nullptr;
if (none || cfg_.deterministic) {
decide("--prefill-interleave", "0", none ? none : "--deterministic keeps a "
"timing-independent schedule (--prefill-interleave N or auto overrides it)");
} else {
cfg_.prefill_interleave = -1;
cfg_.prefill_interleave_share = 1.0;
decide("--prefill-interleave", "auto:1", "decode-only steps for as long as a chunk "
"step took while prompts prefill beside decoding sequences");
}
}
/* Control vectors are resolved before any rank declares, because the plugin reads the /* Control vectors are resolved before any rank declares, because the plugin reads the
* direction table from RadBuildCtx. Only `--control-vector off|on` loads one; without it * direction table from RadBuildCtx. Only `--control-vector off|on` loads one; without it
* nothing is looked for and the graph declares no projection op. With it, a plugin that does * nothing is looked for and the graph declares no projection op. With it, a plugin that does
@@ -1827,6 +1899,7 @@ int Engine::plan() {
f.staging = r->program.is_generator() ? gen::Driver::device_bytes(r->program) f.staging = r->program.is_generator() ? gen::Driver::device_bytes(r->program)
: r->program.is_audio_generator() ? gen::AudioDriver::device_bytes(r->program) : r->program.is_audio_generator() ? gen::AudioDriver::device_bytes(r->program)
: r->program.is_video_generator() ? gen::VideoDriver::device_bytes(r->program) : r->program.is_video_generator() ? gen::VideoDriver::device_bytes(r->program)
: r->program.is_shape_generator() ? gen::ShapeDriver::device_bytes(r->program)
: BatchBuilder::device_bytes(r->program, cfg_, kg); : BatchBuilder::device_bytes(r->program, cfg_, kg);
if (f.staging < 0) return RAD_E_INVAL; if (f.staging < 0) return RAD_E_INVAL;
late_step_bytes_ = std::max(late_step_bytes_, f.staging); late_step_bytes_ = std::max(late_step_bytes_, f.staging);
@@ -3052,6 +3125,26 @@ int Engine::load_weights() {
"rows are read from the container%s", into, why.c_str(), "rows are read from the container%s", into, why.c_str(),
card ? " by the host gather" : "")); card ? " by the host gather" : ""));
} }
/* --ngram-placement disk=DIR: the table's own file instead of the container. */
if (cfg_.ngram_resolved == TablePlacement::Disk && !cfg_.ngram_disk_dir.empty() &&
is_ngram_table(r->program, (rad_weight)i) && n >= kTableShareMin) {
void* m = nullptr;
for (size_t k = 0; k < table_files_.size() && !m; ++k)
if (table_file_src_[k] == w.host_ptr) m = table_files_[k].base;
std::string why;
if (!m) {
const int fs = table_file_map((const uint8_t*)w.ptr, n, (int64_t)p0.offset,
&m, &why);
if (fs != RAD_OK) {
RAD_ERR("--ngram-placement disk=%s: '%s': %s",
cfg_.ngram_disk_dir.c_str(), w.name.c_str(), why.c_str());
return fs;
}
table_file_src_.push_back(w.host_ptr);
}
w.ptr = m;
w.host_ptr = m;
}
/* No readahead on a mapped weight: a host kernel gathers a few rows from a table /* No readahead on a mapped weight: a host kernel gathers a few rows from a table
* too large to be resident, so the default 128 KiB readahead would read 32 pages * too large to be resident, so the default 128 KiB readahead would read 32 pages
* for a row of a few hundred bytes. MADV_RANDOM is per range, so the rest of the * for a row of a few hundred bytes. MADV_RANDOM is per range, so the rest of the
@@ -3871,6 +3964,7 @@ int Engine::start() {
/* Null for all-in-VRAM: the mover never runs and lookup uses WeightInfo::ptr. */ /* Null for all-in-VRAM: the mover never runs and lookup uses WeightInfo::ptr. */
d.residency = r->plan.strategy == Strategy::AllVram ? nullptr : r->mover.residency(); d.residency = r->plan.strategy == Strategy::AllVram ? nullptr : r->mover.residency();
d.arch_step = arch_step_; d.arch_step = arch_step_;
d.arch_pass_key = arch_pass_key_;
d.profile_ops = cfg_.profile_ops; d.profile_ops = cfg_.profile_ops;
bind_kv_pools(r->program, [&](int32_t g) { return r->kv.plan(g); }, &d.kv); bind_kv_pools(r->program, [&](int32_t g) { return r->kv.plan(g); }, &d.kv);
d.registry = &rad_tools_registry(); d.registry = &rad_tools_registry();
@@ -3916,10 +4010,15 @@ int Engine::start() {
}, },
&r->ctx)); &r->ctx));
if (r->fstager.enabled() && r->index == 0) if (r->fstager.enabled() && r->index == 0)
RAD_INFO("file stager: %zu routed layers hold experts read from the container; each " RAD_INFO("file stager: it covers %zu routed layers (a pool-cached unit of one may "
"pass reads a layer's (up to %s) into one of two VRAM buffers before its " "be read from the container); each pass reads a layer's (up to %s) into one "
"first expert op, so every step is paced by the drive", "of two VRAM buffers before its first expert op, so every step is paced by the drive%s",
r->fstager.n_layers(), humanb(r->plan.file_layer_max).c_str()); r->fstager.n_layers(), humanb(r->plan.file_layer_max).c_str(),
r->fstager.whole_rows() > 0
? fmt("; a pass of %lld tokens or more reads its layers whole, each "
"while the card computes the one before",
(long long)r->fstager.whole_rows()).c_str()
: "");
if (r->stager.enabled() && r->fstager.enabled()) { if (r->stager.enabled() && r->fstager.enabled()) {
r->stagers.set(&r->stager, &r->fstager); r->stagers.set(&r->stager, &r->fstager);
r->ctx.set_stager(&r->stagers); r->ctx.set_stager(&r->stagers);
@@ -4138,10 +4237,16 @@ int Engine::start() {
: fmt("%s --gpu-headroom-mib", humanb(want).c_str()); : fmt("%s --gpu-headroom-mib", humanb(want).c_str());
if (room < allowance) { if (room < allowance) {
const int64_t raise_mib = (allowance - room + MiB - 1) / MiB; const int64_t raise_mib = (allowance - room + MiB - 1) / MiB;
const int64_t need_head = std::max<int64_t>(cfg_.gpu_headroom_mib, 0) + raise_mib;
const std::string fix = cfg_.gpu_memory_mib > 0
? fmt("Set --gpu-memory-mib to at most %lld: what is left here falls with it one "
"for one.",
(long long)(props.vram_bytes / MiB - need_head))
: fmt("Set --gpu-headroom-mib to at least %lld: what is left here rises with it "
"one for one.", (long long)need_head);
RAD_WARN("card %d settled at %s free against %s, which leaves %s for a kernel's first " RAD_WARN("card %d settled at %s free against %s, which leaves %s for a kernel's first "
"launch to load its code object and size its scratch in -- under the %s this " "launch to load its code object and size its scratch in -- under the %s this "
"engine allows for its own. %s Set --gpu-headroom-mib to at least %lld: what " "engine allows for its own. %s %s",
"is left here rises with it one for one.",
r->device, humanb(got).c_str(), asked.c_str(), r->device, humanb(got).c_str(), asked.c_str(),
humanb(std::max<int64_t>(room, 0)).c_str(), humanb(allowance).c_str(), humanb(std::max<int64_t>(room, 0)).c_str(), humanb(allowance).c_str(),
got < want got < want
@@ -4149,7 +4254,7 @@ int Engine::start() {
"another process on it or an allocation the budget does not " "another process on it or an allocation the budget does not "
"count.", humanb(want - got).c_str()).c_str() "count.", humanb(want - got).c_str()).c_str()
: "", : "",
(long long)(std::max<int64_t>(cfg_.gpu_headroom_mib, 0) + raise_mib)); fix.c_str());
} else if (got < want) { } else if (got < want) {
RAD_INFO("card %d settled at %s free against %s: %s of the headroom was taken after " RAD_INFO("card %d settled at %s free against %s: %s of the headroom was taken after "
"the budget read the card, by another process on it or an allocation the " "the budget read the card, by another process on it or an allocation the "
@@ -4211,6 +4316,8 @@ int Engine::load_vocab() {
return RAD_E_FORMAT; return RAD_E_FORMAT;
} }
RAD_TRY(vocab_deserialize(file_->base(), (uint64_t)file_->size(), vs.h, vb)); RAD_TRY(vocab_deserialize(file_->base(), (uint64_t)file_->size(), vs.h, vb));
} else if (meta_textless(rad_meta_gets(&meta_, "radiance.text", nullptr))) {
vocab_textless(vb);
} else if (ckpt_->is_gguf()) { } else if (ckpt_->is_gguf()) {
/* GGUF names its pre-tokeniser; the chain is reconstructed from the name or refused (a /* GGUF names its pre-tokeniser; the chain is reconstructed from the name or refused (a
* container converted with --tokenizer bakes in the declared one). */ * container converted with --tokenizer bakes in the declared one). */
+8 -2
View File
@@ -1,6 +1,6 @@
/* engine_gen.cpp -- a generator's loop: the driver's passes (core/gen/pass.h; driver.h for /* engine_gen.cpp -- a generator's loop: the driver's passes (core/gen/pass.h; driver.h for
* images, audio_driver.h for audio, video_driver.h for video) run on the ranks like token steps, one at a time, each drained * images, audio_driver.h for audio, video_driver.h for video, shape_driver.h for shapes) run on the
* before the next. * ranks like token steps, one at a time, each drained before the next.
* *
* Draining is cheap: a pass is tens to thousands of milliseconds of device work, and the next * Draining is cheap: a pass is tens to thousands of milliseconds of device work, and the next
* pass depends only on the driver's host bookkeeping, so the wait costs the microseconds of * pass depends only on the driver's host bookkeeping, so the wait costs the microseconds of
@@ -29,6 +29,12 @@ static const char* pass_name(int gen) {
case RAD_GEN_PASS_ADECODE: return "adecode"; case RAD_GEN_PASS_ADECODE: return "adecode";
case RAD_GEN_PASS_VDECODE: return "vdecode"; case RAD_GEN_PASS_VDECODE: return "vdecode";
case RAD_GEN_PASS_VUPSCALE: return "vupscale"; case RAD_GEN_PASS_VUPSCALE: return "vupscale";
case RAD_GEN_PASS_VENCODE: return "vencode";
case RAD_GEN_PASS_AENCODE: return "aencode";
case RAD_GEN_PASS_SCOND: return "scond";
case RAD_GEN_PASS_SSTEP: return "sstep";
case RAD_GEN_PASS_SLATENT: return "slatent";
case RAD_GEN_PASS_SQUERY: return "squery";
default: return ""; default: return "";
} }
} }
+223 -30
View File
@@ -13,6 +13,7 @@
#include <cstdlib> #include <cstdlib>
#include <cstring> #include <cstring>
#include <fstream> #include <fstream>
#include <sstream>
#include <map> #include <map>
namespace rad { namespace rad {
@@ -54,8 +55,9 @@ void MetaOwn::finish() {
* since the plugin only sees RadModelMeta, whose typed fields size everything at declare. * since the plugin only sees RadModelMeta, whose typed fields size everything at declare.
* *
* A text-only model puts its dimensions at the top level; a multimodal one nests them under * A text-only model puts its dimensions at the top level; a multimodal one nests them under
* `text_config` beside `vision_config`. Every key is flattened into the free-form list by dotted * `text_config` beside `vision_config` (NVIDIA's omni wrappers: `llm_config`). Every key is
* path, and typed fields are read from `text_config.X`, falling back to `X`, so a plugin finds * flattened into the free-form list by dotted path, and typed fields are read from
* `text_config.X`, then `llm_config.X`, falling back to `X`, so a plugin finds
* `vision_config.depth` under that name either way. * `vision_config.depth` under that name either way.
*/ */
/* An array's scalars appended to `s` space-separated, nested arrays flattened row-major (a /* An array's scalars appended to `s` space-separated, nested arrays flattened row-major (a
@@ -95,10 +97,20 @@ static void flatten_json(const nlohmann::json& j, const std::string& prefix, Met
else if (v.is_string()) out->kv(key, v.get<std::string>()); else if (v.is_string()) out->kv(key, v.get<std::string>());
else if (v.is_array()) { else if (v.is_array()) {
/* An array of scalars becomes a space-separated string (mrope_section "11 11 10", /* An array of scalars becomes a space-separated string (mrope_section "11 11 10",
* layer_types "linear_attention full_attention ..."), nested arrays row-major. * layer_types "linear_attention full_attention ..."), nested arrays row-major. An
* Arrays of objects are skipped. */ * array of objects is flattened element by element under its index (Nemotron-H
* Puzzle's per-layer `block_configs.1.n_routed_experts`); other mixed arrays are
* skipped. */
std::string s; std::string s;
if (join_scalars(v, &s)) out->kv(key, s); if (join_scalars(v, &s)) {
out->kv(key, s);
} else {
bool objects = !v.empty();
for (const auto& e : v) objects = objects && e.is_object();
if (objects)
for (size_t i = 0; i < v.size(); ++i)
flatten_json(v[i], key + "." + std::to_string(i), out);
}
} }
} }
} }
@@ -196,31 +208,38 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
flatten_json(j, "", out); flatten_json(j, "", out);
/* Alias text_config.X to a bare X where no bare X exists, so plugins read the same free-form /* Alias text_config.X (or llm_config.X) to a bare X where no bare X exists, so plugins read
* keys (e.g. `partial_rotary_factor`) with or without a vision tower. A bare key wins where * the same free-form keys (e.g. `partial_rotary_factor`) with or without a vision tower. A
* both exist. */ * bare key wins where both exist. */
{ {
const size_t n = out->keys.size(); const size_t n = out->keys.size();
for (size_t i = 0; i < n; ++i) { for (const char* pre : { "text_config.", "llm_config." }) {
const std::string& k = out->keys[i]; const size_t len = std::strlen(pre);
if (k.rfind("text_config.", 0) != 0) continue; for (size_t i = 0; i < n; ++i) {
const std::string bare = k.substr(12); const std::string& k = out->keys[i];
bool have = false; if (k.rfind(pre, 0) != 0) continue;
for (size_t j2 = 0; j2 < n; ++j2) if (out->keys[j2] == bare) { have = true; break; } const std::string bare = k.substr(len);
if (!have) out->kv(bare, out->vals[i]); bool have = false;
for (size_t j2 = 0; j2 < out->keys.size(); ++j2)
if (out->keys[j2] == bare) { have = true; break; }
if (!have) out->kv(bare, out->vals[i]);
}
} }
} }
auto gs = [&](const char* k) -> const char* { return out->get(k); }; auto gs = [&](const char* k) -> const char* { return out->get(k); };
/* text_config first, then the top level. */ /* text_config first, then llm_config, then the top level. */
auto gi = [&](const char* k, int64_t dflt) -> int64_t { auto nested = [&](const char* k) -> const char* {
const char* v = gs((std::string("text_config.") + k).c_str()); const char* v = gs((std::string("text_config.") + k).c_str());
if (!v) v = gs(k); if (!v) v = gs((std::string("llm_config.") + k).c_str());
return v ? v : gs(k);
};
auto gi = [&](const char* k, int64_t dflt) -> int64_t {
const char* v = nested(k);
return v ? strtoll(v, nullptr, 10) : dflt; return v ? strtoll(v, nullptr, 10) : dflt;
}; };
auto gf = [&](const char* k, double dflt) -> double { auto gf = [&](const char* k, double dflt) -> double {
const char* v = gs((std::string("text_config.") + k).c_str()); const char* v = nested(k);
if (!v) v = gs(k);
return v ? strtod(v, nullptr) : dflt; return v ? strtod(v, nullptr) : dflt;
}; };
@@ -232,6 +251,11 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
/* LFM2-VL names the wrapper, not the text model; one plugin serves LFM2 with or without /* LFM2-VL names the wrapper, not the text model; one plugin serves LFM2 with or without
* its tower. `model_type` stays in the free-form keys. */ * its tower. `model_type` stays in the free-form keys. */
if (out->arch == "lfm2vl") out->arch = "lfm2"; if (out->arch == "lfm2vl") out->arch = "lfm2";
/* Gemma 4 12B (`gemma4_unified`): its text model is Gemma 4's, served by the gemma4
* plugins; `model_type` tells them apart. */
if (out->arch == "gemma4unified") out->arch = "gemma4";
/* Nemotron-H Omni wraps a Nemotron-H Puzzle text model (`llm_config`) the same way. */
if (out->arch == "nemotronhomni") out->arch = "nemotronh";
} }
if (const char* nm = gs("_name_or_path")) out->name = nm; if (const char* nm = gs("_name_or_path")) out->name = nm;
@@ -240,6 +264,15 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
* moe_top_k. They are the last fallbacks in each chain, so a config carrying both spellings * moe_top_k. They are the last fallbacks in each chain, so a config carrying both spellings
* reads the HuggingFace one. */ * reads the HuggingFace one. */
m.n_layers = gi("num_hidden_layers", gi("n_layer", 0)); m.n_layers = gi("num_hidden_layers", gi("n_layer", 0));
/* Nemotron-H Puzzle states no count: HF derives it from the per-layer list. */
if (m.n_layers == 0)
if (const char* types = nested("layers_block_type"))
for (const char* p = types; *p;) {
while (*p == ' ') ++p;
if (!*p) break;
++m.n_layers;
while (*p && *p != ' ') ++p;
}
m.n_embd = gi("hidden_size", gi("n_embd", 0)); m.n_embd = gi("hidden_size", gi("n_embd", 0));
m.n_head = gi("num_attention_heads", gi("n_head", 0)); m.n_head = gi("num_attention_heads", gi("n_head", 0));
m.n_head_kv = gi("num_key_value_heads", m.n_head); m.n_head_kv = gi("num_key_value_heads", m.n_head);
@@ -688,6 +721,124 @@ int Checkpoint::open_diffusers() {
return RAD_OK; return RAD_OK;
} }
/* config.yaml's maps of scalars as dotted keys, a list's items space-separated, booleans as 1 and
* 0 and a trailing comment dropped: the subset Hunyuan3D-2's configs are written in. Anything else
* (a multi-line value, a list of maps) is refused, not guessed at. */
static int meta_from_yaml(const std::string& path, MetaOwn* out) {
std::ifstream f(path);
if (!f) {
RAD_ERR("%s: cannot read", path.c_str());
return RAD_E_IO;
}
std::vector<std::pair<size_t, std::string>> stack; /* indentation, key */
std::string line;
int ln = 0;
auto trim = [](std::string s) {
const size_t a = s.find_first_not_of(" \t\r"), b = s.find_last_not_of(" \t\r");
return a == std::string::npos ? std::string() : s.substr(a, b - a + 1);
};
while (std::getline(f, line)) {
++ln;
if (const size_t h = line.find(" #"); h != std::string::npos) line.resize(h);
const std::string body = trim(line);
if (body.empty() || body[0] == '#') continue;
const size_t ind = line.find_first_not_of(' ');
const size_t colon = body.find(':');
if (colon == std::string::npos || body[0] == '-') {
RAD_ERR("%s:%d: not a `key: value` line of the YAML this importer reads", path.c_str(), ln);
return RAD_E_FORMAT;
}
while (!stack.empty() && stack.back().first >= ind) stack.pop_back();
const std::string key = trim(body.substr(0, colon));
std::string val = trim(body.substr(colon + 1));
std::string full;
for (const auto& s : stack) full += s.second + ".";
full += key;
if (val.empty()) {
stack.emplace_back(ind, key);
continue;
}
if (val.front() == '[') {
if (val.back() != ']') {
RAD_ERR("%s:%d: a list must close on its line", path.c_str(), ln);
return RAD_E_FORMAT;
}
std::string items;
for (char& ch : val) if (ch == '[' || ch == ']' || ch == ',') ch = ' ';
std::istringstream is(val);
for (std::string it; is >> it;) items += (items.empty() ? "" : " ") + it;
val = items;
} else if (val == "True" || val == "true") {
val = "1";
} else if (val == "False" || val == "false") {
val = "0";
} else if (val.size() >= 2 && (val.front() == '"' || val.front() == '\'') &&
val.back() == val.front()) {
val = val.substr(1, val.size() - 2);
}
out->set(full, val);
}
return RAD_OK;
}
/* A Hunyuan3D-2 shape model (tencent/Hunyuan3D-2's hunyuan3d-dit-v2-0 and its kin): a folder of
* config.yaml and one safetensors holding three networks under `model.` (the DiT),
* `conditioner.` (DINOv2's image encoder) and `vae.` (the shape VAE), the names kept. config.yaml's
* keys go into the metadata by dotted path (model.params.hidden_size, vae.params.scale_factor,
* conditioner.params.main_image_encoder.kwargs.config.num_hidden_layers, ...). The architecture
* is `hunyuan3d2`, and the model reads no text (`radiance.text` none). */
int Checkpoint::open_hy3d(const std::string& weights) {
kind_ = SafeT;
RAD_TRY(add_shard(weights));
RAD_TRY(meta_from_yaml(dir_ + "/config.yaml", &meta_));
meta_.arch = "hunyuan3d2";
meta_.set("radiance.text", "none");
/* The typed dimensions are the denoiser's: its blocks, width and heads, read off its tensors;
* the vocabulary is the one token of a model that reads no text, and the context a step's
* rows (both branches of the 1370 conditioning rows and the latent). */
{
RadModelMeta& m = meta_.m;
const SrcTensor* lat = find("model.latent_in.weight");
const SrcTensor* mlp = find("model.double_blocks.0.img_mlp.0.weight");
const SrcTensor* qn = find("model.double_blocks.0.img_attn.norm.query_norm.scale");
const SrcTensor* vae = find("vae.post_kl.weight");
int64_t layers = 0;
while (find("model.double_blocks." + std::to_string(layers) + ".img_mod.lin.weight"))
++layers;
for (int64_t s = 0; find("model.single_blocks." + std::to_string(s) + ".linear1.weight"); ++s)
++layers;
if (!lat || lat->shape.size() != 2 || !mlp || mlp->shape.size() != 2 || !qn ||
qn->shape.size() != 1 || qn->shape[0] <= 0 || !vae || !layers) {
RAD_ERR("%s: Hunyuan3D-2's DiT or shape VAE is incomplete", weights.c_str());
return RAD_E_FORMAT;
}
m.n_layers = layers;
m.n_embd = lat->shape[0];
m.head_dim = qn->shape[0];
m.n_head = m.n_head_kv = m.n_embd / m.head_dim;
m.n_ff = mlp->shape[0];
m.n_vocab = 1;
m.n_ctx_train = 2 * (1370 + 3072);
m.rms_eps = 1e-6f;
m.rope_theta = 10000.0f;
m.rope_scale = 1.0f;
}
meta_.finish();
return RAD_OK;
}
/* Whether `file` is a Hunyuan3D-2 shape checkpoint: its DiT and image encoder by name. */
static bool hy3d_weights(const std::string& file) {
SafeTensorsFile probe;
if (probe.open(file) != RAD_OK) return false;
bool dit = false, enc = false;
for (const auto& t : probe.tensors()) {
dit = dit || t.name == "model.latent_in.weight";
enc = enc || t.name.rfind("conditioner.main_image_encoder.", 0) == 0;
}
return dit && enc;
}
/* A single-file Stable Diffusion XL checkpoint in Stability's (sgm) layout, the form SDXL and its /* A single-file Stable Diffusion XL checkpoint in Stability's (sgm) layout, the form SDXL and its
* finetunes (Illustrious, NoobAI, Pony and the rest) are published in: one safetensors holding * finetunes (Illustrious, NoobAI, Pony and the rest) are published in: one safetensors holding
* *
@@ -887,6 +1038,16 @@ int Checkpoint::open_safetensors(const std::string& path) {
((path_exists(dir_ + "/model_index.json") && !path_exists(dir_ + "/config.json")) || ((path_exists(dir_ + "/model_index.json") && !path_exists(dir_ + "/config.json")) ||
path_exists(dir_ + "/modular_model_index.json"))) path_exists(dir_ + "/modular_model_index.json")))
return open_diffusers(); return open_diffusers();
/* A Hunyuan3D-2 shape model: config.yaml beside its one safetensors (the fp16 one when the
* folder holds both). */
if (!is_index && path_exists(dir_ + "/config.yaml")) {
std::string w = path;
if (!is_file)
for (const char* f : { "/model.fp16.safetensors", "/model.safetensors" })
if (path_exists(dir_ + f)) { w = dir_ + f; break; }
if (w != path || is_file)
if (hy3d_weights(w)) return open_hy3d(w);
}
if (is_file) { if (is_file) {
shards.push_back(path); shards.push_back(path);
/* A single-file Stable Diffusion XL checkpoint, as Stability and every SDXL finetune /* A single-file Stable Diffusion XL checkpoint, as Stability and every SDXL finetune
@@ -1274,16 +1435,17 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
if (why) *why = std::move(m); if (why) *why = std::move(m);
return rc; return rc;
}; };
const Import im = imports_at(name); /* a drafter's own form under its prefix */
/* CtFp8 has no imported form: its FP8 weights read stock (ckpt_resolve). */ /* CtFp8 has no imported form: its FP8 weights read stock (ckpt_resolve). */
if (import_ == Import::None || import_ == Import::CtFp8) return RAD_E_NOTFOUND; if (im == Import::None || im == Import::CtFp8) return RAD_E_NOTFOUND;
if (auto hit = imported_.find(name); hit != imported_.end()) { if (auto hit = imported_.find(name); hit != imported_.end()) {
*codes = hit->second.first; *codes = hit->second.first;
*scale = hit->second.second; *scale = hit->second.second;
return RAD_OK; return RAD_OK;
} }
if (import_ == Import::ParoI5 || import_ == Import::ParoI4) { if (im == Import::ParoI5 || im == Import::ParoI4) {
const bool i5 = import_ == Import::ParoI5; const bool i5 = im == Import::ParoI5;
/* Paro int5: `X.weight` is X.qweight/.qweight_hi (codes), X.scales (f16 [G, N]) and /* Paro int5: `X.weight` is X.qweight/.qweight_hi (codes), X.scales (f16 [G, N]) and
* X.qzeros/.qzeros_hi (zero points). The view describes the logical [N, K] u5 matrix; * X.qzeros/.qzeros_hi (zero points). The view describes the logical [N, K] u5 matrix;
* ckpt_plane_rows re-lays the planes row by row. */ * ckpt_plane_rows re-lays the planes row by row. */
@@ -1323,13 +1485,13 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
return RAD_OK; return RAD_OK;
} }
if (import_ == Import::QuarkMx || import_ == Import::ParoMx || import_ == Import::ParoM2) { if (im == Import::QuarkMx || im == Import::ParoMx || im == Import::ParoM2) {
/* Quark's MXFP4 is `fp4_e2m1*e8m0[1x32]` as stored: two codes per byte (element 2j in the /* Quark's MXFP4 is `fp4_e2m1*e8m0[1x32]` as stored: two codes per byte (element 2j in the
* low nibble), one biased exponent per 32 of K. The view only renames dtypes and the * low nibble), one biased exponent per 32 of K. The view only renames dtypes and the
* logical width. Excluded layers are plain tensors. ParoQuant's M2XFP4 grid carries one * logical width. Excluded layers are plain tensors. ParoQuant's M2XFP4 grid carries one
* more plane (`weight_meta`, [N, K/32] u8) that is handed to the weight through * more plane (`weight_meta`, [N, K/32] u8) that is handed to the weight through
* import_meta: its bytes are the encoding's third plane as they ship. */ * import_meta: its bytes are the encoding's third plane as they ship. */
const bool m2 = import_ == Import::ParoM2; const bool m2 = im == Import::ParoM2;
const SrcTensor* w = find(name); const SrcTensor* w = find(name);
const SrcTensor* e = w ? find(name + "_scale") : nullptr; const SrcTensor* e = w ? find(name + "_scale") : nullptr;
if (!w || !e || w->rad_dtype != RAD_U8) return RAD_E_NOTFOUND; if (!w || !e || w->rad_dtype != RAD_U8) return RAD_E_NOTFOUND;
@@ -1356,7 +1518,7 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
return RAD_OK; return RAD_OK;
} }
if (import_ == Import::CtInt4) { if (im == Import::CtInt4) {
/* CT-INT4: `X.weight` ships as X.weight_packed (i32 [N, K/8], eight codes per word from the /* 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 * low bits, each the signed code plus 8) and X.weight_scale ([N, K/group]), and when
* asymmetric X.weight_zero_point (see SrcTensor::ct_zero). compressed-tensors dequantises * asymmetric X.weight_zero_point (see SrcTensor::ct_zero). compressed-tensors dequantises
@@ -1427,7 +1589,7 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
return RAD_OK; return RAD_OK;
} }
if (import_ == Import::ModelOpt) { if (im == Import::ModelOpt) {
/* ModelOpt's NVFP4: `X.weight` U8 [N, K/2] (two e2m1 codes a byte, the even k in the low /* ModelOpt's NVFP4: `X.weight` U8 [N, K/2] (two e2m1 codes a byte, the even k in the low
* nibble), `X.weight_scale` e4m3 [N, K/16] and `X.weight_scale_2` f32, one per tensor. * nibble), `X.weight_scale` e4m3 [N, K/16] and `X.weight_scale_2` f32, one per tensor.
* ModelOpt dequantises * ModelOpt dequantises
@@ -1483,7 +1645,7 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
return RAD_OK; return RAD_OK;
} }
if (import_ == Import::Nvfp4) { if (im == Import::Nvfp4) {
/* NVFP4 (compressed-tensors' nvfp4-pack-quantized): `X.weight_packed` U8 [N, K/2], two /* NVFP4 (compressed-tensors' nvfp4-pack-quantized): `X.weight_packed` U8 [N, K/2], two
* e2m1 codes per byte with the even k in the low nibble; `X.weight_scale` e4m3 [N, K/16]; * e2m1 codes per byte with the even k in the low nibble; `X.weight_scale` e4m3 [N, K/16];
* `X.weight_global_scale` f32, one per tensor. The global scale is a divisor: the value is * `X.weight_global_scale` f32, one per tensor. The global scale is a divisor: the value is
@@ -1661,6 +1823,36 @@ int Checkpoint::add_draft(const std::string& dir, const std::string& prefix) {
std::unordered_map<std::string, std::string> owner; std::unordered_map<std::string, std::string> owner;
RAD_TRY(shard_list(dir, dir + "/model.safetensors.index.json", false, &shards, &owner)); RAD_TRY(shard_list(dir, dir + "/model.safetensors.index.json", false, &shards, &owner));
for (const auto& sh : shards) RAD_TRY(add_shard(sh, prefix, owner.empty() ? nullptr : &owner)); for (const auto& sh : shards) RAD_TRY(add_shard(sh, prefix, owner.empty() ? nullptr : &owner));
/* The drafter's own quantisation. One is read: ModelOpt's NVFP4 in groups of 16 (LiLiCorr
* ships `modelopt_fp4` / `W4A16_NVFP4`: NVFP4 weights, bf16 activations, which a recipe rule
* decodes like the target's NVFP4). Its names take that form (imports_at); anything else
* quantised is refused by name rather than read as plain tensors. */
const std::string dq = prefix + "quantization_config.";
auto qd = [&](const char* k) {
const char* v = meta_.get(dq + k);
return v ? std::string(v) : std::string();
};
const std::string qm = qd("quant_method");
if (!qm.empty()) {
const std::string qa = qd("quant_algo"), gs = qd("group_size");
const bool modelopt = qm == "modelopt" || qm == "modelopt_fp4";
if (!modelopt || (qa != "NVFP4" && qa != "W4A16_NVFP4") || (!gs.empty() && gs != "16")) {
RAD_ERR("drafter %s: quantization_config %s / %s (group %s) is not one this reads; "
"ModelOpt's NVFP4 in groups of 16 is", dir.c_str(), qm.c_str(), qa.c_str(),
gs.empty() ? "unstated" : gs.c_str());
return RAD_E_UNSUPPORTED;
}
if (import_ != Import::None && import_ != Import::ModelOpt) {
RAD_ERR("drafter %s: an NVFP4 drafter beside a target imported in another form is not "
"read", dir.c_str());
return RAD_E_UNSUPPORTED;
}
draft_import_ = Import::ModelOpt;
draft_prefix_ = prefix;
/* As the target's: the tool's config is provenance, not a served format. */
for (std::string& k : meta_.keys)
if (k.rfind(dq, 0) == 0) k = prefix + "imported_" + k.substr(prefix.size());
}
meta_.finish(); meta_.finish();
return RAD_OK; return RAD_OK;
} }
@@ -2580,8 +2772,9 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
"rad-convert imports with its scales rounded to bf16 -- serve the " "rad-convert imports with its scales rounded to bf16 -- serve the "
"container it writes"; "container it writes";
} }
} else if (dt == RAD_FP4E2M1 && scaled && (ck.imports() == Checkpoint::Import::Nvfp4 || } else if (dt == RAD_FP4E2M1 && scaled &&
ck.imports() == Checkpoint::Import::ModelOpt)) { (ck.imports_at(p0.name) == Checkpoint::Import::Nvfp4 ||
ck.imports_at(p0.name) == Checkpoint::Import::ModelOpt)) {
/* NVFP4 as import_piece reads it: e2m1 codes beside the f32 scale the e4m3 one and the /* NVFP4 as import_piece reads it: e2m1 codes beside the f32 scale the e4m3 one and the
* second level make, one per 16 of K, each piece with its own second level. Not trivial * second level make, one per 16 of K, each piece with its own second level. Not trivial
* (the scale is derived), so the loader refuses it and rad-convert decodes it for a * (the scale is derived), so the loader refuses it and rad-convert decodes it for a
+10
View File
@@ -187,6 +187,12 @@ public:
enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoM2, ParoI5, ParoI4, Nvfp4, CtFp8, enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoM2, ParoI5, ParoI4, Nvfp4, CtFp8,
ModelOpt }; ModelOpt };
Import imports() const { return import_; } 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. */
Import imports_at(const std::string& name) const {
return draft_import_ != Import::None && name.rfind(draft_prefix_, 0) == 0 ? draft_import_
: import_;
}
const std::string& import_refusal() const { return import_why_; } const std::string& import_refusal() const { return import_why_; }
/* The pieces an imported `name` (a `.weight`) is read from, as views owned here: GPTQ-packed /* The pieces an imported `name` (a `.weight`) is read from, as views owned here: GPTQ-packed
@@ -209,6 +215,7 @@ private:
int open_safetensors(const std::string& path); int open_safetensors(const std::string& path);
int open_diffusers(); int open_diffusers();
int open_sgm(); int open_sgm();
int open_hy3d(const std::string& weights);
int add_companions(); int add_companions();
int add_torch_files(); int add_torch_files();
int open_gguf(const std::string& path); int open_gguf(const std::string& path);
@@ -230,6 +237,9 @@ private:
int64_t fp8_br_ = 128, fp8_bc_ = 128; int64_t fp8_br_ = 128, fp8_bc_ = 128;
Import import_ = Import::None; Import import_ = Import::None;
std::string import_why_; std::string import_why_;
/* add_draft's drafter, when it ships a quantisation of its own: the form and the prefix. */
Import draft_import_ = Import::None;
std::string draft_prefix_;
int64_t ct_group_ = 0; /* CtInt4: the group every weight's config states */ int64_t ct_group_ = 0; /* CtInt4: the group every weight's config states */
bool ct_asym_ = false; /* CtInt4: the config states asymmetric weights */ bool ct_asym_ = false; /* CtInt4: the config states asymmetric weights */
/* import_piece's answers by name, so a weight resolved twice reuses its views. */ /* import_piece's answers by name, so a weight resolved twice reuses its views. */
+3
View File
@@ -56,6 +56,9 @@ struct Cursor {
case GT_ARR: { case GT_ARR: {
uint32_t et = 0; uint64_t n = 0; uint32_t et = 0; uint64_t n = 0;
if (!get(&et) || !get(&n)) return false; if (!get(&et) || !get(&n)) return false;
/* An array of arrays is refused, as the GGUF reader refuses it: each level costs a
* file 12 bytes and this walker a stack frame. */
if (et == GT_ARR) { ok = false; return false; }
for (uint64_t i = 0; i < n && ok; ++i) if (!skip_value(et)) return false; for (uint64_t i = 0; i < n && ok; ++i) if (!skip_value(et)) return false;
return ok; return ok;
} }
+55 -16
View File
@@ -48,7 +48,7 @@ void RadFile::close() {
int RadFile::read_at(void* dst, int64_t bytes, int64_t off) const { int RadFile::read_at(void* dst, int64_t bytes, int64_t off) const {
if (fd_ < 0) { RAD_ERR("read_at on a closed container"); return RAD_E_STATE; } if (fd_ < 0) { RAD_ERR("read_at on a closed container"); return RAD_E_STATE; }
if (off < 0 || bytes < 0 || off + bytes > size_) { if (off < 0 || bytes < 0 || off > size_ || bytes > size_ - off) {
RAD_ERR("read_at [%lld, %lld) is outside the %lld-byte container", RAD_ERR("read_at [%lld, %lld) is outside the %lld-byte container",
(long long)off, (long long)(off + bytes), (long long)size_); (long long)off, (long long)(off + bytes), (long long)size_);
return RAD_E_FORMAT; return RAD_E_FORMAT;
@@ -210,6 +210,21 @@ int RadFile::validate() {
return RAD_E_FORMAT; return RAD_E_FORMAT;
} }
/* The tables are read in place through typed pointers, so each must sit on its element's
* alignment (the writer places every one 8-aligned), as the vocab section's arrays must. */
auto aligned = [&](uint64_t off, uint64_t count, size_t align, const char* what) {
if (count == 0 || off % align == 0) return true;
RAD_ERR("%s: %s starts at %llu, which is not %zu-aligned", path_.c_str(), what,
(unsigned long long)off, align);
return false;
};
if (!aligned(hdr_->meta_off, hdr_->meta_count, alignof(RadFileKV), "the metadata table") ||
!aligned(hdr_->dir_off, hdr_->dir_count, alignof(RadFileEntry), "the weight directory") ||
!aligned(hdr_->plane_off, hdr_->plane_count, alignof(RadFilePlane), "the plane table") ||
!aligned(hdr_->enc_off, hdr_->enc_count, alignof(RadEncoding), "the encoding table") ||
!aligned(hdr_->prof_off, hdr_->prof_count, alignof(RadFileProfile), "the expert profile"))
return RAD_E_FORMAT;
meta_ = (const RadFileKV*)(base_ + hdr_->meta_off); meta_ = (const RadFileKV*)(base_ + hdr_->meta_off);
dir_ = (const RadFileEntry*)(base_ + hdr_->dir_off); dir_ = (const RadFileEntry*)(base_ + hdr_->dir_off);
planes_ = (const RadFilePlane*)(base_ + hdr_->plane_off); planes_ = (const RadFilePlane*)(base_ + hdr_->plane_off);
@@ -335,18 +350,21 @@ int RadFile::validate() {
} }
const RadVocabHeader* v = (const RadVocabHeader*)(base_ + voff); const RadVocabHeader* v = (const RadVocabHeader*)(base_ + voff);
/* Offset 0 means an optional array is absent (scores are unigram-only; types default to /* Offset 0 means an optional array is absent (scores are unigram-only; types default to
* normal). Nothing real lives at file offset 0. */ * normal). Nothing real lives at file offset 0. Token texts, merges and steps are not
auto arr_ok = [&](uint64_t off, uint64_t bytes, size_t align) { * optional: the writer places each one its count says exists, and a reader handed a
return bytes == 0 || off == 0 || * count with no array would read the file header in its place. */
(off >= voff && off - voff <= vbytes && bytes <= vbytes - (off - voff) && auto arr_ok = [&](uint64_t off, uint64_t bytes, size_t align, bool optional) {
off % align == 0); if (bytes == 0) return true;
if (off == 0) return optional;
return off >= voff && off - voff <= vbytes && bytes <= vbytes - (off - voff) &&
off % align == 0;
}; };
const uint64_t nt = v->n_tokens, nm = v->n_merges, ns = v->n_steps; const uint64_t nt = v->n_tokens, nm = v->n_merges, ns = v->n_steps;
if (!arr_ok(v->tok_text_off, nt * sizeof(rad_stroff), alignof(rad_stroff)) || if (!arr_ok(v->tok_text_off, nt * sizeof(rad_stroff), alignof(rad_stroff), false) ||
!arr_ok(v->tok_score_off, nt * sizeof(float), alignof(float)) || !arr_ok(v->tok_score_off, nt * sizeof(float), alignof(float), true) ||
!arr_ok(v->tok_type_off, nt, 1) || !arr_ok(v->tok_type_off, nt, 1, true) ||
!arr_ok(v->merge_off, nm * 2 * sizeof(uint32_t), alignof(uint32_t)) || !arr_ok(v->merge_off, nm * 2 * sizeof(uint32_t), alignof(uint32_t), false) ||
!arr_ok(v->step_off, ns * sizeof(RadVocabStep), alignof(RadVocabStep))) { !arr_ok(v->step_off, ns * sizeof(RadVocabStep), alignof(RadVocabStep), false)) {
RAD_ERR("%s: the %s section's arrays do not fit inside it, or one is not aligned to its " RAD_ERR("%s: the %s section's arrays do not fit inside it, or one is not aligned to its "
"element", "element",
path_.c_str(), what); path_.c_str(), what);
@@ -458,7 +476,17 @@ int RadFile::index_experts() {
return RAD_E_FORMAT; return RAD_E_FORMAT;
} }
const uint64_t ebase = dir_[j].offset; const uint64_t ebase = dir_[j].offset;
if (e_id == 1) g.stride = ebase - g.base; if (e_id == 1) {
/* Expert 1 defines the stride, so the arithmetic test below cannot check it: it
* must step forward by at least one whole unit, or experts overlap (or wrap). */
if (ebase < g.base || ebase - g.base < g.unit_bytes) {
RAD_ERR("%s: layer %d expert 1 starts at %llu, inside or before expert 0's "
"%llu bytes at %llu", path_.c_str(), layer, (unsigned long long)ebase,
(unsigned long long)g.unit_bytes, (unsigned long long)g.base);
return RAD_E_FORMAT;
}
g.stride = ebase - g.base;
}
if (ebase != g.base + (uint64_t)e_id * g.stride) { if (ebase != g.base + (uint64_t)e_id * g.stride) {
RAD_ERR("%s: layer %d expert %d starts at %llu, but base + %d*%llu is %llu -- the " RAD_ERR("%s: layer %d expert %d starts at %llu, but base + %d*%llu is %llu -- the "
"layer has no fixed stride and cannot be addressed by arithmetic", "layer has no fixed stride and cannot be addressed by arithmetic",
@@ -565,8 +593,16 @@ void RadWriter::abort() {
/* The file is the caller's container: restore its header (a no-op unless finish_append() /* The file is the caller's container: restore its header (a no-op unless finish_append()
* failed in that write) and truncate the tail. */ * failed in that write) and truncate the tail. */
if (fd_out_ >= 0) { if (fd_out_ >= 0) {
(void)!::pwrite(fd_out_, &old_hdr_, sizeof old_hdr_, 0); /* A failed restore leaves a file that is neither the old container nor the new one,
(void)!::ftruncate(fd_out_, (off_t)old_size_); * and the caller has only been told that the write failed. */
const bool hdr_ok = ::pwrite(fd_out_, &old_hdr_, sizeof old_hdr_, 0) ==
(ssize_t)sizeof old_hdr_;
const bool cut_ok = ::ftruncate(fd_out_, (off_t)old_size_) == 0;
if (!hdr_ok || !cut_ok)
RAD_ERR("%s: the append was undone only in part (%s) -- the container is damaged; "
"restore it from a copy", path_.c_str(),
!hdr_ok ? "its header could not be rewritten"
: "its tail could not be cut back");
::close(fd_out_); ::close(fd_out_);
} }
if (fd_spill_ >= 0) ::close(fd_spill_); if (fd_spill_ >= 0) ::close(fd_spill_);
@@ -1009,8 +1045,11 @@ int RadWriter::set_vocab_section(const void* blob, int64_t bytes) {
!fits(h->tok_score_off, h->tok_score_off ? (uint64_t)h->n_tokens * sizeof(float) : 0) || !fits(h->tok_score_off, h->tok_score_off ? (uint64_t)h->n_tokens * sizeof(float) : 0) ||
!fits(h->tok_type_off, h->tok_type_off ? h->n_tokens : 0) || !fits(h->tok_type_off, h->tok_type_off ? h->n_tokens : 0) ||
!fits(h->merge_off, (uint64_t)h->n_merges * 2 * sizeof(uint32_t)) || !fits(h->merge_off, (uint64_t)h->n_merges * 2 * sizeof(uint32_t)) ||
!fits(h->step_off, (uint64_t)h->n_steps * sizeof(RadVocabStep))) { !fits(h->step_off, (uint64_t)h->n_steps * sizeof(RadVocabStep)) ||
RAD_ERR("the vocab section's arrays do not fit inside its %lld bytes. Its offsets must be " (h->n_tokens && !h->tok_text_off) || (h->n_merges && !h->merge_off) ||
(h->n_steps && !h->step_off)) {
RAD_ERR("the vocab section's arrays do not fit inside its %lld bytes, or one its count "
"names is absent. Its offsets must be "
"SECTION-RELATIVE -- serialise with a section_file_off of 0 and let finish() " "SECTION-RELATIVE -- serialise with a section_file_off of 0 and let finish() "
"rebase them.", (long long)bytes); "rebase them.", (long long)bytes);
return RAD_E_INVAL; return RAD_E_INVAL;
+7 -1
View File
@@ -295,7 +295,13 @@ int SafeTensorsFile::open(const std::string& path) {
return RAD_E_FORMAT; return RAD_E_FORMAT;
} }
index_.emplace(t.name, tensors_.size()); /* A JSON object's keys are unique; a header naming one tensor twice has two answers to
* find() and is refused rather than resolved to the first. */
if (!index_.emplace(t.name, tensors_.size()).second) {
RAD_ERR("%s: the header names '%s' twice", path.c_str(), name.c_str());
close();
return RAD_E_FORMAT;
}
tensors_.push_back(std::move(t)); tensors_.push_back(std::move(t));
if (!sc.eat(',')) break; if (!sc.eat(',')) break;
+27 -5
View File
@@ -155,6 +155,20 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
} }
} }
/* The view's rectangles come from plugin-stated spans and parts, sum-checked only. A single
* selected plane takes them as its own rectangles below, with no enc_plane_rect to bound
* them, so every one is held to the entry here. */
for (int g = 0; !whole && g < w.n_part_spans; ++g)
if (w.part_lo[g] < 0 || w.part_lo[g] > w.part_hi[g] || w.part_hi[g] > w.part_total[g])
return refuse(fmt("part %d's span [%lld, %lld) is outside its %lld", g,
(long long)w.part_lo[g], (long long)w.part_hi[g],
(long long)w.part_total[g]));
for (const VRect& q : view)
if (q.r0 < 0 || q.r0 > q.r1 || q.r1 > VR || q.c0 < 0 || q.c0 > q.c1 || q.c1 > VC)
return refuse(fmt("the slice [%lld, %lld) x [%lld, %lld) is outside the entry's "
"%lld x %lld", (long long)q.r0, (long long)q.r1, (long long)q.c0,
(long long)q.c1, (long long)VR, (long long)VC));
for (int k = 0; k < w.n_sel; ++k) { for (int k = 0; k < w.n_sel; ++k) {
const RadEncPlane& p = enc.plane[w.sel[k]]; const RadEncPlane& p = enc.plane[w.sel[k]];
PlaneShare& s = out[k]; PlaneShare& s = out[k];
@@ -186,7 +200,10 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
return refuse(fmt("columns [%lld, %lld) of the %s '%s' plane do not fall on whole " return refuse(fmt("columns [%lld, %lld) of the %s '%s' plane do not fall on whole "
"bytes", (long long)pq.col0, (long long)(pq.col0 + pq.cols), "bytes", (long long)pq.col0, (long long)(pq.col0 + pq.cols),
rad_dtype_name(p.dtype), p.role)); rad_dtype_name(p.dtype), p.role));
if (!s.rects.empty() && pq.cols != s.cols) /* A vector's stacked parts lie end to end as one row, so they may differ in width (a
* Mamba convolution's bias is [x | B | C]); a matrix's parts stack as rows. */
const bool vec = rank == 1 && pq.rows == 1;
if (!vec && !s.rects.empty() && pq.cols != s.cols)
return refuse("the share's parts differ in width"); return refuse("the share's parts differ in width");
PlaneShare::Rect r; PlaneShare::Rect r;
r.row0 = pq.row0; r.row0 = pq.row0;
@@ -194,11 +211,16 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
r.byte0 = pq.col0 * bits / 8; r.byte0 = pq.col0 * bits / 8;
r.bytes = rad_enc_row_bytes(p.dtype, pq.cols); r.bytes = rad_enc_row_bytes(p.dtype, pq.cols);
s.rects.push_back(r); s.rects.push_back(r);
s.rows += pq.rows; if (vec) {
s.cols = pq.cols; s.rows = 1;
s.cols += pq.cols;
} else {
s.rows += pq.rows;
s.cols = pq.cols;
}
} }
/* A vector's stacked parts come out as one piece a part, each a row of the share; laid /* Laid end to end, a vector's parts are the declared vector, so only the element count
* end to end they are the declared vector, so only the element count has to agree. */ * has to agree. */
const bool fits = rank == 1 ? s.rows * s.cols == w.sel_rows[k] * w.sel_cols[k] const bool fits = rank == 1 ? s.rows * s.cols == w.sel_rows[k] * w.sel_cols[k]
: s.rows == w.sel_rows[k] && s.cols == w.sel_cols[k]; : s.rows == w.sel_rows[k] && s.cols == w.sel_cols[k];
if (!fits) if (!fits)
+66
View File
@@ -3,7 +3,10 @@
#include "../rad_internal.h" #include "../rad_internal.h"
#include <fcntl.h>
#include <sys/mman.h> #include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <algorithm> #include <algorithm>
#include <atomic> #include <atomic>
@@ -91,6 +94,69 @@ int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t
return RAD_OK; return RAD_OK;
} }
int table_file_open(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
const std::string& path, TableCopy* out, bool* filled, std::string* why) {
if (!out || !filled || !why || !src || n <= 0 || path.empty()) return RAD_E_INVAL;
*out = TableCopy{};
*filled = false;
struct stat st;
if (::stat(path.c_str(), &st) != 0 || st.st_size != n) {
const std::string tmp = path + ".part";
const int fd = ::open(tmp.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
if (fd < 0) {
*why = fmt("creating %s: %s", tmp.c_str(), std::strerror(errno));
return RAD_E_IO;
}
void* m = MAP_FAILED;
if (::ftruncate(fd, (off_t)n) == 0)
m = ::mmap(nullptr, (size_t)n, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (m == MAP_FAILED) {
*why = fmt("sizing %s to %s: %s", tmp.c_str(), humanb(n).c_str(), std::strerror(errno));
::close(fd);
::unlink(tmp.c_str());
return RAD_E_IO;
}
int rc = table_copy_fill(file, src, n, foff, static_cast<uint8_t*>(m), why);
if (rc == RAD_OK && (::msync(m, (size_t)n, MS_SYNC) != 0 || ::fsync(fd) != 0)) {
*why = fmt("writing %s: %s", tmp.c_str(), std::strerror(errno));
rc = RAD_E_IO;
}
::munmap(m, (size_t)n);
::close(fd);
if (rc == RAD_OK && ::rename(tmp.c_str(), path.c_str()) != 0) {
*why = fmt("renaming %s: %s", tmp.c_str(), std::strerror(errno));
rc = RAD_E_IO;
}
if (rc != RAD_OK) {
::unlink(tmp.c_str());
return rc;
}
*filled = true;
}
const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) {
*why = fmt("opening %s: %s", path.c_str(), std::strerror(errno));
return RAD_E_IO;
}
void* m = ::mmap(nullptr, (size_t)n, PROT_READ, MAP_SHARED, fd, 0);
::close(fd);
if (m == MAP_FAILED) {
*why = fmt("mapping %s: %s", path.c_str(), std::strerror(errno));
return RAD_E_IO;
}
if (!*filled) {
const int rc = table_copy_check(src, n, static_cast<const uint8_t*>(m), why);
if (rc != RAD_OK) {
::munmap(m, (size_t)n);
*why = fmt("%s does not match the container (%s); remove it and it is filled again",
path.c_str(), why->c_str());
return rc;
}
}
*out = TableCopy{ m, (size_t)n };
return RAD_OK;
}
void table_copy_free(TableCopy* c) { void table_copy_free(TableCopy* c) {
if (!c || !c->base) return; if (!c || !c->base) return;
::munlock(c->base, c->bytes); ::munlock(c->base, c->bytes);
+8
View File
@@ -37,6 +37,14 @@ int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t
* another process filled. */ * another process filled. */
int table_copy_check(const uint8_t* src, int64_t n, const uint8_t* buf, std::string* why); int table_copy_check(const uint8_t* src, int64_t n, const uint8_t* buf, std::string* why);
/* --ngram-placement disk=DIR: [src, src + n) read from its own file `path` (the table's bytes and
* nothing else), mapped read-only in `out` (`bytes` = n). A missing file, or one of another size, is
* filled from the container under `path`.part and renamed, so a file under `path` is complete
* (`*filled` true); an existing one is checked as table_copy_check checks. The disk gather finds the
* file behind the mapping and reads it directly. Release with munmap(out->base, out->bytes). */
int table_file_open(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
const std::string& path, TableCopy* out, bool* filled, std::string* why);
/* Unlock and unmap; a no-op for a copy never made. */ /* Unlock and unmap; a no-op for a copy never made. */
void table_copy_free(TableCopy* c); void table_copy_free(TableCopy* c);
+9 -4
View File
@@ -175,10 +175,15 @@ int TuneCache::load(const std::string& home, const std::string& machine) {
continue; continue;
} }
if (tok[0] == "machine") { if (tok[0] == "machine") {
if (tok.size() >= 2 && std::string(tok[1]) != machine) /* A cache from another card is wrong, not just slow (tunecache.h): a file renamed or
RAD_WARN("%s: measured on '%.*s' but this machine is '%s' -- the rows may not " * copied to this machine's name is refused, as another format version is. */
"describe this card", path.c_str(), (int)tok[1].size(), tok[1].data(), if (tok.size() >= 2 && std::string(tok[1]) != machine) {
machine.c_str()); RAD_WARN("%s: measured on '%.*s' but this machine is '%s' -- ignoring the cache",
path.c_str(), (int)tok[1].size(), tok[1].data(), machine.c_str());
std::free(line);
::fclose(f);
return RAD_E_FORMAT;
}
continue; continue;
} }
if (tok.size() < 5) { ++bad; continue; } if (tok.size() < 5) { ++bad; continue; }
+771
View File
@@ -0,0 +1,771 @@
/* shape.cpp -- the shape generator's host geometry (shape.h): the picture, the sampler's grid, the
* field's levels, marching cubes and the mesh's files; and the ticket a caller waits on. */
#include "shape.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstring>
namespace rad {
namespace gen {
ShapeGenInfo shape_info(const RadShapeGenDecl& d, const std::string& name) {
ShapeGenInfo g;
g.name = name;
g.canvas = d.canvas;
g.enc_size = d.enc_size;
g.enc_patch = d.enc_patch;
g.border_ratio = d.border_ratio;
for (int c = 0; c < 3; ++c) { g.pix_mean[c] = d.pix_mean[c]; g.pix_std[c] = d.pix_std[c]; }
g.default_steps = d.default_steps;
g.max_steps = d.max_steps;
g.default_guidance = d.default_guidance;
g.bounds = d.bounds;
g.level = d.level;
g.default_resolution = d.default_resolution;
g.min_resolution = d.min_resolution;
g.max_resolution = d.max_resolution;
g.max_lanes = d.max_lanes;
return g;
}
/* ================================================================== the picture */
namespace {
/* An 8-bit image, `ch` channels interleaved. */
struct Img {
int32_t w = 0, h = 0, ch = 0;
std::vector<uint8_t> px;
uint8_t* at(int32_t y, int32_t x) { return px.data() + ((size_t)y * w + x) * ch; }
const uint8_t* at(int32_t y, int32_t x) const { return px.data() + ((size_t)y * w + x) * ch; }
};
/* OpenCV's saturate_cast<uchar> of a float: round half to even, clipped. */
inline uint8_t sat_u8(float v) {
const float r = std::nearbyint(v);
return (uint8_t)(r < 0.0f ? 0.0f : r > 255.0f ? 255.0f : r);
}
/* cv::resize's INTER_AREA when it shrinks both sides: computeResizeAreaTab's weights, a row's
* horizontal sums, then the weighted rows, in float. */
struct AreaTap { int32_t di, si; float alpha; };
std::vector<AreaTap> area_tab(int32_t ssize, int32_t dsize, double scale) {
std::vector<AreaTap> tab;
for (int32_t dx = 0; dx < dsize; ++dx) {
const double fsx1 = dx * scale, fsx2 = fsx1 + scale;
const double cell = std::min(scale, ssize - fsx1);
int32_t sx1 = (int32_t)std::ceil(fsx1), sx2 = (int32_t)std::floor(fsx2);
sx2 = std::min(sx2, ssize - 1);
sx1 = std::min(sx1, sx2);
if (sx1 - fsx1 > 1e-3) tab.push_back({ dx, sx1 - 1, (float)((sx1 - fsx1) / cell) });
for (int32_t sx = sx1; sx < sx2; ++sx) tab.push_back({ dx, sx, (float)(1.0 / cell) });
if (fsx2 - sx2 > 1e-3)
tab.push_back({ dx, sx2, (float)(std::min(std::min(fsx2 - sx2, 1.0), cell) / cell) });
}
return tab;
}
void resize_area_down(const Img& s, int32_t dw, int32_t dh, Img* d) {
const double sx = (double)s.w / dw, sy = (double)s.h / dh;
const std::vector<AreaTap> xt = area_tab(s.w, dw, sx), yt = area_tab(s.h, dh, sy);
const int32_t ch = s.ch;
std::vector<float> row((size_t)dw * ch), acc((size_t)dw * ch);
d->w = dw; d->h = dh; d->ch = ch;
d->px.assign((size_t)dw * dh * ch, 0);
size_t k = 0;
for (int32_t dy = 0; dy < dh; ++dy) {
std::fill(acc.begin(), acc.end(), 0.0f);
for (; k < yt.size() && yt[k].di == dy; ++k) {
std::fill(row.begin(), row.end(), 0.0f);
const uint8_t* src = s.at(yt[k].si, 0);
for (const AreaTap& t : xt)
for (int32_t c = 0; c < ch; ++c)
row[(size_t)t.di * ch + c] += src[(size_t)t.si * ch + c] * t.alpha;
for (size_t i = 0; i < acc.size(); ++i) acc[i] += row[i] * yt[k].alpha;
}
uint8_t* dst = d->at(dy, 0);
for (size_t i = 0; i < acc.size(); ++i) dst[i] = sat_u8(acc[i]);
}
}
/* cv::resize's fixed-point separable filter for 8-bit images: each tap's float coefficient
* rounded to 11 bits, the horizontal sums in int, the vertical sum shifted back by 22 with
* rounding. `taps` coefficients a destination pixel, first at source index ofs[d] (indices
* clamped to the image, OpenCV's BORDER_REPLICATE). */
struct Taps {
int32_t ksize = 0;
std::vector<int32_t> ofs;
std::vector<int16_t> c;
};
Taps taps_linear_area(int32_t ssize, int32_t dsize) {
/* INTER_AREA when it does not shrink both sides: linear taps in OpenCV's area mode. */
const double scale = (double)ssize / dsize, inv = (double)dsize / ssize;
Taps t;
t.ksize = 2;
for (int32_t dx = 0; dx < dsize; ++dx) {
const int32_t sx = (int32_t)std::floor(dx * scale);
float fx = (float)((dx + 1) - (sx + 1) * inv);
fx = fx <= 0 ? 0.0f : fx - std::floor(fx);
t.ofs.push_back(sx);
t.c.push_back((int16_t)std::nearbyint((1.0f - fx) * 2048.0f));
t.c.push_back((int16_t)std::nearbyint(fx * 2048.0f));
}
return t;
}
Taps taps_cubic(int32_t ssize, int32_t dsize) {
const double scale = (double)ssize / dsize;
const float A = -0.75f;
Taps t;
t.ksize = 4;
for (int32_t dx = 0; dx < dsize; ++dx) {
float fx = (float)((dx + 0.5) * scale - 0.5);
const int32_t sx = (int32_t)std::floor(fx);
fx -= sx;
float w[4];
w[0] = ((A * (fx + 1) - 5 * A) * (fx + 1) + 8 * A) * (fx + 1) - 4 * A;
w[1] = ((A + 2) * fx - (A + 3)) * fx * fx + 1;
w[2] = ((A + 2) * (1 - fx) - (A + 3)) * (1 - fx) * (1 - fx) + 1;
w[3] = 1.0f - w[0] - w[1] - w[2];
t.ofs.push_back(sx - 1);
for (float v : w) t.c.push_back((int16_t)std::nearbyint(v * 2048.0f));
}
return t;
}
void resize_fixed(const Img& s, const Taps& tx, const Taps& ty, int32_t dw, int32_t dh, Img* d) {
const int32_t ch = s.ch;
/* Every source row through the horizontal taps, then each destination row from its rows. */
std::vector<int32_t> hrow((size_t)s.h * dw * ch);
for (int32_t y = 0; y < s.h; ++y)
for (int32_t dx = 0; dx < dw; ++dx)
for (int32_t c = 0; c < ch; ++c) {
int32_t sum = 0;
for (int32_t k = 0; k < tx.ksize; ++k) {
const int32_t sx = std::clamp(tx.ofs[(size_t)dx] + k, 0, s.w - 1);
sum += s.at(y, sx)[c] * tx.c[(size_t)dx * tx.ksize + k];
}
hrow[((size_t)y * dw + dx) * ch + c] = sum;
}
d->w = dw; d->h = dh; d->ch = ch;
d->px.assign((size_t)dw * dh * ch, 0);
for (int32_t dy = 0; dy < dh; ++dy)
for (int32_t i = 0; i < dw * ch; ++i) {
int64_t v = 0;
for (int32_t k = 0; k < ty.ksize; ++k) {
const int32_t sy = std::clamp(ty.ofs[(size_t)dy] + k, 0, s.h - 1);
v += (int64_t)hrow[(size_t)sy * dw * ch + i] * ty.c[(size_t)dy * ty.ksize + k];
}
const int64_t r = (v + (1 << 21)) >> 22;
d->px[(size_t)dy * dw * ch + i] = (uint8_t)std::clamp<int64_t>(r, 0, 255);
}
}
/* cv2.resize(src, (dw, dh), INTER_AREA). */
void resize_area(const Img& s, int32_t dw, int32_t dh, Img* d) {
if (dw == s.w && dh == s.h) { *d = s; return; }
if (s.w >= dw && s.h >= dh) { resize_area_down(s, dw, dh, d); return; }
resize_fixed(s, taps_linear_area(s.w, dw), taps_linear_area(s.h, dh), dw, dh, d);
}
/* cv2.resize(src, (dw, dh), INTER_CUBIC). */
void resize_cubic(const Img& s, int32_t dw, int32_t dh, Img* d) {
if (dw == s.w && dh == s.h) { *d = s; return; }
resize_fixed(s, taps_cubic(s.w, dw), taps_cubic(s.h, dh), dw, dh, d);
}
/* torchvision's antialiased bilinear resize along one axis (align_corners false): the triangle
* filter around each output's centre, widened by the scale when shrinking, normalised over the
* taps inside the image. */
struct AaTaps { std::vector<int32_t> lo; std::vector<std::vector<float>> w; };
AaTaps aa_taps(int32_t in, int32_t out) {
const double scale = (double)in / out;
const double support = scale >= 1.0 ? scale : 1.0;
const double inv = scale >= 1.0 ? 1.0 / scale : 1.0;
AaTaps t;
for (int32_t i = 0; i < out; ++i) {
const double center = scale * (i + 0.5);
const int32_t lo = std::max((int32_t)(center - support + 0.5), 0);
const int32_t hi = std::min((int32_t)(center + support + 0.5), in);
std::vector<float> w;
double total = 0.0;
for (int32_t j = lo; j < hi; ++j) {
const double x = std::fabs((j - center + 0.5) * inv);
const double v = x < 1.0 ? 1.0 - x : 0.0;
w.push_back((float)v);
total += v;
}
if (total > 0.0) for (float& v : w) v = (float)(v / total);
t.lo.push_back(lo);
t.w.push_back(std::move(w));
}
return t;
}
} /* namespace */
int shape_picture(const ShapeGenInfo& g, const mm::FrameRGBA& rgba, std::vector<float>* patches,
std::string* why) {
auto no = [&](const std::string& w) {
if (why) *why = w;
return RAD_E_INVAL;
};
const int32_t H = rgba.h, W = rgba.w;
if (H < 1 || W < 1 || rgba.rgba.size() != (size_t)H * W * 4) return no("the picture is empty");
/* ---- ImageProcessorV2.recenter: the alpha's bounding box on a square of the longer side */
int32_t y0 = H, y1 = -1, x0 = W, x1 = -1;
for (int32_t y = 0; y < H; ++y)
for (int32_t x = 0; x < W; ++x)
if (rgba.rgba[((size_t)y * W + x) * 4 + 3]) {
y0 = std::min(y0, y); y1 = std::max(y1, y);
x0 = std::min(x0, x); x1 = std::max(x1, x);
}
if (y1 < 0) return no("the picture is fully transparent: nothing to make a shape of");
const int32_t h = y1 - y0, w = x1 - x0;
if (h == 0 || w == 0)
return no("the picture's opaque part is a single row or column: nothing to make a shape "
"of");
const int32_t size = std::max(H, W);
const int32_t desired = (int32_t)(size * (1.0 - g.border_ratio));
const double scale = (double)desired / std::max(h, w);
const int32_t h2 = (int32_t)(h * scale), w2 = (int32_t)(w * scale);
if (h2 < 1 || w2 < 1)
return no("the picture's opaque part is too thin to scale onto the canvas");
Img crop;
crop.w = w; crop.h = h; crop.ch = 4;
crop.px.resize((size_t)w * h * 4);
for (int32_t y = 0; y < h; ++y)
std::memcpy(crop.at(y, 0), rgba.rgba.data() + ((size_t)(y0 + y) * W + x0) * 4,
(size_t)w * 4);
Img fit;
resize_area(crop, w2, h2, &fit);
const int32_t oy = (size - h2) / 2, ox = (size - w2) / 2;
/* Flattened onto white in float, then truncated to 8 bits, as numpy's astype does. */
Img sq;
sq.w = size; sq.h = size; sq.ch = 3;
sq.px.assign((size_t)size * size * 3, 255);
for (int32_t y = 0; y < h2; ++y)
for (int32_t x = 0; x < w2; ++x) {
const uint8_t* p = fit.at(y, x);
const float a = (float)p[3] / 255.0f;
uint8_t* q = sq.at(oy + y, ox + x);
for (int c = 0; c < 3; ++c) {
const float v = (float)p[c] * a + 255.0f * (1.0f - a);
q[c] = (uint8_t)std::clamp(v, 0.0f, 255.0f);
}
}
/* ---- the canvas, INTER_CUBIC */
const int32_t C = (int32_t)g.canvas;
Img can;
resize_cubic(sq, C, C, &can);
/* ---- the encoder's transform: 0..1, bilinear (antialiased) to enc_size, normalised */
const int32_t E = (int32_t)g.enc_size, P = (int32_t)g.enc_patch, G = E / P;
const AaTaps ta = aa_taps(C, E);
std::vector<float> hor((size_t)C * E * 3), img((size_t)E * E * 3);
for (int32_t y = 0; y < C; ++y)
for (int32_t x = 0; x < E; ++x)
for (int c = 0; c < 3; ++c) {
float s = 0.0f;
const std::vector<float>& wt = ta.w[(size_t)x];
for (size_t k = 0; k < wt.size(); ++k)
s += wt[k] * ((float)can.at(y, ta.lo[(size_t)x] + (int32_t)k)[c] / 255.0f);
hor[((size_t)y * E + x) * 3 + c] = s;
}
for (int32_t y = 0; y < E; ++y)
for (int32_t x = 0; x < E; ++x)
for (int c = 0; c < 3; ++c) {
float s = 0.0f;
const std::vector<float>& wt = ta.w[(size_t)y];
for (size_t k = 0; k < wt.size(); ++k)
s += wt[k] * hor[(((size_t)ta.lo[(size_t)y] + k) * E + x) * 3 + c];
img[((size_t)y * E + x) * 3 + c] =
(float)((s - g.pix_mean[c]) / g.pix_std[c]);
}
/* ---- patches, row-major; a patch's values (channel, row, column) */
const int64_t pd = 3 * (int64_t)P * P;
patches->assign((size_t)G * G * pd, 0.0f);
for (int32_t py = 0; py < G; ++py)
for (int32_t px = 0; px < G; ++px) {
float* o = patches->data() + ((size_t)py * G + px) * pd;
for (int c = 0; c < 3; ++c)
for (int32_t i = 0; i < P; ++i)
for (int32_t j = 0; j < P; ++j)
o[((size_t)c * P + i) * P + j] =
img[(((size_t)py * P + i) * E + px * P + j) * 3 + c];
}
return RAD_OK;
}
/* ================================================================== the sampler and the grid */
std::vector<float> shape_sigmas(int32_t steps) {
std::vector<float> s;
if (steps < 2) return s;
const double step = 1.0 / (steps - 1);
for (int32_t i = 0; i < steps; ++i) s.push_back(i == steps - 1 ? 1.0f : (float)(i * step));
return s;
}
std::vector<int32_t> shape_levels(int32_t resolution) {
std::vector<int32_t> r;
if (resolution < 63) r.push_back(resolution);
for (int32_t v = resolution; v >= 63; v /= 2) r.push_back(v);
std::reverse(r.begin(), r.end());
return r;
}
std::vector<float> shape_axis(double bounds, int32_t r) {
std::vector<float> a((size_t)r + 1);
const double step = 2.0 * bounds / r;
for (int32_t i = 0; i <= r; ++i) a[(size_t)i] = (float)(i * step + -bounds);
a[(size_t)r] = (float)bounds;
return a;
}
namespace {
/* A 3 x 3 x 3 dilation of an n^3 mask (zero outside), as separable maxima along each axis. */
void dilate(std::vector<uint8_t>& m, int64_t n) {
std::vector<uint8_t> t(m.size());
auto pass = [&](const std::vector<uint8_t>& src, std::vector<uint8_t>& dst, int64_t stride) {
for (int64_t p = 0; p < (int64_t)src.size(); ++p) {
const int64_t c = (p / stride) % n;
uint8_t v = src[(size_t)p];
if (c > 0) v |= src[(size_t)(p - stride)];
if (c + 1 < n) v |= src[(size_t)(p + stride)];
dst[(size_t)p] = v;
}
};
pass(m, t, 1);
pass(t, m, n);
pass(m, t, n * n);
m.swap(t);
}
} /* namespace */
std::vector<uint32_t> shape_refine(const std::vector<float>& prev, int32_t rp, int32_t r,
double level, bool last) {
const int64_t np = (int64_t)rp + 1, n = (int64_t)r + 1;
std::vector<uint8_t> near((size_t)(np * np * np), 0);
auto sgn = [](float v) { return (v > 0.0f) - (v < 0.0f); };
const float lv = (float)level;
for (int64_t i = 0; i < np; ++i)
for (int64_t j = 0; j < np; ++j)
for (int64_t k = 0; k < np; ++k) {
const int64_t p = (i * np + j) * np + k;
const float raw = prev[(size_t)p];
if (std::isnan(raw)) continue;
const float v = raw - lv;
const int s = sgn(v);
bool cross = std::fabs(v) < 0.95f;
const int64_t nb[6][3] = { { i - 1, j, k }, { i + 1, j, k }, { i, j - 1, k },
{ i, j + 1, k }, { i, j, k - 1 }, { i, j, k + 1 } };
for (int q = 0; q < 6 && !cross; ++q) {
const int64_t a = nb[q][0], b = nb[q][1], c = nb[q][2];
/* Outside the grid the reference replicates the border, and a neighbour not
* sampled stands in as the point itself: neither crosses. */
if (a < 0 || a >= np || b < 0 || b >= np || c < 0 || c >= np) continue;
const float u = prev[(size_t)((a * np + b) * np + c)];
if (std::isnan(u)) continue;
cross = sgn(u - lv) != s;
}
near[(size_t)p] = cross;
}
if (!last) dilate(near, np);
std::vector<uint8_t> mark((size_t)(n * n * n), 0);
auto up = [&](int64_t c) { return (c * r + rp / 2) / rp; };
for (int64_t i = 0; i < np; ++i)
for (int64_t j = 0; j < np; ++j)
for (int64_t k = 0; k < np; ++k)
if (near[(size_t)((i * np + j) * np + k)])
mark[(size_t)((up(i) * n + up(j)) * n + up(k))] = 1;
dilate(mark, n);
if (last) dilate(mark, n);
std::vector<uint32_t> pts;
for (int64_t p = 0; p < (int64_t)mark.size(); ++p)
if (mark[(size_t)p]) pts.push_back((uint32_t)p);
return pts;
}
/* ================================================================== marching cubes */
namespace {
/* Corner c of a cube is at (c & 1, c >> 1 & 1, c >> 2 & 1) along the grid's (i, j, k). Edge e is
* along axis e / 4 from corner kEdge[e][0] to kEdge[e][1]. */
struct McTables {
int32_t edge[12][2];
/* Each case's triangles as edge triples, -1 ended. */
int8_t tri[256][31];
};
McTables build_tables() {
McTables T{};
int ne = 0;
for (int a = 0; a < 3; ++a)
for (int c = 0; c < 8; ++c)
if (!(c >> a & 1)) { T.edge[ne][0] = c; T.edge[ne][1] = c | (1 << a); ++ne; }
auto edge_of = [&](int c0, int c1) {
for (int e = 0; e < 12; ++e)
if ((T.edge[e][0] == c0 && T.edge[e][1] == c1) ||
(T.edge[e][0] == c1 && T.edge[e][1] == c0))
return e;
return -1;
};
auto pos = [](int c, double* p) { p[0] = c & 1; p[1] = c >> 1 & 1; p[2] = c >> 2 & 1; };
for (int m = 0; m < 256; ++m) {
for (int i = 0; i < 31; ++i) T.tri[m][i] = -1;
if (m == 0 || m == 255) continue;
auto in = [&](int c) { return (m >> c & 1) != 0; };
/* Each face's segments between its crossing edges. A face with all four edges crossing
* (its inside corners diagonal) separates the inside corners, the rule both cubes that
* share the face apply, so the surface has no cracks. */
std::vector<std::array<int, 2>> seg;
for (int a = 0; a < 3; ++a)
for (int s = 0; s < 2; ++s) {
const int u = (a + 1) % 3, v = (a + 2) % 3;
const int base = s << a;
const int cyc[4] = { base, base | (1 << u), base | (1 << u) | (1 << v),
base | (1 << v) };
int fe[4];
bool cr[4];
int ncr = 0;
for (int q = 0; q < 4; ++q) {
fe[q] = edge_of(cyc[q], cyc[(q + 1) % 4]);
cr[q] = in(cyc[q]) != in(cyc[(q + 1) % 4]);
ncr += cr[q];
}
if (ncr == 2) {
int a0 = -1, a1 = -1;
for (int q = 0; q < 4; ++q) {
if (!cr[q]) continue;
if (a0 < 0) a0 = fe[q]; else a1 = fe[q];
}
seg.push_back({ a0, a1 });
} else if (ncr == 4) {
for (int q = 0; q < 4; ++q)
if (in(cyc[q])) seg.push_back({ fe[(q + 3) % 4], fe[q] });
}
}
/* The segments close into loops; each crossing edge is in exactly two. */
std::vector<bool> used(seg.size(), false);
int nt = 0;
for (size_t s0 = 0; s0 < seg.size(); ++s0) {
if (used[s0]) continue;
std::vector<int> loop = { seg[s0][0], seg[s0][1] };
used[s0] = true;
for (bool grew = true; grew;) {
grew = false;
for (size_t q = 0; q < seg.size(); ++q) {
if (used[q]) continue;
const int tail = loop.back();
int nx = -1;
if (seg[q][0] == tail) nx = seg[q][1];
else if (seg[q][1] == tail) nx = seg[q][0];
if (nx < 0) continue;
used[q] = true;
grew = true;
if (nx != loop.front()) loop.push_back(nx);
}
}
/* Orientation: the loop's normal (Newell's, over the edges' midpoints) points from the
* inside corners to the outside ones. */
double nrm[3] = { 0, 0, 0 }, out[3] = { 0, 0, 0 };
std::vector<std::array<double, 3>> mid;
for (int e : loop) {
double p0[3], p1[3];
pos(T.edge[e][0], p0);
pos(T.edge[e][1], p1);
mid.push_back({ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2, (p0[2] + p1[2]) / 2 });
const double sg = in(T.edge[e][0]) ? 1.0 : -1.0;
for (int d = 0; d < 3; ++d) out[d] += sg * (p1[d] - p0[d]);
}
for (size_t q = 0; q < mid.size(); ++q) {
const auto& c = mid[q];
const auto& d = mid[(q + 1) % mid.size()];
nrm[0] += (c[1] - d[1]) * (c[2] + d[2]);
nrm[1] += (c[2] - d[2]) * (c[0] + d[0]);
nrm[2] += (c[0] - d[0]) * (c[1] + d[1]);
}
if (nrm[0] * out[0] + nrm[1] * out[1] + nrm[2] * out[2] < 0)
std::reverse(loop.begin(), loop.end());
for (size_t q = 1; q + 1 < loop.size() && nt < 10; ++q) {
T.tri[m][3 * nt] = (int8_t)loop[0];
T.tri[m][3 * nt + 1] = (int8_t)loop[q];
T.tri[m][3 * nt + 2] = (int8_t)loop[q + 1];
++nt;
}
}
}
return T;
}
const McTables& tables() {
static const McTables t = build_tables();
return t;
}
} /* namespace */
void shape_mesh(const std::vector<float>& field, int32_t r, double bounds, double level,
ShapeMesh* out) {
out->v.clear();
out->f.clear();
const McTables& T = tables();
const int64_t n = (int64_t)r + 1, nn = n * n;
const float lv = (float)level;
const double sc = 2.0 * bounds / (double)n;
/* An edge's vertex by its first grid point: the x edges between planes i and i + 1, and the
* y and z edges of planes i and i + 1. */
std::vector<int32_t> ex((size_t)nn), ey[2], ez[2];
for (int p = 0; p < 2; ++p) { ey[p].assign((size_t)nn, -1); ez[p].assign((size_t)nn, -1); }
auto value = [&](int64_t i, int64_t j, int64_t k) {
return field[(size_t)((i * n + j) * n + k)];
};
for (int64_t i = 0; i + 1 < n; ++i) {
std::fill(ex.begin(), ex.end(), -1);
if (i > 0) {
std::swap(ey[0], ey[1]);
std::swap(ez[0], ez[1]);
std::fill(ey[1].begin(), ey[1].end(), -1);
std::fill(ez[1].begin(), ez[1].end(), -1);
}
for (int64_t j = 0; j + 1 < n; ++j)
for (int64_t k = 0; k + 1 < n; ++k) {
float v[8];
bool skip = false;
int m = 0;
for (int c = 0; c < 8 && !skip; ++c) {
v[c] = value(i + (c & 1), j + (c >> 1 & 1), k + (c >> 2 & 1));
if (std::isnan(v[c])) skip = true;
else if (v[c] > lv) m |= 1 << c;
}
if (skip || m == 0 || m == 255) continue;
for (int t = 0; t < 30 && T.tri[m][t] >= 0; ++t) {
const int e = T.tri[m][t];
const int c0 = T.edge[e][0], c1 = T.edge[e][1], a = e / 4;
const int64_t bi = c0 & 1, bj = c0 >> 1 & 1, bk = c0 >> 2 & 1;
int32_t* slot = a == 0 ? &ex[(size_t)((j + bj) * n + k + bk)]
: a == 1 ? &ey[bi][(size_t)(j * n + k + bk)]
: &ez[bi][(size_t)((j + bj) * n + k)];
if (*slot < 0) {
const float t0 = v[c0], t1 = v[c1];
const float f = t1 != t0 ? (lv - t0) / (t1 - t0) : 0.5f;
float g[3] = { (float)(i + bi), (float)(j + bj), (float)(k + bk) };
g[a] += f;
*slot = (int32_t)(out->v.size() / 3);
for (int d = 0; d < 3; ++d) out->v.push_back((float)(g[d] * sc - bounds));
}
out->f.push_back((uint32_t)*slot);
}
}
}
}
/* ================================================================== files */
namespace {
void put(std::string& s, const void* p, size_t n) { s.append((const char*)p, n); }
template <class T> void put_v(std::string& s, T v) { put(s, &v, sizeof v); }
/* Area-weighted vertex normals, unit length (zero for a vertex of only degenerate faces). */
std::vector<float> vertex_normals(const ShapeMesh& m) {
std::vector<float> nrm(m.v.size(), 0.0f);
for (size_t t = 0; t + 2 < m.f.size(); t += 3) {
const float* a = &m.v[(size_t)m.f[t] * 3];
const float* b = &m.v[(size_t)m.f[t + 1] * 3];
const float* c = &m.v[(size_t)m.f[t + 2] * 3];
const float u[3] = { b[0] - a[0], b[1] - a[1], b[2] - a[2] };
const float w[3] = { c[0] - a[0], c[1] - a[1], c[2] - a[2] };
const float x[3] = { u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2],
u[0] * w[1] - u[1] * w[0] };
for (int q = 0; q < 3; ++q)
for (int d = 0; d < 3; ++d) nrm[(size_t)m.f[t + q] * 3 + d] += x[d];
}
for (size_t i = 0; i + 2 < nrm.size(); i += 3) {
const float l =
std::sqrt(nrm[i] * nrm[i] + nrm[i + 1] * nrm[i + 1] + nrm[i + 2] * nrm[i + 2]);
if (l > 0.0f) for (int d = 0; d < 3; ++d) nrm[i + d] /= l;
}
return nrm;
}
std::string glb(const ShapeMesh& m) {
const size_t nv = m.v.size() / 3, ni = m.f.size();
const std::vector<float> nrm = vertex_normals(m);
float lo[3] = { INFINITY, INFINITY, INFINITY }, hi[3] = { -INFINITY, -INFINITY, -INFINITY };
for (size_t i = 0; i < nv; ++i)
for (int d = 0; d < 3; ++d) {
lo[d] = std::min(lo[d], m.v[i * 3 + d]);
hi[d] = std::max(hi[d], m.v[i * 3 + d]);
}
const size_t vb = nv * 12, ib = ni * 4;
std::string bin;
put(bin, m.v.data(), vb);
put(bin, nrm.data(), vb);
put(bin, m.f.data(), ib);
while (bin.size() % 4) bin.push_back('\0');
using nlohmann::json;
json j;
j["asset"] = { { "version", "2.0" }, { "generator", "radiance" } };
j["scene"] = 0;
j["scenes"] = json::array({ { { "nodes", json::array({ 0 }) } } });
j["nodes"] = json::array({ { { "mesh", 0 } } });
const json prim = { { "attributes", { { "POSITION", 0 }, { "NORMAL", 1 } } },
{ "indices", 2 }, { "mode", 4 } };
j["meshes"] = json::array({ { { "primitives", json::array({ prim }) } } });
j["buffers"] = json::array({ { { "byteLength", bin.size() } } });
j["bufferViews"] = json::array({
{ { "buffer", 0 }, { "byteOffset", 0 }, { "byteLength", vb }, { "target", 34962 } },
{ { "buffer", 0 }, { "byteOffset", vb }, { "byteLength", vb }, { "target", 34962 } },
{ { "buffer", 0 }, { "byteOffset", 2 * vb }, { "byteLength", ib }, { "target", 34963 } } });
j["accessors"] = json::array({
{ { "bufferView", 0 }, { "componentType", 5126 }, { "count", nv }, { "type", "VEC3" },
{ "min", { lo[0], lo[1], lo[2] } }, { "max", { hi[0], hi[1], hi[2] } } },
{ { "bufferView", 1 }, { "componentType", 5126 }, { "count", nv }, { "type", "VEC3" } },
{ { "bufferView", 2 }, { "componentType", 5125 }, { "count", ni },
{ "type", "SCALAR" } } });
std::string js = j.dump();
while (js.size() % 4) js.push_back(' ');
std::string out;
put_v<uint32_t>(out, 0x46546C67u); /* "glTF" */
put_v<uint32_t>(out, 2);
put_v<uint32_t>(out, (uint32_t)(12 + 8 + js.size() + 8 + bin.size()));
put_v<uint32_t>(out, (uint32_t)js.size());
put_v<uint32_t>(out, 0x4E4F534Au); /* "JSON" */
out += js;
put_v<uint32_t>(out, (uint32_t)bin.size());
put_v<uint32_t>(out, 0x004E4942u); /* "BIN\0" */
out += bin;
return out;
}
std::string obj(const ShapeMesh& m) {
std::string s;
char line[128];
for (size_t i = 0; i + 2 < m.v.size(); i += 3) {
const int n = std::snprintf(line, sizeof line, "v %.9g %.9g %.9g\n", (double)m.v[i],
(double)m.v[i + 1], (double)m.v[i + 2]);
s.append(line, (size_t)n);
}
for (size_t t = 0; t + 2 < m.f.size(); t += 3) {
const int n = std::snprintf(line, sizeof line, "f %u %u %u\n", m.f[t] + 1, m.f[t + 1] + 1,
m.f[t + 2] + 1);
s.append(line, (size_t)n);
}
return s;
}
std::string ply(const ShapeMesh& m) {
const size_t nv = m.v.size() / 3, nf = m.f.size() / 3;
std::string s = "ply\nformat binary_little_endian 1.0\nelement vertex " + std::to_string(nv) +
"\nproperty float x\nproperty float y\nproperty float z\nelement face " +
std::to_string(nf) + "\nproperty list uchar int vertex_indices\nend_header\n";
put(s, m.v.data(), m.v.size() * 4);
for (size_t t = 0; t < nf; ++t) {
put_v<uint8_t>(s, 3);
for (int q = 0; q < 3; ++q) put_v<int32_t>(s, (int32_t)m.f[t * 3 + q]);
}
return s;
}
std::string stl(const ShapeMesh& m) {
std::string s(80, '\0');
std::memcpy(&s[0], "radiance", 8);
const size_t nf = m.f.size() / 3;
put_v<uint32_t>(s, (uint32_t)nf);
for (size_t t = 0; t < nf; ++t) {
const float* a = &m.v[(size_t)m.f[t * 3] * 3];
const float* b = &m.v[(size_t)m.f[t * 3 + 1] * 3];
const float* c = &m.v[(size_t)m.f[t * 3 + 2] * 3];
const float u[3] = { b[0] - a[0], b[1] - a[1], b[2] - a[2] };
const float w[3] = { c[0] - a[0], c[1] - a[1], c[2] - a[2] };
float x[3] = { u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2],
u[0] * w[1] - u[1] * w[0] };
const float l = std::sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]);
if (l > 0.0f) for (float& q : x) q /= l;
put(s, x, 12);
put(s, a, 12);
put(s, b, 12);
put(s, c, 12);
put_v<uint16_t>(s, 0);
}
return s;
}
} /* namespace */
int shape_export(const ShapeMesh& m, const std::string& format, std::string* bytes,
std::string* mime, std::string* why) {
if (format == "glb") { *bytes = glb(m); *mime = "model/gltf-binary"; return RAD_OK; }
if (format == "obj") { *bytes = obj(m); *mime = "model/obj"; return RAD_OK; }
if (format == "ply") { *bytes = ply(m); *mime = "application/x-ply"; return RAD_OK; }
if (format == "stl") { *bytes = stl(m); *mime = "model/stl"; return RAD_OK; }
if (why) *why = "type '" + format + "' is not one this server writes: glb, obj, ply or stl";
return RAD_E_INVAL;
}
/* ================================================================== the ticket */
void ShapeTicket::progress(int32_t steps_done, int32_t points_done) {
std::lock_guard<std::mutex> lk(mu_);
steps_done_ = steps_done;
points_done_ = points_done;
}
void ShapeTicket::set_field(std::vector<float>&& field, int32_t r) {
std::lock_guard<std::mutex> lk(mu_);
field_ = std::move(field);
r_ = r;
}
void ShapeTicket::finish(int status, const std::string& why) {
{
std::lock_guard<std::mutex> lk(mu_);
if (done_) return;
done_ = true;
status_ = status;
why_ = why;
}
cv_.notify_all();
}
bool ShapeTicket::wait(int ms) {
std::unique_lock<std::mutex> lk(mu_);
cv_.wait_for(lk, std::chrono::milliseconds(ms), [this] { return done_; });
return done_;
}
bool ShapeTicket::finished() const {
std::lock_guard<std::mutex> lk(mu_);
return done_;
}
int ShapeTicket::status() const {
std::lock_guard<std::mutex> lk(mu_);
return status_;
}
std::string ShapeTicket::why() const {
std::lock_guard<std::mutex> lk(mu_);
return why_;
}
std::vector<float> ShapeTicket::take_field(int32_t* r) {
std::lock_guard<std::mutex> lk(mu_);
if (r) *r = r_;
return std::move(field_);
}
void ShapeTicket::progress_of(int32_t* steps_done, int32_t* points_done) const {
std::lock_guard<std::mutex> lk(mu_);
if (steps_done) *steps_done = steps_done_;
if (points_done) *points_done = points_done_;
}
} /* namespace gen */
} /* namespace rad */
+137
View File
@@ -0,0 +1,137 @@
/* shape.h -- shape generation: the request, the channel its field comes back on, and the host
* geometry around the model's passes.
*
* A shape generator (abi/rad_builder.h, rad_declare_shape_generator) makes a 3-D shape from one
* picture: it denoises a latent, then decodes it into an occupancy field that is sampled on a
* grid. core/gen/shape_driver.h turns a request into those passes; this is what a caller hands it
* (the picture already prepared, shape_picture), what it hands back (progress as the steps and
* the grid's levels run, then the finest grid), and the geometry both sides share: the sampler's
* sigmas, the grid's levels and the points each level queries, and the mesh made of the grid
* (shape_mesh) with its file formats.
*/
#pragma once
#include "rad_core.h"
#include "mm/media.h"
#include <atomic>
#include <cmath>
#include <condition_variable>
#include <cstdint>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace rad {
namespace gen {
/* What the driver knows of the declaration, for the server and the geometry below. */
struct ShapeGenInfo {
std::string name;
int64_t canvas = 0, enc_size = 0, enc_patch = 0;
double border_ratio = 0.0;
double pix_mean[3] = {}, pix_std[3] = {};
int64_t default_steps = 0, max_steps = 0;
double default_guidance = 0.0;
double bounds = 1.0, level = 0.0;
int64_t default_resolution = 0, min_resolution = 0, max_resolution = 0;
int64_t max_lanes = 1;
};
ShapeGenInfo shape_info(const RadShapeGenDecl& d, const std::string& name);
/* The picture as an SCOND pass carries it (RadShapeGenDecl, "The picture"): `rgba` decoded with
* its alpha, out as f32 [(enc_size / enc_patch)^2, 3 enc_patch^2]. Refuses a picture whose alpha
* leaves nothing, or a bounding box of one row or column, as the reference does. */
int shape_picture(const ShapeGenInfo& g, const mm::FrameRGBA& rgba, std::vector<float>* patches,
std::string* why);
/* The sampler's grid points: numpy's linspace(0, 1, steps) taken to f32. An evaluation at each
* but the last steps to the next. */
std::vector<float> shape_sigmas(int32_t steps);
/* The grid's levels, coarsest first: `resolution` halved while it stays at least 63, then
* reversed (one level when it is below 63). */
std::vector<int32_t> shape_levels(int32_t resolution);
/* One axis of a level's grid: numpy's linspace(-bounds, bounds, r + 1) in f32. */
std::vector<float> shape_axis(double bounds, int32_t r);
/* The grid points of level `r` (index (i, j, k) at (i (r+1) + j) (r+1) + k) to query, given the
* coarser level's field `prev` at resolution `rp` (NaN where it was not sampled): the coarse
* points whose sign against `level` differs from a neighbour's, or whose value is within 0.95 of
* zero, dilated once unless this is the last level, put at their places on this grid and dilated
* twice there (once when the coarse set was). As FlashVDM's hierarchical decoding. */
std::vector<uint32_t> shape_refine(const std::vector<float>& prev, int32_t rp, int32_t r,
double level, bool last);
/* A triangle mesh: positions xyz, and faces as three vertex indices, counter-clockwise seen from
* outside the shape. */
struct ShapeMesh {
std::vector<float> v;
std::vector<uint32_t> f;
};
/* Marching cubes over `field` ((r+1)^3 values, the layout above) at `level`, inside above it. A
* cube with a corner not sampled (NaN) makes nothing. Vertices sit on the grid's edges where the
* linear interpolation of their ends crosses the level, one vertex an edge, and grid index g goes
* to g 2 bounds / (r + 1) - bounds (RadShapeGenDecl, "The field"). */
void shape_mesh(const std::vector<float>& field, int32_t r, double bounds, double level,
ShapeMesh* out);
/* The mesh as a file: "glb" (positions, smooth normals and indices), "obj", "ply" (binary) or
* "stl" (binary). The content type goes to `mime`. Refuses another format by name. */
int shape_export(const ShapeMesh& m, const std::string& format, std::string* bytes,
std::string* mime, std::string* why);
/* ================================================================== the request */
class ShapeTicket {
public:
/* driver side */
void progress(int32_t steps_done, int32_t points_done);
/* The finest grid, at resolution `r`, and the end. */
void finish(int status, const std::string& why = std::string());
void set_field(std::vector<float>&& field, int32_t r);
/* caller side: waits at most `ms` milliseconds for the end; true once it came. */
bool wait(int ms);
bool finished() const;
int status() const;
std::string why() const;
/* The field, once finished with RAD_OK; moved out. */
std::vector<float> take_field(int32_t* r);
void progress_of(int32_t* steps_done, int32_t* points_done) const;
std::atomic<bool> cancel{false};
/* Written by the driver at submit: the evaluations, the resolution and the guidance. */
int32_t steps = 0, resolution = 0;
double guidance = 0.0;
/* Usage, written by the driver before finish(): the points the decoder was queried at, and
* per-phase times. */
int64_t points = 0;
int64_t t_submit_ns = 0, t_cond_ns = 0, t_denoised_ns = 0, t_done_ns = 0;
private:
mutable std::mutex mu_;
std::condition_variable cv_;
bool done_ = false;
int status_ = RAD_OK;
std::string why_;
int32_t steps_done_ = 0, points_done_ = 0;
std::vector<float> field_;
int32_t r_ = 0;
};
struct ShapeRequest {
/* The picture, prepared (shape_picture). */
std::vector<float> patches;
int32_t steps = 0; /* sigma grid points; 0: the model's default */
double guidance = NAN; /* NaN: the model's default */
int32_t resolution = 0; /* the finest grid's cells a side; 0: the model's default */
bool dense = false; /* sample every point of the finest grid, no coarser levels */
uint64_t seed = 0;
std::shared_ptr<ShapeTicket> ticket;
};
} /* namespace gen */
} /* namespace rad */
+436
View File
@@ -0,0 +1,436 @@
/* shape_driver.cpp -- the shape generator's pass driver (shape_driver.h). */
#include "shape_driver.h"
#include "rad_internal.h"
#include <algorithm>
#include <cmath>
#include <cstring>
namespace rad {
namespace gen {
namespace {
constexpr int64_t kAlign = 256;
/* Region offsets and sizes, in the enum's order (shape_driver.h), and the total; shared by the
* allocation and the VRAM budget. */
int64_t carve(const RadShapeGenDecl& d, int64_t (*bytes)[2], int n) {
const int64_t side = d.enc_size / d.enc_patch;
const int64_t want[] = {
side * side * 3 * d.enc_patch * d.enc_patch * 4, /* R_PATCH: f32 */
2 * 4, /* R_SIGMA */
2 * 4, /* R_SNEXT */
2 * 4, /* R_CFG */
2 * 4, /* R_PAIR */
2 * 4, /* R_LANES */
2 * 4, /* R_FLAGS */
2 * 2 * 4, /* R_SEED */
3 * 4, /* R_LATCU */
d.max_query * 3 * 4, /* R_QUERY: f32 */
2 * 4, /* R_QCU */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
bytes[r][0] = off;
bytes[r][1] = want[r];
off = align_up(off + want[r], kAlign);
}
return off;
}
} /* namespace */
int64_t ShapeDriver::device_bytes(const Program& prog) {
if (!prog.is_shape_generator()) return 0;
int64_t b[R_N][2];
return carve(prog.shape_gen, b, R_N);
}
int ShapeDriver::init(const Program& prog, const std::vector<RankIO>& ranks) {
fini();
if (!prog.is_shape_generator()) return RAD_E_STATE;
decl_ = prog.shape_gen;
info_ = shape_info(decl_, prog.sgen_name);
ranks_ = ranks;
n_patch_ = (decl_.enc_size / decl_.enc_patch) * (decl_.enc_size / decl_.enc_patch);
patch_dim_ = 3 * decl_.enc_patch * decl_.enc_patch;
int64_t b[R_N][2];
bytes_ = carve(decl_, b, R_N);
for (int r = 0; r < R_N; ++r) {
reg_[r].off = b[r][0];
reg_[r].bytes = b[r][1];
reg_[r].used = 0;
}
host_ = static_cast<char*>(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED));
field_host_ = static_cast<float*>(rad_dev_alloc(decl_.max_query * 4, RAD_MEM_HOST_PINNED));
if (!host_ || !field_host_) {
RAD_ERR("shape generator: no pinned host memory for the pass staging and the field "
"(%lld + %lld bytes)", (long long)bytes_, (long long)(decl_.max_query * 4));
return RAD_E_NOMEM;
}
std::memset(host_, 0, (size_t)bytes_);
dev_.assign(ranks_.size(), nullptr);
for (size_t r = 0; r < ranks_.size(); ++r) {
RAD_TRY(rad_dev_set(ranks_[r].device));
dev_[r] = rad_dev_alloc(bytes_, RAD_MEM_DEVICE);
if (!dev_[r]) {
RAD_ERR("shape generator: rank %zu has no room for the pass staging (%lld bytes)", r,
(long long)bytes_);
return RAD_E_NOMEM;
}
}
if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0].device));
out_.assign(ranks_.size(), RadBatch{});
sout_.assign(ranks_.size(), RadShapeGenBatch{});
free_lanes_.clear();
for (int64_t i = decl_.max_lanes - 1; i >= 0; --i) free_lanes_.push_back((int32_t)i);
return RAD_OK;
}
void ShapeDriver::fini() {
for (size_t r = 0; r < dev_.size(); ++r)
if (dev_[r]) {
if (r < ranks_.size()) rad_dev_set(ranks_[r].device);
rad_dev_free(dev_[r], RAD_MEM_DEVICE);
}
dev_.clear();
if (!ranks_.empty()) rad_dev_set(ranks_[0].device);
if (host_) rad_dev_free(host_, RAD_MEM_HOST_PINNED);
if (field_host_) rad_dev_free(field_host_, RAD_MEM_HOST_PINNED);
host_ = nullptr;
field_host_ = nullptr;
}
/* ================================================================== requests */
int ShapeDriver::submit(std::unique_ptr<ShapeRequest> r, std::string* why) {
if (!r || !r->ticket) return RAD_E_INVAL;
const RadShapeGenDecl& d = decl_;
auto no = [&](const std::string& w) {
if (why) *why = w;
return RAD_E_INVAL;
};
if ((int64_t)r->patches.size() != n_patch_ * patch_dim_)
return no("the picture is not prepared for this model's image encoder");
const int32_t steps = r->steps > 0 ? r->steps : (int32_t)d.default_steps;
if (steps < 2 || steps > d.max_steps)
return no("num_inference_steps must be 2.." + std::to_string(d.max_steps) +
" (sigma grid points, the last one the clean shape)");
const double cfg = std::isnan(r->guidance) ? d.default_guidance : r->guidance;
if (!(cfg >= 0.0) || !std::isfinite(cfg))
return no("guidance_scale must be finite and not negative");
const int32_t res = r->resolution > 0 ? r->resolution : (int32_t)d.default_resolution;
if (res < d.min_resolution || res > d.max_resolution)
return no("octree_resolution must be " + std::to_string(d.min_resolution) + ".." +
std::to_string(d.max_resolution));
auto j = std::make_unique<Job>();
j->sigmas = shape_sigmas(steps);
j->evals = steps - 1;
j->cfg = (float)cfg;
j->levels = r->dense ? std::vector<int32_t>{ res } : shape_levels(res);
ShapeTicket& t = *r->ticket;
t.steps = j->evals;
t.resolution = res;
t.guidance = cfg;
t.t_submit_ns = (int64_t)rad_mono_ns();
std::lock_guard<std::mutex> lk(mu_);
if (closed_) {
if (why) *why = closed_why_;
return closed_status_;
}
j->id = next_id_++;
j->req = std::move(r);
jobs_.push_back(std::move(j));
return RAD_OK;
}
void ShapeDriver::shutdown(const char* why, int status) {
std::lock_guard<std::mutex> lk(mu_);
closed_ = true;
closed_why_ = why ? why : "the engine stopped";
closed_status_ = status;
for (auto& j : jobs_) j->req->ticket->finish(status, closed_why_);
}
int64_t ShapeDriver::queued() const {
std::lock_guard<std::mutex> lk(mu_);
int64_t n = 0;
for (const auto& j : jobs_) if (!j->admitted) ++n;
return n;
}
int64_t ShapeDriver::running() const {
std::lock_guard<std::mutex> lk(mu_);
int64_t n = 0;
for (const auto& j : jobs_) if (j->admitted) ++n;
return n;
}
ShapeDriver::Job* ShapeDriver::job_locked(uint64_t id) {
for (auto& j : jobs_) if (j->id == id) return j.get();
return nullptr;
}
void ShapeDriver::release_locked(Job& j) {
if (j.lane >= 0) {
free_lanes_.push_back(j.lane);
j.lane = -1;
}
}
void ShapeDriver::fail_locked(Job& j, int status, const std::string& why) {
j.failed = true;
j.req->ticket->finish(status, why);
}
/* In arrival order: a request needs only a lane. */
void ShapeDriver::admit_locked() {
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted || j.failed) continue;
if (free_lanes_.empty()) break;
j.lane = free_lanes_.back();
free_lanes_.pop_back();
j.admitted = true;
}
}
/* A level of the grid begins: its field unsampled, its points `pts` (every point when `all`). */
void ShapeDriver::start_level(Job& j, size_t level, std::vector<uint32_t>&& pts, bool all) {
const int32_t r = j.levels[level];
const int64_t n = (int64_t)r + 1;
j.level = level;
j.field.assign((size_t)(n * n * n), NAN);
j.axis = shape_axis(decl_.bounds, r);
j.all = all;
j.pts = std::move(pts);
j.n_pts = all ? n * n * n : (int64_t)j.pts.size();
j.next = 0;
}
/* ================================================================== staging */
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));
}
return RAD_OK;
}
void ShapeDriver::stage_common(const Job& j) {
const int32_t lanes[2] = { j.lane, j.lane };
const int32_t cu[3] = { 0, (int32_t)decl_.latent_rows, (int32_t)(2 * decl_.latent_rows) };
std::memcpy(hptr<int32_t>(R_LANES), lanes, sizeof lanes);
std::memcpy(hptr<int32_t>(R_LATCU), cu, sizeof cu);
reg_[R_LANES].used = sizeof lanes;
reg_[R_LATCU].used = sizeof cu;
}
void ShapeDriver::base_batches(const Job& j, int64_t n_tok, int kind, int step) {
for (size_t r = 0; r < ranks_.size(); ++r) {
RadBatch& B = out_[r];
RadShapeGenBatch& S = sout_[r];
const int ri = (int)r;
B = RadBatch{};
B.step = step;
B.phase = RAD_PHASE_PREFILL;
B.n_tok = n_tok;
B.n_seq = 1;
B.max_q_len = (int32_t)n_tok;
B.max_q_len_prefill = (int32_t)n_tok;
B.gen = kind;
S = RadShapeGenBatch{};
S.lane = j.lane;
S.patches = dptr<float>(ri, R_PATCH);
S.step = j.step;
S.n_steps = j.evals;
S.sigma = dptr<float>(ri, R_SIGMA);
S.sigma_next = dptr<float>(ri, R_SNEXT);
S.cfg = dptr<float>(ri, R_CFG);
S.pair = dptr<int32_t>(ri, R_PAIR);
S.lanes = dptr<int32_t>(ri, R_LANES);
S.flags = dptr<int32_t>(ri, R_FLAGS);
S.seed = dptr<uint32_t>(ri, R_SEED);
S.lat_cu = dptr<int32_t>(ri, R_LATCU);
S.query = dptr<float>(ri, R_QUERY);
S.query_cu = dptr<int32_t>(ri, R_QCU);
B.sgen_b = &S;
}
pass_.kind = kind;
pass_.job = j.id;
}
/* ================================================================== the passes */
const RadBatch* ShapeDriver::next(int step) {
std::lock_guard<std::mutex> lk(mu_);
pass_ = Pass{};
rb_.clear();
if (closed_) return nullptr;
/* Retire finished, failed and cancelled jobs, returning their lanes before admitting. Safe
* because next() runs between passes, with nothing in flight. */
for (auto it = jobs_.begin(); it != jobs_.end();) {
Job& j = **it;
const bool cancelled = j.req->ticket->cancel.load(std::memory_order_acquire);
if (!(j.failed || cancelled || j.finished)) { ++it; continue; }
if (cancelled && !j.failed && !j.finished)
j.req->ticket->finish(RAD_E_CANCELLED, "the request was cancelled");
release_locked(j);
it = jobs_.erase(it);
}
admit_locked();
/* 1. The decoding of a denoised lane: its latent, then its grid. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed || !j.cond_done || j.step < j.evals) continue;
return j.latent_done ? build_query(j, step) : build_latent(j, step);
}
/* 2. A picture. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted && !j.failed && !j.cond_done) return build_cond(j, step);
}
/* 3. The oldest lane's next step. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted && !j.failed && j.cond_done && j.step < j.evals) return build_step(j, step);
}
return nullptr;
}
const RadBatch* ShapeDriver::batch_for(int rank) const {
if (rank < 0 || (size_t)rank >= out_.size() || pass_.kind == 0) return nullptr;
return &out_[(size_t)rank];
}
const RadBatch* ShapeDriver::build_cond(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
std::memcpy(hptr<float>(R_PATCH), j.req->patches.data(), j.req->patches.size() * 4);
reg_[R_PATCH].used = (int64_t)j.req->patches.size() * 4;
stage_common(j);
if (upload() < 0) return nullptr;
base_batches(j, n_patch_, RAD_GEN_PASS_SCOND, step);
return &out_[0];
}
/* The two entries of the step: the picture's latent guided against the unconditioned one, which
* reads the same lane and moves nothing. */
const RadBatch* ShapeDriver::build_step(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const float s = j.sigmas[(size_t)j.step], sn = j.sigmas[(size_t)j.step + 1];
const float sig[2] = { s, s }, nxt[2] = { sn, sn }, cfg[2] = { j.cfg, 1.0f };
const int32_t pair[2] = { 1, -2 };
const int32_t flags[2] = { j.step == 0 ? (int32_t)RAD_GEN_F_FIRST : 0, 0 };
const uint32_t lo = (uint32_t)j.req->seed, hi = (uint32_t)(j.req->seed >> 32);
const uint32_t seed[4] = { lo, hi, lo, hi };
auto stage = [&](int r, const void* p, int64_t n) {
std::memcpy(host_ + reg_[r].off, p, (size_t)n);
reg_[r].used = n;
};
stage(R_SIGMA, sig, sizeof sig);
stage(R_SNEXT, nxt, sizeof nxt);
stage(R_CFG, cfg, sizeof cfg);
stage(R_PAIR, pair, sizeof pair);
stage(R_FLAGS, flags, sizeof flags);
stage(R_SEED, seed, sizeof seed);
stage_common(j);
if (upload() < 0) return nullptr;
base_batches(j, decl_.step_rows, RAD_GEN_PASS_SSTEP, step);
return &out_[0];
}
const RadBatch* ShapeDriver::build_latent(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
stage_common(j);
if (upload() < 0) return nullptr;
base_batches(j, decl_.latent_rows, RAD_GEN_PASS_SLATENT, step);
return &out_[0];
}
/* The level's next run of points, at most max_query, as x, y, z. */
const RadBatch* ShapeDriver::build_query(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const int64_t n = std::min<int64_t>(decl_.max_query, j.n_pts - j.next);
const int64_t side = (int64_t)j.levels[j.level] + 1;
float* q = hptr<float>(R_QUERY);
for (int64_t i = 0; i < n; ++i) {
const int64_t p = j.all ? j.next + i : (int64_t)j.pts[(size_t)(j.next + i)];
q[3 * i] = j.axis[(size_t)(p / (side * side))];
q[3 * i + 1] = j.axis[(size_t)(p / side % side)];
q[3 * i + 2] = j.axis[(size_t)(p % side)];
}
reg_[R_QUERY].used = n * 3 * 4;
const int32_t qcu[2] = { 0, (int32_t)n };
std::memcpy(hptr<int32_t>(R_QCU), qcu, sizeof qcu);
reg_[R_QCU].used = sizeof qcu;
stage_common(j);
if (upload() < 0) return nullptr;
base_batches(j, n, RAD_GEN_PASS_SQUERY, step);
for (auto& S : sout_) S.n_query = n;
pass_.n_query = n;
rb_.assign(1, Readback{ decl_.field_out, n * 4, field_host_ });
return &out_[0];
}
int ShapeDriver::done() {
std::lock_guard<std::mutex> lk(mu_);
const int64_t now = (int64_t)rad_mono_ns();
Job* j = job_locked(pass_.job);
switch (j ? pass_.kind : 0) {
case RAD_GEN_PASS_SCOND:
j->cond_done = true;
j->req->ticket->t_cond_ns = now;
/* The patches are on the card for good; the request keeps no copy. */
std::vector<float>().swap(j->req->patches);
break;
case RAD_GEN_PASS_SSTEP:
++j->step;
j->req->ticket->progress(j->step, 0);
if (j->step >= j->evals) j->req->ticket->t_denoised_ns = now;
break;
case RAD_GEN_PASS_SLATENT:
j->latent_done = true;
start_level(*j, 0, {}, true);
break;
case RAD_GEN_PASS_SQUERY: {
const int64_t n = pass_.n_query;
for (int64_t i = 0; i < n; ++i) {
const int64_t p = j->all ? j->next + i : (int64_t)j->pts[(size_t)(j->next + i)];
j->field[(size_t)p] = field_host_[i];
}
j->next += n;
j->points += n;
j->req->ticket->progress(j->step, (int32_t)std::min<int64_t>(j->points, INT32_MAX));
if (j->next < j->n_pts) break;
/* The level is complete: the next one's points, or the end (also when no point of this
* level is near the surface, which leaves the finer levels nothing to sample). */
if (j->level + 1 < j->levels.size()) {
const int32_t rp = j->levels[j->level], r = j->levels[j->level + 1];
const bool last = j->level + 2 == j->levels.size();
std::vector<uint32_t> pts = shape_refine(j->field, rp, r, decl_.level, last);
if (!pts.empty()) {
start_level(*j, j->level + 1, std::move(pts), false);
break;
}
}
ShapeTicket& t = *j->req->ticket;
t.points = j->points;
t.t_done_ns = now;
t.set_field(std::move(j->field), j->levels[j->level]);
j->finished = true;
t.finish(RAD_OK);
break;
}
default:
break;
}
pass_ = Pass{};
rb_.clear();
return RAD_OK;
}
} /* namespace gen */
} /* namespace rad */
+141
View File
@@ -0,0 +1,141 @@
/* shape_driver.h -- the shape generator's pass driver (shape.h; abi/rad_builder.h's
* RadShapeGenDecl describes the passes).
*
* Driven by the engine thread like the other drivers (pass.h): `next()` picks and stages a pass,
* `done()` folds its result back once every rank has run it. Requests arrive from HTTP threads
* through `submit()` and leave through their ShapeTicket.
*
* A request holds a lane from admission to its last query. Its picture is prepared and its
* schedule fixed at submit; between passes the driver only stages, except when a level of the
* grid is complete, when it works out the points of the next (shape_refine).
*
* Pass priority, one pass at a time:
*
* 1. SLATENT, then the SQUERY passes level by level, of a lane whose denoising is done: they
* finish a request and free its lane.
* 2. SCOND of an admitted request, so its steps can follow the current request's without a gap.
* 3. SSTEP of the oldest lane with steps left. Requests are denoised one after another, not in
* turns: a pass is one request's, so taking turns would only delay the first.
*/
#pragma once
#include "shape.h"
#include "pass.h"
#include "device/device.h"
#include <deque>
#include <mutex>
namespace rad {
namespace gen {
class ShapeDriver final : public IPassDriver {
public:
struct RankIO {
int device = 0;
RadStream stream = nullptr;
};
int init(const Program& prog, const std::vector<RankIO>& ranks);
void fini();
~ShapeDriver() override { fini(); }
/* The bytes init() allocates on each rank's card, for the VRAM budget. */
static int64_t device_bytes(const Program& prog);
/* ---------------------------------------------------------- HTTP threads */
/* Queue a request, refused at once with `why` when it can never run. */
int submit(std::unique_ptr<ShapeRequest> r, std::string* why);
const ShapeGenInfo& info() const { return info_; }
void shutdown(const char* why, int status) override;
/* ---------------------------------------------------------- the engine thread */
const RadBatch* next(int step) override;
const RadBatch* batch_for(int rank) const override;
const std::vector<Readback>& readbacks() const override { return rb_; }
int done() override;
int64_t queued() const override;
int64_t running() const override;
private:
struct Job {
uint64_t id = 0;
std::unique_ptr<ShapeRequest> req;
std::vector<float> sigmas; /* the request's grid points */
float cfg = 0.0f;
int32_t evals = 0; /* steps the request takes: grid points less one */
int32_t lane = -1;
bool admitted = false;
bool cond_done = false;
int32_t step = 0; /* steps done */
bool latent_done = false;
/* The grid: its levels, the one being sampled, its field (NaN where not sampled) and
* the points it samples, all of them when `all` (the coarsest level, and dense
* sampling); `next` is the first not yet queried. */
std::vector<int32_t> levels;
size_t level = 0;
std::vector<float> field;
std::vector<float> axis;
std::vector<uint32_t> pts;
bool all = false;
int64_t n_pts = 0, next = 0;
int64_t points = 0; /* every level's, for the usage */
bool failed = false;
bool finished = false;
};
struct Pass {
int kind = 0;
uint64_t job = 0;
int64_t n_query = 0;
};
struct Region { int64_t off = 0, bytes = 0, used = 0; };
enum { R_PATCH, R_SIGMA, R_SNEXT, R_CFG, R_PAIR, R_LANES, R_FLAGS, R_SEED, R_LATCU, R_QUERY,
R_QCU, R_N };
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
template <class T> T* dptr(int rank, int r) const {
return reinterpret_cast<T*>((char*)dev_[(size_t)rank] + reg_[r].off);
}
int upload();
/* What every pass carries: the lane twice (the step's two entries) and the latents' bounds. */
void stage_common(const Job& j);
void base_batches(const Job& j, int64_t n_tok, int kind, int step);
void start_level(Job& j, size_t level, std::vector<uint32_t>&& pts, bool all);
void admit_locked();
void release_locked(Job& j);
void fail_locked(Job& j, int status, const std::string& why);
Job* job_locked(uint64_t id);
const RadBatch* build_cond(Job& j, int step);
const RadBatch* build_step(Job& j, int step);
const RadBatch* build_latent(Job& j, int step);
const RadBatch* build_query(Job& j, int step);
RadShapeGenDecl decl_{};
ShapeGenInfo info_;
int64_t n_patch_ = 0, patch_dim_ = 0;
std::vector<RankIO> ranks_;
char* host_ = nullptr; /* pinned, same layout as each slab */
int64_t bytes_ = 0;
std::vector<void*> dev_;
Region reg_[R_N];
float* field_host_ = nullptr;
std::vector<Readback> rb_;
std::vector<RadBatch> out_; /* one per rank */
std::vector<RadShapeGenBatch> sout_;
Pass pass_;
mutable std::mutex mu_;
std::deque<std::unique_ptr<Job>> jobs_; /* arrival order */
std::vector<int32_t> free_lanes_;
uint64_t next_id_ = 1;
bool closed_ = false;
std::string closed_why_;
int closed_status_ = RAD_E_STATE;
};
} /* namespace gen */
} /* namespace rad */
+11 -3
View File
@@ -198,6 +198,9 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd,
int64_t (*bytes)[2], int n) { int64_t (*bytes)[2], int n) {
/* A guided model's VCOND carries the negative prompt after the positive. */ /* A guided model's VCOND carries the negative prompt after the positive. */
const int64_t prompts = d.guidance ? 2 : 1; const int64_t prompts = d.guidance ? 2 : 1;
/* A schedule's steps: a request's, at most max_steps, plus the refinement rungs an upscaling
* request appends after them (video_schedule). */
const int64_t sched_cap = (int64_t)d.max_steps + std::max<int32_t>(d.n_refine_rungs, 0);
const int64_t want[] = { const int64_t want[] = {
prompts * d.max_text * 4, /* R_TOK */ prompts * d.max_text * 4, /* R_TOK */
prompts * d.max_text * 4, /* R_POS */ prompts * d.max_text * 4, /* R_POS */
@@ -205,8 +208,8 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd,
3 * max_tok * 4, /* R_ROPE: a step's positions, or the prompt's M-RoPE */ 3 * max_tok * 4, /* R_ROPE: a step's positions, or the prompt's M-RoPE */
RAD_VGEOM_N * 4, /* R_GEOM */ RAD_VGEOM_N * 4, /* R_GEOM */
16 * 4, /* R_SCHED */ 16 * 4, /* R_SCHED */
d.max_steps * 4, /* R_TV */ sched_cap * 4, /* R_TV */
d.max_steps * 4, /* R_TA */ sched_cap * 4, /* R_TA */
4 * 4, /* R_SEED */ 4 * 4, /* R_SEED */
4, /* R_LANE */ 4, /* R_LANE */
4, /* R_FIRST */ 4, /* R_FIRST */
@@ -1008,6 +1011,11 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) {
px[i] = rad_f32_to_bf16(2.0f * ((float)img[i] / 255.0f) - 1.0f); px[i] = rad_f32_to_bf16(2.0f * ((float)img[i] / 255.0f) - 1.0f);
reg_[R_IMG].used = (int64_t)img.size() * 2; reg_[R_IMG].used = (int64_t)img.size() * 2;
} }
if ((int64_t)j.sched.steps * 4 > reg_[R_TV].bytes) {
fail_locked(j, RAD_E_STATE, "the schedule's " + std::to_string(j.sched.steps) +
" steps are more than the timestep regions hold");
return nullptr;
}
float* tv = hptr<float>(R_TV); float* tv = hptr<float>(R_TV);
float* ta = hptr<float>(R_TA); float* ta = hptr<float>(R_TA);
for (int32_t i = 0; i < j.sched.steps; ++i) { for (int32_t i = 0; i < j.sched.steps; ++i) {
@@ -1238,7 +1246,7 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) {
} else { } else {
const int64_t nf = m.enc_frames, area = (int64_t)eh * ew * 3; const int64_t nf = m.enc_frames, area = (int64_t)eh * ew * 3;
stage_frames = ng > 23 ? gd[23] : 0; stage_frames = ng > 23 ? gd[23] : 0;
if (stage_frames < nf || stage_frames * area * 4 > reg_[R_ENCPX].bytes) { if (nf < 1 || stage_frames < nf || stage_frames * area * 4 > reg_[R_ENCPX].bytes) {
fail_locked(j, RAD_E_STATE, "'" + m.name + "' does not fit an encode pass"); fail_locked(j, RAD_E_STATE, "'" + m.name + "' does not fit an encode pass");
return nullptr; return nullptr;
} }
+31 -1
View File
@@ -39,6 +39,7 @@ SamplingParams GenSampling::onto(SamplingParams base) const {
if (ngram_ban_n >= 0) base.ngram_ban_n = ngram_ban_n; if (ngram_ban_n >= 0) base.ngram_ban_n = ngram_ban_n;
if (ngram_window >= 0) base.ngram_window = ngram_window; if (ngram_window >= 0) base.ngram_window = ngram_window;
if (!ngram_whitelist.empty()) base.ngram_whitelist = ngram_whitelist; if (!ngram_whitelist.empty()) base.ngram_whitelist = ngram_whitelist;
if (!suppress.empty()) base.suppress_tokens = suppress;
return base; return base;
} }
@@ -156,6 +157,23 @@ bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampli
out->ngram_whitelist.push_back((int)id); out->ngram_whitelist.push_back((int)id);
} }
} }
/* transformers' suppress_tokens, a JSON array of ids. Dropped entry by entry like the
* whitelist above. */
it = j.find("suppress_tokens");
if (it != j.end() && !it->is_array()) {
RAD_WARN("%s states suppress_tokens that is not an array; ignoring it", src);
} else if (it != j.end()) {
for (const auto& v : *it) {
const int64_t id = v.is_number_integer() ? v.get<int64_t>() : -1;
if (id < 0 || id > INT32_MAX) {
RAD_WARN("%s states a suppress_tokens entry outside [0, %d]; ignoring it",
src, INT32_MAX);
continue;
}
out->suppress.push_back((int)id);
}
}
return out->any(); return out->any();
} }
@@ -175,7 +193,7 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
nlohmann::json j = nlohmann::json::object(); nlohmann::json j = nlohmann::json::object();
static const char* const kFields[] = { "do_sample", "temperature", "top_p", "min_p", "top_k", static const char* const kFields[] = { "do_sample", "temperature", "top_p", "min_p", "top_k",
"no_repeat_ngram_size", "no_repeat_ngram_window_size", "no_repeat_ngram_size", "no_repeat_ngram_window_size",
"no_repeat_ngram_whitelist" }; "no_repeat_ngram_whitelist", "suppress_tokens" };
for (const char* k : kFields) { for (const char* k : kFields) {
const char* v = get(k); const char* v = get(k);
if (!v || !*v) continue; if (!v || !*v) continue;
@@ -195,6 +213,18 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
} }
continue; continue;
} }
if (std::strcmp(k, "suppress_tokens") == 0) {
/* An array of scalars is flattened to a space-separated string (flatten_json). */
nlohmann::json ids = nlohmann::json::array();
char* p = const_cast<char*>(v);
for (char* e = nullptr;; p = e) {
const long long id = std::strtoll(p, &e, 10);
if (e == p) break;
ids.push_back(id);
}
j[k] = std::move(ids);
continue;
}
char* end = nullptr; char* end = nullptr;
const double d = std::strtod(v, &end); const double d = std::strtod(v, &end);
if (end == v) { if (end == v) {
+4 -1
View File
@@ -33,10 +33,13 @@ struct GenSampling {
* has no field for it; a container states it as `generation.no_repeat_ngram_whitelist`, a * has no field for it; a container states it as `generation.no_repeat_ngram_whitelist`, a
* JSON array of ids. Empty means not stated. */ * JSON array of ids. Empty means not stated. */
std::vector<int32_t> ngram_whitelist; std::vector<int32_t> ngram_whitelist;
/* transformers' suppress_tokens: ids never sampled. Empty means not stated. */
std::vector<int32_t> suppress;
bool any() const { bool any() const {
return temp >= 0.0f || top_p >= 0.0f || min_p >= 0.0f || top_k >= 0 || return temp >= 0.0f || top_p >= 0.0f || min_p >= 0.0f || top_k >= 0 ||
ngram_ban_n >= 0 || ngram_window >= 0 || !ngram_whitelist.empty(); ngram_ban_n >= 0 || ngram_window >= 0 || !ngram_whitelist.empty() ||
!suppress.empty();
} }
/* Overlay onto `base` field by field; unstated fields keep base's, so sources stack. */ /* Overlay onto `base` field by field; unstated fields keep base's, so sources stack. */
+14 -10
View File
@@ -381,12 +381,16 @@ int KVManager::declare_runtime_window(int32_t g, int64_t window_tokens) {
fixed_ += align_up(max_seqs_ * q.ring_blocks_max() * q.bytes_per_block, RAD_ALIGN_UNIT); fixed_ += align_up(max_seqs_ * q.ring_blocks_max() * q.bytes_per_block, RAD_ALIGN_UNIT);
if (counted) { if (counted) {
const int64_t was = q.window_blocks * q.bytes_per_block; const int64_t was = q.window_blocks * q.bytes_per_block;
/* The plan counted this group's snapshot section, so both totals carry `was`. /* The plan counted this group's snapshot section, so both totals carry `was`; less
* Saturating hides an accounting bug; surface it in debug builds. */ * is an accounting bug, and the pool would be sized from a wrong total. */
assert(window_ck_bytes_ >= was && checkpoint_bytes_ >= was && if (window_ck_bytes_ < was || checkpoint_bytes_ < was) {
"runtime window: snapshot byte totals below the section being removed"); RAD_ERR("kv group %d: runtime window: the snapshot byte totals (%lld, %lld) are "
window_ck_bytes_ = window_ck_bytes_ > was ? window_ck_bytes_ - was : 0; "below the %lld-byte section being removed", (int)g,
checkpoint_bytes_ = checkpoint_bytes_ > was ? checkpoint_bytes_ - was : 0; (long long)window_ck_bytes_, (long long)checkpoint_bytes_, (long long)was);
return RAD_E_STATE;
}
window_ck_bytes_ -= was;
checkpoint_bytes_ -= was;
} }
} }
return RAD_OK; return RAD_OK;
@@ -520,8 +524,8 @@ int KVManager::carve_into(Pool& kv_pool) {
" vram_kv %10s\n" " vram_kv %10s\n"
" short by %10s\n" " short by %10s\n"
"Lower --max-num-seqs, or give the cache more of the card: a smaller " "Lower --max-num-seqs, or give the cache more of the card: a smaller "
"--gpu-headroom-mib or a larger --host-pool-mib. The engine will not shrink one of " "--gpu-headroom-mib, a larger --gpu-memory-mib, or a larger --host-pool-mib. The "
"them for you (spec §6).", "engine will not shrink one of them for you (spec §6).",
humanb(fixed).c_str(), (long long)max_seqs_, humanb(budget_bytes).c_str(), humanb(fixed).c_str(), (long long)max_seqs_, humanb(budget_bytes).c_str(),
humanb(fixed - budget_bytes + 1).c_str()); humanb(fixed - budget_bytes + 1).c_str());
return RAD_E_NOMEM; return RAD_E_NOMEM;
@@ -550,8 +554,8 @@ int KVManager::carve_into(Pool& kv_pool) {
} }
if (p.n_blocks <= 0) { if (p.n_blocks <= 0) {
RAD_ERR("KV group '%s': a %s KV pool leaves 0 blocks (%s a page) after the fixed " RAD_ERR("KV group '%s': a %s KV pool leaves 0 blocks (%s a page) after the fixed "
"linear/conv costs of %s. Raise --host-pool-mib or lower --gpu-headroom-mib, or " "linear/conv costs of %s. Raise --host-pool-mib or --gpu-memory-mib, or lower "
"lower --max-num-seqs.", "--gpu-headroom-mib or --max-num-seqs.",
p.name.c_str(), humanb(budget_bytes).c_str(), p.name.c_str(), humanb(budget_bytes).c_str(),
humanb(p.bytes_per_block).c_str(), humanb(fixed).c_str()); humanb(p.bytes_per_block).c_str(), humanb(fixed).c_str());
return RAD_E_NOMEM; return RAD_E_NOMEM;
+21 -2
View File
@@ -536,7 +536,10 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
static bool chain_extends(const std::vector<BlockHash>& shorter, static bool chain_extends(const std::vector<BlockHash>& shorter,
const std::vector<BlockHash>& longer) { const std::vector<BlockHash>& longer) {
if (shorter.size() > longer.size()) return false; if (shorter.size() > longer.size()) return false;
for (size_t i = 0; i < shorter.size(); ++i) if (shorter[i] != longer[i]) return false; /* Hashes are chained, so the last block decides; it is compared first, and a chain that
* diverges anywhere rejects in one compare. */
if (!shorter.empty() && shorter.back() != longer[shorter.size() - 1]) return false;
for (size_t i = 0; i + 1 < shorter.size(); ++i) if (shorter[i] != longer[i]) return false;
return true; return true;
} }
@@ -546,7 +549,7 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
std::lock_guard lk(mu_); std::lock_guard lk(mu_);
/* A session is a leaf of the prefix trie. Each turn arrives under a new request id, so the /* A session is a leaf of the prefix trie. Each turn arrives under a new request id, so the
* candidates are the sessions sharing this root (a handful at most): * candidates are the sessions sharing this root (at most kRootSessions):
* *
* - a chain this one extends is no longer a leaf and is absorbed; * - a chain this one extends is no longer a leaf and is absorbed;
* - a chain that extends this one means this is not a leaf either (a preempted request * - a chain that extends this one means this is not a leaf either (a preempted request
@@ -590,6 +593,22 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
s.chain = chain; s.chain = chain;
s.label = std::move(kept_label); s.label = std::move(kept_label);
at_root.push_back(id); at_root.push_back(id);
/* Rows under one root are pruned only when the root block goes, and a prompt every request
* shares (a decision model's instructions) never goes: the list grew by a row a request and
* each insert walked it under the lock the engine threads take (#375: prefill from 9k to
* 2.5k tok/s after 500K requests). Past kRootSessions the least recently used row is
* dropped; a row is bookkeeping, so its blocks stay cached. */
if (at_root.size() > kRootSessions) {
uint64_t oldest = 0, oldest_ns = ~uint64_t{0};
for (uint64_t sid : at_root) {
auto it = sessions_.find(sid);
if (it != sessions_.end() && it->second.last_used_ns < oldest_ns) {
oldest_ns = it->second.last_used_ns;
oldest = sid;
}
}
if (oldest) drop_session(oldest);
}
} }
void IdleTiers::drop_session(uint64_t id) { void IdleTiers::drop_session(uint64_t id) {
+3
View File
@@ -404,6 +404,9 @@ private:
* freed, so ticks do not spin on the queue. */ * freed, so ticks do not spin on the queue. */
bool wb_stuck_ = false; bool wb_stuck_ = false;
std::unordered_map<uint64_t, Session> sessions_; std::unordered_map<uint64_t, Session> sessions_;
/* Rows kept under one root (sessions sharing a first block); past it the least recently used
* goes (note_session). */
static constexpr size_t kRootSessions = 1024;
/* Sessions by first block. A chain is reachable only from position zero, so once its first /* Sessions by first block. A chain is reachable only from position zero, so once its first
* block goes (forget(), or a drop here via drop_rooted) its rows go too; this keeps the table * block goes (forget(), or a drop here via drop_rooted) its rows go too; this keeps the table
* bounded. Sessions sharing a system prompt share a root, hence a list. */ * bounded. Sessions sharing a system prompt share a root, hence a list. */
+22 -3
View File
@@ -76,6 +76,21 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
if (f.unified) b.host_pinned = std::max(b.host_pinned, f.host_pinned); if (f.unified) b.host_pinned = std::max(b.host_pinned, f.host_pinned);
} }
if (!b.unified) b.host_pinned = 0; if (!b.unified) b.host_pinned = 0;
/* --gpu-memory-mib is the inverse of --gpu-headroom-mib: N + headroom = the card, in MiB.
* Convert once the smallest rank capacity is known. A device that reports no capacity has
* nothing to claim, so the flag does not apply. */
if (b.capacity > 0 && cfg.gpu_memory_mib > 0) {
const int64_t cap_mib = b.capacity / kMiB;
if (cfg.gpu_memory_mib > cap_mib) {
b.report = fmt("--gpu-memory-mib %lld is above this card's %lld MiB",
(long long)cfg.gpu_memory_mib, (long long)cap_mib);
if (log) RAD_ERR("%s", b.report.c_str());
if (out) *out = b;
return RAD_E_INVAL;
}
cfg.gpu_headroom_mib = cap_mib - cfg.gpu_memory_mib;
cfg.given["--gpu-headroom-mib"] = "derived from --gpu-memory-mib";
}
b.headroom = std::max<int64_t>(cfg.gpu_headroom_mib, 0) * kMiB; b.headroom = std::max<int64_t>(cfg.gpu_headroom_mib, 0) * kMiB;
int64_t host_reserve = 0; int64_t host_reserve = 0;
for (const VramFacts& f : per_rank) host_reserve = std::max(host_reserve, f.host_reserve); for (const VramFacts& f : per_rank) host_reserve = std::max(host_reserve, f.host_reserve);
@@ -116,6 +131,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
b.queues + b.prefetch + b.host_pinned); b.queues + b.prefetch + b.host_pinned);
if (b.claimable < 0) { if (b.claimable < 0) {
const char* how = cfg.gpu_memory_mib > 0
? "Raise --gpu-memory-mib, lower --max-num-batched-tokens (the arena scales with it), "
"or free the card.\n"
: "Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), "
"or free the card.\n";
b.report = fmt( b.report = fmt(
"VRAM does not cover the fixed costs before a single pool is sized:\n" "VRAM does not cover the fixed costs before a single pool is sized:\n"
" card total %10s\n" " card total %10s\n"
@@ -128,12 +148,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
" expert prefetch %10s (its ring of expert units and buffers)\n" " expert prefetch %10s (its ring of expert units and buffers)\n"
" ------------------------------\n" " ------------------------------\n"
" short by %10s\n" " short by %10s\n"
"Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), " "%s",
"or free the card.\n",
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(), humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(),
humanb(b.headroom).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(), humanb(b.headroom).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(),
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(), humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(),
humanb(b.prefetch).c_str(), humanb(-b.claimable).c_str()); humanb(b.prefetch).c_str(), humanb(-b.claimable).c_str(), how);
if (log) RAD_ERR("%s", b.report.c_str()); if (log) RAD_ERR("%s", b.report.c_str());
if (out) *out = b; if (out) *out = b;
return RAD_E_NOMEM; return RAD_E_NOMEM;
+5 -3
View File
@@ -10,6 +10,8 @@
* loaded code. The only observed term, printed on its own line so a * loaded code. The only observed term, printed on its own line so a
* desktop on the card shows up there instead of shrinking a pool. * desktop on the card shows up there instead of shrinking a pool.
* --gpu-headroom-mib what the operator leaves alone (default 96 MiB). * --gpu-headroom-mib what the operator leaves alone (default 96 MiB).
* --gpu-memory-mib the inverse: claim this much of the card; headroom is the rest.
* Not with --gpu-headroom-mib.
* arena activation arena plus scratch, from arena_plan_bytes() on the buffer * arena activation arena plus scratch, from arena_plan_bytes() on the buffer
* plan, the same call that later allocates it. * plan, the same call that later allocates it.
* *
@@ -32,9 +34,9 @@
* KVManager::ceiling; the experts at the whole plane) and one side's excess goes to the other. * KVManager::ceiling; the experts at the whole plane) and one side's excess goes to the other.
* *
* No flag states a pool size: unbudgeted VRAM is unusable, and on a model whose experts do not * No flag states a pool size: unbudgeted VRAM is unusable, and on a model whose experts do not
* fit every unbudgeted GiB costs decode time. Operators move the inputs instead: --gpu-headroom-mib, * fit every unbudgeted GiB costs decode time. Operators move the inputs instead: --gpu-headroom-mib
* --max-model-len and --max-num-seqs (cache bound), --host-pool-mib (which experts must stay on * or --gpu-memory-mib, --max-model-len and --max-num-seqs (cache bound), --host-pool-mib (which
* the card). * experts must stay on the card).
* *
* The host backend uses half the machine's memory as its capacity (host_vram_bytes) and splits it * The host backend uses half the machine's memory as its capacity (host_vram_bytes) and splits it
* like a card; its weights pool holds what a host kernel cannot read where the container stores it * like a card; its weights pool holds what a host kernel cannot read where the container stores it
+10 -1
View File
@@ -31,7 +31,16 @@ void Item::coords(int64_t first, int64_t count, int32_t* planes) const {
while (s + 1 < n_seg && patch_at(s + 1) <= first) ++s; while (s + 1 < n_seg && patch_at(s + 1) <= first) ++s;
for (int64_t k = 0; k < count; ++k) { for (int64_t k = 0; k < count; ++k) {
while (s + 1 < n_seg && patch_at(s + 1) <= first + k) ++s; while (s + 1 < n_seg && patch_at(s + 1) <= first + k) ++s;
const int64_t within = first + k - patch_at(s); int64_t within = first + k - patch_at(s);
if (within < seg_prefix) {
/* A row the tower fills itself: row -1, the column naming which. */
planes[k] = -1;
planes[count + k] = (int32_t)within;
planes[2 * count + k] = seg_h(s);
planes[3 * count + k] = seg_w(s);
continue;
}
within -= seg_prefix;
const int64_t bw = seg_w(s) / merge; const int64_t bw = seg_w(s) / merge;
int64_t row, col; int64_t row, col;
if (patch_raster) { if (patch_raster) {
+61 -18
View File
@@ -702,21 +702,41 @@ int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_sample
return RAD_OK; return RAD_OK;
} }
namespace {
/* The H.264 encoder the round trip uses: libx264, the reference's, else libopenh264 (the published
* image carries libopenh264 and no libx264). Not any H.264 encoder: the hardware ones need a device
* context this path does not set up. */
const AVCodec* h264_encoder() {
for (const char* name : { "libx264", "libopenh264" })
if (const AVCodec* c = avcodec_find_encoder_by_name(name)) return c;
return nullptr;
}
} /* namespace */
bool h264_roundtrip_available() { bool h264_roundtrip_available() {
return avcodec_find_encoder_by_name("libx264") && avcodec_find_decoder(AV_CODEC_ID_H264); return h264_encoder() && avcodec_find_decoder(AV_CODEC_ID_H264);
} }
/* PyAV's single-frame round trip: VideoFrame.from_ndarray(rgb24).reformat("yuv420p") (plain /* PyAV's single-frame round trip: VideoFrame.from_ndarray(rgb24).reformat("yuv420p") (plain
* SWS_BILINEAR, BT.601 coefficients, limited-range output), libx264 with the given crf, then the * SWS_BILINEAR, BT.601 coefficients, limited-range output), libx264 with the given crf, then the
* decoded frame's to_ndarray("rgb24"), which to_rgb reproduces. */ * decoded frame's to_ndarray("rgb24"), which to_rgb reproduces. Without libx264, libopenh264 takes
* the frame at a quantiser held at the crf, about the compression libx264's crf gives a single intra
* frame, so the first frame is close to the reference's but not exact. libopenh264 takes no side
* under 16, so a smaller picture is encoded with its last row and column repeated out to 16 and
* the decoded frame cut back. */
int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why) { int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why) {
std::string w; std::string w;
if (!why) why = &w; if (!why) why = &w;
const int W = in.w & ~1, H = in.h & ~1; const int W = in.w & ~1, H = in.h & ~1;
if (W <= 0 || H <= 0) { *why = "the picture is smaller than 2x2"; return RAD_E_INVAL; } if (W <= 0 || H <= 0) { *why = "the picture is smaller than 2x2"; return RAD_E_INVAL; }
const AVCodec* enc = avcodec_find_encoder_by_name("libx264"); const AVCodec* enc = h264_encoder();
const AVCodec* dcd = avcodec_find_decoder(AV_CODEC_ID_H264); const AVCodec* dcd = avcodec_find_decoder(AV_CODEC_ID_H264);
if (!enc || !dcd) { *why = "this libavcodec has no libx264 encoder or H.264 decoder"; return RAD_E_UNSUPPORTED; } if (!enc) { *why = "this libavcodec has no H.264 encoder"; return RAD_E_UNSUPPORTED; }
if (!dcd) { *why = "this libavcodec has no H.264 decoder"; return RAD_E_UNSUPPORTED; }
const bool x264 = !std::strcmp(enc->name, "libx264");
const int EW = x264 ? W : std::max(W, 16), EH = x264 ? H : std::max(H, 16);
AVCodecContext* ec = avcodec_alloc_context3(enc); AVCodecContext* ec = avcodec_alloc_context3(enc);
AVCodecContext* dc = avcodec_alloc_context3(dcd); AVCodecContext* dc = avcodec_alloc_context3(dcd);
AVFrame* yuv = av_frame_alloc(); AVFrame* yuv = av_frame_alloc();
@@ -733,8 +753,8 @@ int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why) {
*why = "out of memory"; *why = "out of memory";
st = RAD_E_NOMEM; st = RAD_E_NOMEM;
} else { } else {
ec->width = W; ec->width = EW;
ec->height = H; ec->height = EH;
ec->pix_fmt = AV_PIX_FMT_YUV420P; ec->pix_fmt = AV_PIX_FMT_YUV420P;
ec->time_base = AVRational{ 1, 1 }; ec->time_base = AVRational{ 1, 1 };
ec->framerate = AVRational{ 1, 1 }; ec->framerate = AVRational{ 1, 1 };
@@ -742,19 +762,26 @@ int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why) {
* that many slices, which shapes the bitstream. */ * that many slices, which shapes the bitstream. */
ec->thread_count = 0; ec->thread_count = 0;
ec->thread_type = FF_THREAD_SLICE; ec->thread_type = FF_THREAD_SLICE;
av_opt_set(ec->priv_data, "preset", "veryfast", 0); if (x264) {
av_opt_set(ec->priv_data, "crf", std::to_string(crf).c_str(), 0); av_opt_set(ec->priv_data, "preset", "veryfast", 0);
av_opt_set(ec->priv_data, "crf", std::to_string(crf).c_str(), 0);
} else {
/* libopenh264's rate control held between qmin and qmax: its "off" mode encodes at the
* layer quantiser FFmpeg leaves at the library's default and ignores both. */
ec->qmin = ec->qmax = std::clamp(crf, 1, 51);
av_opt_set(ec->priv_data, "rc_mode", "quality", 0);
}
int e = avcodec_open2(ec, enc, nullptr); int e = avcodec_open2(ec, enc, nullptr);
if (e < 0) fail("opening libx264", e); if (e < 0) fail(x264 ? "opening libx264" : "opening the H.264 encoder", e);
if (st == RAD_OK && (e = avcodec_open2(dc, dcd, nullptr)) < 0) fail("opening the H.264 decoder", e); if (st == RAD_OK && (e = avcodec_open2(dc, dcd, nullptr)) < 0) fail("opening the H.264 decoder", e);
if (st == RAD_OK) { if (st == RAD_OK) {
yuv->format = AV_PIX_FMT_YUV420P; yuv->format = AV_PIX_FMT_YUV420P;
yuv->width = W; yuv->width = EW;
yuv->height = H; yuv->height = EH;
if ((e = av_frame_get_buffer(yuv, 0)) < 0) fail("allocating a frame", e); if ((e = av_frame_get_buffer(yuv, 0)) < 0) fail("allocating a frame", e);
} }
if (st == RAD_OK) { if (st == RAD_OK) {
sws = sws_getContext(W, H, AV_PIX_FMT_RGB24, W, H, AV_PIX_FMT_YUV420P, SWS_BILINEAR, sws = sws_getContext(EW, EH, AV_PIX_FMT_RGB24, EW, EH, AV_PIX_FMT_YUV420P, SWS_BILINEAR,
nullptr, nullptr, nullptr); nullptr, nullptr, nullptr);
if (!sws) fail("no RGB to yuv420p conversion", 0); if (!sws) fail("no RGB to yuv420p conversion", 0);
} }
@@ -765,14 +792,17 @@ int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why) {
if (!rgb) fail("out of memory", AVERROR(ENOMEM)); if (!rgb) fail("out of memory", AVERROR(ENOMEM));
else { else {
rgb->format = AV_PIX_FMT_RGB24; rgb->format = AV_PIX_FMT_RGB24;
rgb->width = W; rgb->width = EW;
rgb->height = H; rgb->height = EH;
if ((e = av_frame_get_buffer(rgb, 0)) < 0) fail("allocating a frame", e); if ((e = av_frame_get_buffer(rgb, 0)) < 0) fail("allocating a frame", e);
else { else {
for (int y = 0; y < H; ++y) for (int y = 0; y < EH; ++y) {
std::memcpy(rgb->data[0] + (ptrdiff_t)y * rgb->linesize[0], uint8_t* row = rgb->data[0] + (ptrdiff_t)y * rgb->linesize[0];
in.rgb.data() + (size_t)y * in.w * 3, (size_t)W * 3); std::memcpy(row, in.rgb.data() + (size_t)std::min(y, H - 1) * in.w * 3,
if (sws_scale(sws, rgb->data, rgb->linesize, 0, H, yuv->data, yuv->linesize) != H) (size_t)W * 3);
for (int x = W; x < EW; ++x) std::memcpy(row + x * 3, row + (W - 1) * 3, 3);
}
if (sws_scale(sws, rgb->data, rgb->linesize, 0, EH, yuv->data, yuv->linesize) != EH)
fail("colour conversion failed", 0); fail("colour conversion failed", 0);
} }
av_frame_free(&rgb); av_frame_free(&rgb);
@@ -795,6 +825,19 @@ int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why) {
st = to_rgb(dec, &back, out, why); st = to_rgb(dec, &back, out, why);
sws_freeContext(back); sws_freeContext(back);
got = st == RAD_OK; got = st == RAD_OK;
if (got && (out->w != W || out->h != H)) {
if (out->w < W || out->h < H) {
fail("the round trip decoded to a smaller frame", 0);
got = false;
} else {
for (int y = 0; y < H; ++y)
std::memmove(out->rgb.data() + (size_t)y * W * 3,
out->rgb.data() + (size_t)y * out->w * 3, (size_t)W * 3);
out->rgb.resize((size_t)W * H * 3);
out->w = W;
out->h = H;
}
}
} }
av_frame_unref(dec); av_frame_unref(dec);
} }
+2 -2
View File
@@ -90,9 +90,9 @@ int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_sample
/* `in` encoded as a one-frame H.264 stream at constant quality `crf` (libx264, preset veryfast, /* `in` encoded as a one-frame H.264 stream at constant quality `crf` (libx264, preset veryfast,
* yuv420p) and decoded back, as a video model's reference pipeline does to a conditioning * yuv420p) and decoded back, as a video model's reference pipeline does to a conditioning
* picture so it carries the compression of the footage the model was trained on. An odd width * picture so it carries the compression of the footage the model was trained on. An odd width
* or height loses its last column or row first. Needs libx264. */ * or height loses its last column or row first. Needs an H.264 encoder: libx264, else libopenh264. */
int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why); int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why);
/* Whether this build can run h264_roundtrip: its libavcodec has libx264. */ /* Whether this build can run h264_roundtrip: its libavcodec has an H.264 encoder and decoder. */
bool h264_roundtrip_available(); bool h264_roundtrip_available();
} /* namespace mm */ } /* namespace mm */
+432 -7
View File
@@ -244,10 +244,74 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
} }
return RAD_OK; return RAD_OK;
} }
if (mt && !std::strcmp(mt, "gemma4_vision")) { /* NVIDIA's Nemotron-H Omni states its tile budget in the processor configs (preprocessor and
* processor_config's image_processor carry the same keys) and its token ids in config.json,
* except <img> and </img>, which the vocabulary names (Processor::init). */
if (mt && !std::strcmp(mt, "radio")) {
family = Family::Radio;
auto geti = [&](const char* k, int64_t dflt) {
const std::string a = std::string("processor.image_processor.") + k;
const std::string b = std::string("preprocessor.") + k;
return rad_meta_geti(&m, a.c_str(), rad_meta_geti(&m, b.c_str(), dflt));
};
patch = (int32_t)geti("patch_size", rad_meta_geti(&m, "vision_config.patch_size", 0));
const double ratio = rad_meta_getf(&m, "downsample_ratio", 0.0);
merge = ratio > 0.0 ? (int32_t)std::lround(1.0 / ratio) : 0;
temporal = 1;
radio_tubelet = (int32_t)rad_meta_geti(
&m, "processor.video_temporal_patch_dim",
rad_meta_geti(&m, "video_temporal_patch_size",
rad_meta_geti(&m, "vision_config.video_temporal_patch_size", 0)));
radio_prefix = (int32_t)(rad_meta_geti(&m, "vision_config.num_cls_tokens", 0) +
rad_meta_geti(&m, "vision_config.num_registers", 0));
tok_image = (int32_t)rad_meta_geti(&m, "img_context_token_id", -1);
if (patch <= 0 || merge <= 0 || radio_tubelet <= 0 || radio_prefix <= 0 || tok_image < 0) {
if (why) *why = "the container states no Nemotron-H Omni processor geometry "
"(vision_config.patch_size, downsample_ratio, video_temporal_patch_size, "
"num_cls_tokens + num_registers, img_context_token_id)";
return RAD_E_NOTFOUND;
}
radio_min_patches = (int32_t)geti("min_num_patches", 1024);
radio_max_patches = (int32_t)geti("max_num_patches", 13312);
radio_max_len = (int32_t)geti("max_model_len", 16384);
radio_video_patches = (int32_t)geti("video_target_num_patches", 1024);
if (!read_triple(m, "processor.image_processor.norm_mean", mean) &&
!read_triple(m, "preprocessor.norm_mean", mean))
read_triple(m, "norm_mean", mean);
if (!read_triple(m, "processor.image_processor.norm_std", stdv) &&
!read_triple(m, "preprocessor.norm_std", stdv))
read_triple(m, "norm_std", stdv);
/* The model card's serving default: 2 frames a second, at most 128 (64 tubelets). */
fps = 2.0;
min_frames = radio_tubelet;
max_frames = 128;
max_frame_rows = 0;
/* The pixel bands only have to be consistent for check(); the tile rule sizes by patches. */
const int64_t p2 = (int64_t)patch * patch;
image_min_pixels = (int64_t)radio_min_patches * p2;
image_max_pixels = std::max<int64_t>(image_min_pixels, (int64_t)radio_max_patches * p2);
video_min_pixels = video_max_pixels = (int64_t)radio_video_patches * p2;
std::string bad;
if (radio_min_patches <= 0 || radio_video_patches <= 0 || radio_max_len <= 0)
bad = "min_num_patches, video_target_num_patches and max_model_len must be positive";
if (bad.empty() && check(&bad) < 0) bad = "the container's Nemotron-H Omni processor "
"configuration is inconsistent: " + bad;
if (!bad.empty()) {
if (why) *why = bad;
return RAD_E_INVAL;
}
return RAD_OK;
}
/* Gemma 4 12B ("unified") has no tower: its embedder takes a whole 48 x 48 pooling window as
* one patch, so a patch is a row (merge 1), and its values are u / 255. The sizes are the
* same: a window is 48 pixels a side either way. */
const bool unified = mt && !std::strcmp(mt, "gemma4_unified_vision");
if (mt && (!std::strcmp(mt, "gemma4_vision") || unified)) {
family = Family::Gemma4; family = Family::Gemma4;
patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0); unit_pixels = unified;
merge = (int32_t)rad_meta_geti(&m, "vision_config.pooling_kernel_size", 0); patch = (int32_t)rad_meta_geti(&m, unified ? "vision_config.model_patch_size"
: "vision_config.patch_size", 0);
merge = unified ? 1 : (int32_t)rad_meta_geti(&m, "vision_config.pooling_kernel_size", 0);
temporal = 1; temporal = 1;
if (patch <= 0 || merge <= 0) { if (patch <= 0 || merge <= 0) {
if (why) *why = "the container states no vision tower geometry (vision_config." if (why) *why = "the container states no vision tower geometry (vision_config."
@@ -267,7 +331,8 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
image_soft_tokens = (int32_t)rad_meta_geti( image_soft_tokens = (int32_t)rad_meta_geti(
&m, "processor.image_processor.max_soft_tokens", &m, "processor.image_processor.max_soft_tokens",
rad_meta_geti(&m, "vision_soft_tokens_per_image", rad_meta_geti(&m, "vision_soft_tokens_per_image",
rad_meta_geti(&m, "vision_config.default_output_length", 280))); rad_meta_geti(&m, "vision_config.default_output_length",
rad_meta_geti(&m, "vision_config.num_soft_tokens", 280))));
video_soft_tokens = (int32_t)rad_meta_geti(&m, "processor.video_processor.max_soft_tokens", video_soft_tokens = (int32_t)rad_meta_geti(&m, "processor.video_processor.max_soft_tokens",
70); 70);
fps = rad_meta_getf(&m, "processor.video_processor.fps", 1.0); fps = rad_meta_getf(&m, "processor.video_processor.fps", 1.0);
@@ -970,6 +1035,134 @@ void resize_bicubic_torch(const Frame& in, int32_t w, int32_t h, Frame* out) {
resize_bicubic_impl(in, w, h, out, true); resize_bicubic_impl(in, w, h, out, true);
} }
/* Python's round(): the nearest integer, a tie to the even one. The default floating-point
* environment rounds that way, which nearbyint follows. */
static inline int64_t py_round(double x) { return (int64_t)std::nearbyint(x); }
void radio_size(int64_t w, int64_t h, const VisionConfig& c, int32_t* wp, int32_t* hp) {
const int64_t div = c.merge, lo = c.radio_min_patches;
const int64_t hi = c.radio_max_patches > 0 ? c.radio_max_patches : INT64_MAX;
const int64_t budget = std::max<int64_t>((int64_t)(c.radio_max_len - 4) * div * div, lo);
const int64_t avail = std::max<int64_t>(std::min<int64_t>(budget, hi), lo);
/* round(x + 0.5): x + 1 rounded down for a fraction, and for a whole x, x or x + 1 by parity
* (Python's tie to even), which the reference's comment does not say but its code does. */
const int64_t ch = py_round((double)h / (double)c.patch + 0.5);
const int64_t cw = py_round((double)w / (double)c.patch + 0.5);
const double factor = std::min(std::sqrt((double)avail / (double)(ch * cw)), 1.0);
int64_t th = (int64_t)std::floor(factor * (double)ch);
int64_t tw = (int64_t)std::floor(factor * (double)cw);
if (avail > lo && th * tw < lo) {
const double up = std::sqrt((double)lo / (double)(th * tw));
th = (int64_t)std::ceil(up * (double)th);
tw = (int64_t)std::ceil(up * (double)tw);
}
if (const int64_t r = th % div) th = (th + div - r) * tw <= avail ? th + div - r
: std::max(div, th - r);
if (const int64_t r = tw % div) tw = th * (tw + div - r) <= avail ? tw + div - r
: std::max(div, tw - r);
*wp = (int32_t)tw;
*hp = (int32_t)th;
}
void radio_video_size(int64_t w, int64_t h, const VisionConfig& c, int32_t* wp, int32_t* hp) {
const int64_t div = c.merge, target = c.radio_video_patches;
const double aspect = (double)w / (double)std::max<int64_t>(h, 1);
int64_t ph = std::max<int64_t>(py_round(std::sqrt((double)target / aspect)), 1);
int64_t pw = std::max<int64_t>(py_round(std::sqrt((double)target * aspect)), 1);
if (div > 1) {
const int64_t rh = ph % div, rw = pw % div;
const int64_t phu = ph + (rh ? div - rh : 0), pwu = pw + (rw ? div - rw : 0);
if (phu * pwu <= target) {
ph = phu;
pw = pwu;
} else {
ph = std::max(div, ph - rh);
pw = std::max(div, pw - rw);
}
}
*wp = (int32_t)pw;
*hp = (int32_t)ph;
}
/* ATen's antialiased bicubic (Keys, a = -0.5) on float, one axis: output i reads inputs
* [lo, lo + n) at the filter's normalised weights, the support widened by the scale when
* shrinking. */
namespace {
struct AaTaps { std::vector<int32_t> lo, n; std::vector<float> w; int32_t width = 0; };
inline float aa_cubic(float x) {
const float a = -0.5f;
x = std::fabs(x);
if (x < 1.0f) return ((a + 2.0f) * x - (a + 3.0f)) * x * x + 1.0f;
if (x < 2.0f) return ((a * x - 5.0f * a) * x + 8.0f * a) * x - 4.0f * a;
return 0.0f;
}
AaTaps aa_taps_f32(int32_t in, int32_t out) {
AaTaps t;
const float scale = (float)in / (float)out;
const float support = scale >= 1.0f ? 2.0f * scale : 2.0f;
const float inv = scale >= 1.0f ? 1.0f / scale : 1.0f;
t.width = (int32_t)std::ceil(support) * 2 + 1;
t.lo.resize((size_t)out);
t.n.resize((size_t)out);
t.w.assign((size_t)out * t.width, 0.0f);
for (int32_t i = 0; i < out; ++i) {
const float center = scale * ((float)i + 0.5f);
const int32_t lo = std::max((int32_t)(center - support + 0.5f), 0);
const int32_t n = std::min((int32_t)(center + support + 0.5f), in) - lo;
float* w = &t.w[(size_t)i * t.width];
float total = 0.0f;
for (int32_t j = 0; j < n && j < t.width; ++j) {
w[j] = aa_cubic(((float)(j + lo) - center + 0.5f) * inv);
total += w[j];
}
for (int32_t j = 0; j < n && j < t.width; ++j) w[j] = total != 0.0f ? w[j] / total : 0.0f;
t.lo[(size_t)i] = lo;
t.n[(size_t)i] = std::min(n, t.width);
}
return t;
}
} /* namespace */
void resize_bicubic_aa_f32(const Frame& in, int32_t w, int32_t h, std::vector<float>* out) {
std::vector<float> src((size_t)in.w * in.h * 3);
for (size_t i = 0; i < src.size(); ++i) src[i] = (float)in.rgb[i];
/* Width first, then height; a side that keeps its size is skipped (its taps are the identity). */
std::vector<float> mid;
const std::vector<float>* cur = &src;
int32_t cw = in.w;
if (w != in.w) {
const AaTaps t = aa_taps_f32(in.w, w);
mid.assign((size_t)w * in.h * 3, 0.0f);
for (int32_t y = 0; y < in.h; ++y)
for (int32_t x = 0; x < w; ++x)
for (int c = 0; c < 3; ++c) {
float acc = 0.0f;
const float* wt = &t.w[(size_t)x * t.width];
for (int32_t j = 0; j < t.n[(size_t)x]; ++j)
acc += src[((size_t)y * in.w + t.lo[(size_t)x] + j) * 3 + c] * wt[j];
mid[((size_t)y * w + x) * 3 + c] = acc;
}
cur = &mid;
cw = w;
}
if (h != in.h) {
const AaTaps t = aa_taps_f32(in.h, h);
out->assign((size_t)cw * h * 3, 0.0f);
for (int32_t y = 0; y < h; ++y) {
const float* wt = &t.w[(size_t)y * t.width];
for (int32_t x = 0; x < cw; ++x)
for (int c = 0; c < 3; ++c) {
float acc = 0.0f;
for (int32_t j = 0; j < t.n[(size_t)y]; ++j)
acc += (*cur)[((size_t)(t.lo[(size_t)y] + j) * cw + x) * 3 + c] * wt[j];
(*out)[((size_t)y * cw + x) * 3 + c] = acc;
}
}
return;
}
*out = *cur;
}
void cap_area(const Frame& in, int64_t max_pixels, Frame* out) { void cap_area(const Frame& in, int64_t max_pixels, Frame* out) {
if (max_pixels <= 0 || (int64_t)in.w * in.h <= max_pixels) { *out = in; return; } if (max_pixels <= 0 || (int64_t)in.w * in.h <= max_pixels) { *out = in; return; }
const double scale = std::sqrt((double)max_pixels / ((double)in.w * in.h)); const double scale = std::sqrt((double)max_pixels / ((double)in.w * in.h));
@@ -1071,7 +1264,8 @@ void patchify(const VisionConfig& c, const std::vector<const Frame*>& frames, It
* processor's rescale u * (1/255). The processors AutoProcessor loads take that product in f32 for * processor's rescale u * (1/255). The processors AutoProcessor loads take that product in f32 for
* pictures (Gemma4ImageProcessor) and in double, rounded to f32, for video (Gemma 4's and * pictures (Gemma4ImageProcessor) and in double, rounded to f32, for video (Gemma 4's and
* EmbeddingGemma 2's video processors); `video` picks which, and the two differ for u = 127. One * EmbeddingGemma 2's video processors); `video` picks which, and the two differ for u = 127. One
* frame per segment. */ * frame per segment. With `unit_pixels` (the 12B, merge 1: a row is one 48 x 48 window) the value
* is p itself, rounded to bf16. */
void patchify_gemma4(const VisionConfig& c, const std::vector<const Frame*>& frames, bool video, void patchify_gemma4(const VisionConfig& c, const std::vector<const Frame*>& frames, bool video,
Item* it) { Item* it) {
const int P = c.patch, M = c.merge; const int P = c.patch, M = c.merge;
@@ -1080,7 +1274,7 @@ void patchify_gemma4(const VisionConfig& c, const std::vector<const Frame*>& fra
for (int v = 0; v < 256; ++v) { for (int v = 0; v < 256; ++v) {
const float p = video ? (float)((double)v * (1.0 / 255.0)) const float p = video ? (float)((double)v * (1.0 / 255.0))
: (float)v * (float)(1.0 / 255.0); : (float)v * (float)(1.0 / 255.0);
lut[v] = rad_f32_to_bf16(2.0f * (p - 0.5f)); lut[v] = rad_f32_to_bf16(c.unit_pixels ? p : 2.0f * (p - 0.5f));
} }
const int64_t dim = it->patch_dim; const int64_t dim = it->patch_dim;
it->pixels.assign((size_t)it->n_patch * (size_t)dim, 0); it->pixels.assign((size_t)it->n_patch * (size_t)dim, 0);
@@ -1100,6 +1294,55 @@ void patchify_gemma4(const VisionConfig& c, const std::vector<const Frame*>& fra
} }
} }
/* Radio's patch rows (Family::Radio), segment by segment: `n_prefix` zero rows, then the patches
* in merge-block order. A row is [the tubelet's frames (frame, channel, y, x) | the picture's
* (channel, y, x)]: a picture fills the second part, a video tubelet the first, the rest zero.
* Each value is (u / 255 - mean) / std in f32 on the resized float pixels, rounded to bf16, as the
* reference processor's tensor ops and the model's cast to bf16 give it. `frames` holds
* grid_t * tubelet frames of [grid_h * patch, grid_w * patch, 3] floats for a video, one for a
* picture. */
void patchify_radio(const VisionConfig& c, const std::vector<const std::vector<float>*>& frames,
bool video, Item* it) {
const int P = c.patch, M = c.merge, T = c.radio_tubelet;
const int gh = it->grid_h, gw = it->grid_w, W = gw * P;
const int64_t dim = it->patch_dim, pp = 3LL * P * P;
it->pixels.assign((size_t)it->n_patch * (size_t)dim, 0);
uint16_t* dst = it->pixels.data();
auto norm = [&](float u, int ch) {
return rad_f32_to_bf16((u / 255.0f - c.mean[ch]) / c.stdv[ch]);
};
for (int g = 0; g < it->grid_t; ++g) {
dst += (size_t)it->seg_prefix * dim;
for (int bh = 0; bh < gh / M; ++bh)
for (int bw = 0; bw < gw / M; ++bw)
for (int mh = 0; mh < M; ++mh)
for (int mw = 0; mw < M; ++mw) {
const int py0 = (bh * M + mh) * P, px0 = (bw * M + mw) * P;
const int nf = video ? T : 1;
uint16_t* o = dst + (video ? 0 : (int64_t)T * pp);
for (int t = 0; t < nf; ++t) {
const std::vector<float>& f = *frames[(size_t)(g * nf + t)];
for (int ch = 0; ch < 3; ++ch)
for (int y = 0; y < P; ++y)
for (int x = 0; x < P; ++x)
*o++ = norm(f[((size_t)(py0 + y) * W + px0 + x) * 3 + ch], ch);
}
dst += dim;
}
}
}
/* Radio's item geometry: finish_item's, with the prefix rows counted in the patches. */
void finish_item_radio(const VisionConfig& c, Item* it) {
it->patch_dim = c.patch_dim();
it->seg_prefix = c.radio_prefix;
it->rows_h = it->grid_h / c.merge;
it->rows_w = it->grid_w / c.merge;
it->seg_rows = it->rows_h * it->rows_w;
it->n_seg = it->grid_t;
it->n_patch = (int64_t)it->grid_t * (c.radio_prefix + (int64_t)it->grid_h * it->grid_w);
}
void finish_item(const VisionConfig& c, Item* it) { void finish_item(const VisionConfig& c, Item* it) {
it->patch_dim = c.patch_dim(); it->patch_dim = c.patch_dim();
it->n_patch = (int64_t)it->grid_t * it->grid_h * it->grid_w; it->n_patch = (int64_t)it->grid_t * it->grid_h * it->grid_w;
@@ -1153,6 +1396,26 @@ int Processor::init(const VisionConfig& cfg,
encode_text_ = std::move(encode_text); encode_text_ = std::move(encode_text);
return RAD_OK; return RAD_OK;
} }
if (cfg.family == Family::Radio) {
/* The markers around a run are vocabulary words, not config ids. A tile is one segment of
* one pass with its prefix rows, so the picture budget is lowered to what a pass holds;
* a video frame's target must fit as it is. */
if (!token_id) return RAD_E_INVAL;
cfg_.tok_start = token_id("<img>");
cfg_.tok_end = token_id("</img>");
if (cfg_.tok_start < 0 || cfg_.tok_end < 0) return RAD_E_NOTFOUND;
const int64_t cap = cfg.max_patches - cfg.radio_prefix;
if (cap < cfg.radio_min_patches || cap < cfg.radio_video_patches) return RAD_E_INVAL;
if (cfg_.radio_max_patches > cap) cfg_.radio_max_patches = (int32_t)cap;
/* A video's budget: max_frames frames in tubelets, each its prefix plus the frame target
* (the video tile never exceeds it). */
if (cfg_.max_video_patches <= 0)
cfg_.max_video_patches = (int64_t)((cfg.max_frames + cfg.radio_tubelet - 1) /
cfg.radio_tubelet) *
(cfg.radio_prefix + cfg.radio_video_patches);
encode_text_ = std::move(encode_text);
return RAD_OK;
}
if (cfg.family == Family::Glm5Next) { if (cfg.family == Family::Glm5Next) {
/* A token is merge^2 patches and an image is one segment of one pass, so the budget is /* A token is merge^2 patches and an image is one segment of one pass, so the budget is
* lowered to what a pass holds. */ * lowered to what a pass holds. */
@@ -1712,6 +1975,99 @@ int Processor::image_pixtral(const Frame& f, std::shared_ptr<Item>* out, std::st
return RAD_OK; return RAD_OK;
} }
/* NVIDIA's Nemotron-H Omni image processor: one tile, sized by radio_size, resized with torch's
* antialiased bicubic on float pixels (none when the size already fits). */
int Processor::image_radio(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const {
const VisionConfig& c = cfg_;
int32_t wp = 0, hp = 0;
radio_size(f.w, f.h, c, &wp, &hp);
std::vector<float> px;
resize_bicubic_aa_f32(f, wp * c.patch, hp * c.patch, &px);
auto it = std::make_shared<Item>();
it->kind = Kind::Image;
it->grid_t = 1;
it->grid_h = hp;
it->grid_w = wp;
it->rope_1d = true;
finish_item_radio(c, it.get());
if (it->n_patch > c.max_patches) {
if (why) *why = "the image resizes to more patches than one encoder pass holds";
return RAD_E_INVAL;
}
patchify_radio(c, { &px }, false, it.get());
one_run(it.get(), c.tok_start, it->seg_rows, c.tok_image, c.tok_end);
*out = std::move(it);
return RAD_OK;
}
/* Its video path: every frame at the video tile (radio_video_size of the first), `tubelet`
* frames a segment (the last repeated to fill one), each run labelled as the reference processor
* labels a tubelet -- "Frame i sampled at T seconds and frame i+1 sampled at T' seconds: ", T the
* frame's source index times int(1000 / fps) ms -- the runs joined by a newline. No pruning (EVS):
* every tubelet keeps all its rows. */
int Processor::video_radio(const Video& v, std::shared_ptr<Item>* out, std::string* why) const {
const VisionConfig& c = cfg_;
if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; }
int32_t wp = 0, hp = 0;
radio_video_size(v.frames[0].w, v.frames[0].h, c, &wp, &hp);
const int32_t T = c.radio_tubelet;
const int64_t nf = (int64_t)v.frames.size();
auto it = std::make_shared<Item>();
it->kind = Kind::Video;
it->grid_t = (int32_t)((nf + T - 1) / T);
it->grid_h = hp;
it->grid_w = wp;
it->rope_1d = true;
finish_item_radio(c, it.get());
if (c.radio_prefix + (int64_t)hp * wp > c.max_patches) {
if (why) *why = "a video frame resizes to more patches than one encoder pass holds";
return RAD_E_INVAL;
}
if (it->n_patch > c.max_video_patches) {
if (why) *why = "the video is over the server's patch budget for one video";
return RAD_E_INVAL;
}
std::vector<std::vector<float>> resized((size_t)nf);
for (int64_t i = 0; i < nf; ++i)
resize_bicubic_aa_f32(v.frames[(size_t)i], wp * c.patch, hp * c.patch, &resized[(size_t)i]);
std::vector<const std::vector<float>*> frames;
for (int64_t i = 0; i < (int64_t)it->grid_t * T; ++i)
frames.push_back(&resized[(size_t)std::min(i, nf - 1)]);
patchify_radio(c, frames, true, it.get());
content_key(*it, &it->key_hi, &it->key_lo);
const int64_t frame_ms = v.info.fps > 0.0 ? (int64_t)(1000.0 / v.info.fps) : 0;
for (int32_t g = 0; g < it->grid_t; ++g) {
std::string label = g > 0 ? "\n" : "";
for (int32_t j = 0; j < T; ++j) {
const int64_t fi = (int64_t)g * T + j;
if (fi >= nf) break;
char part[96];
if (frame_ms > 0)
std::snprintf(part, sizeof part, "%s%s %lld sampled at %.2f seconds",
j ? " and " : "", j ? "frame" : "Frame", (long long)(fi + 1),
(double)(v.index[(size_t)fi] * frame_ms) / 1000.0);
else
std::snprintf(part, sizeof part, "%s%s %lld", j ? " and " : "",
j ? "frame" : "Frame", (long long)(fi + 1));
label += part;
}
label += ": ";
const std::vector<int32_t> tt = encode_text_ ? encode_text_(label) : std::vector<int32_t>{};
if (tt.empty()) {
if (why) *why = "the tokenizer produced nothing for a video frame label";
return RAD_E_STATE;
}
it->expand.insert(it->expand.end(), tt.begin(), tt.end());
it->expand.push_back(c.tok_start);
it->seg_at.push_back((int32_t)it->expand.size());
it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_image);
it->expand.push_back(c.tok_end);
}
*out = std::move(it);
return RAD_OK;
}
int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why, int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why,
const ImageMode& mode) const { const ImageMode& mode) const {
const VisionConfig& c = cfg_; const VisionConfig& c = cfg_;
@@ -1723,6 +2079,7 @@ int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::strin
if (c.family == Family::Pixtral) return image_pixtral(f, out, why); if (c.family == Family::Pixtral) return image_pixtral(f, out, why);
if (c.family == Family::Lfm2) return image_lfm2(f, out, why); if (c.family == Family::Lfm2) return image_lfm2(f, out, why);
if (c.family == Family::Glm5Next) return image_glm5next(f, out, why); if (c.family == Family::Glm5Next) return image_glm5next(f, out, why);
if (c.family == Family::Radio) return image_radio(f, out, why);
if (c.family == Family::UnlimitedOcr) return image_unlimitedocr(f, mode, out, why); if (c.family == Family::UnlimitedOcr) return image_unlimitedocr(f, mode, out, why);
int64_t h = 0, w = 0; int64_t h = 0, w = 0;
RAD_TRY(smart_resize_image(f.h, f.w, c.factor(), c.image_min_pixels, c.image_max_pixels, RAD_TRY(smart_resize_image(f.h, f.w, c.factor(), c.image_min_pixels, c.image_max_pixels,
@@ -1816,6 +2173,7 @@ int Processor::video_gemma4(const Video& v, std::shared_ptr<Item>* out, std::str
int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const { int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const {
const VisionConfig& c = cfg_; const VisionConfig& c = cfg_;
if (c.family == Family::Gemma4) return video_gemma4(v, out, why); if (c.family == Family::Gemma4) return video_gemma4(v, out, why);
if (c.family == Family::Radio) return video_radio(v, out, why);
if (c.family == Family::Glm5Next || c.family == Family::Pixtral) { if (c.family == Family::Glm5Next || c.family == Family::Pixtral) {
if (why) *why = "this model's processor takes pictures, not video"; if (why) *why = "this model's processor takes pictures, not video";
return RAD_E_UNSUPPORTED; return RAD_E_UNSUPPORTED;
@@ -2131,12 +2489,40 @@ static int qwen3asr_from_meta(const RadModelMeta& m, AudioConfig* c, std::string
return RAD_OK; return RAD_OK;
} }
/* Gemma4UnifiedAudioFeatureExtractor's framing (Gemma 4 12B): processor_config.json's
* `feature_extractor` and the clip cap `audio_seq_length` (in frames). The frame's width is what the
* embedder takes, so it stands in `n_mels` as a mel spectrum's bins do. */
static int unified_from_meta(const RadModelMeta& m, AudioConfig* c, std::string* why) {
c->family = AudioFamily::Gemma4Unified;
c->rate = (int32_t)rad_meta_geti(&m, "processor.feature_extractor.sampling_rate", 16000);
c->frame_length = (int32_t)rad_meta_geti(
&m, "processor.feature_extractor.audio_samples_per_token",
rad_meta_geti(&m, "audio_config.audio_samples_per_token",
rad_meta_geti(&m, "audio_config.audio_embed_dim", 0)));
c->hop = c->frame_length;
c->n_mels = c->frame_length;
c->max_samples = rad_meta_geti(&m, "processor.audio_seq_length", 750) * c->frame_length;
c->tok_audio = (int32_t)rad_meta_geti(&m, "audio_token_id", -1);
c->tok_start = (int32_t)rad_meta_geti(&m, "boa_token_id", -1);
c->tok_end = (int32_t)rad_meta_geti(&m, "eoa_token_id",
rad_meta_geti(&m, "eoa_token_index", -1));
if (c->rate <= 0 || c->frame_length <= 0 || c->max_samples <= 0 || c->tok_audio < 0 ||
c->tok_start < 0 || c->tok_end < 0) {
if (why) *why = "the container's audio framing is incomplete (sampling_rate, "
"audio_samples_per_token, audio_seq_length, audio_token_id, boa_token_id, "
"eoa_token_id)";
return RAD_E_INVAL;
}
return RAD_OK;
}
int AudioConfig::from_meta(const RadModelMeta& m, std::string* why) { int AudioConfig::from_meta(const RadModelMeta& m, std::string* why) {
const char* mt = rad_meta_gets(&m, "audio_config.model_type", ""); const char* mt = rad_meta_gets(&m, "audio_config.model_type", "");
if (mt && !std::strcmp(mt, "qwen3_asr_encoder")) return qwen3asr_from_meta(m, this, why); if (mt && !std::strcmp(mt, "qwen3_asr_encoder")) return qwen3asr_from_meta(m, this, why);
if (mt && !std::strcmp(mt, "gemma4_unified_audio")) return unified_from_meta(m, this, why);
if (!mt || std::strcmp(mt, "gemma4_audio")) { if (!mt || std::strcmp(mt, "gemma4_audio")) {
if (why) *why = "the container states no audio tower this processor knows (audio_config." if (why) *why = "the container states no audio tower this processor knows (audio_config."
"model_type gemma4_audio or qwen3_asr_encoder)"; "model_type gemma4_audio, gemma4_unified_audio or qwen3_asr_encoder)";
return RAD_E_NOTFOUND; return RAD_E_NOTFOUND;
} }
/* preprocessor_config.json's keys (`preprocessor.`), else processor_config.json's /* preprocessor_config.json's keys (`preprocessor.`), else processor_config.json's
@@ -2273,6 +2659,12 @@ int Processor::init_audio(const AudioConfig& cfg, std::string* why) {
return refuse(RAD_E_INVAL, "the audio encoder's pass (" + std::to_string(cfg.max_frames) + return refuse(RAD_E_INVAL, "the audio encoder's pass (" + std::to_string(cfg.max_frames) +
" frames) is not whole rows of " + " frames) is not whole rows of " +
std::to_string(cfg.merge) + " frames"); std::to_string(cfg.merge) + " frames");
/* The 12B's frames are samples: no window, no FFT, no mel bank. */
if (cfg.family == AudioFamily::Gemma4Unified) {
acfg_ = cfg;
audio_on_ = true;
return RAD_OK;
}
const bool qwen = cfg.family == AudioFamily::Qwen3ASR; const bool qwen = cfg.family == AudioFamily::Qwen3ASR;
/* Gemma 4's FFT is radix 2; Qwen3-ASR's runs mixed radix over any length. */ /* Gemma 4's FFT is radix 2; Qwen3-ASR's runs mixed radix over any length. */
if (!qwen && (cfg.fft < 2 || (cfg.fft & (cfg.fft - 1)) != 0)) if (!qwen && (cfg.fft < 2 || (cfg.fft & (cfg.fft - 1)) != 0))
@@ -2481,11 +2873,44 @@ int Processor::audio_qwen3asr(const std::vector<float>& samples, std::shared_ptr
return RAD_OK; return RAD_OK;
} }
/* The 12B's clip (AudioFamily::Gemma4Unified): ceil(n / frame_length) frames of samples, the last
* zero-padded, each sample rounded to bf16 as the reference casts the frames for its embedder; one
* frame a placeholder. The reference cuts nothing; a clip past `max_samples` is cut there. */
int Processor::audio_unified(const std::vector<float>& samples, std::shared_ptr<Item>* out,
std::string* why) const {
const AudioConfig& c = acfg_;
const int64_t n = std::min<int64_t>((int64_t)samples.size(), c.max_samples);
const int64_t fl = c.frame_length, rows = (n + fl - 1) / fl;
if (rows * c.merge > c.max_frames) {
if (why) *why = "the clip is more frames than one audio encoder pass holds";
return RAD_E_INVAL;
}
auto it = std::make_shared<Item>();
it->kind = Kind::Audio;
it->grid_t = 1;
it->grid_h = (int32_t)rows;
it->grid_w = 1;
it->patch_dim = fl;
it->n_patch = rows;
it->valid = (int32_t)rows;
it->rows_h = (int32_t)rows;
it->rows_w = 1;
it->seg_rows = (int32_t)rows;
it->n_seg = rows > 0 ? 1 : 0;
it->pixels.assign((size_t)(rows * fl), 0);
for (int64_t i = 0; i < n; ++i) it->pixels[(size_t)i] = rad_f32_to_bf16(samples[(size_t)i]);
one_run(it.get(), c.tok_start, rows, c.tok_audio, c.tok_end);
if (rows == 0) it->encoded = true;
*out = std::move(it);
return RAD_OK;
}
int Processor::audio_from(const std::vector<float>& samples, std::shared_ptr<Item>* out, int Processor::audio_from(const std::vector<float>& samples, std::shared_ptr<Item>* out,
std::string* why) const { std::string* why) const {
if (!audio_on_) { if (why) *why = "this program declares no audio encoder"; return RAD_E_UNSUPPORTED; } if (!audio_on_) { if (why) *why = "this program declares no audio encoder"; return RAD_E_UNSUPPORTED; }
const AudioConfig& c = acfg_; const AudioConfig& c = acfg_;
if (c.family == AudioFamily::Qwen3ASR) return audio_qwen3asr(samples, out, why); if (c.family == AudioFamily::Qwen3ASR) return audio_qwen3asr(samples, out, why);
if (c.family == AudioFamily::Gemma4Unified) return audio_unified(samples, out, why);
const int64_t n = std::min<int64_t>((int64_t)samples.size(), c.max_samples); const int64_t n = std::min<int64_t>((int64_t)samples.size(), c.max_samples);
const int64_t real = c.real_frames(n); const int64_t real = c.real_frames(n);
const int64_t rows = (real + c.merge - 1) / c.merge; const int64_t rows = (real + c.merge - 1) / c.merge;
+49 -5
View File
@@ -50,6 +50,8 @@ enum class Kind { Image, Video, Audio };
* channel) as 2 * (u / 255) - 1, the reference model's own input scaling; a video is * channel) as 2 * (u / 255) - 1, the reference model's own input scaling; a video is
* frames sampled at `fps` (at most `max_frames`, thinned evenly), each its own segment * frames sampled at `fps` (at most `max_frames`, thinned evenly), each its own segment
* at the per-frame budget, each spelled <boi> placeholders <eoi> with no timestamp. * at the per-frame budget, each spelled <boi> placeholders <eoi> with no timestamp.
* Gemma 4 12B ("unified", no tower) is the same with a whole pooling window as one
* patch (patch = 48, merge 1) and its values u / 255 (`unit_pixels`).
* Lfm2 LFM2-VL's: a picture within its token budget (times a tolerance) is resized whole -- * Lfm2 LFM2-VL's: a picture within its token budget (times a tolerance) is resized whole --
* sides multiples of patch * merge, pixels within the budget's band -- and one past it * sides multiples of patch * merge, pixels within the budget's band -- and one past it
* is cut into tile x tile crops, min_tiles..max_tiles of them in the ratio nearest its * is cut into tile x tile crops, min_tiles..max_tiles of them in the ratio nearest its
@@ -79,8 +81,19 @@ enum class Kind { Image, Video, Audio };
* Pixtral Nemotron 3.5's noncausal Mistral3 wrapper: longest-edge resize, then ceil each side * Pixtral Nemotron 3.5's noncausal Mistral3 wrapper: longest-edge resize, then ceil each side
* to patch * merge; PIL bicubic and CLIP normalization. Raster (channel, y, x) patches; * to patch * merge; PIL bicubic and CLIP normalization. Raster (channel, y, x) patches;
* image placeholders per merged grid row, each followed by IMG_BREAK (last: IMG_END). * image placeholders per merged grid row, each followed by IMG_BREAK (last: IMG_END).
* Every token has ordinary 1-D positions, and separators retain their token embedding. */ * Every token has ordinary 1-D positions, and separators retain their token embedding.
enum class Family { QwenVL, Gemma4, Lfm2, UnlimitedOcr, Glm5Next, Pixtral }; * Radio NVIDIA's Nemotron-H Omni with C-RADIO: a picture becomes one tile whose patch grid
* falls between min_num_patches and max_num_patches, aspect ratio kept and both sides
* even (the pixel shuffle's factor), resized with torch's antialiased bicubic on float
* pixels; a video frame the same at about video_target_num_patches. Values are
* (u / 255 - mean) / std in f32, rounded to bf16. A patch row is the tubelet's frames
* (frame, channel, y, x) and then the picture's (channel, y, x), the part not in use
* zero, so one embedding GEMM serves both projections. Each segment carries `n_prefix`
* zero rows ahead of its patches, which the tower fills with its class and register
* tokens. Pictures are spelled <img> placeholders </img>; a video one such run a
* tubelet, each after its "Frame i sampled at T seconds and frame i+1 ...: " label,
* runs joined by a newline. Tokens at their positions (NoPE). */
enum class Family { QwenVL, Gemma4, Lfm2, UnlimitedOcr, Glm5Next, Pixtral, Radio };
struct VisionConfig { struct VisionConfig {
Family family = Family::QwenVL; Family family = Family::QwenVL;
@@ -88,6 +101,8 @@ struct VisionConfig {
/* Gemma4: soft tokens (output rows) an image and a video frame may take. One of 70, 140, /* Gemma4: soft tokens (output rows) an image and a video frame may take. One of 70, 140,
* 280, 560, 1120, the budgets the model was trained at. */ * 280, 560, 1120, the budgets the model was trained at. */
int32_t image_soft_tokens = 0, video_soft_tokens = 0; int32_t image_soft_tokens = 0, video_soft_tokens = 0;
/* Gemma4: patch values u / 255 rather than 2 * (u / 255) - 1 (the 12B's embedder). */
bool unit_pixels = false;
int64_t image_min_pixels = 0, image_max_pixels = 0; int64_t image_min_pixels = 0, image_max_pixels = 0;
int64_t video_min_pixels = 0, video_max_pixels = 0; int64_t video_min_pixels = 0, video_max_pixels = 0;
/* Glm5Next: the band an image's canvas falls in, in output rows (tokens). */ /* Glm5Next: the band an image's canvas falls in, in output rows (tokens). */
@@ -104,6 +119,11 @@ struct VisionConfig {
/* Lfm2: the tiling (see Family). `max_segment_patches` is the tower's longest segment. */ /* Lfm2: the tiling (see Family). `max_segment_patches` is the tower's longest segment. */
int32_t min_tiles = 0, max_tiles = 0, tile = 0; int32_t min_tiles = 0, max_tiles = 0, tile = 0;
bool use_thumbnail = false; bool use_thumbnail = false;
/* Radio: a picture's patch budget [radio_min_patches, radio_max_patches] (with the global cap
* radio_max_len tokens), the per-frame target of a video, the frames a tubelet packs and the
* learned rows (class and register tokens) a segment carries ahead of its patches. */
int32_t radio_min_patches = 0, radio_max_patches = 0, radio_max_len = 0;
int32_t radio_video_patches = 0, radio_tubelet = 0, radio_prefix = 0;
double max_pixels_tolerance = 0.0; double max_pixels_tolerance = 0.0;
int64_t max_segment_patches = 0; int64_t max_segment_patches = 0;
@@ -135,7 +155,11 @@ struct VisionConfig {
* engine again after command-line overrides. */ * engine again after command-line overrides. */
int check(std::string* why) const; int check(std::string* why) const;
int64_t patch_dim() const { return 3LL * temporal * patch * patch; } int64_t patch_dim() const {
/* Radio's row is a tubelet's frames and then the picture's patch (Family::Radio). */
if (family == Family::Radio) return 3LL * (1 + radio_tubelet) * patch * patch;
return 3LL * temporal * patch * patch;
}
int32_t factor() const { return patch * merge; } int32_t factor() const { return patch * merge; }
/* Read from the container; refuses one with no vision tower. Processor-only keys the /* Read from the container; refuses one with no vision tower. Processor-only keys the
@@ -165,6 +189,9 @@ struct ImageMode {
* through an fft-point FFT, magnitudes through an HTK mel bank, log(x + mel_floor). * through an fft-point FFT, magnitudes through an HTK mel bank, log(x + mel_floor).
* The clip's real frames, then zero frames to whole output rows. * The clip's real frames, then zero frames to whole output rows.
* *
* Gemma4Unified Gemma4UnifiedAudioFeatureExtractor (the 12B's): no spectrum; a frame is
* `frame_length` samples as they are, the last zero-padded, one frame a row.
*
* Qwen3ASR Qwen3ASRFeatureExtractor (Whisper's): a clip shorter than `min_samples` is * Qwen3ASR Qwen3ASRFeatureExtractor (Whisper's): a clip shorter than `min_samples` is
* zero-padded to it; frames are torch.stft's, centred with a reflected n_fft / 2 at * zero-padded to it; frames are torch.stft's, centred with a reflected n_fft / 2 at
* each end, a periodic Hann window and power spectra, the last frame dropped, so n * each end, a periodic Hann window and power spectra, the last frame dropped, so n
@@ -176,7 +203,7 @@ struct ImageMode {
* padding, and, where that exceeds a whole chunk, frames past it that the encoder * padding, and, where that exceeds a whole chunk, frames past it that the encoder
* reads as zero. Plane 1 of the coordinates marks those (RadBatch::enc_coord), which * reads as zero. Plane 1 of the coordinates marks those (RadBatch::enc_coord), which
* keeps one chunk's convolution from seeing the next. */ * keeps one chunk's convolution from seeing the next. */
enum class AudioFamily { Gemma4, Qwen3ASR }; enum class AudioFamily { Gemma4, Qwen3ASR, Gemma4Unified };
/* Audio features, configured from the container: Gemma 4's framing from `preprocessor.*` (the /* Audio features, configured from the container: Gemma 4's framing from `preprocessor.*` (the
* checkpoint's preprocessor_config.json), Qwen3-ASR's from `processor.feature_extractor.*` * checkpoint's preprocessor_config.json), Qwen3-ASR's from `processor.feature_extractor.*`
@@ -257,6 +284,10 @@ struct Item {
/* Patches are in raster order (row by row), not merge-block order: the coordinate planes /* Patches are in raster order (row by row), not merge-block order: the coordinate planes
* invert the one or the other (Unlimited-OCR's tower reads a picture patch by patch). */ * invert the one or the other (Unlimited-OCR's tower reads a picture patch by patch). */
bool patch_raster = false; bool patch_raster = false;
/* Rows ahead of each segment's patches that the encoder fills itself (Family::Radio: C-RADIO's
* class and register tokens): zero pixels, coordinate (-1, k), counted in patch_at and
* n_patch but never in a segment's output rows. */
int32_t seg_prefix = 0;
int32_t seg_h(int32_t s) const { return segments.empty() ? grid_h : segments[(size_t)s].h; } int32_t seg_h(int32_t s) const { return segments.empty() ? grid_h : segments[(size_t)s].h; }
int32_t seg_w(int32_t s) const { return segments.empty() ? grid_w : segments[(size_t)s].w; } int32_t seg_w(int32_t s) const { return segments.empty() ? grid_w : segments[(size_t)s].w; }
@@ -265,7 +296,7 @@ struct Item {
bool seg_is_sep(int32_t s) const { return !segments.empty() && segments[(size_t)s].sep; } bool seg_is_sep(int32_t s) const { return !segments.empty() && segments[(size_t)s].sep; }
/* Segment s's first patch and first output row; s == n_seg is the end of the item. */ /* Segment s's first patch and first output row; s == n_seg is the end of the item. */
int64_t patch_at(int32_t s) const { int64_t patch_at(int32_t s) const {
if (segments.empty()) return (int64_t)s * grid_h * grid_w; if (segments.empty()) return (int64_t)s * (seg_prefix + (int64_t)grid_h * grid_w);
return s >= n_seg ? n_patch : segments[(size_t)s].patch0; return s >= n_seg ? n_patch : segments[(size_t)s].patch0;
} }
int64_t row_at(int32_t s) const { int64_t row_at(int32_t s) const {
@@ -424,6 +455,8 @@ private:
std::string* why) const; std::string* why) const;
int image_glm5next(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const; int image_glm5next(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
int image_pixtral(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const; int image_pixtral(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
int image_radio(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
int video_radio(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
/* Lfm2's markers: <|img_thumbnail|>, and <|img_row_R_col_C|> at (R-1) * max_tiles + C-1. */ /* Lfm2's markers: <|img_thumbnail|>, and <|img_row_R_col_C|> at (R-1) * max_tiles + C-1. */
int32_t tok_thumbnail_ = -1; int32_t tok_thumbnail_ = -1;
std::vector<int32_t> tok_tiles_; std::vector<int32_t> tok_tiles_;
@@ -434,6 +467,8 @@ private:
bool audio_on_ = false; bool audio_on_ = false;
int audio_qwen3asr(const std::vector<float>& samples, std::shared_ptr<Item>* out, int audio_qwen3asr(const std::vector<float>& samples, std::shared_ptr<Item>* out,
std::string* why) const; std::string* why) const;
int audio_unified(const std::vector<float>& samples, std::shared_ptr<Item>* out,
std::string* why) const;
std::vector<float> hann_; /* the window, float32 as the reference stores it */ std::vector<float> hann_; /* the window, float32 as the reference stores it */
std::vector<double> mel_; /* [n_mels, fft/2 + 1]: filter b's weight on bin k */ std::vector<double> mel_; /* [n_mels, fft/2 + 1]: filter b's weight on bin k */
@@ -459,6 +494,15 @@ std::vector<int64_t> sample_frames_gemma4(const VideoInfo& info, double fps, int
* within `max_patches`, aspect ratio kept (get_aspect_ratio_preserving_size). */ * within `max_patches`, aspect ratio kept (get_aspect_ratio_preserving_size). */
int gemma4_size(int64_t h, int64_t w, int32_t patch, int32_t pool, int64_t max_patches, int gemma4_size(int64_t h, int64_t w, int32_t patch, int32_t pool, int64_t max_patches,
int64_t* oh, int64_t* ow, std::string* why); int64_t* oh, int64_t* ow, std::string* why);
/* Radio's tile for a picture of w x h pixels (NVIDIA's _compute_target_patches, Python's
* round-half-even included) and for a video frame (_compute_target_patches_video), in patches. */
void radio_size(int64_t w, int64_t h, const VisionConfig& c, int32_t* wp, int32_t* hp);
void radio_video_size(int64_t w, int64_t h, const VisionConfig& c, int32_t* wp, int32_t* hp);
/* torch's F.interpolate(mode="bicubic", align_corners=False, antialias=True) of packed RGB bytes
* taken as float, without rounding or clamping: [h, w, 3] f32 in 0..255 give or take the
* filter's overshoot. Separable, width first, as ATen's CPU kernel; a side that keeps its size is
* the identity. */
void resize_bicubic_aa_f32(const Frame& in, int32_t w, int32_t h, std::vector<float>* out);
/* PIL's antialiased bicubic resample of packed RGB, bit for bit: fixed-point coefficients, a /* PIL's antialiased bicubic resample of packed RGB, bit for bit: fixed-point coefficients, a
* horizontal pass into an 8-bit intermediate and then a vertical one. */ * horizontal pass into an 8-bit intermediate and then a vertical one. */
void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out); void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out);
+221 -137
View File
@@ -334,6 +334,22 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
std::memset(calm_, 0, 8 << 20); std::memset(calm_, 0, 8 << 20);
} }
/* ---- the file tier's cache cycle (stage_file_units) -------------------------------------
*
* The stager covers the plan's file-tier units from the start; it may cover more
* (cover_file_units). Each layer's file-tier bytes start as the plan's, which the plan sized
* the stager's buffers for. */
file_ok_.assign(plan.units.size(), 0);
layer_file_.assign((size_t)std::max(n_layers_, 1), 0);
file_cap_ = file_buf_bytes_;
for (size_t u = 0; u < plan.units.size(); ++u) {
const MoveUnit& mu = plan.units[u];
if (mu.tier != Tier::SSD || mu.access != RAD_ACCESS_CONDITIONAL) continue;
file_ok_[u] = 1;
if (mu.layer >= 0) layer_file_[(size_t)mu.layer] += align_up(mu.bytes, RAD_ALIGN_UNIT);
}
victims_.assign(plan.classes.size(), VictimRank{});
/* ---- streams, events, move records ------------------------------------------------------ */ /* ---- streams, events, move records ------------------------------------------------------ */
RAD_TRY(rad_stream_create(&mover_, /*high_priority=*/0)); RAD_TRY(rad_stream_create(&mover_, /*high_priority=*/0));
/* Every event here is local: they order the mover's queue against this card's compute queue /* Every event here is local: they order the mover's queue against this card's compute queue
@@ -664,18 +680,6 @@ int64_t Mover::stage_need(const std::vector<int32_t>& units, int64_t* largest) c
/* ---- a routed layer read from the container (see mover.h) ---------------------------------- */ /* ---- a routed layer read from the container (see mover.h) ---------------------------------- */
namespace { namespace {
/* One weight's bytes: where they are in the container and where they go. */
struct FileExt {
int64_t foff = 0, bytes = 0;
char* dst = nullptr;
/* Into a hot-cache slot rather than the layer buffer: counted as
* ssd_promoted_bytes, and the copy leaves the unit resident. */
bool hot = false;
/* Into a host pool slot rather than the layer buffer: counted as
* ssd_deposit_bytes, and the copy leaves the unit resident in RAM. */
bool deposit = false;
};
/* The largest gap a run reads through instead of starting another pread. A routed layer's /* The largest gap a run reads through instead of starting another pread. A routed layer's
* weights sit together in the container, each on RAD_ALIGN_UNIT, so a gap between two file-tier * weights sit together in the container, each on RAD_ALIGN_UNIT, so a gap between two file-tier
* weights is either alignment padding (cheaper to read than a second pread) or units on another * weights is either alignment padding (cheaper to read than a second pread) or units on another
@@ -685,36 +689,125 @@ constexpr int64_t kReadThrough = (int64_t)256 << 10;
} /* namespace */ } /* namespace */
bool Mover::on_file_tier(const std::vector<int32_t>& units) const {
for (int32_t u : units) {
if (u < 0 || (size_t)u >= unit_.size()) continue;
const UnitState& us = unit_[(size_t)u];
if (us.tier == Tier::SSD && us.slab_slot < 0 && us.klass >= 0) return true;
}
return false;
}
bool Mover::routes_any(const std::vector<int32_t>& units, const int32_t* ecnt,
int32_t n_expert) const {
if (!plan_ || !ecnt) return !units.empty();
for (int32_t u : units) {
if (u < 0 || (size_t)u >= plan_->units.size()) continue;
const int32_t e = plan_->units[(size_t)u].expert;
if (e < 0 || e >= n_expert || ecnt[e] != 0) return true;
}
return false;
}
void Mover::cover_file_units(const std::vector<int32_t>& more) {
/* A unit whose container bytes are not its kernel's layout cannot be read back. */
for (int32_t u : more)
if (u >= 0 && (size_t)u < file_ok_.size() && plan_->units[(size_t)u].file_direct)
file_ok_[(size_t)u] = 1;
}
/* A full pool's relabel victim for a deposit of class `klass`: its coldest pooled unit that the
* file stager reads back (Mover::file_ok_), with nothing in flight, outside the `protect` layers,
* and whose layer's file-tier part still fits the stager's buffer with it. -1 when none, or when
* that unit is not colder than `below` (the unit being read): trading a pooled unit for a colder
* one would only make the next step read the warmer one from the drive.
*
* The protected layers are the one being read and any whose ops are about to be issued: a
* relabelled unit's weights are published at the zero region at once, so taking one of theirs
* would hand the next GEMM zeros for a routed expert. Every other layer is safe: one already
* issued this pass read the pool slot, which the quarantine keeps until those kernels are done,
* and a later one is read back by its own trigger, since the stager covers the unit. The
* routing counts protect nothing here: they are the counts of the layer being read, and indexing
* them by another layer's expert number protected a random set while a whole-layer read (no
* counts) protected nothing at all.
*
* The cap keeps every read of a layer within the stager's buffer: the plan sized it for the
* largest layer's file-tier part, and a relabel adds to its victim's. */
int32_t Mover::pick_victim(int32_t klass, const int32_t* protect, int n_protect, float below) {
if (klass < 0 || (size_t)klass >= victims_.size() || !heat_) return -1;
VictimRank& vr = victims_[(size_t)klass];
if (vr.at != dispatch_) {
vr.at = dispatch_;
vr.by_heat.clear();
for (int32_t v = 0; v < (int32_t)unit_.size(); ++v) {
const UnitState& vs = unit_[(size_t)v];
if (vs.klass != klass || vs.tier != Tier::HostPinned || vs.pool_slot < 0 ||
vs.slab_slot >= 0 || !file_ok_[(size_t)v])
continue;
vr.by_heat.push_back({ heat_->heat(v), v });
}
/* Hottest first; on equal heat the higher unit first, so the back is the coldest and,
* among equally cold ones, the lowest: the unit a scan keeping its first strict minimum
* would pick. */
std::sort(vr.by_heat.begin(), vr.by_heat.end(),
[](const std::pair<float, int32_t>& a, const std::pair<float, int32_t>& b) {
return a.first != b.first ? a.first > b.first : a.second > b.second;
});
}
for (size_t k = vr.by_heat.size(); k-- > 0;) {
const int32_t v = vr.by_heat[k].second;
if (v < 0) continue;
const UnitState& vs = unit_[(size_t)v];
/* Within a dispatch a unit leaves the pool only by a relabel, so one that is not there any
* more is gone for the rest of it. A copy in flight or a protected layer only waits. */
if (vs.klass != klass || vs.tier != Tier::HostPinned || vs.pool_slot < 0 ||
vs.slab_slot >= 0) {
vr.by_heat[k].second = -1;
continue;
}
if (copying_[(size_t)v]) continue;
const int32_t layer = plan_->units[(size_t)v].layer;
bool held = layer < 0 || (size_t)layer >= layer_file_.size();
for (int p = 0; p < n_protect && !held; ++p) held = protect[p] >= 0 && protect[p] == layer;
if (held) continue;
if (layer_file_[(size_t)layer] + align_up(vs.bytes, RAD_ALIGN_UNIT) > file_cap_) continue;
/* Every candidate further in is at least as warm. */
if (!(vr.by_heat[k].first < below)) return -1;
vr.by_heat[k].second = -1;
while (!vr.by_heat.empty() && vr.by_heat.back().second < 0) vr.by_heat.pop_back();
return v;
}
return -1;
}
int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_t cap, int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_t cap,
RadEvent after, RadEvent done, std::vector<int32_t>* staged, RadEvent after, RadEvent done, FileRead* rd, const int32_t* ecnt,
std::vector<int32_t>* skipped, const int32_t* ecnt, int32_t n_expert, const int32_t* protect, int n_protect) {
int32_t n_expert, std::vector<int32_t>* promoted) { if (!plan_ || !dst || !rd || !done) return RAD_E_INVAL;
if (!plan_ || !dst || !staged || !done) return RAD_E_INVAL;
staged->clear();
if (skipped) skipped->clear();
if (promoted) promoted->clear();
if (!file_.ok() || !windows_ || n_windows_ <= 0) return RAD_E_STATE; if (!file_.ok() || !windows_ || n_windows_ <= 0) return RAD_E_STATE;
/* The layout in `dst`, unit by unit in the order given, and every weight's extent. */ /* The layout in `dst`, unit by unit in the order given after what earlier calls for the
std::vector<FileExt> ext; * layer packed, and every weight's extent. */
std::vector<int64_t> at; fext_.clear();
std::vector<char*> pbases; /* hot-cache units' slot bases, in promoted order */ fat_.clear();
int64_t off = 0, hot_bytes = 0; fbase_.clear();
frec_.clear();
const size_t staged0 = rd->staged.size(), skipped0 = rd->skipped.size(),
promoted0 = rd->promoted.size();
const int64_t used0 = rd->used;
int64_t off = rd->used, hot_bytes = 0;
for (int32_t u : units) { for (int32_t u : units) {
if (u < 0 || (size_t)u >= unit_.size()) return RAD_E_INVAL; if (u < 0 || (size_t)u >= unit_.size()) return RAD_E_INVAL;
UnitState& us = unit_[(size_t)u]; UnitState& us = unit_[(size_t)u];
if (us.tier != Tier::SSD || us.slab_slot >= 0 || us.klass < 0) continue; if (us.tier != Tier::SSD || us.slab_slot >= 0 || us.klass < 0) continue;
/* Routing-aware reads: the layer's router has run by the time the stager triggers const MoveUnit& mu = plan_->units[(size_t)u];
* (the trigger is the layer's first expert op), so `ecnt` holds this pass's counts. /* Routing-aware reads: `ecnt` holds the counts of the rows about to run, taken at the
* An expert counted zero has no sorted rows, so no GEMM run names it and nothing * layer's trigger behind its router. An expert counted zero has no sorted rows, so no
* reads its weights: leave its bytes on the drive. The dummy publication below * GEMM run names it and nothing reads its weights: leave its bytes on the drive. The
* keeps every table entry valid for the pass. */ * dummy publication below keeps every table entry valid for the pass. */
if (ecnt && skipped) { if (ecnt && mu.expert >= 0 && mu.expert < n_expert && ecnt[mu.expert] == 0) {
const MoveUnit& mu = plan_->units[(size_t)u]; rd->skipped.push_back(u);
if (mu.expert >= 0 && mu.expert < n_expert && ecnt[mu.expert] == 0) { continue;
skipped->push_back(u);
continue;
}
} }
/* The hot VRAM cache: heat past the admission bar and a free /* The hot VRAM cache: heat past the admission bar and a free
* budgeted slot, and this pass's read lands in the slot and stays there. The read is * budgeted slot, and this pass's read lands in the slot and stays there. The read is
@@ -722,7 +815,7 @@ int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_
* bookkeeping (the container is ground truth), so a mistake costs one future * bookkeeping (the container is ground truth), so a mistake costs one future
* re-read. No free slot, no heat, or no move record: the buffer path below, as * re-read. No free slot, no heat, or no move record: the buffer path below, as
* before. */ * before. */
if (promoted && plan_->dynamic && heat_ && heat_->admit_hot(u) && !unit_in_flight(u)) { if (plan_->dynamic && heat_ && heat_->admit_hot(u) && !unit_in_flight(u)) {
ClassPools& cp = pools_[(size_t)us.klass]; ClassPools& cp = pools_[(size_t)us.klass];
const int rec = free_move_record(); const int rec = free_move_record();
int64_t slot = -1; int64_t slot = -1;
@@ -730,7 +823,6 @@ int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_
else slot = cp.slab.take_where([&](int64_t s) { return s < cp.n_fixed; }); else slot = cp.slab.take_where([&](int64_t s) { return s < cp.n_fixed; });
if (slot >= 0 && record_gate() < 0) { cp.slab.add_free(slot); slot = -1; } if (slot >= 0 && record_gate() < 0) { cp.slab.add_free(slot); slot = -1; }
if (slot >= 0) { if (slot >= 0) {
const MoveUnit& mu = plan_->units[(size_t)u];
char* const base = cp.slot_ptr(slot); char* const base = cp.slot_ptr(slot);
Move& m = moves_[(size_t)rec]; Move& m = moves_[(size_t)rec];
m.state = Move::State::Copying; m.state = Move::State::Copying;
@@ -746,74 +838,58 @@ int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_
for (size_t k = 0; k < mu.weights.size(); ++k) { for (size_t k = 0; k < mu.weights.size(); ++k) {
const WeightInfo& w = prog_->weights[mu.weights[k]]; const WeightInfo& w = prog_->weights[mu.weights[k]];
if (w.stored_bytes <= 0) continue; /* nothing to read, nothing to place */ if (w.stored_bytes <= 0) continue; /* nothing to read, nothing to place */
ext.push_back(FileExt{ (int64_t)w.file_offset, w.stored_bytes, fext_.push_back(FileExt{ (int64_t)w.file_offset, w.stored_bytes,
base + mu.offset[k], true }); base + mu.offset[k], true, false });
} }
promoted->push_back(u); rd->promoted.push_back(u);
pbases.push_back(base); fbase_.push_back(base);
frec_.push_back((int32_t)rec);
hot_bytes += us.bytes; hot_bytes += us.bytes;
continue; continue;
} }
} }
/* A free pool slot and this read deposits the unit into the pool -- the O_DIRECT /* A free pool slot and this read deposits the unit into the pool: its window's copy list
* read's destination IS the slot, and the unit becomes a pool unit: the GEMM reads it * carries it into the slot, and the unit becomes a pool unit -- the GEMM reads it
* zero-copy this step, heat promotes it at PCIe speed, and its demotion is a copyless * zero-copy this step, heat promotes it at PCIe speed, and its demotion is a copyless
* drop. The pool is ALL cache: no free slot and the coldest idle pool unit -- native * drop. The pool is all cache: with no free slot, its coldest unit the stager covers is
* or deposited, the container is ground truth for both -- relabels back to the file * relabelled back to the file tier, copyless (the container holds every unit's bytes),
* tier, copyless. Its slot feeds a future deposit after the * provided it is colder than this one (pick_victim). The slot it gives up feeds a later
* coldest idle pool unit -- native or deposited, the container is ground truth for both -- * deposit after the quarantine; this read takes the buffer path. */
* relabels back to the file tier, copyless. Its slot feeds a future deposit after the if (plan_->dynamic && heat_ && !unit_in_flight(u)) {
* quarantine; this read takes the buffer path. */
if (promoted && plan_->dynamic && heat_ && !unit_in_flight(u)) {
ClassPools& cp = pools_[(size_t)us.klass]; ClassPools& cp = pools_[(size_t)us.klass];
const int rec = free_move_record(); const int rec = free_move_record();
int64_t g = -1; int64_t g = -1;
if (rec < 0) ++stats_.no_record; if (rec < 0) ++stats_.no_record;
else if (record_gate() >= 0) g = cp.pool.take(); else if (record_gate() >= 0) g = cp.pool.take();
if (g < 0 && heat_) { if (g < 0 && rec >= 0) {
/* The pool is full. Eviction is a copyless relabel: the /* The deposit's own record is still free (nothing uses it this read), so the
* container holds every unit's bytes, so the victim loses nothing but its slot -- * relabel may take the same one. */
* it becomes a file-tier unit whose next read deposits again. The victim is the const int r2 = free_move_record();
* coldest idle unit of the class, however it got there: the cache adapts to the const int32_t victim =
* workload, not to where a unit started. The freed slot feeds a future deposit r2 >= 0 ? pick_victim(us.klass, protect, n_protect, heat_->heat(u)) : -1;
* after the quarantine; this read takes the buffer path. */
int32_t victim = -1;
float best = 0;
for (int32_t v = 0; v < (int32_t)unit_.size(); ++v) {
UnitState& vs = unit_[(size_t)v];
if (vs.klass != us.klass ||
vs.tier != Tier::HostPinned || vs.pool_slot < 0 ||
vs.slab_slot >= 0 || copying_[(size_t)v] || unit_in_flight(v))
continue;
const MoveUnit& mv = plan_->units[(size_t)v];
if (mv.expert >= 0 && mv.expert < n_expert && ecnt && ecnt[mv.expert] > 0)
continue; /* routed this pass: still wanted */
const float h = heat_->heat(v);
if (victim < 0 || h < best) { victim = v; best = h; }
}
if (victim >= 0) { if (victim >= 0) {
const int r2 = free_move_record(); UnitState& vs = unit_[(size_t)victim];
if (r2 >= 0) { const MoveUnit& mv = plan_->units[(size_t)victim];
UnitState& vs = unit_[(size_t)victim]; Move& m2 = moves_[(size_t)r2];
const MoveUnit& mv = plan_->units[(size_t)victim]; m2.state = Move::State::Published; /* nothing to copy: the drive has it */
Move& m2 = moves_[(size_t)r2]; m2.kind = Move::Kind::Evict;
m2.state = Move::State::Published; /* nothing to copy: the drive has it */ m2.unit = victim;
m2.kind = Move::Kind::Evict; m2.slab_slot = -1;
m2.unit = victim; m2.pool_slot = vs.pool_slot;
m2.slab_slot = -1; for (size_t k = 0; k < mv.weights.size(); ++k)
m2.pool_slot = vs.pool_slot; res_.publish(mv.weights[k], calm_);
for (size_t k = 0; k < mv.weights.size(); ++k) vs.tier = Tier::SSD;
res_.publish(mv.weights[k], calm_); vs.site = Site::DeviceStaged;
vs.tier = Tier::SSD; vs.pool_slot = -1;
vs.site = Site::DeviceStaged; layer_file_[(size_t)mv.layer] += align_up(vs.bytes, RAD_ALIGN_UNIT);
vs.pool_slot = -1; heat_->set_tier(victim, Tier::SSD);
heat_->set_tier(victim, Tier::SSD); /* No pool slot to promote from until a read deposits it again, which makes
++stats_.pool_evictions; * it movable once more; its layer's trigger reads it meanwhile. */
} heat_->set_movable(victim, false);
++stats_.pool_evictions;
} }
} }
if (g >= 0) { if (g >= 0) {
const MoveUnit& mu = plan_->units[(size_t)u];
Move& m = moves_[(size_t)rec]; Move& m = moves_[(size_t)rec];
m.state = Move::State::Copying; m.state = Move::State::Copying;
m.kind = Move::Kind::Deposit; m.kind = Move::Kind::Deposit;
@@ -824,20 +900,23 @@ int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_
us.pool_slot = g; us.pool_slot = g;
us.tier = Tier::HostPinned; us.tier = Tier::HostPinned;
us.site = Site::DeviceZeroCopy; us.site = Site::DeviceZeroCopy;
if (mu.layer >= 0 && (size_t)mu.layer < layer_file_.size())
layer_file_[(size_t)mu.layer] -= align_up(us.bytes, RAD_ALIGN_UNIT);
heat_->set_tier(u, Tier::HostPinned); heat_->set_tier(u, Tier::HostPinned);
heat_->set_movable(u, true); /* the slot makes it a PCIe-speed promotion candidate */ heat_->set_movable(u, true); /* the slot makes it a PCIe-speed promotion candidate */
heat_->set_busy(u, true); heat_->set_busy(u, true);
++stats_.ssd_deposits; ++stats_.ssd_deposits;
char* const slot = (char*)cp.pool_base + g * cp.stride;
for (size_t k = 0; k < mu.weights.size(); ++k) { for (size_t k = 0; k < mu.weights.size(); ++k) {
const WeightInfo& w = prog_->weights[mu.weights[k]]; const WeightInfo& w = prog_->weights[mu.weights[k]];
if (w.stored_bytes <= 0) continue; /* nothing to read, nothing to place */ if (w.stored_bytes <= 0) continue; /* nothing to read, nothing to place */
ext.push_back(FileExt{ (int64_t)w.file_offset, w.stored_bytes, fext_.push_back(FileExt{ (int64_t)w.file_offset, w.stored_bytes,
(char*)cp.pool_base + g * cp.stride + mu.offset[k], slot + mu.offset[k], false, true });
false, true });
} }
for (size_t k = 0; k < mu.weights.size(); ++k) for (size_t k = 0; k < mu.weights.size(); ++k)
res_.publish(mu.weights[k], res_.publish(mu.weights[k],
(char*)cp.pool_dev + g * cp.stride + mu.offset[k]); (char*)cp.pool_dev + g * cp.stride + mu.offset[k]);
frec_.push_back((int32_t)rec);
continue; continue;
} }
} }
@@ -847,42 +926,58 @@ int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_
"the plan sized for the largest one", humanb(cap).c_str()); "the plan sized for the largest one", humanb(cap).c_str());
return RAD_E_SCRATCH; return RAD_E_SCRATCH;
} }
const MoveUnit& mu = plan_->units[(size_t)u];
for (size_t k = 0; k < mu.weights.size(); ++k) { for (size_t k = 0; k < mu.weights.size(); ++k) {
const WeightInfo& w = prog_->weights[mu.weights[k]]; const WeightInfo& w = prog_->weights[mu.weights[k]];
if (w.stored_bytes <= 0) continue; /* nothing to read, and nothing to place */ if (w.stored_bytes <= 0) continue; /* nothing to read, and nothing to place */
ext.push_back(FileExt{ (int64_t)w.file_offset, w.stored_bytes, dst + off + mu.offset[k] }); fext_.push_back(FileExt{ (int64_t)w.file_offset, w.stored_bytes,
dst + off + mu.offset[k], false, false });
} }
staged->push_back(u); rd->staged.push_back(u);
at.push_back(off); fat_.push_back(off);
off += need; off += need;
} }
/* Skipped units' table entries must not name their stale addresses either: point them rd->used = off;
* into the layer buffer, whose base is a valid allocation no zero-count expert reads
* through (a dead row would read row 0 of a real expert's region and discard it). The /* Publish before the reads: nothing resolves these addresses until the caller's layer op,
* caller nulls them again with the staged units. Published even when EVERY unit of the * which waits on `done` first. Skipped units' entries must not name stale addresses either:
* layer was skipped -- a decode step can route nothing to a layer -- because the kernels * they point at the zero region, which no zero-count expert reads through (a dead row reads
* still issue the layer's table and a null entry fails the step. */ * zeros and discards them). Published even when EVERY unit of the layer was skipped -- a
if (skipped) { * decode step can route nothing to a layer -- because the kernels still issue the layer's
for (int32_t u : *skipped) { * table and a null entry fails the step. The caller nulls them again with the staged units.
const MoveUnit& mu = plan_->units[(size_t)u]; * Hot-cache units publish at their slots and stay published: nothing unstages them, and
for (size_t j = 0; j < mu.weights.size(); ++j) * retire() finishes their admission when the copies land. */
res_.publish(mu.weights[j], calm_); for (size_t k = skipped0; k < rd->skipped.size(); ++k) {
stats_.ssd_skipped_bytes += (uint64_t)unit_[(size_t)u].bytes; const int32_t u = rd->skipped[k];
} const MoveUnit& mu = plan_->units[(size_t)u];
stats_.ssd_skipped_units += (uint64_t)skipped->size(); for (size_t j = 0; j < mu.weights.size(); ++j) res_.publish(mu.weights[j], calm_);
stats_.ssd_skipped_bytes += (uint64_t)unit_[(size_t)u].bytes;
} }
if (ext.empty()) return RAD_OK; stats_.ssd_skipped_units += (uint64_t)(rd->skipped.size() - skipped0);
for (size_t k = staged0; k < rd->staged.size(); ++k) {
const int32_t u = rd->staged[k];
const MoveUnit& mu = plan_->units[(size_t)u];
for (size_t j = 0; j < mu.weights.size(); ++j)
res_.publish(mu.weights[j], dst + fat_[k - staged0] + mu.offset[j]);
stats_.ssd_read_bytes += (uint64_t)unit_[(size_t)u].bytes;
}
for (size_t k = promoted0; k < rd->promoted.size(); ++k) {
const int32_t u = rd->promoted[k];
const MoveUnit& mu = plan_->units[(size_t)u];
for (size_t j = 0; j < mu.weights.size(); ++j)
res_.publish(mu.weights[j], fbase_[k - promoted0] + mu.offset[j]);
stats_.ssd_read_bytes += (uint64_t)unit_[(size_t)u].bytes;
}
if (fext_.empty()) return RAD_OK;
/* Container order, so a window is one long run of the drive rather than a seek per weight. */ /* Container order, so a window is one long run of the drive rather than a seek per weight. */
std::stable_sort(ext.begin(), ext.end(), std::stable_sort(fext_.begin(), fext_.end(),
[](const FileExt& a, const FileExt& b) { return a.foff < b.foff; }); [](const FileExt& a, const FileExt& b) { return a.foff < b.foff; });
/* The dashboard's SSD panel and /stats ssd_reads read these: the file tier's container /* The dashboard's SSD panel and /stats ssd_reads read these: the file tier's container
* reads are the expert SSD traffic the metric names. The scheduled prefetch path counted * reads are the expert SSD traffic the metric names. The scheduled prefetch path counted
* its own link reads here; the file stager's were invisible, so the panels showed zero * its own link reads here; the file stager's were invisible, so the panels showed zero
* however much the drive streamed. */ * however much the drive streamed. */
stats_.ssd_reads += (uint64_t)ext.size(); stats_.ssd_reads += (uint64_t)fext_.size();
for (const FileExt& e : ext) { for (const FileExt& e : fext_) {
stats_.ssd_bytes += (uint64_t)e.bytes; stats_.ssd_bytes += (uint64_t)e.bytes;
/* The copies below move the same bytes from the windows to their destination, which /* The copies below move the same bytes from the windows to their destination, which
* crosses the link either way: into the layer buffer when the unit is discarded at the * crosses the link either way: into the layer buffer when the unit is discarded at the
@@ -902,8 +997,8 @@ int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_
std::vector<Seg> segs; std::vector<Seg> segs;
std::vector<Cp> cps; std::vector<Cp> cps;
size_t i = 0; size_t i = 0;
int64_t piece = 0; /* bytes of ext[i] already placed */ int64_t piece = 0; /* bytes of fext_[i] already placed */
while (i < ext.size()) { while (i < fext_.size()) {
const int w = win_next_; const int w = win_next_;
win_next_ = (win_next_ + 1) % n_windows_; win_next_ = (win_next_ + 1) % n_windows_;
char* win = windows_ + (int64_t)w * W; char* win = windows_ + (int64_t)w * W;
@@ -921,8 +1016,8 @@ int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_
* cannot finish across this window and the next. */ * cannot finish across this window and the next. */
segs.clear(); segs.clear();
cps.clear(); cps.clear();
while (i < ext.size()) { while (i < fext_.size()) {
const FileExt& e = ext[i]; const FileExt& e = fext_[i];
const int64_t fo = e.foff + piece, left = e.bytes - piece; const int64_t fo = e.foff + piece, left = e.bytes - piece;
int64_t wo; int64_t wo;
if (!segs.empty() && fo >= segs.back().fs && fo <= segs.back().fe + kReadThrough) { if (!segs.empty() && fo >= segs.back().fs && fo <= segs.back().fe + kReadThrough) {
@@ -958,26 +1053,14 @@ int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_
win_rec_[(size_t)w] = 1; win_rec_[(size_t)w] = 1;
} }
RAD_TRY(rad_event_record(done, mover_)); RAD_TRY(rad_event_record(done, mover_));
/* The hot-cache admissions and deposits are copies like the staged units': their records
* land behind them, so retire() finishes a move when its bytes are in its slot. */
for (int32_t rec : frec_) RAD_TRY(rad_event_record(moves_[(size_t)rec].ev, mover_));
rd->copied = true;
for (size_t k = 0; k < staged->size(); ++k) {
const int32_t u = (*staged)[k];
const MoveUnit& mu = plan_->units[(size_t)u];
for (size_t j = 0; j < mu.weights.size(); ++j)
res_.publish(mu.weights[j], dst + at[k] + mu.offset[j]);
stats_.ssd_read_bytes += (uint64_t)unit_[(size_t)u].bytes;
}
/* Hot-cache units publish at their slots and stay published: nothing unstages them, and
* retire() finishes their admission when the copies land. */
for (size_t k = 0; k < pbases.size(); ++k) {
const int32_t u = (*promoted)[k];
const MoveUnit& mu = plan_->units[(size_t)u];
for (size_t j = 0; j < mu.weights.size(); ++j)
res_.publish(mu.weights[j], pbases[k] + mu.offset[j]);
stats_.ssd_read_bytes += (uint64_t)unit_[(size_t)u].bytes;
}
++stats_.ssd_layers; ++stats_.ssd_layers;
stats_.ssd_units += (uint64_t)(staged->size() + pbases.size()); stats_.ssd_units += (uint64_t)((rd->staged.size() - staged0) + (rd->promoted.size() - promoted0));
stats_.h2d_bytes += (uint64_t)(off + hot_bytes); stats_.h2d_bytes += (uint64_t)(off - used0 + hot_bytes);
return RAD_OK; return RAD_OK;
} }
@@ -1809,6 +1892,7 @@ int Mover::retire(HeatEngine* heat) {
break; break;
case Move::Kind::Release: case Move::Kind::Release:
case Move::Kind::Drop: case Move::Kind::Drop:
case Move::Kind::Evict: /* published at issue, never Copying */
break; break;
} }
/* Safe without synchronisation: both copies of the bytes are valid now (see /* Safe without synchronisation: both copies of the bytes are valid now (see
+75 -16
View File
@@ -366,8 +366,9 @@ struct MoverStats {
uint64_t ssd_layers = 0, ssd_units = 0, ssd_read_bytes = 0, ssd_preads = 0; uint64_t ssd_layers = 0, ssd_units = 0, ssd_read_bytes = 0, ssd_preads = 0;
uint64_t ssd_read_ns = 0, ssd_wait_ns = 0; uint64_t ssd_read_ns = 0, ssd_wait_ns = 0;
/* Routing-aware reads: units of experts whose routing count was zero at the layer's /* Routing-aware reads: units of experts whose routing count was zero at the layer's
* trigger, not read (their weights are re-published to the layer buffer as a dummy * trigger, not read (their weights are published at the zero region for the pass, and
* address for the pass, and nulled again with the staged units). */ * nulled again with the staged units). Counted per read: a later slice of the layer's rows
* that reads some of them counts the rest again. */
uint64_t ssd_skipped_units = 0, ssd_skipped_bytes = 0; uint64_t ssd_skipped_units = 0, ssd_skipped_bytes = 0;
}; };
@@ -604,28 +605,58 @@ public:
* and published there; afterwards unstage_units publishes them as null again. The plan * and published there; afterwards unstage_units publishes them as null again. The plan
* charges the two buffers to the weights pool (Plan::file_stage_vram). * charges the two buffers to the weights pool (Plan::file_stage_vram).
* *
* stage_file_units reads every file-tier unit of `units` into `dst`, packed at RAD_ALIGN_UNIT * stage_file_units reads the file-tier units of `units` into `dst`, packed at RAD_ALIGN_UNIT
* in the order given, through the pinned read windows: container-order * in the order given from `rd->used` on, through the pinned read windows:
* runs, each window draining to `dst` on the mover's stream while the next * container-order runs, each window drained to its destinations by one
* fills, behind `after` (if set), with `done` recorded last. Published * copy list on the mover's stream while the next fills, behind `after` (if
* settled. RAD_E_SCRATCH if the units exceed `cap`. The reads block this * set), with `done` recorded last. Published settled, so the compute
* thread. * stream must wait on `done` before an op reads any of them; `rd->copied`
* says whether there is anything to wait for (a hot-cache admission or a
* pool deposit is a copy like a staged unit's). RAD_E_SCRATCH if the units
* exceed `cap`. The reads block this thread. Appends to `rd`, so a second
* call for another slice of the layer's rows adds what the first left out.
*
* Routing-aware reads: with `ecnt` (host, `n_expert` entries, the layer's per-expert routing
* counts for the rows about to run), a unit whose expert is counted zero is not read: it goes
* to `rd->skipped`, its weights are published at the zero region (valid memory a no-run
* expert never reads through), and the caller nulls it again with the staged units. Null
* `ecnt` reads every file-tier unit given.
*
* A read that finds the pool full relabels its coldest unit back to the file tier (see the
* definition). Units of the `protect` layers (plan layer numbers; the one being read and any
* whose ops are about to be issued) are never taken, whatever their counts.
* *
* Routing-aware reads: with `ecnt` (host, `n_expert` entries, the layer's per-expert
* routing counts for the current pass), a unit whose expert is counted zero is not read:
* it goes to `skipped`, its weights are published at `dst` (a dummy address inside the
* layer buffer, valid memory a no-run expert never reads through), and the caller nulls
* it again with the staged units. Null `ecnt` reads the whole layer.
* file_buffer buffer 0 or 1 of the plan's two, or null when the plan has none. */ * file_buffer buffer 0 or 1 of the plan's two, or null when the plan has none. */
struct FileRead {
std::vector<int32_t> staged; /* read into the layer buffer; nulled at release */
std::vector<int32_t> skipped; /* counted zero; published at the zero region */
std::vector<int32_t> promoted; /* read into hot-cache slots; they keep that address */
int64_t used = 0; /* bytes of the buffer the staged units take */
bool copied = false; /* `done` is behind copies an op will read */
void clear() {
staged.clear(); skipped.clear(); promoted.clear();
used = 0;
copied = false;
}
};
int stage_file_units(const std::vector<int32_t>& units, char* dst, int64_t cap, int stage_file_units(const std::vector<int32_t>& units, char* dst, int64_t cap,
RadEvent after, RadEvent done, std::vector<int32_t>* staged, RadEvent after, RadEvent done, FileRead* rd,
std::vector<int32_t>* skipped = nullptr,
const int32_t* ecnt = nullptr, int32_t n_expert = 0, const int32_t* ecnt = nullptr, int32_t n_expert = 0,
std::vector<int32_t>* promoted = nullptr); const int32_t* protect = nullptr, int n_protect = 0);
char* file_buffer(int i) const { char* file_buffer(int i) const {
return (file_vram_ && (i == 0 || i == 1)) ? file_vram_ + i * file_buf_bytes_ : nullptr; return (file_vram_ && (i == 0 || i == 1)) ? file_vram_ + i * file_buf_bytes_ : nullptr;
} }
int64_t file_buffer_bytes() const { return file_vram_ ? file_buf_bytes_ : 0; } int64_t file_buffer_bytes() const { return file_vram_ ? file_buf_bytes_ : 0; }
/* Whether any of `units` is on the file tier now (no slab slot, no pool slot): a layer with
* none has nothing to read, and its trigger skips the read and the drain it would cost. */
bool on_file_tier(const std::vector<int32_t>& units) const;
/* Whether `ecnt` (as stage_file_units takes it) routes any of `units`. */
bool routes_any(const std::vector<int32_t>& units, const int32_t* ecnt, int32_t n_expert) const;
/* The units the file stager reads back when they are on the file tier: every routed unit the
* plan put there, plus `more` (pooled and resident ones it also covers). Only a covered unit
* may be relabelled back to the file tier to make room for a deposit, since nothing else
* would ever read it again. Called once, at the stager's bring-up. */
void cover_file_units(const std::vector<int32_t>& more);
/* A snapshot by value: the counters are atomics read while the rank thread writes them. */ /* A snapshot by value: the counters are atomics read while the rank thread writes them. */
MoverStats stats() const { return stats_.snapshot(); } MoverStats stats() const { return stats_.snapshot(); }
@@ -779,6 +810,34 @@ private:
int win_next_ = 0; int win_next_ = 0;
std::vector<RadEvent> win_ev_; std::vector<RadEvent> win_ev_;
std::vector<uint8_t> win_rec_; std::vector<uint8_t> win_rec_;
/* stage_file_units' working lists, kept so a read allocates nothing once warm. A FileExt is
* one weight's bytes: where they are in the container and where they go -- the layer
* buffer, a hot-cache slot (`hot`, counted as ssd_promoted_bytes) or a pool slot
* (`deposit`, counted as ssd_deposit_bytes). */
struct FileExt {
int64_t foff = 0, bytes = 0;
char* dst = nullptr;
bool hot = false;
bool deposit = false;
};
std::vector<FileExt> fext_;
std::vector<int64_t> fat_; /* the staged units' buffer offsets */
std::vector<char*> fbase_; /* the hot-cache units' slot bases */
std::vector<int32_t> frec_; /* move records whose copies this read issues */
/* The file tier's cache cycle. `file_ok_`: by unit, the file stager reads it back when it is
* on the file tier (cover_file_units). `layer_file_`: by plan layer, the bytes of its units
* that are on the file tier or in the hot VRAM cache (which hands them back to the file tier
* when evicted), at the stager's packing; a relabel keeps it within `file_cap_`, the stager's
* buffer, so any read of a layer fits. */
std::vector<uint8_t> file_ok_;
std::vector<int64_t> layer_file_;
int64_t file_cap_ = 0;
/* A full pool's relabel candidates per class, ranked once per dispatch like donors_: every
* covered pooled unit, hottest first, so the coldest is at the back. Heat does not change
* within a dispatch, so this picks what a scan of every unit at each read would. */
struct VictimRank { int at = -1; std::vector<std::pair<float, int32_t>> by_heat; };
std::vector<VictimRank> victims_;
int32_t pick_victim(int32_t klass, const int32_t* protect, int n_protect, float below);
/* The lead gate's ring: one event a dispatch, and a host wait on the one from /* The lead gate's ring: one event a dispatch, and a host wait on the one from
* max_lead_dispatches ago. */ * max_lead_dispatches ago. */
+134 -52
View File
@@ -380,7 +380,7 @@ int FileStager::init(const Program& prog, const Plan& plan, Mover* mover,
if (!mover) return RAD_OK; if (!mover) return RAD_OK;
/* Routing-aware reads. The source may still decline per layer (a layer that has not /* Routing-aware reads. The source may still decline per layer (a layer that has not
* reported this pass is read whole). */ * reported yet is read whole). */
routes_ = routes; routes_ = routes;
routes_ud_ = routes_ud; routes_ud_ = routes_ud;
scratch_ = nullptr; scratch_ = nullptr;
@@ -391,12 +391,38 @@ int FileStager::init(const Program& prog, const Plan& plan, Mover* mover,
RAD_MEM_HOST_PINNED); RAD_MEM_HOST_PINNED);
if (!scratch_) { scratch_n_ = 0; routes_ = nullptr; } if (!scratch_) { scratch_n_ = 0; routes_ = nullptr; }
} }
/* A pass's rows each route n_expert_used of the model's n_expert experts, so a pass of
* kWholeRows * n_expert / n_expert_used rows routes kWholeRows to an expert on average, on
* every rank: an expert-parallel rank holds fewer experts and gets their share of the rows. */
whole_rows_ = routes_ && prog.meta.n_expert_used > 0
? (kWholeRows * prog.meta.n_expert + prog.meta.n_expert_used - 1) /
prog.meta.n_expert_used
: 0;
whole_ = false;
/* A unit declared and never read has no op span and is left out. */ /* The plan's file-tier units, and under a dynamic plan every movable routed unit of a class
size_t c = 0; * that has some: a deposit can relabel those to the file tier (see stager.h, "which units").
layers_ = routed_layers(plan, [](const MoveUnit& mu) { * A unit declared and never read has no op span and is left out. */
auto on_file = [](const MoveUnit& mu) {
return mu.tier == Tier::SSD && mu.access == RAD_ACCESS_CONDITIONAL; return mu.tier == Tier::SSD && mu.access == RAD_ACCESS_CONDITIONAL;
}, &c); };
std::vector<uint8_t> file_class(plan.classes.size(), 0);
for (const MoveUnit& mu : plan.units)
if (on_file(mu) && mu.slab_class >= 0 && (size_t)mu.slab_class < file_class.size())
file_class[(size_t)mu.slab_class] = 1;
auto may_be = [&](const MoveUnit& mu) {
return on_file(mu) ||
(plan.dynamic && mu.access == RAD_ACCESS_CONDITIONAL && mu.movable &&
mu.expert >= 0 && mu.slab_class >= 0 && (size_t)mu.slab_class < file_class.size() &&
file_class[(size_t)mu.slab_class]);
};
size_t c = 0;
layers_ = routed_layers(plan, may_be, &c);
bool wide = !layers_.empty();
if (c > 0) {
wide = false;
layers_ = routed_layers(plan, on_file, &c);
}
if (layers_.empty()) return RAD_OK; if (layers_.empty()) return RAD_OK;
/* A layer's copies stay published until the next one starts, so interleaved layers would need /* A layer's copies stay published until the next one starts, so interleaved layers would need
* a third buffer for the read-ahead; with no fallback address, such a plan is refused. */ * a third buffer for the read-ahead; with no fallback address, such a plan is refused. */
@@ -423,6 +449,13 @@ int FileStager::init(const Program& prog, const Plan& plan, Mover* mover,
if ((size_t)layers_[i].first_op < first_of_.size()) if ((size_t)layers_[i].first_op < first_of_.size())
first_of_[(size_t)layers_[i].first_op] = (int32_t)i; first_of_[(size_t)layers_[i].first_op] = (int32_t)i;
mover_ = mover; mover_ = mover;
if (wide) {
std::vector<int32_t> more;
for (const Layer& L : layers_)
for (int32_t u : L.units)
if (!on_file(plan.units[(size_t)u])) more.push_back(u);
mover_->cover_file_units(more);
}
for (int b = 0; b < 2; ++b) for (int b = 0; b < 2; ++b)
if (rad_event_create_local(&done_[b]) < 0 || rad_event_create_local(&free_[b]) < 0) { if (rad_event_create_local(&done_[b]) < 0 || rad_event_create_local(&free_[b]) < 0) {
layers_.clear(); layers_.clear();
@@ -441,6 +474,7 @@ bool FileStager::begin_pass(const RadBatch* b) {
first_op_ = true; first_op_ = true;
pass_kind_ = b->draft_pass; pass_kind_ = b->draft_pass;
last_issued_ = -1; last_issued_ = -1;
whole_ = whole_rows_ > 0 && b->n_tok >= whole_rows_;
return true; return true;
} }
@@ -449,46 +483,101 @@ bool FileStager::will_issue(int32_t li) const {
return it == pass_last_.end() || layers_[(size_t)li].first_op <= it->second; return it == pass_last_.end() || layers_[(size_t)li].first_op <= it->second;
} }
int FileStager::start(int32_t li, RadStream s) { bool FileStager::counted(int32_t li) const {
if (!routes_ || whole_) return false;
int64_t n = 0;
const int32_t* dev = routes_(routes_ud_, layers_[(size_t)li].layer, &n);
return dev && n > 0 && n <= scratch_n_;
}
/* Called only at the layer's trigger or a repeat of it, so the router of the rows about to run
* has been issued on `s` ahead of the copy. The drain costs far less than the read it decides. */
int FileStager::counts(int32_t li, RadStream s, const int32_t** ecnt, int32_t* n_expert) {
*ecnt = nullptr;
*n_expert = 0;
if (!routes_) return RAD_OK;
int64_t n = 0;
const int32_t* dev = routes_(routes_ud_, layers_[(size_t)li].layer, &n);
if (!dev || n <= 0 || n > scratch_n_) return RAD_OK;
RAD_TRY(rad_memcpy_async(scratch_, dev, (size_t)n * sizeof(int32_t), s));
RAD_TRY(rad_stream_sync(s));
*ecnt = scratch_;
*n_expert = (int32_t)n;
return RAD_OK;
}
/* Read layer `li` into its buffer: with this pass's counts when the source has them (only at the
* layer's trigger), whole otherwise. A layer with nothing on the file tier now is not held. */
int FileStager::start(int32_t li, RadStream s, bool* resync) {
const int b = li & 1; const int b = li & 1;
if (holds_[b] >= 0) return RAD_E_STATE; /* released before the next read, by construction */ if (holds_[b] >= 0) return RAD_E_STATE; /* released before the next read, by construction */
/* Routing-aware reads: the trigger (this call) runs at the layer's first expert op, const Layer& L = layers_[(size_t)li];
* after the layer's router on the same stream, so this pass's counts are ordered if (!mover_->on_file_tier(L.units)) return RAD_OK;
* before the copy. The stream sync costs far less than a gigabyte-scale layer read;
* a source that declines (no report yet this pass) reads the whole layer. */
const int32_t* ecnt = nullptr; const int32_t* ecnt = nullptr;
int32_t n_expert = 0; int32_t n_expert = 0;
if (routes_) { if (counted(li)) RAD_TRY(counts(li, s, &ecnt, &n_expert));
int64_t n = 0; /* The layer read, the one held in the other buffer, and the one whose ops are being issued
const int32_t* dev = routes_(routes_ud_, layers_[(size_t)li].layer, &n); * (cur_: it may hold nothing on the file tier, and so be held by neither): their pooled units
if (dev && n > 0 && n <= scratch_n_ && * must keep their addresses. */
rad_memcpy_async(scratch_, dev, (size_t)n * sizeof(int32_t), s) >= 0 && const int32_t protect[3] = { L.layer, holds_[b ^ 1] >= 0 ? layers_[(size_t)holds_[b ^ 1]].layer
rad_stream_sync(s) >= 0) { : -1,
ecnt = scratch_; cur_ >= 0 ? layers_[(size_t)cur_].layer : -1 };
n_expert = (int32_t)n; rd_[b].clear();
} holds_[b] = li;
} *resync = true;
const int rc = mover_->stage_file_units(layers_[(size_t)li].units, buf_[b], cap_, RAD_TRY(mover_->stage_file_units(L.units, buf_[b], cap_, free_rec_[b] ? free_[b] : nullptr,
free_rec_[b] ? free_[b] : nullptr, done_[b], done_[b], &rd_[b], ecnt, n_expert, protect, 3));
&staged_[b], &skipped_[b], ecnt, n_expert, pending_[b] = rd_[b].copied;
&promoted_[b]); return RAD_OK;
if (rc < 0) return rc; }
if (!staged_[b].empty() || !promoted_[b].empty()) holds_[b] = li;
/* Another slice of the current layer's rows: its router has rewritten the counts, and an expert
* the earlier slices did not route is read now. The buffer is the layer's, and the new units are
* packed after the ones already there, so nothing is waited on before the copies. */
int FileStager::top_up(int32_t li, RadStream s, bool* resync) {
const int b = li & 1;
if (holds_[b] != li || rd_[b].skipped.empty()) return RAD_OK;
const int32_t* ecnt = nullptr;
int32_t n_expert = 0;
RAD_TRY(counts(li, s, &ecnt, &n_expert));
/* The earlier slices were read with counts, so the source has them; were it to decline,
* everything left is read. A slice that routes nothing new changes nothing. */
if (!mover_->routes_any(rd_[b].skipped, ecnt, n_expert)) return RAD_OK;
again_.swap(rd_[b].skipped);
rd_[b].skipped.clear();
rd_[b].copied = false;
const int32_t protect[3] = { layers_[(size_t)li].layer,
holds_[b ^ 1] >= 0 ? layers_[(size_t)holds_[b ^ 1]].layer : -1,
cur_ >= 0 ? layers_[(size_t)cur_].layer : -1 };
*resync = true;
const int rc = mover_->stage_file_units(again_, buf_[b], cap_, nullptr, done_[b], &rd_[b],
ecnt, n_expert, protect, 3);
again_.clear();
RAD_TRY(rc);
if (rd_[b].copied) pending_[b] = true;
return wait(b, s);
}
int FileStager::wait(int32_t b, RadStream s) {
if (!pending_[b]) return RAD_OK;
RAD_TRY(rad_event_wait(s, done_[b]));
pending_[b] = false;
++waits_;
return RAD_OK; return RAD_OK;
} }
int FileStager::finish(int32_t b, RadStream s) { int FileStager::finish(int32_t b, RadStream s) {
/* A read the pass never reached (a read-ahead past where it ended) still deposited into the
* pool or admitted into the hot cache, whose publications outlive it: order the stream behind
* those copies before anything later can read them. */
RAD_TRY(wait(b, s));
RAD_TRY(rad_event_record(free_[b], s)); RAD_TRY(rad_event_record(free_[b], s));
free_rec_[b] = true; free_rec_[b] = true;
mover_->unstage_units(staged_[b]); mover_->unstage_units(rd_[b].staged);
staged_[b].clear(); /* The skipped units' dummy publications go to null too. Hot-cache units are not unstaged:
if (!skipped_[b].empty()) { * their publications name their slots, which outlive the buffer. */
mover_->unstage_units(skipped_[b]); /* the dummy publications go to null too */ mover_->unstage_units(rd_[b].skipped);
skipped_[b].clear(); rd_[b].clear();
}
/* Hot-cache units are NOT unstaged: their publications name their slots, which outlive
* the buffer. The layer's copies into them landed before its ops ran (the done_ wait). */
promoted_[b].clear();
holds_[b] = -1; holds_[b] = -1;
return RAD_OK; return RAD_OK;
} }
@@ -497,41 +586,34 @@ int FileStager::before_op(rad_op h, RadStream s, bool* resync) {
*resync = false; *resync = false;
if ((int32_t)h > last_issued_) last_issued_ = (int32_t)h; if ((int32_t)h > last_issued_) last_issued_ = (int32_t)h;
/* Read the pass's first routed layer at its first op of any kind. */ /* Read the pass's first routed layer at its first op of any kind, when it is read whole. */
if (first_op_) { if (first_op_) {
first_op_ = false; first_op_ = false;
const auto it = std::lower_bound(layers_.begin(), layers_.end(), (int32_t)h, const auto it = std::lower_bound(layers_.begin(), layers_.end(), (int32_t)h,
[](const Layer& L, int32_t op) { return L.first_op < op; }); [](const Layer& L, int32_t op) { return L.first_op < op; });
if (it != layers_.end()) { if (it != layers_.end()) {
const int32_t li = (int32_t)(it - layers_.begin()); const int32_t li = (int32_t)(it - layers_.begin());
if (will_issue(li)) { if (will_issue(li) && !counted(li)) RAD_TRY(start(li, s, resync));
RAD_TRY(start(li, s));
*resync = true;
}
} }
} }
if ((size_t)h >= first_of_.size()) return RAD_OK; if ((size_t)h >= first_of_.size()) return RAD_OK;
const int32_t li = first_of_[(size_t)h]; const int32_t li = first_of_[(size_t)h];
if (li < 0 || li == cur_) return RAD_OK; if (li < 0) return RAD_OK;
if (li == cur_) return top_up(li, s, resync);
/* Entering layer `li`: the layer before is behind every op issued so far on this stream. */ /* Entering layer `li`: the layer before is behind every op issued so far on this stream. */
for (int b = 0; b < 2; ++b) for (int b = 0; b < 2; ++b)
if (holds_[b] >= 0 && holds_[b] != li) { RAD_TRY(finish(b, s)); *resync = true; } if (holds_[b] >= 0 && holds_[b] != li) { RAD_TRY(finish(b, s)); *resync = true; }
/* A layer the read-ahead skipped (the learned bound said the pass ends before it) is read /* Read here unless read ahead: a counted layer always, a whole one the read-ahead skipped
* here rather than issued without addresses. */ * (the learned bound said the pass ends before it). */
if (holds_[li & 1] != li) { if (holds_[li & 1] != li) RAD_TRY(start(li, s, resync));
RAD_TRY(start(li, s)); RAD_TRY(wait(li & 1, s));
*resync = true;
}
if (holds_[li & 1] == li) RAD_TRY(rad_event_wait(s, done_[li & 1]));
cur_ = li; cur_ = li;
const int32_t next = li + 1; const int32_t next = li + 1;
if ((size_t)next < layers_.size() && will_issue(next)) { if ((size_t)next < layers_.size() && will_issue(next) && !counted(next))
RAD_TRY(start(next, s)); RAD_TRY(start(next, s, resync));
*resync = true;
}
return RAD_OK; return RAD_OK;
} }
+82 -28
View File
@@ -214,47 +214,92 @@ private:
* GEMM is handed every expert's pointer at issue. So on every pass, decode included, each routed * GEMM is handed every expert's pointer at issue. So on every pass, decode included, each routed
* layer's file-tier units are read into one of the mover's two file buffers before the layer's * layer's file-tier units are read into one of the mover's two file buffers before the layer's
* first expert op and published there, then published as null when the next routed layer starts. * first expert op and published there, then published as null when the next routed layer starts.
* The router's picks are not known on the host without a round trip, so the layer's whole
* file-tier part is read; decode is then paced by the drive, which is the trade the flag makes.
* *
* the pass's first op read the first routed layer the pass issues * ---- which experts -------------------------------------------------------------------------------
* a layer's first op release the layer before (record its buffer free on the stream, publish *
* null), wait on this layer's copies, and read the next layer into the * Only the experts the layer's rows route to are read. Their counts are known only once the
* buffer just released -- its copies queue behind that free event * layer's router has run, so a layer is read at its own trigger, its first expert op: the counts
* are copied back behind the router on the same stream (one drain of the stream), and a unit
* counted zero is published at the mover's zero region instead of being read. The read cannot
* start earlier: counts taken before the router are another layer's, or the last pass's, and a
* truly routed expert they count zero would be computed from zeros. The card waits for every
* read either way, so reading at the trigger costs what reading the next layer ahead behind the
* same drain did.
*
* A layer the count source cannot give counts for (the first pass, before any report) is read
* whole, and since that read needs no counts it goes ahead of time as before: at the pass's
* first op for the first routed layer, at a layer's trigger for the next one, into the buffer
* just released.
*
* So is every layer of a pass large enough that its rows route nearly every expert, kWholeRows
* rows an expert on average by the model's expert count and top-k (whole_rows()). An exact read
* takes the same bytes there, and each layer costs the card's work plus the drive's, since the
* card idles behind the drain while the drive reads. A whole read needs no counts, so nothing
* drains the stream, and the drive reads the next layer while the card computes the one before.
* At 64 rows an expert, one routed an eighth as often as the average is left out of about one
* pass in 3000, and read for nothing then. Smaller passes skip enough to pay for the drain: at
* decode nearly every file-tier expert.
*
* the pass's first op read the first routed layer the pass issues, if it is read whole
* a layer's first op release the layer before (record its buffer free on the stream,
* publish null), read this layer unless read ahead, wait on its
* copies, and read the next layer ahead if it is read whole -- its
* copies queue behind the free event of the buffer it takes
* a repeat of that op another slice of rows: read what its counts route that the earlier
* slices' did not, and wait on those copies
* the pass's end release whatever is still held * the pass's end release whatever is still held
* *
* A layer is released when the next one starts, not at its own last op: a routed block that slices * A layer is released when the next one starts, not at its own last op: a routed block that slices
* a large step into passes of `rows` tokens issues its expert ops once per slice, so a release at * a large step into passes of `rows` tokens issues its expert ops once per slice, so a release at
* the last op would leave the next slice reading null. Repeats of the current layer's first op do * the last op would leave the next slice reading null. Each slice routes its own rows, which is
* nothing. * why a repeat reads again.
* *
* The read blocks the issuing thread while the card runs what was issued before it. A layer's * Every read that issued a copy is waited on, a hot-cache admission's or a pool deposit's as much
* file-tier part is gigabytes against milliseconds of compute, so the step is drive-bound either * as a staged unit's: all are published settled, so the wait is the only thing between the GEMM
* way; a reader thread would gain little and add a second writer of the residency table. * and the slot's previous bytes.
*
* The read blocks the issuing thread while the card runs what was issued before it; a reader
* thread would gain little and add a second writer of the residency table.
* *
* A layer is read ahead only when the pass will issue it (a bound learned per draft_pass from the * A layer is read ahead only when the pass will issue it (a bound learned per draft_pass from the
* last pass of that kind), so a trunk pass does not read the MTP head's layer. */ * last pass of that kind), so a trunk pass does not read the MTP head's layer.
*
* ---- which units -------------------------------------------------------------------------------
*
* Under a dynamic plan the pool is a cache of the file tier: a deposit may relabel a pooled unit
* back to the file tier (Mover::stage_file_units). A pooled unit the plan put in the pool is then
* on the file tier too, so the stager covers every movable routed unit of a class with file-tier
* units, not only the plan's file-tier ones, and tells the mover so (Mover::cover_file_units); a
* trigger whose layer has nothing on the file tier skips the read and its drain. Where covering
* them would interleave two layers' spans, only the plan's file-tier units are covered, and the
* mover relabels none of the others. */
class FileStager final : public OpStager { class FileStager final : public OpStager {
public: public:
~FileStager() override; ~FileStager() override;
/* Routing-aware reads: the engine binds a source of the layer's per-expert routing /* Routing-aware reads: the engine binds a source of a layer's per-expert routing counts
* counts for the current pass (the router reports them to the Ctx before the layer's * (Ctx::route_counts_device). It returns the device pointer of `n_expert` i32 counts that the
* first expert op, which is the stager's trigger). Returns the device pointer of * layer's router rewrites every pass before the layer's first expert op, which is the
* `n_expert` i32 counts, or null when the layer has not reported this pass — the * stager's trigger, or null when it has none (the layer has not reported yet) -- the stager
* caller then reads the whole layer. Null `routes` reads whole layers. */ * then reads the whole layer. Null `routes` reads whole layers. */
using RouteCounts = const int32_t* (*)(void* ud, int32_t layer, int64_t* n_expert); using RouteCounts = const int32_t* (*)(void* ud, int32_t layer, int64_t* n_expert);
/* Binds the routed layers with file-tier units and the ops that read them, over the mover's /* Binds the routed layers with file-tier units and the ops that read them, over the mover's
* two file buffers. Leaves enabled() false when no routed unit is on the file tier. Refuses a * two file buffers. Leaves enabled() false when no routed unit is on the file tier. Refuses a
* plan whose routed layers are read by interleaved ops, since a file-tier unit has no other * plan whose routed file-tier layers are read by interleaved ops, since a file-tier unit has
* address to fall back on. */ * no other address to fall back on. */
int init(const Program& prog, const Plan& plan, Mover* mover, int init(const Program& prog, const Plan& plan, Mover* mover,
RouteCounts routes = nullptr, void* routes_ud = nullptr); RouteCounts routes = nullptr, void* routes_ud = nullptr);
bool enabled() const { return !layers_.empty(); } bool enabled() const { return !layers_.empty(); }
size_t n_layers() const { return layers_.size(); } size_t n_layers() const { return layers_.size(); }
int64_t buffer_bytes() const { return cap_; } int64_t buffer_bytes() const { return cap_; }
/* Stream waits on the stager's copies so far, one per read that issued any. Tests read it. */
int64_t waits() const { return waits_; }
/* The smallest pass, in tokens, whose layers are read whole and ahead (see "which experts"),
* or 0 when every pass is read exactly (no routing source, or the model's top-k unknown). */
int64_t whole_rows() const { return whole_rows_; }
static constexpr int64_t kWholeRows = 64;
bool begin_pass(const RadBatch* b) override; bool begin_pass(const RadBatch* b) override;
int before_op(rad_op h, RadStream s, bool* resync) override; int before_op(rad_op h, RadStream s, bool* resync) override;
@@ -262,7 +307,8 @@ public:
private: private:
using Layer = StagedLayer; using Layer = StagedLayer;
std::vector<Layer> layers_; /* the routed layers with file-tier units, in first-op order */ int64_t waits_ = 0;
std::vector<Layer> layers_; /* the routed layers the stager covers, in first-op order */
std::vector<int32_t> first_of_; /* by op: the layer whose first op it is, or -1 */ std::vector<int32_t> first_of_; /* by op: the layer whose first op it is, or -1 */
Mover* mover_ = nullptr; Mover* mover_ = nullptr;
@@ -272,16 +318,15 @@ private:
void* routes_ud_ = nullptr; void* routes_ud_ = nullptr;
int32_t* scratch_ = nullptr; /* pinned, for the trigger's blocking counts copy */ int32_t* scratch_ = nullptr; /* pinned, for the trigger's blocking counts copy */
int64_t scratch_n_ = 0; int64_t scratch_n_ = 0;
std::vector<int32_t> skipped_[2]; /* per buffer: units not read, nulled at release */ /* Per buffer: what its layer's reads staged (nulled at release), skipped (likewise) and read
/* Per buffer: units the stager read into hot-cache slots. Unlike the * into hot-cache slots (whose publications outlive the buffer -- the slot is their address
* staged ones they keep their publications when the buffer is released — the slot is * until heat evicts one). */
* their address from here on, until heat evicts one. */ Mover::FileRead rd_[2];
std::vector<int32_t> promoted_[2]; std::vector<int32_t> again_; /* a repeat's candidates: the layer's skipped units */
RadEvent done_[2] = { nullptr, nullptr }; /* behind a buffer's copies, on the mover stream */ RadEvent done_[2] = { nullptr, nullptr }; /* behind a buffer's copies, on the mover stream */
RadEvent free_[2] = { nullptr, nullptr }; /* behind the ops that read a buffer's layer */ RadEvent free_[2] = { nullptr, nullptr }; /* behind the ops that read a buffer's layer */
bool free_rec_[2] = { false, false }; bool free_rec_[2] = { false, false };
std::vector<int32_t> staged_[2]; bool pending_[2] = { false, false }; /* copies no stream has waited on yet */
int start(int32_t li, RadStream s);
int32_t holds_[2] = { -1, -1 }; /* the layer a buffer holds, or -1 */ int32_t holds_[2] = { -1, -1 }; /* the layer a buffer holds, or -1 */
int32_t cur_ = -1; /* the layer whose ops are being issued */ int32_t cur_ = -1; /* the layer whose ops are being issued */
@@ -290,9 +335,18 @@ private:
int32_t pass_kind_ = 0; int32_t pass_kind_ = 0;
int32_t last_issued_ = -1; int32_t last_issued_ = -1;
std::map<int32_t, int32_t> pass_last_; /* by draft_pass: the last op such a pass issued */ std::map<int32_t, int32_t> pass_last_; /* by draft_pass: the last op such a pass issued */
int64_t whole_rows_ = 0;
bool whole_ = false; /* this pass reads every layer whole (whole_rows) */
bool will_issue(int32_t li) const; bool will_issue(int32_t li) const;
int start(int32_t li); /* Whether layer `li` is read with counts, at its own trigger; otherwise it is read whole,
* and may be read ahead. */
bool counted(int32_t li) const;
/* The counts of the rows about to run, copied back behind the router on `s`, or null. */
int counts(int32_t li, RadStream s, const int32_t** ecnt, int32_t* n_expert);
int start(int32_t li, RadStream s, bool* resync);
int top_up(int32_t li, RadStream s, bool* resync);
int wait(int32_t b, RadStream s);
int finish(int32_t b, RadStream s); int finish(int32_t b, RadStream s);
}; };
+57 -5
View File
@@ -52,9 +52,10 @@ bool target_covers(const std::string& declared, const char* arch) {
} }
/* Two schemas for one op are the same when every positional slot means the same thing: parameter /* Two schemas for one op are the same when every positional slot means the same thing: parameter
* keys, types and requiredness (what the selector matches on) and operand count, roles and * keys, types, requiredness (what the selector matches on) and roles (the core reads the first
* optionality (arguments are positional). Operand names are for diagnostics only (ABI), so "b" * registrant's: a chunk or a capacity named by one plugin applies to every plugin's rows), and
* and "w_gate" in slot 1 agree. */ * operand count, roles and optionality (arguments are positional). Operand names are for
* diagnostics only (ABI), so "b" and "w_gate" in slot 1 agree. */
bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* diff) { bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* diff) {
if (a.n_params != b.n_params) { if (a.n_params != b.n_params) {
*diff = fmt("%d parameters vs %d", a.n_params, b.n_params); *diff = fmt("%d parameters vs %d", a.n_params, b.n_params);
@@ -77,6 +78,10 @@ bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* diff)
x.required ? "required" : "optional", y.required ? "required" : "optional"); x.required ? "required" : "optional", y.required ? "required" : "optional");
return false; return false;
} }
if (x.role != y.role) {
*diff = fmt("parameter '%s' has role %d vs %d", or_empty(x.key), x.role, y.role);
return false;
}
} }
if (a.n_operands != b.n_operands) { if (a.n_operands != b.n_operands) {
*diff = fmt("%d operands vs %d", a.n_operands, b.n_operands); *diff = fmt("%d operands vs %d", a.n_operands, b.n_operands);
@@ -212,6 +217,8 @@ int Registry::commit_(Staged& s, int order) {
p.arch_declare = dl_fn<int (*)(RadBuilder*, const RadModelMeta*, const RadBuildCtx*)>( p.arch_declare = dl_fn<int (*)(RadBuilder*, const RadModelMeta*, const RadBuildCtx*)>(
s.handle, "rad_arch_declare"); s.handle, "rad_arch_declare");
p.arch_step = dl_fn<void (*)(RadCtx*, const RadBatch*)>(s.handle, "rad_arch_step"); p.arch_step = dl_fn<void (*)(RadCtx*, const RadBatch*)>(s.handle, "rad_arch_step");
p.arch_pass_key = dl_fn<uint64_t (*)(RadCtx*, const RadBatch*, const int32_t*)>(
s.handle, "rad_arch_pass_key");
if (!id_fn || !p.arch_declare || !p.arch_step) { if (!id_fn || !p.arch_declare || !p.arch_step) {
err_("architecture plugin '%s' is missing rad_arch_id, rad_arch_declare or " err_("architecture plugin '%s' is missing rad_arch_id, rad_arch_declare or "
"rad_arch_step", p.name.c_str()); "rad_arch_step", p.name.c_str());
@@ -291,6 +298,27 @@ int Registry::commit_(Staged& s, int order) {
unstage_(s); unstage_(s);
return RAD_E_INVAL; return RAD_E_INVAL;
} }
/* The counts are the plugin's word; the tables they index are walked at every
* selection and every issue, so a null table or an operand count past what an issue
* can carry (MAX_OPERANDS) is refused here, by name, rather than read there. */
if (sch->n_params < 0 || (sch->n_params && !sch->params) || sch->n_operands < 0 ||
sch->n_operands > MAX_OPERANDS || (sch->n_operands && !sch->operands)) {
err_("kernel plugin '%s': op '%s' declares %d parameters and %d operands, a table "
"missing, or more operands than an issue carries (%d)", p.name.c_str(),
sch->op, sch->n_params, sch->n_operands, MAX_OPERANDS);
unstage_(s);
return RAD_E_INVAL;
}
for (int q = 0; q < sch->n_params; ++q) {
const RadParamSpec& ps = sch->params[q];
if (!ps.key || !ps.key[0] || ps.role < RAD_PROLE_NONE ||
ps.role > RAD_PROLE_CAPACITY) {
err_("kernel plugin '%s': op '%s' parameter %d has no key or an unknown role "
"(%d)", p.name.c_str(), sch->op, q, ps.role);
unstage_(s);
return RAD_E_INVAL;
}
}
std::string diff; std::string diff;
auto it = schemas_.find(sch->op); auto it = schemas_.find(sch->op);
if (it != schemas_.end()) { if (it != schemas_.end()) {
@@ -338,6 +366,23 @@ int Registry::commit_(Staged& s, int order) {
unstage_(s); unstage_(s);
return RAD_E_INVAL; return RAD_E_INVAL;
} }
/* The selector reads every constraint of every row at every query, and the tuner every
* tunable, so their tables must exist wherever a count says they do. */
if (k->n_tunables < 0 || (k->n_tunables && !k->tunables) || k->n_constraints < 0 ||
(k->n_constraints && !k->constraints)) {
err_("kernel '%s' in plugin '%s' declares %d tunables and %d constraints with a "
"missing table", k->name, p.name.c_str(), k->n_tunables, k->n_constraints);
unstage_(s);
return RAD_E_INVAL;
}
for (int c = 0; c < k->n_constraints; ++c)
if (!k->constraints[c].key || !k->constraints[c].key[0] ||
(k->constraints[c].op == RAD_C_IN && !k->constraints[c].sval)) {
err_("kernel '%s' in plugin '%s' declares constraint %d with no key, or an IN "
"with no set", k->name, p.name.c_str(), c);
unstage_(s);
return RAD_E_INVAL;
}
/* Every tunable axis must carry a default that is one of its own values. Untuned /* Every tunable axis must carry a default that is one of its own values. Untuned
* shapes (no cache, an unmeasured shape, another card's cache) run the defaults, with * shapes (no cache, an unmeasured shape, another card's cache) run the defaults, with
* no other fallback (spec §15). Checked at load rather than first use so a bad axis * no other fallback (spec §15). Checked at load rather than first use so a bad axis
@@ -382,8 +427,15 @@ int Registry::commit_(Staged& s, int order) {
if (no_device_code_) if (no_device_code_)
why = "no card is visible, so this process runs on the host backend and no GPU code " why = "no card is visible, so this process runs on the host backend and no GPU code "
"object runs here"; "object runs here";
if (n_device > 0 && s.code_to > s.code_from && /* The code range decides only the per-card test: on the host backend the rows go even when
(no_device_code_ || rad::dev_code_runs(s.code_from, s.code_to, code_device_, &why) == 0)) { * this dlopen registered no fat binary (no HIP in the build, or the library already
* mapped by another registry). */
const bool no_code_here =
n_device > 0 &&
(no_device_code_ ||
(s.code_to > s.code_from &&
rad::dev_code_runs(s.code_from, s.code_to, code_device_, &why) == 0));
if (no_code_here) {
std::vector<std::pair<const RadKernelInfo*, int>> keep; std::vector<std::pair<const RadKernelInfo*, int>> keep;
for (const auto& r : staged_rows) for (const auto& r : staged_rows)
if (r.first->domain != RAD_DOMAIN_DEVICE) keep.push_back(r); if (r.first->domain != RAD_DOMAIN_DEVICE) keep.push_back(r);
+1
View File
@@ -82,6 +82,7 @@ struct Plugin {
std::string arch_quant; std::string arch_quant;
int (*arch_declare)(RadBuilder*, const RadModelMeta*, const RadBuildCtx*) = nullptr; int (*arch_declare)(RadBuilder*, const RadModelMeta*, const RadBuildCtx*) = nullptr;
void (*arch_step)(RadCtx*, const RadBatch*) = nullptr; void (*arch_step)(RadCtx*, const RadBatch*) = nullptr;
uint64_t (*arch_pass_key)(RadCtx*, const RadBatch*, const int32_t*) = nullptr;
/* Optional (rad_builder.h); null means every question answers zero. Asked before declare, so /* Optional (rad_builder.h); null means every question answers zero. Asked before declare, so
* model facts that are inputs to declaration are still read by the plugin, not the core. */ * model facts that are inputs to declaration are still read by the plugin, not the core. */
int (*arch_probe)(const RadModelMeta*, RadArchProbe*) = nullptr; int (*arch_probe)(const RadModelMeta*, RadArchProbe*) = nullptr;
+30 -2
View File
@@ -17,6 +17,11 @@
namespace rad { namespace rad {
/* The widest conventional op is gdn_conv_prep at sixteen operands (docs/OPS.md). Thirty-two leaves
* room for an architecture plugin's private ops without a variable-length array on the hot path.
* The plugin loader refuses a schema with more, so no issue carries more. */
constexpr int MAX_OPERANDS = 32;
namespace mm { struct Item; struct PromptMedia; } namespace mm { struct Item; struct PromptMedia; }
class Registry; class Registry;
@@ -451,9 +456,15 @@ public:
std::vector<int64_t> decoder_max_area; std::vector<int64_t> decoder_max_area;
} vgen_str; } vgen_str;
bool is_video_generator() const { return video_gen.max_lanes != 0; } bool is_video_generator() const { return video_gen.max_lanes != 0; }
/* The declared shape generator (rad_declare_shape_generator); `max_lanes` 0 when none. Its
* name points at `sgen_name`. */
RadShapeGenDecl shape_gen{};
std::string sgen_name;
bool is_shape_generator() const { return shape_gen.max_lanes != 0; }
/* Driven by passes, not token steps: any generator. */ /* Driven by passes, not token steps: any generator. */
bool is_pass_driven() const { bool is_pass_driven() const {
return is_generator() || is_audio_generator() || is_video_generator(); return is_generator() || is_audio_generator() || is_video_generator() ||
is_shape_generator();
} }
/* Two arenas, because a host-site activation cannot index device memory. The buffer plan /* Two arenas, because a host-site activation cannot index device memory. The buffer plan
@@ -671,6 +682,10 @@ struct SamplingParams {
* duplicates ignored. Empty (the default) is off: the ban is then bit-identical to the * duplicates ignored. Empty (the default) is off: the ban is then bit-identical to the
* no-whitelist form. */ * no-whitelist form. */
std::vector<int32_t> ngram_whitelist; std::vector<int32_t> ngram_whitelist;
/* Token ids this request never samples (generation_config.json's suppress_tokens: Gemma 4's
* end-of-image and end-of-audio markers). Global ids, duplicates ignored; empty is off. The
* sampler takes them out of the row as it does a grammar's mask. */
std::vector<int32_t> suppress_tokens;
}; };
/* Raw logits at chosen vocabulary ids at the prompt's last position, for a caller that answers /* Raw logits at chosen vocabulary ids at the prompt's last position, for a caller that answers
@@ -824,7 +839,13 @@ struct Config {
* prefill stager arms for. 0 = off: the chunk takes every token the step has left. N > 0: cap * prefill stager arms for. 0 = off: the chunk takes every token the step has left. N > 0: cap
* the chunk at N tokens on such a step. See Scheduler::step, docs/GUIDE.md. */ * the chunk at N tokens on such a step. See Scheduler::step, docs/GUIDE.md. */
int64_t busy_prefill_chunk = -1; int64_t busy_prefill_chunk = -1;
int64_t prefill_interleave = 0; /* --prefill-interleave: decode-only steps between chunks */ double prefill_interleave_share = 0.25; /* --prefill-interleave auto[:SHARE] */
/* Whether --prefill-interleave was given. Not given, engine bring-up serves auto:1 (decode-only
* steps for as long as a chunk step took) except under --deterministic, in KL mode and for a
* generator; the Config default 0 is what a Scheduler built directly (tests) gets. */
bool prefill_interleave_set = false;
int64_t prefill_interleave = 0; /* --prefill-interleave: decode-only steps between chunks;
* -1 auto (Scheduler::interleave_steps) */
/* --preempt-wait-ms: how long a preempted prefill may wait for the whole-recompute gate /* --preempt-wait-ms: how long a preempted prefill may wait for the whole-recompute gate
* before the scheduler evicts cache blocks and preempts a lower-priority running request to * before the scheduler evicts cache blocks and preempts a lower-priority running request to
* make room for it. 0 = fall back on the next step; default 5000 ms. */ * make room for it. 0 = fall back on the next step; default 5000 ms. */
@@ -848,6 +869,9 @@ struct Config {
int64_t vram_weights_mib = 0; int64_t vram_weights_mib = 0;
int64_t vram_kv_mib = 0; int64_t vram_kv_mib = 0;
int64_t gpu_headroom_mib = 96; /* --gpu-headroom-mib, left unclaimed on every card */ int64_t gpu_headroom_mib = 96; /* --gpu-headroom-mib, left unclaimed on every card */
/* --gpu-memory-mib: claim this much of every card; 0 uses gpu_headroom_mib. Inverse of
* headroom: N + headroom = the card, in MiB. Not with --gpu-headroom-mib. */
int64_t gpu_memory_mib = 0;
/* --kv-cache-dtype bf16|fp8|fp8_v4|k6_v4. fp8 is an E4M3 cache with per-(sequence, head) /* --kv-cache-dtype bf16|fp8|fp8_v4|k6_v4. fp8 is an E4M3 cache with per-(sequence, head)
* descales; it halves the per-token cost, most of the KV pool at production context. fp8_v4 * descales; it halves the per-token cost, most of the KV pool at production context. fp8_v4
* keeps K as E4M3 and V as int4 in groups of 32, k6_v4 also K as int6 (RadBuildCtx::kv_quant), * keeps K as E4M3 and V as int4 in groups of 32, k6_v4 also K as int6 (RadBuildCtx::kv_quant),
@@ -887,6 +911,10 @@ struct Config {
/* --ngram-placement ram=DIR: the pinned n-gram copy is the file DIR/ngram-<id>.tab (a tmpfs), /* --ngram-placement ram=DIR: the pinned n-gram copy is the file DIR/ngram-<id>.tab (a tmpfs),
* mapped shared, so engines on separate cards hold one table. Empty: a private copy. */ * mapped shared, so engines on separate cards hold one table. Empty: a private copy. */
std::string ngram_share_dir; std::string ngram_share_dir;
/* --ngram-placement disk=DIR: the table is read from its own file, DIR/ngram-<id>.bin, filled
* from the container at the first start, instead of from the container (a faster drive than
* the model's). Empty: from the container. */
std::string ngram_disk_dir;
TablePlacement embedding_resolved = TablePlacement::Vram; TablePlacement embedding_resolved = TablePlacement::Vram;
TablePlacement ngram_resolved = TablePlacement::Disk; TablePlacement ngram_resolved = TablePlacement::Disk;
/* Set by the resolver: pinned host MiB per rank for the token embedding when it resolves to /* Set by the resolver: pinned host MiB per rank for the token embedding when it resolves to
+56 -14
View File
@@ -31,11 +31,15 @@ int Ctx::init(const CtxDesc& d) {
registry_ = d.registry; registry_ = d.registry;
kv_ = d.kv; kv_ = d.kv;
arch_step_ = d.arch_step; arch_step_ = d.arch_step;
arch_pass_key_ = d.arch_pass_key;
profiling_ = d.profile_ops; profiling_ = d.profile_ops;
/* The rank owns one device. Set it here so allocation lands on the right card, and again from /* The rank owns one device. Set it here so allocation lands on the right card, and again from
* the rank thread in bind_thread() because the backend's current device is thread-local. */ * the rank thread in bind_thread() because the backend's current device is thread-local. */
RAD_TRY(rad_dev_set(device_)); RAD_TRY(rad_dev_set(device_));
RadDeviceProps props{};
if (rad_dev_props(device_, &props) >= 0 && !props.is_host_backend && props.n_cu > 0)
wgp_count_ = props.n_cu;
if (d.stream) { if (d.stream) {
stream_ = d.stream; stream_ = d.stream;
@@ -367,6 +371,7 @@ int Ctx::bind_ops() {
ip.args.instance = r.instance; ip.args.instance = r.instance;
ip.args.rank = rank_; ip.args.rank = rank_;
ip.args.world_size = world_size_; ip.args.world_size = world_size_;
ip.args.wgp_count = wgp_count_;
/* A launch that ends its own link hold gets the hold word as an extra /* A launch that ends its own link hold gets the hold word as an extra
* `link_gate` parameter after the geometry's. */ * `link_gate` parameter after the geometry's. */
if (r.row->releases_link) if (r.row->releases_link)
@@ -777,13 +782,30 @@ const int32_t* Ctx::route_counts_device(int layer, int64_t* n_expert) const {
if (n_expert) *n_expert = 0; if (n_expert) *n_expert = 0;
if (layer < 0 || (size_t)layer >= route_.size()) return nullptr; if (layer < 0 || (size_t)layer >= route_.size()) return nullptr;
const RouteSlot& s = route_[(size_t)layer]; const RouteSlot& s = route_[(size_t)layer];
/* No step gate: route_report lands at the END of the block's passes (heat consumes it a /* No step gate: route_report lands at the END of the block's passes, so at the file stager's
* step later), but the reported buffer is the block's own ecnt, whose CONTENT the router * trigger (the layer's first expert op) the pointer is the one the last pass reported. That
* kernel rewrote this pass -- and the file stager's trigger runs after that router on the * is right only for a buffer whose address is the same in this pass: the block's own counts
* same stream, so a stream-ordered copy reads this pass's counts. The counts are indexed * buffer, which its router rewrites every pass -- and the trigger runs after that router on
* by the rank's local expert slot (the kernel subtracts expert_base), which is also what * the same stream, so a stream-ordered copy reads the counts of the rows about to run. The
* the mover's units carry. */ * counts are indexed by the rank's local expert slot (the kernel subtracts expert_base),
* which is also what the mover's units carry. */
if (!s.routing.expert_count || s.reported < 0) return nullptr; if (!s.routing.expert_count || s.reported < 0) return nullptr;
/* A transient buffer is at another offset at another arena level, and liveness lets a
* later buffer share its bytes, since no declared op reads the counts (the report is a
* handoff, not an op): the bytes under the last pass's pointer may be anything. A whole read
* is slow but right; counts read there could name a routed expert zero and leave it
* unread. Every architecture here declares the counts RAD_BUF_PERSIST. */
const char* p = (const char*)s.routing.expert_count;
const char* base = (const char*)arena_.base();
if (base && program_ && p >= base + program_->arena_fixed_bytes && p < base + arena_.bytes()) {
if (!route_transient_noted_) {
route_transient_noted_ = true;
RAD_WARN("rank %d: layer %d reports its routing counts in a transient buffer, so the "
"file stager reads its routed experts whole; declare the counts "
"RAD_BUF_PERSIST", rank_, layer);
}
return nullptr;
}
if (n_expert) *n_expert = s.routing.n_expert ? s.routing.n_expert : route_n_expert_; if (n_expert) *n_expert = s.routing.n_expert ? s.routing.n_expert : route_n_expert_;
return s.routing.expert_count; return s.routing.expert_count;
} }
@@ -942,23 +964,36 @@ int Ctx::lane_join(int from, int to) {
/* The key below reads every RadBatch field a pass's shape or arguments can depend on, by hand. A /* The key below reads every RadBatch field a pass's shape or arguments can depend on, by hand. A
* field added to RadBatch changes its size: decide whether the key must read it, then update the * field added to RadBatch changes its size: decide whether the key must read it, then update the
* size here. `agen_b` and `vgen_b` are set only on generator passes, which are never recorded * size here. The ABI-35 host mirrors are used by issue-time split selection; unsupported dynamic
* (below). */ * geometries fail closed via the pass-key contract, while Qwen keys its full-group maximum in the
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 408, * architecture callback. `agen_b`, `vgen_b` and `sgen_b` are set only on generator passes, which are
* never recorded (below). */
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 480,
"RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on"); "RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on");
static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 80, static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 88,
"RadKVGroupBatch changed: check that Ctx::pass_key reads every new field"); "RadKVGroupBatch changed: check that Ctx::pass_key reads every new field");
uint64_t Ctx::pass_key(const RadBatch* b) const { uint64_t Ctx::pass_key(const RadBatch* b) const {
/* Not recordable: encoder passes are shaped by their media, and passes carrying encoder rows /* Not recordable: encoder passes are shaped by their media, and passes carrying encoder rows
* issue the scatter only when they have some. */ * issue the scatter only when they have some (and the second attention over a run read both
if (b->enc || b->n_mm_rows > 0) return 0; * ways, n_bidi, only on such a pass). */
if (b->enc || b->n_mm_rows > 0 || b->n_bidi > 0) return 0;
/* A plugin with no pass-key callback cannot key a launch that splits its KV by the live
* context, so a prefill or mixed pass of a program holding such a launcher is not recorded.
* Its decode, verify and draft passes are: their launches get the keyed context bound in
* place of the live maximum (Ctx::issue_body). */
if (!arch_pass_key_ && (b->phase == RAD_PHASE_PREFILL || b->phase == RAD_PHASE_MIXED)) {
for (const IssuePlan& ip : issue_table_)
if (ip.row && ip.row->info &&
(ip.row->info->capabilities & RAD_KERNEL_CAP_DYNAMIC_PREFILL_SPLIT))
return 0;
}
/* A pass carrying a request's words for the plugin is shaped by them (a head issues per /* A pass carrying a request's words for the plugin is shaped by them (a head issues per
* sequence from their counts), and such a step samples a prompt's first token, which is not * sequence from their counts), and such a step samples a prompt's first token, which is not
* the repeating decode pass. */ * the repeating decode pass. */
if (b->n_plugin_words > 0) return 0; if (b->n_plugin_words > 0) return 0;
/* A generator pass is shaped by what RadBatch::gen_b, agen_b or vgen_b carries, which no key /* A generator pass is shaped by what RadBatch::gen_b, agen_b, vgen_b or sgen_b carries, which
* below reads. */ * no key below reads. */
if (b->gen) return 0; if (b->gen) return 0;
uint64_t h = 0x9e3779b97f4a7c15ull; uint64_t h = 0x9e3779b97f4a7c15ull;
auto mix = [&](uint64_t v) { auto mix = [&](uint64_t v) {
@@ -976,6 +1011,8 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
ptr(b->token_ids); ptr(b->positions); ptr(b->cu_seqlens); ptr(b->seq_ids); ptr(b->token_ids); ptr(b->positions); ptr(b->cu_seqlens); ptr(b->seq_ids);
ptr(b->out_ids); ptr(b->q_lens); ptr(b->ctx_lens); ptr(b->num_accepted); ptr(b->out_ids); ptr(b->q_lens); ptr(b->ctx_lens); ptr(b->num_accepted);
ptr(b->spec_parent); ptr(b->checkpoint_tok); ptr(b->checkpoint_slot); ptr(b->draft_out_ids); ptr(b->spec_parent); ptr(b->checkpoint_tok); ptr(b->checkpoint_slot); ptr(b->draft_out_ids);
/* A block drafter's query pass reads it (null on every other pass). */
ptr(b->anchor_rows);
/* Null on a step with no adapter row, which then issues no adapter op (Ctx::issue_lora): the /* Null on a step with no adapter row, which then issues no adapter op (Ctx::issue_lora): the
* two are different passes. The slots themselves are read on the card. */ * two are different passes. The slots themselves are read on the card. */
ptr(b->lora_slot); ptr(b->lora_slot);
@@ -989,6 +1026,11 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
/* A streamed group's view by the memory it names, never its address (kvstream_view_key). */ /* A streamed group's view by the memory it names, never its address (kvstream_view_key). */
mix(kvstream_view_key(k.stream)); mix(kvstream_view_key(k.stream));
} }
if (arch_pass_key_) {
const uint64_t geometry = arch_pass_key_(const_cast<Ctx*>(this), b, b->kv_used_max_h);
if (!geometry) return 0;
mix(geometry);
}
mix((uint64_t)level_); mix((uint64_t)level_);
mix(dense_epoch_); mix(dense_epoch_);
mix(domain_epoch_.load(std::memory_order_relaxed)); mix(domain_epoch_.load(std::memory_order_relaxed));
+11 -8
View File
@@ -40,10 +40,6 @@ class Registry;
struct XpState; struct XpState;
struct XpLayer; struct XpLayer;
/* The widest conventional op is gdn_conv_prep at sixteen operands (docs/OPS.md). Thirty-two leaves
* room for an architecture plugin's private ops without a variable-length array on the hot path. */
constexpr int MAX_OPERANDS = 32;
typedef void (*ArchStepFn)(RadCtx*, const RadBatch*); typedef void (*ArchStepFn)(RadCtx*, const RadBatch*);
/* "[shape]/[stride]" of a tensor's live dimensions, for diagnostics. */ /* "[shape]/[stride]" of a tensor's live dimensions, for diagnostics. */
@@ -196,6 +192,7 @@ struct CtxDesc {
RadStream stream = nullptr; /* null: the Ctx creates its own compute stream */ RadStream stream = nullptr; /* null: the Ctx creates its own compute stream */
ResidencyTable* residency = nullptr; /* null in the all-in-VRAM case */ ResidencyTable* residency = nullptr; /* null in the all-in-VRAM case */
ArchStepFn arch_step = nullptr; /* the architecture plugin's rad_arch_step */ ArchStepFn arch_step = nullptr; /* the architecture plugin's rad_arch_step */
uint64_t (*arch_pass_key)(RadCtx*, const RadBatch*, const int32_t*) = nullptr;
bool profile_ops = false; /* spec §16, and it changes what you measure */ bool profile_ops = false; /* spec §16, and it changes what you measure */
/* Whether a repeated pass may be recorded and played back. False for a caller whose pass /* Whether a repeated pass may be recorded and played back. False for a caller whose pass
* issues work the batch does not describe (e.g. a test driving another component through * issues work the batch does not describe (e.g. a test driving another component through
@@ -260,6 +257,7 @@ public:
} }
/* This rank's device ordinal, for the calls that name a card rather than a stream. */ /* This rank's device ordinal, for the calls that name a card rather than a stream. */
int device() const { return device_; } int device() const { return device_; }
int wgp_count() const { return wgp_count_; }
int world_size() const { return world_size_; } int world_size() const { return world_size_; }
RadStream stream() const { return stream_; } RadStream stream() const { return stream_; }
Program* program() const { return program_; } Program* program() const { return program_; }
@@ -334,10 +332,11 @@ public:
/* Called by the drain, so the ring knows which banks are still unread. */ /* Called by the drain, so the ring knows which banks are still unread. */
void mark_credited(int layer, int bank); void mark_credited(int layer, int bank);
const RadRouting* last_routing(int layer) const; const RadRouting* last_routing(int layer) const;
/* The device pointer of `layer`'s expert counts for the current step, with `n_expert` set, /* The device pointer of the buffer `layer`'s router writes its expert counts to, as the
* or null when the layer has not reported this step (a routing-aware file stager then * layer last reported it, with `n_expert` set; null when the layer has not reported yet, or
* reads the layer whole). The pointer is stream-ordered behind the router: a copy on the * when the buffer is a transient one (a routing-aware file stager then reads the layer
* compute stream at the stager's trigger sees this pass's counts. */ * whole). The router rewrites it every pass before the layer's first expert op, so a copy on
* the compute stream at the stager's trigger sees the counts of the rows about to run. */
const int32_t* route_counts_device(int layer, int64_t* n_expert) const; const int32_t* route_counts_device(int layer, int64_t* n_expert) const;
/* ---------------------------------------------------------- the placement seam */ /* ---------------------------------------------------------- the placement seam */
@@ -657,6 +656,8 @@ private:
bool staging_ = false; /* the stager armed for the pass being issued */ bool staging_ = false; /* the stager armed for the pass being issued */
int issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n); int issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n);
ArchStepFn arch_step_ = nullptr; ArchStepFn arch_step_ = nullptr;
uint64_t (*arch_pass_key_)(RadCtx*, const RadBatch*, const int32_t*) = nullptr;
int wgp_count_ = 32;
/* The expert prefetch's state (xp_state.h), null while it is off. */ /* The expert prefetch's state (xp_state.h), null while it is off. */
std::unique_ptr<XpState> xp_; std::unique_ptr<XpState> xp_;
@@ -778,6 +779,8 @@ private:
std::vector<RouteSlot> route_; std::vector<RouteSlot> route_;
int64_t route_n_expert_ = 0; int64_t route_n_expert_ = 0;
/* route_counts_device has said once that a layer's counts are a transient buffer. */
mutable bool route_transient_noted_ = false;
/* A bank is one step's histograms for every layer: [kRouteBanks][n_layer][n_expert] in pinned /* A bank is one step's histograms for every layer: [kRouteBanks][n_layer][n_expert] in pinned
* host memory. A report copies a layer's counts into its row of the card-side * host memory. A report copies a layer's counts into its row of the card-side
* [n_layer][n_expert] (an on-card copy that orders nothing else); the end of the pass copies * [n_layer][n_expert] (an on-card copy that orders nothing else); the end of the pass copies
+75
View File
@@ -10,6 +10,7 @@
* the host. See ctx.h for the cost budget (spec §3.2). * the host. See ctx.h for the cost budget (spec §3.2).
*/ */
#include <algorithm> #include <algorithm>
#include <cstdint>
#include <chrono> #include <chrono>
#include <functional> #include <functional>
#include <unordered_map> #include <unordered_map>
@@ -62,6 +63,66 @@ std::string tensor_shape_str(const RadTensor& t) {
return s + "]"; return s + "]";
} }
/* A device launch may use a host-side KV bound only when its exact operand maps to the host mirror
* of seqused (including a sequence slice), or to the position just after a one-sequence prefill
* piece. Never copy seqused back from a device queue here: the AQL upload may still be pending on
* another queue. */
static bool issue_vector_operand(const RadTensor& t) {
return (t.rank == 1 && t.stride[0] == 1) ||
(t.rank == 2 && t.shape[1] == 1 && t.stride[0] == 1 && t.stride[1] == 1);
}
static bool issue_host_span_max(const RadTensor& t, const int32_t* device, const int32_t* host,
int64_t total, int32_t* out) {
if (!t.data || !issue_vector_operand(t) || t.shape[0] <= 0 || !device || !host || total <= 0 || !out)
return false;
const std::uintptr_t p = reinterpret_cast<std::uintptr_t>(t.data);
const std::uintptr_t base = reinterpret_cast<std::uintptr_t>(device);
if (p < base) return false;
const std::uintptr_t delta = p - base;
if (delta % sizeof(int32_t)) return false;
const std::uint64_t first = delta / sizeof(int32_t);
const std::uint64_t count = (std::uint64_t)t.shape[0];
if (first > (std::uint64_t)total || count > (std::uint64_t)total - first) return false;
int32_t maximum = host[first];
for (std::uint64_t i = 1; i < count; ++i) maximum = std::max(maximum, host[first + i]);
*out = maximum;
return true;
}
static int32_t issue_kv_used_max_h(const RadBatch* b, const RadTensor* t, int n) {
if (!b || !t || b->n_seq <= 0) return -1;
bool have = false;
int32_t found = -1;
auto add = [&](int32_t value) {
if (!have) { found = value; have = true; }
else if (found != value) return false;
return true;
};
for (int i = 0; i < n; ++i) {
if (!t[i].data || !issue_vector_operand(t[i]) || t[i].shape[0] <= 0) continue;
if (b->kv) for (int g = 0; g < b->n_kv_groups; ++g) {
if (b->kv_used_max_h && t[i].data == b->kv[g].seqused &&
t[i].shape[0] == b->n_seq) {
if (!add(b->kv_used_max_h[g])) return -1;
continue;
}
int32_t used = -1;
if (issue_host_span_max(t[i], b->kv[g].seqused, b->kv[g].seqused_h,
b->n_seq, &used) && !add(used)) return -1;
}
/* ArPieces' first attention uses positions[R] as its exact KV end: it is the position after
* the first query piece. This special operand is one length for one ordinary prefill seq. */
if (b->phase == RAD_PHASE_PREFILL && b->n_seq == 1 && b->n_spec == 0 &&
b->draft_pass == 0 && t[i].shape[0] == 1) {
int32_t used = -1;
if (issue_host_span_max(t[i], b->positions, b->positions_h, b->n_tok, &used) &&
!add(used)) return -1;
}
}
return have ? found : -1;
}
/* Element offset to byte offset. False when it cannot be expressed: a mid-byte offset into a /* Element offset to byte offset. False when it cannot be expressed: a mid-byte offset into a
* packed sub-byte weight (e.g. an odd W4 element), or a plugin-private dtype with no core-known * packed sub-byte weight (e.g. an odd W4 element), or a plugin-private dtype with no core-known
* size. */ * size. */
@@ -854,6 +915,17 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
/* The rest of RadArgs was filled in at prepare; args.t already points at tbuf_. There is one /* The rest of RadArgs was filled in at prepare; args.t already points at tbuf_. There is one
* entry per schema operand, the trailing optional ones the issue left out null. */ * entry per schema operand, the trailing optional ones the issue left out null. */
ip.args.n_t = std::max(n_opd, (int)p.n_opd_schema); ip.args.n_t = std::max(n_opd, (int)p.n_opd_schema);
ip.args.kv_used_max_h = issue_kv_used_max_h(batch_, t, ip.args.n_t);
/* A plugin with no pass-key callback has its decode, verify and draft passes recorded
* (pass_key), and a played pass keeps the arguments it was recorded with, so a launch there
* must not read a bound the key does not: it gets the step's context bound plus its longest
* query, both keyed, which crosses a bucket every 1024 tokens or more (batch.cpp) instead of
* moving with every token. Its prefill and mixed passes are never recorded and keep the
* exact maximum. */
if (ip.args.kv_used_max_h > 0 && !arch_pass_key_ && batch_ &&
batch_->phase != RAD_PHASE_PREFILL && batch_->phase != RAD_PHASE_MIXED)
ip.args.kv_used_max_h = (int32_t)std::min<int64_t>(
INT32_MAX, (int64_t)batch_->max_ctx_len + batch_->max_q_len);
p.issued = true; p.issued = true;
++n_issues_; ++n_issues_;
@@ -1280,6 +1352,9 @@ int rad_kv_layer_index(RadCtx* c, rad_kvgroup group, int layer) {
} }
int rad_rank(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->rank() : 0; } int rad_rank(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->rank() : 0; }
int rad_world_size(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->world_size() : 1; } int rad_world_size(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->world_size() : 1; }
int rad_ctx_wgp_count(RadCtx* c) {
return c ? static_cast<rad::Ctx*>(c)->wgp_count() : 32;
}
RadStream rad_stream(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->stream() : nullptr; } RadStream rad_stream(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->stream() : nullptr; }
/* The second lane. `rad_lane` selects the lane subsequent issues launch on; `rad_lane_join` /* The second lane. `rad_lane` selects the lane subsequent issues launch on; `rad_lane_join`
+50 -20
View File
@@ -119,8 +119,13 @@ static RadOperand opd_none() {
static int64_t rows_for(const SamplerConfig& c) { static int64_t rows_for(const SamplerConfig& c) {
/* One row per sampled position: a verify samples n_spec+1 positions per sequence, each with /* One row per sampled position: a verify samples n_spec+1 positions per sequence, each with
* its own RNG coordinate. Sized for the worst step, as the arena is (spec §3.1). */ * its own RNG coordinate. Sized for the worst step, as the arena is (spec §3.1). A step
return c.max_seqs * (int64_t)(c.max_spec + 1); * carries at most max_tok tokens and samples at most one row per token, so a deep drafter
* at the default 256 sequences no longer sizes every plane for 256 * (depth + 1) rows; a
* drafter's greedy pass stages one row per drafting sequence, so never below max_seqs. */
const int64_t want = c.max_seqs * (int64_t)(c.max_spec + 1);
if (c.max_tok <= 0) return want;
return std::min(want, std::max(c.max_tok, c.max_seqs));
} }
/* ================================================================== declare */ /* ================================================================== declare */
@@ -331,8 +336,9 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
RAD_TRY(stage_alloc()); RAD_TRY(stage_alloc());
declared_ = true; declared_ = true;
RAD_INFO("sampler: %lld-token vocabulary (%lld this rank), %lld rows, %lld mask words " RAD_INFO("sampler: %lld-token vocabulary (%lld this rank), %lld rows%s, %lld mask words "
"(%s per row)", (long long)cfg_.n_vocab, (long long)nv, (long long)rows, "(%s per row)", (long long)cfg_.n_vocab, (long long)nv, (long long)rows,
rows < cfg_.max_seqs * (int64_t)(cfg_.max_spec + 1) ? " (the step's token bound)" : "",
(long long)mask_words_, humanb(mask_words_ * 4).c_str()); (long long)mask_words_, humanb(mask_words_ * 4).c_str());
return RAD_OK; return RAD_OK;
} }
@@ -980,6 +986,7 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
if (budget && think.inside() && think.body >= sp.thinking_budget) if (budget && think.inside() && think.body >= sp.thinking_budget)
force_close(p, row, sp.reasoning.close); force_close(p, row, sp.reasoning.close);
if (!sp.suppress_tokens.empty()) suppress(p, row, sp.suppress_tokens);
if (want_lp) { if (want_lp) {
/* Temperature the candidate value carries: early and late, each counted only /* Temperature the candidate value carries: early and late, each counted only
@@ -1038,6 +1045,19 @@ void Sampler::force_close(DeviceSampleParams& p, int64_t row, int32_t close) {
p.flags |= RAD_SP_MASK; p.flags |= RAD_SP_MASK;
} }
void Sampler::suppress(DeviceSampleParams& p, int64_t row, const std::vector<int32_t>& ids) {
uint32_t* dst = mask_stage_ + row * mask_words_;
if (!(p.flags & RAD_SP_MASK)) {
std::memset(dst, 0xff, (size_t)mask_words_ * 4);
p.mask_row = (int32_t)row;
p.flags |= RAD_SP_MASK;
}
for (int32_t id : ids) {
const int64_t at = (int64_t)id - cfg_.vocab_off;
if (at >= 0 && at < cfg_.n_vocab_local) dst[at >> 5] &= ~(1u << (uint32_t)(at & 31));
}
}
int Sampler::build_greedy(int64_t n) { int Sampler::build_greedy(int64_t n) {
if (!declared_) return RAD_E_STATE; if (!declared_) return RAD_E_STATE;
if (n < 0) return RAD_E_INVAL; if (n < 0) return RAD_E_INVAL;
@@ -1054,13 +1074,11 @@ int Sampler::build_greedy(int64_t n) {
any_ngram_wl_ = false; any_ngram_wl_ = false;
any_couple_ = false; any_couple_ = false;
cur_stage_ = greedy_stage_; cur_stage_ = greedy_stage_;
/* A drafter's rows run the argmax only, so the n-gram plane is cleared: `run` reads it from /* Nothing a step's build staged is written here: a drafter's pass is built right after the
* the staging, and a stale pair from an earlier request's build must not issue the ban over * step's chain was issued, whose uploads read the pinned staging only when the stream reaches
* history that was not staged this step. The exemption plane needs no clear: `run` uploads * them, behind the step's forward. So the n-gram pairs stay as the step staged them and the
* it only beside an issued ban, every row that runs the ban has its words rewritten in full * ban is gated on any_ngram_, which this clears; before, the pairs were zeroed here and a
* by the build that staged the pair (build_step), and rows below a zeroed pair are skipped * banning step with drafter passes uploaded the zeros, so the ban never ran on the card. */
* by the op before they read a word. */
std::memset(ngram_stage_, 0, (size_t)cap * 2 * sizeof(int32_t));
if (greedy_ready_) return RAD_OK; if (greedy_ready_) return RAD_OK;
for (int64_t i = 0; i < cap; ++i) { for (int64_t i = 0; i < cap; ++i) {
DeviceSampleParams& p = greedy_stage_[i]; DeviceSampleParams& p = greedy_stage_[i];
@@ -1083,27 +1101,32 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
const RadStream s = rad_stream(c); const RadStream s = rad_stream(c);
bool any_mask = false, any_greedy = false, any_chain = false; bool any_mask = false, any_greedy = false, any_chain = false;
bool any_penalty = false, any_dry = false, any_xtc = false, any_ngram = false; bool any_penalty = false, any_dry = false, any_xtc = false;
bool any_topp = false, any_minp = false, any_typ = false, any_temp = false; bool any_topp = false, any_minp = false, any_typ = false, any_temp = false;
for (int64_t i = 0; i < n_seq_; ++i) { for (int64_t i = 0; i < n_seq_; ++i) {
const DeviceSampleParams& p = cur_stage_[i]; const DeviceSampleParams& p = cur_stage_[i];
any_mask |= (p.flags & RAD_SP_MASK) != 0; any_mask |= (p.flags & RAD_SP_MASK) != 0;
any_penalty |= (p.flags & RAD_SP_PENALTY) != 0; any_penalty |= (p.flags & RAD_SP_PENALTY) != 0;
any_dry |= (p.flags & RAD_SP_DRY) != 0; any_dry |= (p.flags & RAD_SP_DRY) != 0;
any_xtc |= (p.flags & RAD_SP_XTC) != 0;
/* The pair plane is read directly, not through cur_stage_: it is per-step staging the
* LAST builder filled (build_step writes a row's pair, build_greedy zeroes every pair),
* so it agrees with cur_stage_ by builder contract. A new builder must keep that
* contract: stage the pair with the params, zero it with the greedy ones. */
any_ngram |= ngram_stage_[2 * i] > 0;
if (p.flags & RAD_SP_GREEDY) any_greedy = true; if (p.flags & RAD_SP_GREEDY) any_greedy = true;
else { else {
any_chain = true; any_chain = true;
/* sample_temp leaves a row at temperature <= 0 or exactly 1 as it is */ /* sample_temp leaves a row at temperature <= 0 or exactly 1 as it is */
any_temp |= p.temp > 0.0f && p.temp != 1.0f; any_temp |= p.temp > 0.0f && p.temp != 1.0f;
any_topp |= p.top_p < 1.0f; /* The cuts only remove candidates, and a top-1 row has one: a greedy row over a split
any_minp |= p.min_p > 0.0f; * vocabulary or asking for logprobs, and every row of a drafter's greedy pass. Every
any_typ |= p.typical_p < 1.0f; * implementation keeps it (top-p and min-p keep the best, typical keeps a lone
* candidate, XTC needs two above its threshold), so such a row issues none of them;
* nor does a top_p or typical_p outside (0, 1), which every kernel skips. A drafter's
* greedy pass under a split vocabulary, whose rows are zeroed, issued top-p and
* typical every round: two launches with a max and a sum over the candidate width a
* row, for nothing. */
if (p.top_k != 1) {
any_topp |= p.top_p > 0.0f && p.top_p < 1.0f;
any_minp |= p.min_p > 0.0f;
any_typ |= p.typical_p > 0.0f && p.typical_p < 1.0f;
any_xtc |= (p.flags & RAD_SP_XTC) != 0;
}
} }
} }
@@ -1115,6 +1138,13 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
return RAD_E_STATE; return RAD_E_STATE;
} }
/* The ban runs only for a build_step build in which some row's staged history holds a whole
* n-gram (any_ngram_; build_greedy clears it). A shorter one bans nothing, however the op is
* implemented, so neither the op nor its planes are issued for it. The pair plane is not
* scanned for a row with a positive n: a drafter's greedy build leaves it as the step staged
* it (see build_greedy). */
const bool any_ngram = any_ngram_;
/* Async copies on the compute stream, only of what some row reads. The mask is 19 KiB per /* Async copies on the compute stream, only of what some row reads. The mask is 19 KiB per
* constrained sequence at a 151K vocab, which keeps a host-side grammar affordable * constrained sequence at a 151K vocab, which keeps a host-side grammar affordable
* (spec §13). */ * (spec §13). */
+15 -2
View File
@@ -106,6 +106,12 @@ struct SamplerConfig {
int64_t max_seqs = 0; /* the largest number of sequences one step may carry */ int64_t max_seqs = 0; /* the largest number of sequences one step may carry */
int64_t max_hist = 2048; /* the penalty window bound; a longer request is truncated */ int64_t max_hist = 2048; /* the penalty window bound; a longer request is truncated */
int max_spec = 0; int max_spec = 0;
/* The step's token bound (--max-num-batched-tokens), 0 for none. A step samples one row per
* token it verifies or completes, and the model's logits rows are capped here too
* (rad_arch.h, max_logit_rows), so rows past it could never be staged; the planes are sized
* for min(max_seqs * (max_spec + 1), max(max_tok, max_seqs)). Never below max_seqs: a drafter
* pass stages one greedy row per sequence it drafts for (build_greedy). */
int64_t max_tok = 0;
int rank = 0; int rank = 0;
int world_size = 1; int world_size = 1;
/* This rank's first vocabulary row. sample_topk adds it to the candidate ids it packs into /* This rank's first vocabulary row. sample_topk adds it to the candidate ids it packs into
@@ -218,6 +224,9 @@ public:
* meaningful only where the row carries RAD_SP_MASK. */ * meaningful only where the row carries RAD_SP_MASK. */
const uint32_t* staged_mask(int64_t row) const { return mask_stage_ + row * mask_words_; } const uint32_t* staged_mask(int64_t row) const { return mask_stage_ + row * mask_words_; }
int64_t mask_words() const { return mask_words_; } int64_t mask_words() const { return mask_words_; }
/* Staged row `row`'s n-gram ban pair {n, window}, as the last build_step staged it: a greedy
* build leaves it, since that step's upload may not have read it yet. */
const int32_t* staged_ngram(int64_t row) const { return ngram_stage_ + 2 * row; }
/* Staged row `row`'s bound coupled state, as `run` uploads it: all-zero where the row carries /* Staged row `row`'s bound coupled state, as `run` uploads it: all-zero where the row carries
* none (bonus row, greedy row, uncoupled step). Lets a build be checked without a device. */ * none (bonus row, greedy row, uncoupled step). Lets a build be checked without a device. */
const RadMtpCoupleState& staged_couple(int64_t row) const { return couple_stage_[row]; } const RadMtpCoupleState& staged_couple(int64_t row) const { return couple_stage_[row]; }
@@ -267,6 +276,9 @@ private:
* inside the block. A grammar mask on the row wins: the close is forced only where the * inside the block. A grammar mask on the row wins: the close is forced only where the
* grammar admits it, otherwise at a later position. */ * grammar admits it, otherwise at a later position. */
void force_close(DeviceSampleParams& p, int64_t row, int32_t close); void force_close(DeviceSampleParams& p, int64_t row, int32_t close);
/* Take `ids` out of the row: from the grammar's mask where it has one, from a full row where
* not. */
void suppress(DeviceSampleParams& p, int64_t row, const std::vector<int32_t>& ids);
SamplerConfig cfg_{}; SamplerConfig cfg_{};
const VocabView* vocab_ = nullptr; const VocabView* vocab_ = nullptr;
@@ -341,8 +353,9 @@ private:
/* Whether any DRY row this step has breakers; only then is the breaker plane uploaded and /* Whether any DRY row this step has breakers; only then is the breaker plane uploaded and
* passed to sample_dry. */ * passed to sample_dry. */
bool any_brk_ = false; bool any_brk_ = false;
/* Whether any row this step runs the n-gram ban. Its history is the plane the penalties use, /* Whether any row this step runs the n-gram ban over a history at least its n-gram long; a
* so this only decides whether that plane is uploaded and the op issued. */ * shorter one bans nothing. Its history is the plane the penalties use, so this only decides
* whether that plane is uploaded and the op issued. Cleared by build_greedy. */
bool any_ngram_ = false; bool any_ngram_ = false;
/* Whether any banned row this step whitelists a column of this rank's shard; only then is /* Whether any banned row this step whitelists a column of this rank's shard; only then is
* the exemption plane uploaded and passed to sample_ngram_ban. */ * the exemption plane uploaded and passed to sample_ngram_ban. */
+6 -1
View File
@@ -48,7 +48,11 @@ struct StepSlot {
* drafter's context rows by it. 0 after a chain verify, which needs neither. */ * drafter's context rows by it. 0 after a chain verify, which needs neither. */
int32_t npath; int32_t npath;
int32_t path[RAD_SCHED_MAX_SPEC]; int32_t path[RAD_SCHED_MAX_SPEC];
int32_t pad[2]; /* The last verify step's row of its last committed position, in that step's own row order,
* which a block drafter's context pass mirrors. ADV_BLOCK hands it to the query pass
* (RadBatch::anchor_rows): LiLiCorr's correlator reads the context state there. */
int32_t hrow;
int32_t pad[1];
}; };
enum AdvMode : int32_t { enum AdvMode : int32_t {
@@ -115,6 +119,7 @@ struct AdvanceArgs {
int32_t n_groups = 0; int32_t n_groups = 0;
char* slab = nullptr; /* this rank's device slab */ char* slab = nullptr; /* this rank's device slab */
int64_t tok_off = 0, pos_off = 0, ctx_off = 0, acc_off = 0, out_off = 0; int64_t tok_off = 0, pos_off = 0, ctx_off = 0, acc_off = 0, out_off = 0;
int64_t arow_off = -1; /* [n_seq] ADV_BLOCK: each row's StepSlot::hrow; -1 when not carved */
int64_t sid_off = 0, cu_off = 0, q_off = 0; int64_t sid_off = 0, cu_off = 0, q_off = 0;
/* [4][row_pitch] int32: device-row flag; the verify step's token row of the row's first /* [4][row_pitch] int32: device-row flag; the verify step's token row of the row's first
* verified position; its first sampled row, or -1 for a row that sampled nothing; and one * verified position; its first sampled row, or -1 for a row that sampled nothing; and one
+3
View File
@@ -153,6 +153,7 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
S.ctx = head + 1; S.ctx = head + 1;
S.n_acc = acc + 1; S.n_acc = acc + 1;
S.tok[0] = y[acc == 0 ? 0 : S.path[acc - 1]]; S.tok[0] = y[acc == 0 ? 0 : S.path[acc - 1]];
S.hrow = rtok + (acc == 0 ? 0 : S.path[acc - 1]); /* rows are nodes, in order */
S.npath = acc; S.npath = acc;
return; return;
} }
@@ -167,6 +168,7 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
const int32_t head = ctx[i] + (rtok - k) + acc; const int32_t head = ctx[i] + (rtok - k) + acc;
S.acc = acc; S.acc = acc;
S.head = head; S.head = head;
S.hrow = rtok + acc;
S.ctx = head + 1; S.ctx = head + 1;
S.n_acc = acc + 1; S.n_acc = acc + 1;
S.tok[0] = y[acc]; S.tok[0] = y[acc];
@@ -296,6 +298,7 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
for (int32_t j = 1; j < n; ++j) tok[k + j] = aux; for (int32_t j = 1; j < n; ++j) tok[k + j] = aux;
for (int32_t j = 0; j < n; ++j) adv_pos(a, pos, k + j, base + j); for (int32_t j = 0; j < n; ++j) adv_pos(a, pos, k + j, base + j);
ctx[i] = base; ctx[i] = base;
if (a.arow_off >= 0) adv_i32(a, a.arow_off)[i] = S.hrow;
adv_groups(a, i, k, base, n); adv_groups(a, i, k, base, n);
return; return;
} }
+45 -1
View File
@@ -123,6 +123,7 @@ void BatchBuilder::carve(Set& s, char* h) {
/* The advance's per-sequence runtime-window data (advance.h); 0 when there is none. */ /* The advance's per-sequence runtime-window data (advance.h); 0 when there is none. */
pair(&s.h_rpos, &s.d_rpos, S); pair(&s.h_rpos, &s.d_rpos, S);
pair(&s.h_tlen, &s.d_tlen, S); pair(&s.h_tlen, &s.d_tlen, S);
pair(&s.h_arow, &s.d_arow, S);
s.h_grp = ::rad::carve<AdvGroup>(h, oh, (int64_t)s.groups.size()); s.h_grp = ::rad::carve<AdvGroup>(h, oh, (int64_t)s.groups.size());
s.d_grp = ::rad::carve<AdvGroup>(d, od, (int64_t)s.groups.size()); s.d_grp = ::rad::carve<AdvGroup>(d, od, (int64_t)s.groups.size());
for (size_t gi = 0; gi < s.groups.size(); ++gi) { for (size_t gi = 0; gi < s.groups.size(); ++gi) {
@@ -135,6 +136,7 @@ void BatchBuilder::carve(Set& s, char* h) {
* moves a rotary position off the token index. */ * moves a rotary position off the token index. */
pair(&s.h_rope, &s.d_rope, mm_on_ ? 3 * T : 0); pair(&s.h_rope, &s.d_rope, mm_on_ ? 3 * T : 0);
pair(&s.h_mmrow, &s.d_mmrow, mm_on_ ? T : 0); pair(&s.h_mmrow, &s.d_mmrow, mm_on_ ? T : 0);
pair(&s.h_bidi, &s.d_bidi, bidi_on_ ? 4 * T : 0);
/* Each row's adapter slot, carved only when the engine serves adapters, so an engine without /* Each row's adapter slot, carved only when the engine serves adapters, so an engine without
* them lays the slab out as if the array did not exist. */ * them lays the slab out as if the array did not exist. */
pair(&s.h_lora, &s.d_lora, lora_on_ ? T : 0); pair(&s.h_lora, &s.d_lora, lora_on_ ? T : 0);
@@ -245,6 +247,7 @@ int BatchBuilder::alloc_set(Set& s, const std::vector<KVGroupInfo>& groups) {
o.kv.assign(ranks_.size(), std::vector<RadKVGroupBatch>(s.groups.size())); o.kv.assign(ranks_.size(), std::vector<RadKVGroupBatch>(s.groups.size()));
o.stream.assign(ranks_.size(), std::vector<RadKVStream>(s.groups.size())); o.stream.assign(ranks_.size(), std::vector<RadKVStream>(s.groups.size()));
o.batch.assign(ranks_.size(), RadBatch{}); o.batch.assign(ranks_.size(), RadBatch{});
o.kv_used_max_h.assign(s.groups.size(), 0);
o.seqs.clear(); o.seqs.clear();
o.seqs.reserve((size_t)max_seqs_); /* a build fills it without allocating */ o.seqs.reserve((size_t)max_seqs_); /* a build fills it without allocating */
o.has_seqs = false; o.has_seqs = false;
@@ -480,6 +483,7 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
}); });
mm_on_ = prog.encoder.modalities != 0 || prog.audio_encoder.modalities != 0; mm_on_ = prog.encoder.modalities != 0 || prog.audio_encoder.modalities != 0;
bidi_on_ = prog.encoder.modalities != 0 && prog.encoder.bidirectional != 0;
lora_on_ = cfg.lora.enabled(); lora_on_ = cfg.lora.enabled();
pw_cap_ = prog.plugin_words; pw_cap_ = prog.plugin_words;
return RAD_OK; return RAD_OK;
@@ -725,7 +729,13 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
first = kv.first_block_pos(e.seq, (int32_t)gi); first = kv.first_block_pos(e.seq, (int32_t)gi);
has_win = kv.runtime_window(e.seq, (int32_t)gi, &win); has_win = kv.runtime_window(e.seq, (int32_t)gi, &win);
if (has_win) { if (has_win) {
assert(!ring_blocks || ring_blocks == (int32_t)win.ring_blocks); /* The ring size sets the group header's geometry, so every sequence in the
* group must report the same one. */
if (ring_blocks && ring_blocks != (int32_t)win.ring_blocks) {
RAD_ERR("kv group %d: sequences report ring sizes of %d and %d blocks",
(int)gi, (int)ring_blocks, (int)win.ring_blocks);
return RAD_E_STATE;
}
ring_blocks = (int32_t)win.ring_blocks; ring_blocks = (int32_t)win.ring_blocks;
} }
bt_len = (int64_t)bt.size(); bt_len = (int64_t)bt.size();
@@ -808,6 +818,10 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
(int)g.sidx_pitch); (int)g.sidx_pitch);
} }
} }
int32_t group_used = 0;
for (int64_t i = 0; i < n_seq; ++i)
group_used = std::max(group_used, g.h_used[i]);
o.kv_used_max_h[gi] = group_used;
/* A state group's rows are one slot per sequence: n_seq words, restaged whole. */ /* A state group's rows are one slot per sequence: n_seq words, restaged whole. */
if (!L.paged) { if (!L.paged) {
stage(g.bt_fix, np, n_seq); stage(g.bt_fix, np, n_seq);
@@ -846,6 +860,7 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
b.block_table = on_rank(base, s.dev[0], g.d_bt); b.block_table = on_rank(base, s.dev[0], g.d_bt);
b.block_table_pitch = pitch; b.block_table_pitch = pitch;
b.seqused = on_rank(base, s.dev[0], g.d_used); b.seqused = on_rank(base, s.dev[0], g.d_used);
b.seqused_h = g.h_used;
b.state_index = on_rank(base, s.dev[0], g.d_sidx); b.state_index = on_rank(base, s.dev[0], g.d_sidx);
b.state_index_pitch = g.sidx_pitch; b.state_index_pitch = g.sidx_pitch;
b.block_size = L.block_size; b.block_size = L.block_size;
@@ -933,6 +948,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
int64_t n_out = 0, n_dout = 0; int64_t n_out = 0, n_dout = 0;
int32_t rope_mixed = 0; int32_t rope_mixed = 0;
int64_t n_mm = 0; int64_t n_mm = 0;
int64_t n_bidi = 0;
bool lora_rows = false; bool lora_rows = false;
int32_t cvec_rows = 0; int32_t cvec_rows = 0;
int64_t n_pw = 0; int64_t n_pw = 0;
@@ -1022,6 +1038,23 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
n_mm += got; n_mm += got;
} }
} }
/* The part of each picture's or video frame's run inside this chunk, read both ways
* (RadBatch::n_bidi), on a trunk pass: its rows see the keys up to the run's end, or the
* chunk's where a run longer than any step was cut (Scheduler::bidi_fit). */
if (bidi_on_ && plan.draft_pass == 0 && shift == 0 && e.req && e.req->media) {
const mm::PromptMedia& pm = *e.req->media;
const int64_t c0 = e.ctx_len, c1 = c0 + e.n_tokens, T = max_tok_;
for (const mm::RopeLayout::Run& run : pm.rope.runs) {
const int64_t a = std::max<int64_t>(run.tok, c0);
const int64_t b = std::min<int64_t>((int64_t)run.tok + run.n, c1);
if (a >= b || pm.items[(size_t)run.item].item->kind == mm::Kind::Audio) continue;
s.h_bidi[n_bidi] = (int32_t)b;
s.h_bidi[T + n_bidi] = (int32_t)(k + a - c0);
s.h_bidi[2 * T + n_bidi] = (int32_t)(b - a);
s.h_bidi[3 * T + n_bidi] = (int32_t)i;
++n_bidi;
}
}
if (e.ckpt_tok >= 0 && e.ckpt_slot >= 0) { if (e.ckpt_tok >= 0 && e.ckpt_slot >= 0) {
/* checkpoint_tok indexes this step's tokens: the sequence's base plus the offset the /* checkpoint_tok indexes this step's tokens: the sequence's base plus the offset the
* scheduler chose, the last token of a checkpoint interval (§7.3). */ * scheduler chose, the last token of a checkpoint interval (§7.3). */
@@ -1075,6 +1108,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
s.h_q[i] = e.n_tokens; s.h_q[i] = e.n_tokens;
s.h_ctx[i] = e.ctx_len; s.h_ctx[i] = e.ctx_len;
s.h_acc[i] = e.n_accepted; s.h_acc[i] = e.n_accepted;
s.h_arow[i] = -1;
if (e.is_prefill) { if (e.n_tokens > max_q_pf) max_q_pf = e.n_tokens; } if (e.is_prefill) { if (e.n_tokens > max_q_pf) max_q_pf = e.n_tokens; }
else { if (e.n_tokens > max_q_dec) max_q_dec = e.n_tokens; } else { if (e.n_tokens > max_q_dec) max_q_dec = e.n_tokens; }
} }
@@ -1205,6 +1239,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
B.n_seq = n_seq; B.n_seq = n_seq;
B.token_ids = on_rank(base, b0, s.d_tok); B.token_ids = on_rank(base, b0, s.d_tok);
B.positions = on_rank(base, b0, s.d_pos); B.positions = on_rank(base, b0, s.d_pos);
B.positions_h = s.h_pos;
B.cu_seqlens = on_rank(base, b0, s.d_cu); B.cu_seqlens = on_rank(base, b0, s.d_cu);
B.seq_ids = on_rank(base, b0, s.d_sid); B.seq_ids = on_rank(base, b0, s.d_sid);
B.n_out = n_out; B.n_out = n_out;
@@ -1220,6 +1255,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
B.max_q_len_decode = max_q_dec; B.max_q_len_decode = max_q_dec;
B.max_q_len_prefill = max_q_pf; B.max_q_len_prefill = max_q_pf;
B.max_ctx_len = (int32_t)ctx_bound; B.max_ctx_len = (int32_t)ctx_bound;
B.kv_used_max_h = o.kv_used_max_h.data();
B.n_kv_groups = (int)o.kv[r].size(); B.n_kv_groups = (int)o.kv[r].size();
B.kv = o.kv[r].data(); B.kv = o.kv[r].data();
B.draft_pass = plan.draft_pass; B.draft_pass = plan.draft_pass;
@@ -1230,10 +1266,17 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
B.num_accepted = cfg_.n_spec > 0 ? on_rank(base, b0, s.d_acc) : nullptr; B.num_accepted = cfg_.n_spec > 0 ? on_rank(base, b0, s.d_acc) : nullptr;
/* Staged above on a tree step: each row's parent row, -2 for an ordinary causal one. */ /* Staged above on a tree step: each row's parent row, -2 for an ordinary causal one. */
B.spec_parent = plan.spec_is_tree ? on_rank(base, b0, s.d_parent) : nullptr; B.spec_parent = plan.spec_is_tree ? on_rank(base, b0, s.d_parent) : nullptr;
/* Pass 1 is a block drafter's query pass (a serial head has no pass 1). */
B.anchor_rows = plan.draft_pass == 1 ? on_rank(base, b0, s.d_arow) : nullptr;
B.rope_pos = mm_on_ ? on_rank(base, b0, s.d_rope) : nullptr; B.rope_pos = mm_on_ ? on_rank(base, b0, s.d_rope) : nullptr;
B.rope_mixed = rope_mixed; B.rope_mixed = rope_mixed;
B.n_mm_rows = n_mm; B.n_mm_rows = n_mm;
B.mm_rows = n_mm ? on_rank(base, b0, s.d_mmrow) : nullptr; B.mm_rows = n_mm ? on_rank(base, b0, s.d_mmrow) : nullptr;
B.n_bidi = n_bidi;
B.bidi_used = n_bidi ? on_rank(base, b0, s.d_bidi) : nullptr;
B.bidi_row = n_bidi ? s.h_bidi + max_tok_ : nullptr;
B.bidi_n = n_bidi ? s.h_bidi + 2 * max_tok_ : nullptr;
B.bidi_seq = n_bidi ? s.h_bidi + 3 * max_tok_ : nullptr;
B.mm_embd = n_mm ? mm_dev_[r] : nullptr; B.mm_embd = n_mm ? mm_dev_[r] : nullptr;
/* Null on a step with no adapter row: the core then issues no adapter op, and the step /* Null on a step with no adapter row: the core then issues no adapter op, and the step
* runs the same pass as an engine serving no adapters. */ * runs the same pass as an engine serving no adapters. */
@@ -1309,6 +1352,7 @@ AdvanceArgs BatchBuilder::advance_args(int rank) const {
a.ctx_off = off(s.d_ctx); a.ctx_off = off(s.d_ctx);
a.acc_off = off(s.d_acc); a.acc_off = off(s.d_acc);
a.out_off = off(s.d_out); a.out_off = off(s.d_out);
a.arow_off = off(s.d_arow);
a.sid_off = off(s.d_sid); a.sid_off = off(s.d_sid);
a.cu_off = off(s.d_cu); a.cu_off = off(s.d_cu);
a.q_off = off(s.d_q); a.q_off = off(s.d_q);
+9
View File
@@ -220,12 +220,19 @@ private:
* runtime window (advance.h). Per sequence because each prompt has its own floor. */ * runtime window (advance.h). Per sequence because each prompt has its own floor. */
int32_t *h_rpos = nullptr, *d_rpos = nullptr; int32_t *h_rpos = nullptr, *d_rpos = nullptr;
int32_t *h_tlen = nullptr, *d_tlen = nullptr; int32_t *h_tlen = nullptr, *d_tlen = nullptr;
/* [max_seqs] a block drafter's query pass: each row's last committed row in the context
* pass just run (RadBatch::anchor_rows), written on the card by ADV_BLOCK. */
int32_t *h_arow = nullptr, *d_arow = nullptr;
char* h_derived = nullptr; /* derivation staging, byte-addressed */ char* h_derived = nullptr; /* derivation staging, byte-addressed */
/* [3][n_tok] rotary positions and [n_tok] encoder-row targets (RadBatch::rope_pos, /* [3][n_tok] rotary positions and [n_tok] encoder-row targets (RadBatch::rope_pos,
* mm_rows): carved only when the program declared an encoder, empty otherwise. */ * mm_rows): carved only when the program declared an encoder, empty otherwise. */
int32_t *h_rope = nullptr, *d_rope = nullptr; int32_t *h_rope = nullptr, *d_rope = nullptr;
int32_t *h_mmrow = nullptr, *d_mmrow = nullptr; int32_t *h_mmrow = nullptr, *d_mmrow = nullptr;
/* [4][max_tok] the runs read both ways (RadBatch::n_bidi): their key counts (the one plane
* the device reads), first rows, rows and sequences; carved only when the program's
* encoder asks for them (RadEncoderDecl::bidirectional). */
int32_t *h_bidi = nullptr, *d_bidi = nullptr;
/* [n_tok] each row's runtime LoRA adapter slot (RadBatch::lora_slot): carved only when the /* [n_tok] each row's runtime LoRA adapter slot (RadBatch::lora_slot): carved only when the
* engine serves adapters, empty otherwise. */ * engine serves adapters, empty otherwise. */
int32_t *h_lora = nullptr, *d_lora = nullptr; int32_t *h_lora = nullptr, *d_lora = nullptr;
@@ -265,6 +272,7 @@ private:
/* Per rank and group, the RadKVStream a batch names: each rank's own copy, outside the slab. */ /* Per rank and group, the RadKVStream a batch names: each rank's own copy, outside the slab. */
std::vector<std::vector<RadKVStream>> stream; std::vector<std::vector<RadKVStream>> stream;
std::vector<RadBatch> batch; std::vector<RadBatch> batch;
std::vector<int32_t> kv_used_max_h;
/* The build's sequences in row order (step_seqs); none for an encoder pass. */ /* The build's sequences in row order (step_seqs); none for an encoder pass. */
std::vector<uint64_t> seqs; std::vector<uint64_t> seqs;
bool has_seqs = false; bool has_seqs = false;
@@ -344,6 +352,7 @@ private:
* (see RadBatch::mm_embd). The staging is refilled only after its last upload has run * (see RadBatch::mm_embd). The staging is refilled only after its last upload has run
* (`mm_ev_`). */ * (`mm_ev_`). */
bool mm_on_ = false; bool mm_on_ = false;
bool bidi_on_ = false; /* RadEncoderDecl::bidirectional */
/* The engine serves runtime LoRA adapters (Config::lora): the batch carries each row's slot. */ /* The engine serves runtime LoRA adapters (Config::lora): the batch carries each row's slot. */
bool lora_on_ = false; bool lora_on_ = false;
/* Program::plugin_words: the words a sequence may carry, 0 for none. */ /* Program::plugin_words: the words a sequence may carry, 0 for none. */
+4 -2
View File
@@ -9,11 +9,13 @@
namespace rad { namespace rad {
/* lcm, with a non-positive side meaning "no constraint yet". */ /* lcm, with a non-positive side meaning "no constraint yet". The sides are plugin-declared; an lcm
* past int64 saturates, so the quantum check refuses it rather than wrapping to a small one. */
static int64_t lcm64(int64_t a, int64_t b) { static int64_t lcm64(int64_t a, int64_t b) {
if (a <= 0) return b; if (a <= 0) return b;
if (b <= 0) return a; if (b <= 0) return a;
return std::lcm(a, b); const int64_t q = a / std::gcd(a, b);
return q > INT64_MAX / b ? INT64_MAX : q * b;
} }
/* The op's sequence-chunk parameter, found by role (RAD_PROLE_SEQ_CHUNK) in its schema. Steps /* The op's sequence-chunk parameter, found by role (RAD_PROLE_SEQ_CHUNK) in its schema. Steps
+160 -28
View File
@@ -138,7 +138,14 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
"prompt unfinished while other sequences decode, the next %lld steps carry " "prompt unfinished while other sequences decode, the next %lld steps carry "
"decode rows only and admit nothing", (long long)cfg.prefill_interleave, "decode rows only and admit nothing", (long long)cfg.prefill_interleave,
(long long)cfg.prefill_interleave); (long long)cfg.prefill_interleave);
else if (cfg.prefill_interleave < 0)
RAD_INFO("scheduler: --prefill-interleave auto: after a prefill chunk that leaves its "
"prompt unfinished while other sequences decode, decode-only steps follow for up "
"to %.2f of the chunk step's measured time (at most %lld steps)",
cfg.prefill_interleave_share, (long long)kInterleaveAutoMax);
interleave_left_ = 0; interleave_left_ = 0;
ema_chunk_s_ = 0.0;
ema_decode_s_ = 0.0;
held_prefill_ = 0; held_prefill_ = 0;
draft_refill_ = 0; draft_refill_ = 0;
if (cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_BLOCK && prog.drafter.window > 0 && if (cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_BLOCK && prog.drafter.window > 0 &&
@@ -375,6 +382,11 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
s.arrived_us = mono_us(); s.arrived_us = mono_us();
s.first_tok_us = 0; s.first_tok_us = 0;
s.preempted_us = 0; s.preempted_us = 0;
/* A recycled slot keeps its struct, and the prefill figure is computed from admitted_us
* whenever it is non-zero: left standing, it would date this request's first token to the
* admission of whichever request held the slot before. The re-admission guard below needs
* it zero for the same reason -- a stale stamp would read as an earlier admission. */
s.admitted_us = 0;
s.slot = slot; s.slot = slot;
s.card = -1; s.card = -1;
s.running = false; s.running = false;
@@ -584,14 +596,11 @@ void Scheduler::trim_prefix_cache() {
if (short_by > 0) (void)pc_->trim(short_by); if (short_by > 0) (void)pc_->trim(short_by);
} }
void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free, /* What a request computed, into the prefix cache, while it still owns the blocks: at its close,
bool publish, int status, const char* why) { * and at a preemption, whose recompute then adopts its prompt instead of computing it again.
++step_finished_; * True when published. */
/* Publish before freeing: this is the only moment the whole prefix is both computed and still bool Scheduler::publish_prefix(SchedReq& s) {
* owned. insert() takes its own KV references, so the blocks survive the free below. Cancelled if (cfg_.prefix_cache && pc_ && kv_->has_sequence(s.req->id) &&
* and failed requests are published too; their prompts were computed, and a client that hangs
* up mid-answer is likely to ask for that prefix again. */
if (publish && cfg_.prefix_cache && pc_ && kv_->has_sequence(s.req->id) &&
s.req->n_computed > 0 && !kv_->has_runtime_window(s.req->id)) { s.req->n_computed > 0 && !kv_->has_runtime_window(s.req->id)) {
/* R-SWA: a sequence with a runtime window is not published (KVManager::set_window). Its /* R-SWA: a sequence with a runtime window is not published (KVManager::set_window). Its
* table is a reference plus a ring rather than a prefix from position 0, and the window * table is a reference plus a ring rather than a prefix from position 0, and the window
@@ -613,8 +622,20 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
RAD_DEBUG("prefix cache: request %llu not published: %s", RAD_DEBUG("prefix cache: request %llu not published: %s",
(unsigned long long)s.req->id, rad_strerror(rc)); (unsigned long long)s.req->id, rad_strerror(rc));
trim_prefix_cache(); trim_prefix_cache();
return rc >= 0;
} }
} }
return false;
}
void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free,
bool publish, int status, const char* why) {
++step_finished_;
/* Publish before freeing: this is the only moment the whole prefix is both computed and still
* owned. insert() takes its own KV references, so the blocks survive the free below. Cancelled
* and failed requests are published too; their prompts were computed, and a client that hangs
* up mid-answer is likely to ask for that prefix again. */
if (publish) (void)publish_prefix(s);
if (cfg_.prefix_cache && pc_) pc_->release(*s.req); if (cfg_.prefix_cache && pc_) pc_->release(*s.req);
/* Prompt lookup's index is this text's alone. */ /* Prompt lookup's index is this text's alone. */
@@ -901,6 +922,8 @@ int Scheduler::requests_locked(ReqStat* out, int max) const {
o.slot = s.slot; o.slot = s.slot;
o.age_s = (double)(now - s.arrived_us) / 1e6; o.age_s = (double)(now - s.arrived_us) / 1e6;
o.ttft_s = s.first_tok_us ? (double)(s.first_tok_us - s.arrived_us) / 1e6 : -1.0; o.ttft_s = s.first_tok_us ? (double)(s.first_tok_us - s.arrived_us) / 1e6 : -1.0;
o.prefill_s = (s.first_tok_us && s.admitted_us)
? (double)(s.first_tok_us - s.admitted_us) / 1e6 : -1.0;
/* Since the first token, not admission, so time spent queued does not read as slow /* Since the first token, not admission, so time spent queued does not read as slow
* decode. */ * decode. */
const double dec = s.first_tok_us ? (double)(now - s.first_tok_us) / 1e6 : 0.0; const double dec = s.first_tok_us ? (double)(now - s.first_tok_us) / 1e6 : 0.0;
@@ -968,7 +991,7 @@ int64_t Scheduler::chunk_end(const Request& r, int64_t n_target) const {
* so a chunk clamped to it is already aligned; in the other order a chunk past the checkpoint * so a chunk clamped to it is already aligned; in the other order a chunk past the checkpoint
* would be rounded down and miss the boundary. */ * would be rounded down and miss the boundary. */
int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget, int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget,
int64_t* checkpoint_pos, int64_t keep_at) const { int64_t* checkpoint_pos, int64_t keep_at, const Request* r) const {
if (checkpoint_pos) *checkpoint_pos = -1; if (checkpoint_pos) *checkpoint_pos = -1;
int64_t remaining = n_target - n_computed; int64_t remaining = n_target - n_computed;
if (remaining <= 0 || budget <= 0) return 0; if (remaining <= 0 || budget <= 0) return 0;
@@ -1093,9 +1116,48 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
if (checkpoint_pos && *checkpoint_pos > aligned) *checkpoint_pos = -1; if (checkpoint_pos && *checkpoint_pos > aligned) *checkpoint_pos = -1;
} }
} }
if (r) {
const int64_t fit = bidi_fit(*r, n_computed, n_target, want, budget);
/* A trimmed chunk keeps a window snapshot it still carries (as above); a grown one drops it. */
if (fit != want && checkpoint_pos && (fit > want || *checkpoint_pos > n_computed + fit))
*checkpoint_pos = -1;
want = fit;
}
return want; return want;
} }
/* A chunk that ended inside a run read both ways would give the run's rows of this chunk keys the
* next chunk writes. So it ends before the run, on a quantum (and before every run that lands in,
* as a video's frames do); a chunk that starts at or inside the run (nothing fits before it) runs
* to the run's end, rounded up to a quantum unless the sequence ends first, past every run that
* lands in, or waits for a step that holds that. A run no step holds is cut where the chunk falls,
* and its rows see the run up to the cut (RadBatch::bidi_used). */
int64_t Scheduler::bidi_fit(const Request& r, int64_t n_computed, int64_t n_target, int64_t want,
int64_t budget) const {
if (!prog_ || !prog_->encoder.bidirectional || !r.media || want <= 0) return want;
const mm::PromptMedia& pm = *r.media;
const int64_t Q = std::max<int64_t>(geo_.quantum, 1);
/* The run read both ways that a chunk ending at `end` would cut, or null. */
auto cut = [&](int64_t end) -> const mm::RopeLayout::Run* {
if (end >= n_target) return nullptr;
const mm::RopeLayout::Run* run = pm.rope.run_at(end);
if (!run || run->tok == end || pm.items[(size_t)run->item].item->kind == mm::Kind::Audio)
return nullptr;
return run;
};
int64_t end = n_computed + want;
for (const mm::RopeLayout::Run* run = cut(end); run; run = cut(end)) {
const int64_t before = (int64_t)run->tok / Q * Q;
if (before <= n_computed) break;
end = before;
}
if (!cut(end)) return end - n_computed;
for (const mm::RopeLayout::Run* run = cut(end); run; run = cut(end))
end = std::min<int64_t>(n_target, ((int64_t)run->tok + run->n + Q - 1) / Q * Q);
if (end - n_computed <= budget) return end - n_computed;
return end - n_computed > cfg_.max_tok ? want : 0;
}
/* The tail checkpoint of a `target`-token prompt, or -1. Under --prefix-resume exact, where its /* The tail checkpoint of a `target`-token prompt, or -1. Under --prefix-resume exact, where its
* last chunk starts (below). Under nearest, its last quantum boundary, only past the first * last chunk starts (below). Under nearest, its last quantum boundary, only past the first
* interval (a shorter prompt is cheap to redo) and only where it gains at least a quarter * interval (a shorter prompt is cheap to redo) and only where it gains at least a quarter
@@ -1215,14 +1277,44 @@ int64_t Scheduler::busy_cap(int64_t n_computed, int64_t n_target, int64_t budget
return std::min(std::max(cap, Q), budget); return std::min(std::max(cap, Q), budget);
} }
/* ------------------------------------------------------------------ decode-only steps */
/* How many decode-only steps follow a chunk that ran beside decoding sequences
* (--prefill-interleave). N as given; under auto, as many as fit in Config::prefill_interleave_share of a chunk
* step's measured time at a decode step's, so the prefill gives up at most a fifth of its rate
* (a quarter of a chunk step) however many sequences decode, and the decoders get the steps that
* share buys: several where decode steps are cheap beside the chunk, none where one costs more
* than a quarter of it (they still ride every chunk). One until both costs are measured, which
* takes the first decode-only step. Both are wall times read off step_finished, so under auto
* which steps carry a chunk follows the device's timing and differs from run to run; a number
* schedules the same steps every time. */
void Scheduler::step_cost_locked(bool chunk, double seconds) {
double& ema = chunk ? ema_chunk_s_ : ema_decode_s_;
ema = ema > 0.0 ? ema + kInterleaveEma * (seconds - ema) : seconds;
}
void Scheduler::note_step_cost(bool chunk, double seconds) {
std::lock_guard<std::mutex> lk(mu_);
if (seconds > 0) step_cost_locked(chunk, seconds);
}
int64_t Scheduler::interleave_steps() const {
if (cfg_.prefill_interleave >= 0) return cfg_.prefill_interleave;
if (ema_chunk_s_ <= 0.0 || ema_decode_s_ <= 0.0) return 1;
const double n = cfg_.prefill_interleave_share * ema_chunk_s_ / ema_decode_s_;
return n >= (double)kInterleaveAutoMax ? kInterleaveAutoMax : (int64_t)n;
}
/* ------------------------------------------------------------------ preemption */ /* ------------------------------------------------------------------ preemption */
void Scheduler::preempt_back() { bool Scheduler::preempt_back() {
int32_t slot = running_.back(); int32_t slot = running_.back();
SchedReq& s = *reqs_[(size_t)slot]; SchedReq& s = *reqs_[(size_t)slot];
Request& r = *s.req; Request& r = *s.req;
/* Preemption by recompute: the blocks go back and the request restarts from zero. Its output /* Preemption by recompute: the blocks go back and the request restarts from zero. Its output
* is the tail of its token sequence, so it simply re-prefills prompt ++ output. */ * is the tail of its token sequence, so it simply re-prefills prompt ++ output. What it computed
* is published first: the recompute adopts it from the cache, and under pressure the cache gives
* the blocks back (the newest entries last). */
const bool published = publish_prefix(s);
kv_->preempt(r.id); kv_->preempt(r.id);
drop_card(s); drop_card(s);
r.n_computed = 0; r.n_computed = 0;
@@ -1242,6 +1334,7 @@ void Scheduler::preempt_back() {
running_.pop_back(); running_.pop_back();
queue_insert(waiting_, slot); /* original arrival -> the front of its priority class */ queue_insert(waiting_, slot); /* original arrival -> the front of its priority class */
++m_.preemptions; ++m_.preemptions;
return published;
} }
/* ------------------------------------------------------------------ admission */ /* ------------------------------------------------------------------ admission */
@@ -1319,6 +1412,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
const RestoreResult rr = pc_->restore(r, whole_only); const RestoreResult rr = pc_->restore(r, whole_only);
if (rr == RestoreResult::Declined) { if (rr == RestoreResult::Declined) {
s.restore_waited = true; s.restore_waited = true;
admit_next_step_ = true;
RAD_DEBUG("admit %llu: the restore waits a step for %d deferred release(s)", RAD_DEBUG("admit %llu: the restore waits a step for %d deferred release(s)",
(unsigned long long)r.id, n_deferred_); (unsigned long long)r.id, n_deferred_);
return RAD_E_FULL; return RAD_E_FULL;
@@ -1471,9 +1565,12 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
* to what really has to run. */ * to what really has to run. */
const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty()); const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty());
const int64_t end = chunk_end(r, target); const int64_t end = chunk_end(r, target);
want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at); want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at, &r);
if (cap < budget && want > 0) /* A run read both ways (bidi_fit) the share cannot hold takes the step instead. */
admit_full_ = plan_chunk(r.n_computed, end, budget, nullptr, r.checkpoint_at); if (want <= 0 && cap < budget && prog_->encoder.bidirectional)
want = plan_chunk(r.n_computed, end, budget, &ckpt, r.checkpoint_at, &r);
else if (cap < budget && want > 0)
admit_full_ = plan_chunk(r.n_computed, end, budget, nullptr, r.checkpoint_at, &r);
} }
int rc = RAD_OK; int rc = RAD_OK;
if (want <= 0) rc = RAD_E_FULL; if (want <= 0) rc = RAD_E_FULL;
@@ -1522,6 +1619,8 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
if (s.card < 0) { s.card = free_cards_.back(); free_cards_.pop_back(); } if (s.card < 0) { s.card = free_cards_.back(); free_cards_.pop_back(); }
r.state = ReqState::Running; r.state = ReqState::Running;
if (!s.admitted_us) s.admitted_us = mono_us(); /* first admission; a re-admit after
* preemption keeps the original stamp */
s.preempted_us = 0; s.preempted_us = 0;
s.running = true; s.running = true;
server::sink_admitted(r.sink); server::sink_admitted(r.sink);
@@ -1552,6 +1651,9 @@ void Scheduler::undo_hit(SchedReq& s) {
bool Scheduler::preempted_can_prefill(const SchedReq& s) const { bool Scheduler::preempted_can_prefill(const SchedReq& s) const {
const Request& r = *s.req; const Request& r = *s.req;
const int64_t target = s.seq_len(); const int64_t target = s.seq_len();
/* What the recompute adopts from the cache (its own prefix, published at the preemption) needs
* no new block. */
const int64_t hit = (cfg_.prefix_cache && pc_) ? pc_->lookup(r, nullptr, nullptr).n_attn_tokens : 0;
for (size_t g = 0; g < kvgeom_.g.size(); ++g) { for (size_t g = 0; g < kvgeom_.g.size(); ++g) {
const KVGeom::G& gg = kvgeom_.g[g]; const KVGeom::G& gg = kvgeom_.g[g];
@@ -1559,7 +1661,7 @@ bool Scheduler::preempted_can_prefill(const SchedReq& s) const {
* wanted the whole prompt from a pool of none and kept a preempted request out for good. */ * wanted the whole prompt from a pool of none and kept a preempted request out for good. */
if (!gg.paged || kv_->total_blocks((int32_t)g) <= 0) continue; if (!gg.paged || kv_->total_blocks((int32_t)g) <= 0) continue;
int64_t need = (target + gg.block_size - 1) / gg.block_size - int64_t need = (target + gg.block_size - 1) / gg.block_size -
(int64_t)kv_->block_table(r.id, (int32_t)g).size(); (int64_t)kv_->block_table(r.id, (int32_t)g).size() - hit / gg.block_size;
if (need < 0) need = 0; if (need < 0) need = 0;
for (int32_t slot : running_) { for (int32_t slot : running_) {
const SchedReq& rs = *reqs_[(size_t)slot]; const SchedReq& rs = *reqs_[(size_t)slot];
@@ -1692,7 +1794,7 @@ const RadBatch* Scheduler::step() {
running_.erase(std::find(running_.begin(), running_.end(), victim)); running_.erase(std::find(running_.begin(), running_.end(), victim));
running_.push_back(victim); running_.push_back(victim);
} }
preempt_back(); if (preempt_back()) evict_rounds = 0; /* its blocks stay in the cache: evict them first */
} }
} }
@@ -1704,7 +1806,7 @@ const RadBatch* Scheduler::step() {
bool any_decoding = false; bool any_decoding = false;
bool hold_prefill = false; bool hold_prefill = false;
held_prefill_ = 0; held_prefill_ = 0;
if (cfg_.prefill_interleave > 0) { if (cfg_.prefill_interleave != 0) {
for (int32_t slot : running_) { for (int32_t slot : running_) {
const SchedReq& s = *reqs_[(size_t)slot]; const SchedReq& s = *reqs_[(size_t)slot];
if (!s.req || !s.running) continue; if (!s.req || !s.running) continue;
@@ -1820,10 +1922,13 @@ const RadBatch* Scheduler::step() {
const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty(), const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty(),
/*rows_only=*/shares == 0); /*rows_only=*/shares == 0);
const int64_t end = chunk_end(r, target); const int64_t end = chunk_end(r, target);
want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at); want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at, &r);
if (cap < budget && want > 0 && capped_at < 0) { /* A run read both ways (bidi_fit) the share cannot hold takes the step instead. */
if (want <= 0 && cap < budget && prog_->encoder.bidirectional)
want = plan_chunk(r.n_computed, end, budget, &ckpt, r.checkpoint_at, &r);
else if (cap < budget && want > 0 && capped_at < 0) {
const int64_t full = plan_chunk(r.n_computed, end, budget, nullptr, const int64_t full = plan_chunk(r.n_computed, end, budget, nullptr,
r.checkpoint_at); r.checkpoint_at, &r);
if (want < full) { capped_at = (int32_t)plan_.e.size(); capped_full = full; } if (want < full) { capped_at = (int32_t)plan_.e.size(); capped_full = full; }
} }
/* A prefill with no room left does not end the walk: it takes nothing this step, but /* A prefill with no room left does not end the walk: it takes nothing this step, but
@@ -1910,7 +2015,9 @@ const RadBatch* Scheduler::step() {
/* The back of the running set gives its blocks up. When that is this request, the /* The back of the running set gives its blocks up. When that is this request, the
* requests ahead of it hold the pool: it is preempted by recompute and waits for * requests ahead of it hold the pool: it is preempted by recompute and waits for
* them, rather than failed. */ * them, rather than failed. */
preempt_back(); /* A victim that published keeps its blocks in the cache: eviction gets its rounds
* back, so they are reclaimed before anyone else is preempted. */
if (preempt_back()) evict_rounds = 0;
preempted_here = true; preempted_here = true;
if (last) { yielded = true; break; } if (last) { yielded = true; break; }
} }
@@ -2001,13 +2108,28 @@ const RadBatch* Scheduler::step() {
(int64_t)plan_.e.size() + 1 < cfg_.max_seqs && free_cards_.size() > 1 (int64_t)plan_.e.size() + 1 < cfg_.max_seqs && free_cards_.size() > 1
? share_tok : 0; ? share_tok : 0;
admit_full_ = 0; admit_full_ = 0;
admit_next_step_ = false;
const int as = admit_one(s, budget, areserve); const int as = admit_one(s, budget, areserve);
if (as == kAdmitWait) { ++at; continue; } /* A preempted request waiting for its whole-recompute gate lets the next one be asked;
* an overdue one does not. The room the overdue path made this step is for it, and a
* request queued behind it would take that room back: a victim just forced off for it,
* its prompt published, needs almost nothing to come back, and under KV pressure the
* same victim was forced off and re-admitted 26 times in 16 s while the overdue request
* waited. */
if (as == kAdmitWait) {
if (s.req->state == ReqState::Preempted && preempt_wait_overdue(s)) break;
++at;
continue;
}
/* An overdue preempted prefill on an idle engine that still cannot be admitted will /* An overdue preempted prefill on an idle engine that still cannot be admitted will
* not become admissible by waiting: nothing is running to finish and free the pool. * not become admissible by waiting: nothing is running to finish and free the pool.
* Fail it (spec §17) and ask the next request, instead of parking the step loop. */ * Fail it (spec §17) and ask the next request, instead of parking the step loop. Not
if (as < 0 && running_.empty() && s.req && s.req->state == ReqState::Preempted && * when this step admitted someone ahead of it (the budget or a card went to them) or
preempt_wait_overdue(s)) { * the refusal is a restore waiting a step for deferred releases: both clear by the
* next step, and failing them lost two of ten preempted requests under KV pressure
* once their prompts were published at the preemption (1. 11. 2026). */
if (as < 0 && running_.empty() && plan_.e.empty() && !admit_next_step_ && s.req &&
s.req->state == ReqState::Preempted && preempt_wait_overdue(s)) {
RAD_WARN("request %llu failed: overdue preempted prefill could not be admitted " RAD_WARN("request %llu failed: overdue preempted prefill could not be admitted "
"with nothing running (%s)", "with nothing running (%s)",
(unsigned long long)s.req->id, rad_strerror(as)); (unsigned long long)s.req->id, rad_strerror(as));
@@ -2081,7 +2203,7 @@ const RadBatch* Scheduler::step() {
if (cfg_.busy_prefill_chunk > 0) limit = std::min(limit, std::max(had, cfg_.busy_prefill_chunk)); if (cfg_.busy_prefill_chunk > 0) limit = std::min(limit, std::max(had, cfg_.busy_prefill_chunk));
int64_t ckpt = -1; int64_t ckpt = -1;
const int64_t grown = e.ckpt_slot < 0 && limit > had const int64_t grown = e.ckpt_slot < 0 && limit > had
? plan_chunk(r.n_computed, chunk_end(r, s.seq_len()), limit, &ckpt, r.checkpoint_at) ? plan_chunk(r.n_computed, chunk_end(r, s.seq_len()), limit, &ckpt, r.checkpoint_at, &r)
: had; : had;
if (grown > had && kv_->ensure_from(r.id, r.n_computed + grown, r.n_computed) >= 0) { if (grown > had && kv_->ensure_from(r.id, r.n_computed + grown, r.n_computed) >= 0) {
e.n_tokens = (int32_t)grown; e.n_tokens = (int32_t)grown;
@@ -2135,13 +2257,13 @@ const RadBatch* Scheduler::step() {
case RAD_PHASE_MIXED: ++m_.steps_mixed; break; case RAD_PHASE_MIXED: ++m_.steps_mixed; break;
default: ++m_.steps_decode; break; default: ++m_.steps_decode; break;
} }
if (cfg_.prefill_interleave > 0) { if (cfg_.prefill_interleave != 0) {
/* Armed only while a prompt continues past this step: after a last chunk nothing is left /* Armed only while a prompt continues past this step: after a last chunk nothing is left
* to interleave, and holding would only keep the next request out. */ * to interleave, and holding would only keep the next request out. */
bool continues = false; bool continues = false;
for (const StepEntry& e : plan_.e) for (const StepEntry& e : plan_.e)
if (e.is_prefill && !e.produces_token) continues = true; if (e.is_prefill && !e.produces_token) continues = true;
if (any_pf) interleave_left_ = any_decoding && continues ? cfg_.prefill_interleave : 0; if (any_pf) interleave_left_ = any_decoding && continues ? interleave_steps() : 0;
else if (interleave_left_ > 0) --interleave_left_; else if (interleave_left_ > 0) --interleave_left_;
if (held_prefill_ > 0) ++m_.steps_held; if (held_prefill_ > 0) ++m_.steps_held;
} }
@@ -2562,7 +2684,14 @@ int Scheduler::commit(StepResult& res) {
/* Not while a step issued ahead writes past `valid`; that step's commit rolls back to /* Not while a step issued ahead writes past `valid`; that step's commit rolls back to
* the end it reaches. */ * the end it reaches. */
if (a < e.n_spec && !(next_open_ && s.entry_next >= 0)) { if (a < e.n_spec && !(next_open_ && s.entry_next >= 0)) {
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
if (kv_rollback_test_hook_) kv_rollback_test_hook_(r.id, e.n_spec, a, valid, true);
#endif
int st = kv_->rollback(r.id, valid); int st = kv_->rollback(r.id, valid);
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
if (st >= 0 && kv_rollback_test_hook_)
kv_rollback_test_hook_(r.id, e.n_spec, a, valid, false);
#endif
if (st < 0) RAD_WARN("kv rollback for request %llu: %s", if (st < 0) RAD_WARN("kv rollback for request %llu: %s",
(unsigned long long)r.id, rad_strerror(st)); (unsigned long long)r.id, rad_strerror(st));
} }
@@ -2736,6 +2865,9 @@ void Scheduler::step_finished() {
/* The window ages by all elapsed time, idle included; only the busy part is added as time the /* The window ages by all elapsed time, idle included; only the busy part is added as time the
* tokens took. */ * tokens took. */
const double aged = std::chrono::duration<double>(step_end - last_step_at_).count(); const double aged = std::chrono::duration<double>(step_end - last_step_at_).count();
/* --prefill-interleave auto's two step costs (interleave_steps). */
if (wall > 0 && cfg_.prefill_interleave < 0)
step_cost_locked(plan_.phase != RAD_PHASE_DECODE, wall);
if (wall > 0) { if (wall > 0) {
constexpr double kWindowS = 1.0; constexpr double kWindowS = 1.0;
const double f = std::exp(-aged / kWindowS); const double f = std::exp(-aged / kWindowS);
Loaded 100 of 365 files, more files were not shown because too many files have changed in this diff. Show more