merge origin/main: the upstream LoRA-runtime refactor beneath the ref2va port

Merges upstream 1.10.0 (152 commits: the LoRA acquire/runtime refactor, the
form-1 LTX-2 scheduler family, guidance terms + negative prompts, decoder
selection, input_reference, new architectures) into the ref2va port branch.
Resolution rule throughout: keep BOTH feature sets; ABI numbering follows
upstream (RAD_ABI_VERSION 26, RAD_FORMAT_VER 2), with the port's video fields
unioned into RadVideoGenBatch/RadVideoGenDecl and abi_layout_table.h
regenerated from the live table.

Notable reconciliations:
  * videos.cpp: the task grammars are disjoint by capability -- keyframe tasks
    (i2va/l2va/flash-attn l2va/fl2va) are recognized only when decl.encodes,
    so upstream models keep refusing them as unknown tasks; input_reference,
    the LoRA tag/field pipeline, and the guidance/negative_prompt rendering
    coexist with refs/ref2va; the prompt put() helper hoisted to block scope
    for the media branch.
  * video_schedule(): upstream's (steps, video_tokens, refine) keeps its
    positional slots; the port's shift_video/shift_audio overrides move to the
    tail so upstream's schedule tests call unchanged.
  * r4d_selftest conv3d cases: the port's sp/st/causal/down/refl geometry and
    upstream's tpad/tpre fold into one reference (ft = causal ? 2 : tpad==2 ?
    2+tpre : 1); rms_mod rows keep the port's i8/fp8 quant modes alongside
    upstream's wadd/norm_once/norm parameters.
  * tests/oot_plugins.sh: the per-plugin cmake --install gains a --prefix
    staging dir -- plugin .so files still land in the absolute
    RAD_PLUGIN_INSTALL_HOME, but libr4d now also installs r4d_selftest to a
    relative bin/, which needs no root.

Host ctest: 112/113 (mm_test's webp gap pre-exists this merge); r4d_selftest,
engine_e2e, oot_plugins, abi_layout, all LoRA tests green.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
gearwave00001andClaude committed 2026-10-22 18:38:04 -05:00
commit a1a75da7e9
415 files changed
+78837 -5310

No files matched your search

+25 -1
View File
@@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.21)
# VERSION is the server release that /version reports. The plugin ABI version is separate and is
# read from abi/rad_abi.h below.
project(radiance VERSION 1.8.1 LANGUAGES C CXX)
project(radiance VERSION 1.10.0 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -184,6 +184,30 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb)
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb
DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance)
endif()
# The published refusal-direction vector for qwen4exp, copied into the built home's vectors/ so a
# Flash-Next container offers the switch with nothing for an operator to install: core/cvec.cpp looks
# for <home>/vectors/<arch>-control-vector.gguf after the sidecar paths. The file is Cudecnik's,
# unchanged (huggingface.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection; the gguf is sha256
# ef0724c5b79297e4..., the json d4a3dd842506a6fb..., and that is what the measurements in
# docs/GUIDE.md 4.10 were made with). Refresh with:
#
# huggingface-cli download Cudecnik/Qwen3.8-Flash-Next-refusal-projection \
# Qwen3.8-Flash-Next-refusal-projection.{gguf,json}
#
# The directions are derived from Qwen3.8-Flash-Next's weights and stay under the Qwen Community
# License 1.0 (data/vectors/LICENSE.qwen-community-1.0.txt, NOTICE); radiance's Apache-2.0 grant
# covers the code that reads them, never the file. It ships loaded only when the deployment asks
# (--control-vector), and the request default is off, because what it removes is a safety behaviour.
file(MAKE_DIRECTORY ${RAD_PLUGIN_OUT}/vectors)
foreach(rrad_vector qwen4exp-control-vector.gguf qwen4exp-control-vector.json)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/data/vectors/${rrad_vector}
${RAD_PLUGIN_OUT}/vectors/${rrad_vector} COPYONLY)
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/vectors/${rrad_vector}
DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance/vectors)
endforeach()
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/vectors/LICENSE.qwen-community-1.0.txt
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME qwen-community.LICENSE)
# The downloader behind `radiance --model <owner/name>` (core/hf_model.cpp). The engine looks in
# <bin>/../libexec/radiance/, so the build tree mirrors that layout.
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
+21 -8
View File
@@ -207,21 +207,34 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
# ------------------------------------------------------------------------------------------- test
FROM build AS test
ARG JOBS=
# Tests at a time when it should differ from JOBS (below).
ARG TEST_JOBS=
# A factor on every test's CPU budget (RAD_TEST_CPU_BUDGET_SCALE, tests/rad_test.h), for a host
# slower per thread than the one the budgets were set on: a VM on an EPYC 7302 spends 4.6x the
# quoted CPU time on tokenizer_test's reference pass.
ARG TEST_CPU_BUDGET_SCALE=
# A ctest -E regex of entries to leave out, for a host where a timing assertion does not hold:
# tokenizer_perf_test's one-word ratio reads 10-12 against its 9 on a Zen 2 VM with 512 KiB of L2,
# where the sandbox leaves it CPU time rather than instructions to count.
ARG TEST_EXCLUDE=
# Host-only: a build container has no /dev/kfd. The `gpu`-labelled tests (the *_card entries,
# r4d_selftest, kbench) run against a card from this stage:
# docker buildx build --target build -t radiance-build . && docker run --rm \
# --device /dev/kfd --device /dev/dri --security-opt seccomp=unconfined radiance-build \
# ctest --test-dir /build -L gpu --output-on-failure
# Tests run JOBS at a time (default one per two hardware threads, about one per core on an SMT
# machine: the per-binary CPU budgets in tests/CMakeLists.txt hold for tests that do not share a
# core); the `perf` entries, which assert wall-clock costs, run alone (RUN_SERIAL). The build
# sandbox forbids io_uring, so avx_check skips its file-backed gather case, and perf_event_open, so
# the tests that bound work count CPU time rather than instructions (tests/work_counter.h). The
# `oot` suite (every shipped plugin rebuilt against the installed package) repeats this stage's
# whole compile, so it runs from the development tree instead (tests/oot_plugins.sh).
# Tests run TEST_JOBS at a time, else JOBS (default one per two hardware threads, about one per
# core on an SMT machine: the per-binary CPU budgets in tests/CMakeLists.txt hold for tests that do
# not share a core); the `perf` entries, which assert wall-clock costs, run alone (RUN_SERIAL). The
# build sandbox forbids io_uring, so avx_check skips its file-backed gather case, and
# perf_event_open, so the tests that bound work count CPU time rather than instructions
# (tests/work_counter.h). The `oot` suite (every shipped plugin rebuilt against the installed
# package) repeats this stage's whole compile, so it runs from the development tree instead
# (tests/oot_plugins.sh).
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
bash /src/docker/llvm-check.sh /build \
&& ctest --test-dir /build -LE 'gpu|oot' -j"${JOBS:-$(( ($(nproc) + 1) / 2 ))}" --output-on-failure \
&& RAD_TEST_CPU_BUDGET_SCALE="${TEST_CPU_BUDGET_SCALE}" \
ctest --test-dir /build -LE 'gpu|oot' ${TEST_EXCLUDE:+-E "${TEST_EXCLUDE}"} \
-j"${TEST_JOBS:-${JOBS:-$(( ($(nproc) + 1) / 2 ))}}" --output-on-failure \
&& touch /build/host-tests-passed
# ----------------------------------------------------------------------------------------- rootfs
+32 -3
View File
@@ -15,7 +15,8 @@ Written by Deadcode, with contributions from:
adaptive draft window, the MoE prefill forms, the sorted operand's decode kernel, two K blocks a
pass for up to 80 routed rows, --prefill-span, the towers' lookup tables counted once, and for
Gemma 4 its assistant head as a drafter that reads the trunk's cache, bf16 checkpoints, the fused
w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume
w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume, and the
Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files
- mechkbfan: the token embedding in the pinned host pool
- Code000: the n-gram gather on the card and the MTP head's history-pass skip
- baKon: three-rank tensor parallelism, serving any world size from the shipped container, the
@@ -23,7 +24,8 @@ Written by Deadcode, with contributions from:
context length, root and capabilities, /props, the three-rank two-shot all-reduce and tiered-int8
wire, the diagnosis of the three-rank lossy-wire crash, cardclock.py, --busy-prefill-chunk, curl,
jq and a CA bundle in the image with hfget.sh under its busybox, rad-export, --prefill-interleave,
and runtime LoRA adapters served beside the base model and picked per request
runtime LoRA adapters served beside the base model and picked per request, and the prefix cache's
reserved snapshots held until their save lands
- hazyumps: static YaRN for the Qwen rotary paths
- malic: ParoQuant, with its MXFP4, int5 and int4 checkpoints imported and served, the Givens
rotation as stages and as dense per-group matrices on the matrix cores, and the 5- and 4-bit
@@ -37,9 +39,27 @@ Written by Deadcode, with contributions from:
- gearwave00001: /v1/messages as Claude Code sends it
- devmilan: the NVFP4 and FP8 compressed-tensors imports
- sfjes: Gemma 4 31B dense -- its plugin, its two attention classes and their kernels, and prefix
reuse that leaves a windowed group alone
reuse that leaves a windowed group alone -- and --host-headroom-mib
- zivius: LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of their Codeberg
PR 50, and Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime
- mici81: Gemma 3 dense (TranslateGemma 27B) -- its plugin, the windowed h128 attention, the
sandwich junction's all-reduce and its DFlash2 drafter -- the fp8_v4 and k6_v4 KV caches, GPTQ's
factorisations through LAPACK and a column-split linear's Hessian from per-rank parts,
R4D_AR_MAX_BLOCKS for two engines on one set of cards, and added tokens decoded as HuggingFace
decodes them
- 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
- davetha: JSON Schema patterns read unanchored, with their shorthand classes and escapes
- Nunze: the eight-rank all-reduce's bands, weighted shards from the PCIe links and pieces, the
sampler's candidate width at eight ranks, the image test stage's parallelism, budgets and
exclusions, jinja's dotted integer index, GLM-5.3-Flash's kernels in libr4d and tool calls whose
name the opener opens
- John McDonough: GLM-5.3-Flash -- its plugin, its blocks (mHC streams, KDA, the DSA indexer and
sparse latent attention, f32-scaled FP8 and MXFP4 experts under sigmoid routing) and their
reference and AVX ops -- a Quark export's block-FP8 layers, the signed QSA ranking, the
one-sequence KV floor over the live plan, and prefill staging paid by expert residency
- Memoria: the dashboard's decode floor and recent window, the sparklines' percentile range, and
the bringup time in /stats
This product includes software from the following projects, each under the MIT License. The
license text is in the file named beside each.
@@ -56,3 +76,12 @@ LiquidAI/d1-3B repository): the prompt it renders, its question blocks, the opti
fallback codebook and the answer spellings, unchanged, in code rewritten in C++. That text is Liquid
AI, Inc.'s, under the LFM Open License v1.0, whose terms -- including its limit on commercial use --
apply to it; the license is in core/server/LICENSE.lfm.
data/vectors/qwen4exp-control-vector.gguf and data/vectors/qwen4exp-control-vector.json are the
published refusal-direction vector for Qwen3.8-Flash-Next, by Cudecnik
(huggingface.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection), copied unchanged. The directions
were measured out of Qwen3.8-Flash-Next's own residual stream, so they are Qwen's, under the Qwen
Community License 1.0 -- data/vectors/LICENSE.qwen-community-1.0.txt -- which carries the file and
every copy of it, including its condition that a Model-as-a-Service or AI-work-assistant business
needs a separate license from Qwen to use it commercially. radiance's Apache-2.0 grant covers the
code that loads and applies the file; it does not cover the file or its directions.
+75 -1
View File
@@ -23,19 +23,37 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC
| Qwen3.8-27B FP8, DFlash2 drafter, vision | `qwen3.8-27b-fp8.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-fp8) | `qwen3.8-27b-fp8.yaml` |
| Qwen3.8-27B MXFP4 (AMD Quark AWQ), DFlash2 drafter, vision | `qwen3.8-27b-mxfp4.rad` (19 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-mxfp4) | `qwen3.8-27b-mxfp4.yaml` |
| Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` |
| Ornith-1.5-35B-A3B FP8, MTP, vision | `ornith-1.5-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-fp8) | `ornith-1.5-35b-a3b.yaml` |
| Ornith-1.5-35B-A3B w4a8: 4-bit experts (GPTQ), MTP, vision, fits one card | `ornith-1.5-35b-a3b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-w4a8) | `ornith-1.5-35b-a3b-w4a8.yaml` |
| Sage-A1.5 FP8, MTP, vision | `sage-a1.5-fp8.rad` (35 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8) | `sage-a1.5.yaml`, `sage-a1.5-tp1.yaml` |
| Sage-A1.5 FP8, DFlash2 drafter, vision | `sage-a1.5-fp8-df2.rad` (34 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8-df2) | `sage-a1.5-df2.yaml` |
| MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` |
| MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` |
| Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` |
| Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | `gemma4-31b-heretic-ara-w4a8.yaml` |
| Gemma 4 31B: int4 trunk, int8 activations and lm_head, DFlash drafter, vision | `gemma4-31b-dense-w4a8-df.rad` (22 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash) | `gemma4-31b-w4a8-df.yaml` |
| Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | `gemma4-31b-q8-df.yaml` |
| Gemma 4 31B on four cards: int4 trunk, int8 activations and lm_head, RedHatAI's DFlash2 drafter, vision | `gemma4-31b-dense-w4a8-df2-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2) | `gemma4-31b-w4a8-df2-tp4.yaml` |
| Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` |
| Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` |
| Krea 2 Turbo FP8: text to image, one card | `krea-2-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-fp8) | `krea-2-turbo.yaml` |
| Krea 2 Raw FP8: the same, undistilled | `krea-2-raw-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-raw-radiance-fp8) | `krea-2-raw.yaml` |
| FLUX.3 [klein] FP8: text to image and edits from up to ten pictures, one card | `flux-3-klein-fp8.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-fp8) | `flux-3-klein.yaml` |
| FLUX.3 [klein] base FP8 | `flux-3-klein-base-fp8.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-base-fp8) | `flux-3-klein.yaml` |
| LTX-2.5 distilled FP8: video with its stereo soundtrack from text or a first frame, one card | `ltx-2.5-distilled-fp8.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-distilled-fp8) | `ltx-2.5.yaml` |
| LTX-2.5 base FP8 | `ltx-2.5-fp8.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-fp8) | `ltx-2.5.yaml` |
| MiniMax-H3 FP8: video with its stereo soundtrack from text | `minimax-h3-fp8.rad` (60 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-fp8) | `minimax-h3.yaml` |
| FastH3 8-Step V2 FP8: the same in eight steps | `fasth3-8-step-v2-fp8.rad` (62 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-fp8) | `fasth3.yaml` |
| MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `minimax-music3.yaml` |
| Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `breeze-tts2.yaml` |
| Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.yaml` |
| TranslateGemma 27B MXFP4 (GPTQ), translation; optional DFlash2 drafter | `translategemma-27b-mxfp4-gptq.rad` (17 GiB) | [convert](#convert-a-checkpoint) | `translategemma-27b.yaml` |
| GLM-5.3-Flash: MXFP4 experts and block-FP8 attention (AMD Quark), MTP, vision, eight cards | `glm53-flash-mxfp4.rad` (172 GiB) | [convert](#convert-a-checkpoint) | `glm53-flash.yaml` |
| Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` |
| Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` |
| Stable Diffusion XL bf16 and its finetunes (Illustrious, NoobAI, Pony): text to image, one card | `illustrious-xl-v2.0-bf16.rad` (6.4 GiB), from any single-file SDXL checkpoint | [convert](#convert-a-checkpoint) | `sdxl.yaml` |
| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` |
| Anima Aesthetic FP8: anime and illustration, text to image, one card (Base and Turbo convert the same way) | `anima-aesthetic-fp8.rad` (3.0 GiB) | [convert](#convert-a-checkpoint) | `anima.yaml` |
| Qwen3-ASR 1.7B bf16: speech to text, `/v1/audio/transcriptions` and live over `/v1/realtime`, 30 languages, one card | the checkpoint as it ships (4.1 GiB) | [Qwen/Qwen3-ASR-1.7B-hf](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf) | — |
A container holds everything the server needs: the weights, the tokeniser, the chat template and
@@ -54,6 +72,26 @@ with a scale search, bf16 lm_head); see [Convert a checkpoint](#convert-a-checkp
that container decodes at 103 tok/s on prose and 141 on code, against 112 and 150 for keptn42's,
and accepts 0.46 of its drafts on prose against 0.50.
TranslateGemma 27B is converted from Google's bf16 checkpoint in three steps: an int8 container to
calibrate in, its Gram matrices over translation prompts, then MXFP4 with GPTQ
(`data/recipes/translategemma-27b-*.recipe`, the steps in docs/ARCHITECTURES.md). On two R9700s it
decodes 56 tok/s a stream (205 at four) and scores mean KL 0.042 against the bf16 model on held-out
translations; with a DFlash2 drafter, 152 a stream. Its chat template takes structured turns
naming the two languages and refuses the plain turn the server renders at startup, so
`translategemma-27b.yaml` serves a plain Gemma 3 template (`deploy/compose/gemma3.jinja`) and a
client sends on `/v1/completions` the prompt the checkpoint's template renders.
GLM-5.3-Flash is converted from AMD's Quark export (`amd/GLM-5.3-Flash-Quark-MXFP4`) with
`data/recipes/glm53-mxfp4.recipe`, which keeps every weight as stored except the latent
attention's small kv_b, decoded to bf16. At 172 GiB it takes eight R9700s (`--tp 8`), every expert
resident, and its own MTP layer drafts. On eight R9700s it prefills 3958 tok/s at 6k tokens,
decodes 166 tok/s on one stream and 426 over eight, and 506 under eight streams of agent turns.
Pictures go through its own vision tower, up to 4096 tokens an image at the default encoder pass
(`--mm-max-patches 32000` serves the checkpoint's 8000); the KV cache is bf16. Its template knows
the reasoning efforts `low` and
`high` and renders any other as its maximum, so `glm53-flash.yaml` maps `medium` and `xhigh`
to `high`.
The ParoQuant containers keep the trunk exactly as the ParoQuant releases ship it, with the learned
Givens rotations it was trained in. Convert int4 from `z-lab/Qwen3.8-27B-PARO`, int5 from
`Launch80/Qwen3.8-27B-PARO-int5` and MXFP4 from `MisterSnrub/Qwen3.8-27B-PARO-MXFP4-v2`, each with
@@ -85,7 +123,9 @@ only.
## Run with Docker
The host needs Docker and an `amdgpu` driver that supports ROCm 10.1; it does not need ROCm. The
card needs Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup). The image
card works best with Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup);
without it the engine keeps kernel arguments in pinned host memory, and every dispatch reads them
over the link. The image
is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its kernels
built for `gfx1201`. Pull it, clone this repository for its compose files, then start a model from
one of them:
@@ -223,11 +263,24 @@ build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-w4a8.ra
--recipe data/recipes/gemma4-31b-dense-bf16-w4a8.recipe \
--set quantization_config.quant_method=compressed-tensors \
--draft-model /srv/models/hf/google/gemma-4-31B-it-assistant
build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-dense-w4a8-df.rad \
--recipe data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe \
--set quantization_config.quant_method=compressed-tensors \
--draft-model /srv/models/hf/z-lab/gemma-4-31B-it-DFlash
build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-dense-q8-df.rad \
--recipe data/recipes/gemma4-31b-dense-bf16-q8-df.recipe \
--set quantization_config.quant_method=compressed-tensors \
--draft-model /srv/models/hf/z-lab/gemma-4-31B-it-DFlash
build/bin/rad-convert /srv/models/hf/z-lab/Qwen3.8-27B-PARO -o qwen3.8-27b-paro-int4.rad \
--recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe \
--draft-model /srv/models/hf/z-lab/Qwen3.8-27B-DFlash2
build/bin/rad-convert /srv/models/hf/ukisai/Swift-1.5-Qwen3.8-27b-W4A16-AWQ -o swift15-27b-w4a16.rad \
--recipe data/recipes/q38-27b-w4a16.recipe
# Any single-file SDXL checkpoint (SDXL 1.0, Illustrious, NoobAI, Pony, a civitai finetune), with
# CLIP's tokenizer.json from openai/clip-vit-large-patch14
build/bin/rad-convert /srv/models/hf/OnomaAIResearch/Illustrious-XL-v2.0/Illustrious-XL-v2.0.safetensors \
-o illustrious-xl-v2.0-bf16.rad --recipe data/recipes/sdxl-bf16.recipe \
--tokenizer /srv/models/hf/openai/clip-vit-large-patch14/tokenizer.json
```
With Docker, use `docker run --rm -v /srv/models:/models --entrypoint rad-convert stilldeadcode/radiance ...`.
@@ -253,6 +306,27 @@ ctest --test-dir build -L oot # rebuilds every bundled plugin out o
`CMakePresets.json` names the same runs (`ctest --preset fast`, `host`, `gpu`, `full`, `asan`), and
[`docs/GUIDE.md`](docs/GUIDE.md) §1.3 describes the tiers and the test binaries' options.
## Draft acceptance
Speculative decoding drafts up to `--num-speculative-tokens` tokens a step; the target model
verifies them in one pass, and a draft survives only if it matches what the target would have
produced. A position is verified only when every earlier position survived, so the same events
admit two ratios, and they differ only in the denominator:
- **Conditional** -- accepted / *reached*: of the drafts actually verified at a position, how
many passed. The dashboard's live "conditionally accepted" figure and the per-position bars are
conditional. Always the higher number, and it moves with the workload.
- **Marginal** -- accepted / *drafted*: of everything the drafter proposed, how much survived.
The engine's `draft_accept` (/stats, and `radiance:draft_acceptance_ratio` on /metrics) is
marginal, cumulative over the life of the process. Lower by construction, and slow to move.
They cannot agree, and neither is the other one broken. At depth 3 a step drafts three tokens
but reaches position 3 only when 1 and 2 both passed, so marginal is roughly the product of the
conditionals: bars reading 56/75/77% give (0.56 + 0.56x0.75 + 0.56x0.75x0.77) / 3 = 43%. A live
63% beside a lifetime 43% is one lane, two questions. Quote the conditional when asking "how
good is the drafter right now"; quote the marginal when asking "what fraction of draft work
became text." Never compare the two across that boundary.
## Documentation
| | |
+26 -2
View File
@@ -17,7 +17,7 @@ extern "C" {
* kind of plugin reports it, and a plugin that does not report exactly this version is refused at
* load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a
* change of shape: a plugin without it gets the default. */
#define RAD_ABI_VERSION 24u
#define RAD_ABI_VERSION 26u
/* ================================================================== plugin identity */
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
@@ -135,7 +135,13 @@ typedef struct RadLayout {
* RAD_E_DTYPE the kernel does not read this encoding (an fp8 GEMM handed int4, a rotated
* weight to a kernel that does not rotate its activation). A declare-time
* error naming the weight, the encoding and the kernel.
* RAD_E_SHAPE the selected planes, or their extents, are not what the kernel reads. */
* RAD_E_SHAPE the selected planes, or their extents, are not what the kernel reads.
* RAD_LAYOUT_ANY the kernel reads the stored bytes without interpreting them (a prefetch
* into the cache), so it takes whatever form another reader chose and claims
* none: the builder does not count it when settling the stored form, and the
* runtime's layout check accepts it. A weight only such kernels read is
* stored as it is. */
#define RAD_LAYOUT_ANY 1
typedef int (*RadLayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n_planes,
RadLayout* out);
@@ -498,6 +504,24 @@ typedef void (*RadPluginCloseFn)(void);
* it, which is always correct. Symbol name: `rad_kernel_concurrent`. */
typedef int (*RadKernelConcurrentFn)(int i);
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means it can chain. Chaining replaces
* the packet processor's ordering between dependent launches (the AQL barrier bit) with a wait in
* the kernel. Where chaining is on the engine resolves the row with the parameter `chain` = 1, and
* the launch may then emit chained forms of its kernels, recognised by "r4dchain" in the kernel's
* name; only those get a record and lose the bit. A chained form, before its first read of an
* operand, one lane a block waits until the 64-bit word at the record's `ctr` reaches `target`,
* then the block barriers and acquires at agent scope; after its last write the block releases at
* agent scope, barriers, and one lane adds 1 to `ctr`. Every block, including one with nothing to
* do, adds exactly once. The record is RAD_CHAIN_REC_BYTES at byte RAD_CHAIN_KARG_OFF of the
* kernel's argument segment: { magic, target, ctr, check }, with check = magic ^ target ^ ctr ^
* RAD_CHAIN_CHECK. A record whose magic or check does not match means: run without waiting and do
* not add. Without the symbol, or with 0, the engine never asks. Symbol name: `rad_kernel_chain`. */
typedef int (*RadKernelChainFn)(int i);
#define RAD_CHAIN_KARG_OFF 992
#define RAD_CHAIN_REC_BYTES 32
#define RAD_CHAIN_MAGIC 0x3130434e48434452ull /* "RDCHCN01" */
#define RAD_CHAIN_CHECK 0x9e3779b97f4a7c15ull
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means it is a collective. Its
* launches exchange data with the other ranks' cards, so the interconnect carries their bytes
* while they run and the step waits on it. The engine keeps its own bulk traffic on those links
+332 -9
View File
@@ -56,6 +56,30 @@ double rad_meta_getf(const RadModelMeta* m, const char* key, double dflt);
const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* dflt);
/* ================================================================== build context */
/* RadBuildCtx::kv_quant. A layout groups each head's dims by 32 with an f16 scale per group, the
* group's absmax over the largest code. A token's row in a head, at head_dim HD (a multiple of 32):
*
* RAD_KVQ_V4 (fp8_v4), 25 * HD / 16 bytes:
* [0, HD) K, E4M3 as the fp8 cache stores it
* [HD, 3HD/2) V's int4 codes, dim d in the nibble at bit 4 * (d % 2) of byte d / 2
* [3HD/2, 25HD/16) V's scales (absmax / 7)
* RAD_KVQ_K6V4 (k6_v4), 22 * HD / 16 bytes:
* [0, HD/2) K's low four bits, as V's codes above
* [HD/2, 3HD/4) K's high two bits, a 4-byte word per 16 dims whose byte j holds dims 2j
* and 2j+1 in bits 0-3 and dims 8+2j and 9+2j in bits 4-7
* [3HD/4, 5HD/4) V's int4 codes
* [5HD/4, 21HD/16) K's scales (absmax / 31)
* [21HD/16, 22HD/16) V's scales (absmax / 7)
*
* Codes are two's complement (int4 -7..7, int6 -31..31). The group is declared at RAD_F8E4M3 with
* head_dim the row's bytes / 2 so the core sizes pages from it; only the layout's kernels read
* it. */
enum {
RAD_KVQ_NONE = 0,
RAD_KVQ_V4 = 1,
RAD_KVQ_K6V4 = 2
};
typedef struct RadBuildCtx {
int rank; /* declare runs once per rank; the plugin declares dimensions */
int world_size; /* already divided -- the core inserts no collectives (spec §9) */
@@ -86,7 +110,7 @@ typedef struct RadBuildCtx {
* RAD_DT_INVALID (the zero-initialised default) means the plugin's default, bf16 for every
* architecture in this tree. RAD_F8E4M3 is the only other implemented value: the fp8kv
* attention family is band-gated on it, and the store side writes E4M3 with per-(sequence,
* head) descales.
* head) descales. `kv_quant` below narrows the trunk's attention cache further.
*
* An ABI field rather than an environment variable because it changes what the model
* computes, so it must have one visible answer: --kv-cache-dtype. */
@@ -140,8 +164,58 @@ typedef struct RadBuildCtx {
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int64_t max_mixed_tok;
/* A narrower layout of the trunk's attention cache under kv_dtype RAD_F8E4M3, from
* --kv-cache-dtype fp8_v4 or k6_v4: a RAD_KVQ_* (below). The engine sets it only for a plugin
* whose probe has the layout's bit in RadArchProbe::kv_quant_ok and refuses the flag
* otherwise, so no plugin sees it that would store plain E4M3 instead. A drafter's cache stays
* E4M3.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int kv_quant;
/* ---- appended in ABI 26 (control vectors) */
/* A control vector loaded from a GGUF `controlvector` file found for this model, or null.
*
* The engine loads and validates it once, at bringup, and the plugin only reads it: the
* direction table lives in device memory on every rank, in the activations' own float form,
* and a per-request switch reaches the step through a derived buffer the plugin declares
* itself (a row mask, `projection_on_rows`). Nothing is reloaded to turn the feature on or
* off, and with the mask zero the model computes what it computes without a vector.
*
* The plugin decides where in its own graph the projection applies; for the gated-residual
* architectures that is after each block's write into the wide stream, which is the point
* llama.cpp's control-vector hook uses for `qwen4exp`. A plugin that does not declare an op
* reading this table ignores it.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
const struct RadControlVector* cvec;
} RadBuildCtx;
/* ================================================================== control vectors */
/* A direction per layer, in the shape llama.cpp's `--cvec-mode project` applies it:
*
* h <- h - s_l (h . v_l) v_l v_l = d_l / |d_l|, s_l = |d_l| (times the user scale)
*
* with `v_l` unit and `s_l` the norm the file stored (so a unit vector's scale is 1). The engine
* normalises the rows when it uploads them, so a kernel reads `dir` as the unit direction and
* takes `s` from `scales`; a zero scale means "this layer is not steered".
*
* `dir` is [n_layers, n_embd] f32, row `l` that layer's direction, row 0 unused (layer 0 has no
* direction in the format). Each rank has its own copy: the pointer a plugin receives is that
* rank's, and the residual stream is replicated, so no collective is involved.
*
* `n_layers` is the model's layer count, which may be longer than the file's (the published
* Flash-Next vector carries 47 of 48 rows). The steered range is not a separate field: a layer is
* steered exactly when its `scales` entry is nonzero, so a plugin asks that and cannot disagree
* with the loader. */
typedef struct RadControlVector {
const float* dir; /* device, [n_layers, n_embd] f32, unit rows */
const float* scales; /* host, [n_layers] f32, |d_l| * user scale; 0 = not steered */
int64_t n_embd;
int64_t n_layers;
} RadControlVector;
/* ================================================================== weights */
/* Access class, declared per weight because only the architecture plugin knows it. It tells the
* placement planner whether prefetch can be exact (spec §5.2). */
@@ -377,6 +451,16 @@ int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const int64_t* lo,
* at issue. Additive export. */
int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g);
/* Every rank holds the same bytes for this paged group, so a tier stores it once. Under tensor
* parallelism a host slot for a cached entry is otherwise every rank's shard end to end; a group
* declared replicated takes one window at the front of the slot, written by rank 0 and read by
* every rank on a restore. The plugin asserts the replication (an MLA latent cache that every
* rank computes whole, an indexer's key cache every rank pools into); the engine moves bytes and
* cannot know. RADIANCE_DEBUG_TIER_VERIFY checks the claim: each follower hashes what it would
* have written and the leader compares. Paged groups only, and never a group this rank declared
* zero. No effect at one rank. Additive export; RAD_ABI_VERSION does not move. */
int rad_kv_group_replicated(RadBuilder* b, rad_kvgroup g);
#define RAD_BUFS(...) ((const rad_buf[]){ __VA_ARGS__ }), \
(int)(sizeof((const rad_buf[]){ __VA_ARGS__ }) / sizeof(rad_buf))
@@ -396,7 +480,7 @@ int rad_op_declared(RadBuilder* b, const char* op);
* convert-time fusions (q/k/v into one qkv, gate and up into gate_up). It is the only component
* that knows both sides, and rad-convert reads the map from it (spec §2.4). */
enum { RAD_MAP_COPY = 0, RAD_MAP_CONCAT = 1, RAD_MAP_WNORM = 2, RAD_MAP_ROWS = 3,
RAD_MAP_TRANSPOSE = 4, RAD_MAP_EMA = 5 };
RAD_MAP_TRANSPOSE = 4, RAD_MAP_EMA = 5, RAD_MAP_TAP = 6, RAD_MAP_COLS = 7 };
typedef struct RadNameMap {
const char* declared; /* the name given to rad_decl_weight */
@@ -412,7 +496,8 @@ typedef struct RadNameMap {
int src_index[8];
/* RAD_MAP_ROWS only: piece i is rows [src_index[i], src_index[i] + src_rows[i]) of the 2-D (or
* higher, rows along dim 0) tensor src[i]; the pieces join along dim 0. */
* higher, rows along dim 0) tensor src[i]; the pieces join along dim 0. RAD_MAP_COLS: columns
* [src_index[0], src_index[0] + src_rows[0]) of src[0]'s last dimension. */
int64_t src_rows[8];
} RadNameMap;
@@ -430,7 +515,13 @@ typedef struct RadNameMap {
*
* RAD_MAP_ROWS keeps only row ranges of its sources (see src_rows), joined: a head read over a
* fraction of a vocabulary (an audio model's codes, a few rows of a text model's 200K) stores that
* fraction rather than the whole table.
* fraction rather than the whole table. Successive ROWS maps for one name extend it in call order,
* as CONCAT maps do, so a weight may take more than eight pieces (an output projection whose rows
* are permuted, one piece a row).
*
* RAD_MAP_COLS keeps one column range of src[0] (see src_rows): a linear whose input carries
* channels the runtime never feeds (Cosmos's padding-mask channel, always zero) is read over the
* columns it is fed.
*
* RAD_MAP_TRANSPOSE swaps the last two dimensions of src[0] in each leading slice, [.., a, b] to
* [.., b, a]: a linear a checkpoint keeps as (in, out), where the GEMMs read (out, in).
@@ -440,7 +531,13 @@ typedef struct RadNameMap {
* divided by max(usage, 1e-5), in f32. Successive EMA maps for one name stack their codebooks
* along dim 0, as CONCAT maps extend (a residual quantiser's codebooks as one table).
*
* TRANSPOSE and EMA are computed at convert in f32, like WNORM, and stored as the recipe says. */
* RAD_MAP_TAP keeps one index of one dimension of src[0], dropping that dimension: index
* src_index[0] (negative counts from the end) of dimension `concat_dim`. A causal 3-D convolution
* run on a single frame reads only its last temporal tap, so [cout, cin, kt, kh, kw] read at tap -1
* of dimension 2 is the 2-D convolution it then is.
*
* TRANSPOSE, EMA, TAP and COLS are computed at convert in f32, like WNORM, and stored as the recipe
* says. */
int rad_decl_name_map(RadBuilder* b, const RadNameMap* m);
@@ -556,6 +653,15 @@ int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d);
* checkpoint was trained with is the plugin's to know. */
int rad_drafter_shared_kv(RadBuilder* b, int pos_offset);
/* Whether this engine's launches chain (RadKernelChainFn, abi/rad_abi.h): the core's decision, on
* the AQL backend only, which keeps a completion counter per queue -- by default where the model's
* plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter
* decodes speculatively, or as RADIANCE_CHAIN says. A plugin that places work by whether a kernel
* waits in its prologue behind the one before it -- a weight read issued on lane 0 right after its
* GEMM -- asks this instead of reading the environment, so it follows that decision. Additive
* export; RAD_ABI_VERSION does not move. */
int rad_chain_on(void);
/* ================================================================== the encoder */
/* A media encoder the plugin runs on an encoder pass (RadBatch::enc). The core drives the pass and
* reads its result, so the plugin declares it. A plugin that declares none serves text only, and
@@ -621,8 +727,21 @@ enum { RAD_GEN_PASS_COND = 1, RAD_GEN_PASS_DENOISE = 2, RAD_GEN_PASS_DECODE = 3
* in all three; a picture of h x w tokens holds the count in the first, and its row
* and column, centred on zero (-(n - n/2) .. n/2 - 1), in the other two, after which
* the count moves on by max(h, w). Text rows attend causally, a picture's rows to
* each other both ways, every row to every row before it. */
enum { RAD_GEN_LAYOUT_JOINT_GRID = 1 };
* each other both ways, every row to every row before it.
*
* JOINT_STEP the conditioning is not cached as keys and values but rides in every denoising
* step beside the image, since the model updates it as it goes. The conditioning
* is the prompt's rows after `drop_prefix`, then `pad_token` rows up to a multiple
* of `pad_multiple`, then each reference picture's latent tokens in raster order
* (the pictures are not in the prompt; `tmpl_image` is unused). No KV group is
* declared: the COND pass leaves the conditioning's rows in the plugin's own state,
* once for every lane the request's images run in, and each DENOISE entry is that
* conditioning followed by the image (RadGenBatch, "the joint layout"). Rotary
* positions are four f32 components (t, h, w, l): a text or padding row is (0, 0,
* 0, l), l its index with `rope_text_l` and 0 without; a picture's token at row h,
* column w (from 0) is (0, s h, s w, l) with s `rope_hw_scale`, l -(1 + k) for
* the k-th reference picture and 0 for the image being made. */
enum { RAD_GEN_LAYOUT_JOINT_GRID = 1, RAD_GEN_LAYOUT_JOINT_STEP = 2 };
typedef struct RadGeneratorDecl {
const char* name; /* "qwen-image" -- for messages */
@@ -662,7 +781,8 @@ typedef struct RadGeneratorDecl {
/* The sampler: flow matching, Euler steps from sigma 1 towards 0.
* A fixed schedule: `n_sigmas` values, the terminal 0 implied; a request may not change the
* step count. Otherwise `default_steps` sigmas from 1 to 1/steps, shifted:
* step count. Otherwise `default_steps` sigmas from 1 to 1/steps (or off `sigma_grid`'s
* table), shifted:
* dyn_shift 0 sigma' = shift * s / (1 + (shift - 1) * s)
* dyn_shift 1 mu linear in the image's token count, 256 -> base_shift .. max_seq ->
* max_shift; shift_exp 1: exp(mu) / (exp(mu) + (1/s - 1)), 0: mu / (mu + ...)
@@ -684,10 +804,122 @@ typedef struct RadGeneratorDecl {
* pixels of the image a decode pass made. */
int64_t max_lanes;
rad_buf image_out;
/* ---- the JOINT_STEP layout (zero for JOINT_GRID) */
/* The most rows one conditioning lays out (text, padding and reference latents together):
* the plugin keeps `cond_rows` rows a lane a branch, and a longer prompt is refused. */
int64_t cond_rows;
double rope_hw_scale;
int32_t rope_text_l;
int32_t pad_multiple;
int32_t pad_token;
/* Guidance as the model's card states its scale s: 1 when s means cond + s (cond - uncond),
* which the core runs as s + 1, 0 when it means uncond + s (cond - uncond). `default_cfg` is
* in the card's terms. */
int32_t cfg_original;
/* The negative prompt guidance uses when a request names none ("" is a prompt); null when a
* guided request must name its own. */
const char* default_negative;
/* 1: a reference picture is shrunk to `ref_area` only when larger and cut to `size_multiple`
* by a centred crop; 0: resized to `ref_area` at its own aspect. */
int32_t ref_shrink_only;
/* ---- appended in ABI 25 (Anima, SDXL) */
/* `aux_tokens` nonzero: the conditioning also reads the user's prompt through the container's
* second tokenizer (rad-convert --tokenizer2), as that tokenizer encodes it alone, special
* tokens included, and the COND pass carries the ids (RadGenBatch::aux_ids). A prompt whose
* second tokenisation is longer than `aux_max_tokens` is refused. */
int64_t aux_max_tokens;
/* The unshifted sigmas of a schedule that is not fixed: 0 is diffusers' linspace(1, 1 / steps,
* steps); N > 0 picks them off a table of N timesteps as ComfyUI's `simple` scheduler does,
* step i at (N - floor(i N / steps)) / N, each an f32 quotient of the table's own. */
int32_t sigma_grid;
/* A prompt shorter than this many tokens after `drop_prefix` is padded with `pad_token` up to
* it, the padding read as prompt (a reference tokenizer's minimum length: an empty prompt is
* one padding token, and stays empty rather than becoming " "). 0: no minimum. */
int32_t min_tokens;
int32_t aux_tokens;
/* ---- a discrete-time denoiser (train_steps 0: the flow-matching sampler above)
* A model trained on `train_steps` timesteps of a variance-preserving schedule, betas from
* `beta_start` to `beta_end` (RAD_GEN_BETAS_*), sampled as k-diffusion samples it (Stable
* Diffusion's family). Its schedule is in sigmas, sigma_t = sqrt((1 - abar_t) / abar_t) for
* the cumulative product abar of 1 - beta; `zero_snr` rescales it to a zero terminal SNR
* (the last abar 4.8973451890853435e-08, as ComfyUI does). A request names a sampler
* (RAD_GEN_SAMPLER_*, one of those `samplers` holds as 1 << id, which the plugin's step
* serves) and a scheduler (RAD_GEN_SCHED_*), which places the request's steps between the
* table's largest and smallest sigma, 0 last. A DENOISE pass carries each entry's sigma,
* next and previous sigma in these units, the timestep the denoiser is conditioned on, the
* sampler and the step (RadGenBatch). n_sigmas, shift and the dynamic shift are unused. */
double beta_start, beta_end;
int32_t train_steps;
int32_t beta_schedule;
int32_t zero_snr;
uint32_t samplers;
int32_t default_sampler;
int32_t default_scheduler;
/* ---- the prompt in windows (a CLIP text encoder's fixed context)
* Nonzero: the prompt's tokens after `drop_prefix` are cut into runs of at most
* `chunk_tokens`, each laid out as `chunk_bos`, the run, `chunk_eos`, then `pad_token` up to
* chunk_tokens + 2 rows, the windows end to end; a prompt with no tokens is one window of
* the two markers and padding. The JOINT_STEP layout only, with `pad_multiple` 0, and
* `cond_rows` a whole number of windows. */
int32_t chunk_tokens;
int32_t chunk_bos, chunk_eos;
} RadGeneratorDecl;
/* RadGeneratorDecl::beta_schedule: betas linear in sqrt(beta) (Stable Diffusion's
* "scaled_linear"), or linear in beta. */
enum { RAD_GEN_BETAS_SCALED_LINEAR = 0, RAD_GEN_BETAS_LINEAR = 1 };
/* A discrete-time model's samplers, as k-diffusion (and ComfyUI) name and define them. */
enum {
RAD_GEN_SAMPLER_EULER = 0, /* "euler" */
RAD_GEN_SAMPLER_EULER_ANCESTRAL = 1, /* "euler_ancestral", eta 1 */
RAD_GEN_SAMPLER_DPMPP_2M = 2, /* "dpmpp_2m" */
RAD_GEN_SAMPLER_COUNT = 3
};
/* ... and its schedulers, ComfyUI's: "normal" (timesteps evenly spaced, the last at the smallest
* sigma), "karras" (rho 7), "exponential", "sgm_uniform" (normal without its last point) and
* "simple" (the table read at even strides). */
enum {
RAD_GEN_SCHED_NORMAL = 0,
RAD_GEN_SCHED_KARRAS = 1,
RAD_GEN_SCHED_EXPONENTIAL = 2,
RAD_GEN_SCHED_SGM_UNIFORM = 3,
RAD_GEN_SCHED_SIMPLE = 4,
RAD_GEN_SCHED_COUNT = 5
};
int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d);
/* ================================================================== adapter key names */
/* How LoRA files written for this model name its linears, for an image or video generator served
* with runtime adapters (--lora, --lora-dir, --max-loras; core/lora/). Adapter files from training
* tools and UIs name a module by the model's original code, not by the checkpoint the container
* was converted from, and wrap it in a prefix of their own: `diffusion_model.blocks.3.attn.wq`,
* kohya's `lora_unet_blocks_3_attn_wq`, a bare `blocks.3.attn.wq`. Both calls are optional,
* made before the GEMMs they cover are declared, and only a program that declares a root carries
* adapters at all. Additive exports; RAD_ABI_VERSION does not move.
*
* rad_lora_root declares one network the adapters may reach (the denoiser, a text encoder): every
* LoRA-capable GEMM over a checkpoint tensor whose name starts with `native` gets an adapter path.
* `spellings` lists, space separated, the prefixes adapter keys of this network start with in
* place of `native`; one ending in '_' is kohya's form, in which the rest of the key is the module
* path with every '.' written '_'. `native` itself is always accepted, and "-" stands for a key
* with no prefix at all. A key is tried against the longest matching spelling first.
*
* rad_lora_alias maps an adapter module that the checkpoint names differently. `from` and `to`
* are module paths relative to the root's prefixes (no ".weight"), '#' standing for a decimal
* index that `to` repeats in the same order. Rows [from_lo, from_hi) of the adapter module's
* output (its lora_B rows; from_hi 0 = all of them) land at rows from `to_lo` of the checkpoint
* module `to`. Several aliases with one `from` split a fused adapter module over separate
* checkpoint tensors (a `qkv` over `to_q`, `to_k`, `to_v`); several `from` into one `to` at
* different `to_lo` place separate adapter modules into one fused tensor. A module path that is
* the checkpoint's own needs no alias. */
int rad_lora_root(RadBuilder* b, const char* native, const char* spellings);
int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const char* to,
int64_t from_lo, int64_t from_hi, int64_t to_lo);
/* ================================================================== the audio generator */
/* A program that makes audio from text: an autoregressive language model writes the piece frame by
* frame, with classifier-free guidance (each request runs a conditional and an unconditional
@@ -1080,6 +1312,76 @@ typedef struct RadVideoGenDecl {
int64_t dbg_vd_n_bytes;
rad_buf dbg_vd_pix; /* [1797, 3072] bf16: proj_out pixels of the first tile */
int64_t dbg_vd_pix_bytes;
/* ---- appended in ABI 24 (LTX-2.5) */
/* The sampler's form. 0: the grid points above. 1: diffusers' FlowMatchEulerDiscrete as
* LTX-2 runs it -- a request's `steps` are its evaluations n, between 1 and max_steps; sigmas
* linspace(1, 1/n, n), computed in f64 and taken to f32, and with `dyn_shift` 1 shifted by mu
* as exp(mu) / (exp(mu) + 1/s - 1) in f32, mu linear in the video's latent tokens from
* `base_seq` (`base_shift`) to `max_seq` (`max_shift`); then, with `shift_terminal` > 0,
* stretched so the last is shift_terminal; and a closing 0. A trained schedule (n_rungs > 0)
* is the rungs taken to f32 and a closing 0, with default_steps and max_steps both n_rungs.
* Both modalities step the same sigmas; shift_video and shift_audio are unused. */
int32_t sched_kind;
int32_t dyn_shift;
double base_shift, max_shift;
int64_t base_seq, max_seq;
double shift_terminal;
/* With latent upscaling under a trained schedule of form 1: the sigmas the evaluations after
* the upscale step through (a second stage's own schedule, its first the sigma the upscaled
* latents are re-noised to), instead of the schedule's tail. The small size then runs every
* rung, its last to the clean estimate, and a request's refinement is n_refine_rungs. */
int32_t n_refine_rungs;
const double* refine_rungs;
/* The text rows of every VSTEP pass, whatever the prompt's length (0: the prompt's tokens):
* a model whose text encoder writes a fixed number of rows. */
int64_t step_text_rows;
/* Guidance terms (RadVideoGenBatch::guidance_h) when `guidance` is 1: the defaults a request
* that names none gets, the video's scale, spatio-temporal scale, modality scale and rescale,
* then the soundtrack's four. A request whose video or soundtrack scale is not 1 is guided
* against a negative prompt: its own, else `default_negative` (null: ""). The VCOND pass then
* carries both prompts, the positive first (two cu_seqlens entries). */
int32_t guidance;
double guidance_default[8];
const char* default_negative;
/* Image to video: 1 when the model can start from a first frame (OpenAI's
* `input_reference`), handed to the VCOND pass resized to the size the first evaluations run
* at (RadVideoGenBatch `image`), after an H.264 round trip at `image_crf` when that is > 0
* (the compression the model was trained against). */
int32_t image_cond;
int32_t image_crf;
/* A left-padded text encoder: the VCOND pass's positions count so that each prompt ends at
* `text_left_pad` - 1, the place it holds in a sequence padded on the left to that length (0:
* from 0). */
int64_t text_left_pad;
/* The soundtrack's latent rows a step carries for each latent (0: audio_channels, a stream of
* rows a channel); a model whose latent holds every channel at once carries 1. */
int32_t audio_streams;
/* A latent upscaler of one fixed factor, upscale_max: a request's sides must then be
* multiples of size_multiple x upscale_max, so the small size is exactly the full size over
* the factor. */
int32_t upscale_exact;
/* A length head: a model that predicts from the prompt how long its video should be. With
* `duration_out` set, every VCOND pass writes to it (f32 [1], device) the natural log of that
* length in seconds. For a request that names no length the core takes its exponent, clamps it
* to [duration_min, duration_max] seconds, rounds it to frames at the frame rate and floors
* that to the chunk grid (frames_per_chunk n + frames_tail; one chunk more when the floor falls
* under duration_min and duration_max allows it), then holds it to min_chunks..max_chunks and
* to what a pass carries. Until that VCOND pass is done such a request is shaped at
* `default_chunks`, so the pass may not depend on the length: its geometry carries the
* provisional frame count, and `t_video` / `t_audio` the provisional schedule. 0: a request
* that names no length is made at default_chunks. `duration_dtype` is the precision the model
* takes the exponent in: RAD_F32, or RAD_BF16 for a head run in bf16, whose length is
* exp(x) in f32 rounded to bf16. Frames round half to even, as Python's round(). */
rad_buf duration_out;
double duration_min, duration_max;
uint32_t duration_dtype;
/* Decoders: a model with more than one way to turn its latents into frames names them,
* space-separated, its default first (LTX-2.5: "vae diffusion"). A request may name one; every
* VDECODE pass carries its index (RadVideoGenBatch::decoder). `decoder_max_area`, when set,
* holds each decoder's largest frame in pixels (0: max_area), and a request over it is refused.
* Null: one decoder. */
const char* decoders;
const int64_t* decoder_max_area;
} RadVideoGenDecl;
int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d);
@@ -1104,6 +1406,14 @@ const char* rad_arch_id(void);
* served at: (unquantised)". */
const char* rad_arch_quant(void);
/* Whether this plugin may serve a checkpoint whose quantisation was imported weight by weight
* (Quark, ParoQuant, GPTQ, NVFP4, ...). Such a descriptor names the producing tool, which no plugin
* claims, so the family's one quantised plugin serves it, and two are refused (startup.h). A
* family's second quantised plugin that reads only its own containers returns 0 and leaves imports
* to the first. Optional: absent or non-zero is yes. Additive export; RAD_ABI_VERSION does not
* move. */
int rad_arch_serves_imports(void);
/* What the plugin can say before it declares anything. Optional: a plugin that does not export
* it answers zero to everything, each field's default.
*
@@ -1163,6 +1473,16 @@ typedef struct RadArchProbe {
* `gen_rows` (its largest pass: a step's packed sequence at the largest size and length). It
* keeps no KV. */
int32_t gen_video;
/* The RadBuildCtx::kv_quant layouts the plugin serves for this model, bit 1 << RAD_KVQ_*:
* libr4d has their rows for its attention geometry. A layout whose bit is clear is refused at
* startup with the plugin named. */
int32_t kv_quant_ok;
/* Nonzero when this plugin measured its speculative step faster with chained launches
* (RadKernelChainFn: a dependent kernel waits in its own prologue rather than behind the
* queue's barrier bit). With a drafter decoding speculatively on the AQL backend, the core
* then takes them by default; RADIANCE_CHAIN overrides either way. Zero keeps them off: plain
* decode measured slower chained, and a plugin that never measured them asks for nothing. */
int32_t chain_pays;
} RadArchProbe;
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
@@ -1244,10 +1564,13 @@ typedef struct RadChatFormat {
const char* call_open; /* around each call; "" when calls are not wrapped */
const char* call_close;
const char* name_prefix; /* "" when the model has no tool calls */
/* "" when nothing of its own ends the name: then the object's `{` does, or, for tagged
* arguments in an unwrapped call, the first arg_prefix or call_end, which begin the body */
const char* name_suffix;
const char* call_end;
const char* arg_prefix;
const char* arg_name_suffix; /* "" when arg_value_prefix alone ends the name */
/* "" when arg_value_prefix alone ends the name; both set are written back to back */
const char* arg_name_suffix;
const char* arg_value_prefix;
const char* arg_value_suffix;
+15
View File
@@ -56,9 +56,16 @@ typedef struct RadFileHeader {
uint64_t prof_off, prof_count; /* RadFileProfile[] -- expert popularity */
uint64_t data_off, data_bytes; /* the blob; RAD_ALIGN_POOL-aligned */
/* reserved[RAD_HDR_AUX_VOCAB_OFF] and reserved[RAD_HDR_AUX_VOCAB_BYTES] place a second vocab
* section, laid out as the first (RadVocabHeader + its payload, its strings in the one string
* blob): a tokenizer a generator reads its prompt through beside the model's own
* (RadGeneratorDecl::aux_tokens). Both zero when there is none, as in a file written before
* the section existed; the rest are zero. */
uint64_t reserved[8];
} RadFileHeader;
enum { RAD_HDR_AUX_VOCAB_OFF = 0, RAD_HDR_AUX_VOCAB_BYTES = 1 };
/* ------------------------------------------------------------------ metadata */
typedef struct RadFileKV {
rad_stroff key;
@@ -124,9 +131,17 @@ enum { RAD_TOK_BPE = 1, RAD_TOK_UNIGRAM = 2, RAD_TOK_WORDPIECE = 3, RAD_TOK_RWKV
enum {
RAD_NORM_NFC = 1, RAD_NORM_NFKC = 2, RAD_NORM_NFD = 3, RAD_NORM_NFKD = 4,
RAD_NORM_LOWERCASE = 5, RAD_NORM_STRIP = 6, RAD_NORM_REPLACE = 7, RAD_NORM_PREPEND = 8,
RAD_NORM_PRECOMPILED = 9,
RAD_PRE_BYTELEVEL = 32, RAD_PRE_SPLIT = 33, RAD_PRE_METASPACE = 34,
RAD_PRE_WHITESPACE = 35, RAD_PRE_PUNCTUATION = 36, RAD_PRE_DIGITS = 37,
RAD_PRE_BYTE_FALLBACK = 38,
/* BPE's end-of-word suffix (arg0, CLIP's "</w>"): a word's last symbol carries it, so the
* merges and the vocabulary tell a word's end from its middle. */
RAD_PRE_END_OF_WORD = 39,
/* An added token matched in the normalised text rather than the raw one (tokenizers'
* `normalized`): arg0 its spelling, iarg its id. Cut out after the normalisers and before
* the other pre-tokenisers. */
RAD_PRE_ADDED_NORMALIZED = 40,
RAD_DEC_BYTELEVEL = 64, RAD_DEC_METASPACE = 65, RAD_DEC_REPLACE = 66,
RAD_DEC_STRIP = 67, RAD_DEC_FUSE = 68, RAD_DEC_BYTE_FALLBACK = 69
};
+95 -2
View File
@@ -315,8 +315,79 @@ typedef struct RadGenBatch {
int32_t dec_lane;
int32_t dec_height, dec_width; /* pixels */
int32_t dec_preview; /* the lane's preview latent, not its state */
/* ---- the joint layout (RAD_GEN_LAYOUT_JOINT_STEP)
* COND: `branch` is 0 for the prompt and 1 for the negative prompt, and `n_lane` / `lane_h` /
* `lane` name every lane the conditioning's images run in; the plugin keeps the
* conditioning's row r for lane l at its own row (2 l + branch) cond_rows + r. The prompt's
* last `n_pad` tokens are the padding, and `valid_cu` is {0, the tokens before it}. `rope_f`
* is the conditioning's positions, [4, rows] f32 component-major.
* DENOISE: each entry's rows are its conditioning and then its image's latent tokens, so
* `cu_seqlens` bounds both together. `src` [n_tok] names a row's source: >= 0 the plugin's
* conditioning row (as above), < 0 the image row -(1 + k) of the compact image order, in
* which `img_cu` [n_seq + 1] bounds each entry's image and `img_rows` [n_img] is each image
* row's place in the pass. `mode_cu` [3 n_seq + 1] cuts each entry into its text (padding
* included), its reference pictures and its image: entry e's text is rows [mode_cu[3e],
* mode_cu[3e + 1]), its pictures [mode_cu[3e + 1], mode_cu[3e + 2]), its image up to
* mode_cu[3e + 3]. `rope_f` is [4, n_tok]. Everything sigma, cfg, pair, lane, flags and seed
* say is per entry as for JOINT_GRID, and the lane ops read `img_cu`. */
int32_t branch;
int32_t n_pad;
const int32_t* valid_cu;
int64_t n_img;
const int32_t* img_cu;
const int32_t* img_rows;
const int32_t* mode_cu;
const float* rope_f;
/* DENOISE: the rows again in mode-major order -- every entry's text, then every entry's
* pictures, then every entry's image (the compact image order) -- for a model whose early
* blocks run each mode on its own. `mode_rows` [n_tok] is each one's place in the pass,
* `mode_src` [n_tok] its source as `src` names it, and `mode_rope_f` holds the positions mode
* by mode, mode m's a dense [4, n_m] block at 4 times its start;
* `n_mode_h` [3] counts each mode's rows, so mode m starts at the sum of the counts before
* it, and `mode_ccu` [3, n_seq + 1] bounds each entry's rows of each mode from that start
* (mode m's cu_seqlens at mode_ccu + m (n_seq + 1), each beginning at 0). */
const int32_t* mode_rows;
const int32_t* mode_src;
const int32_t* mode_ccu;
const int64_t* n_mode_h;
const float* mode_rope_f;
/* ---- appended in ABI 25 (Anima, SDXL) */
/* COND, for a generator that reads its prompt through a second tokenizer
* (RadGeneratorDecl::aux_tokens): the user's prompt as that tokenizer encodes it, `n_aux` ids
* on the device, and `aux_cu` {0, n_aux} on the device. 0 and null otherwise. */
int64_t n_aux;
const int32_t* aux_ids;
const int32_t* aux_cu;
/* ---- a discrete-time denoiser (RadGeneratorDecl::train_steps), DENOISE, one value per
* entry: the schedule's sigma before `sigma` (0 on an image's first step), `sigma` on the
* model's trained clock (the nearest of its timesteps, as ComfyUI conditions it), the
* request's sampler (RAD_GEN_SAMPLER_*) and the image's step, from 0. */
const float* sigma_prev;
const float* timestep;
const int32_t* sampler;
const int32_t* step;
/* DENOISE: [n_seq, 2] each entry's image height and width in pixels, f32 (a model
* conditioned on its size); `entry_h` [n_seq, 4] the same entries on the host: the
* conditioning's rows (JOINT_STEP), the height and width in pixels, and the branch (0 the
* prompt, 1 the negative prompt), for a plugin whose ops take an image's geometry from their
* operands and so issue each entry on its own. */
const float* size_px;
const int32_t* entry_h;
/* COND: the pass's token ids on the host ([n_tok]), for a plugin whose issue depends on
* where a window's end-of-text marker sits. */
const int32_t* tokens_h;
/* ---- appended in ABI 26 (Krea 2's rebalance) */
/* COND: the request's RAD_GEN_COND_* options, 0 for none. */
int32_t cond_opts;
} RadGenBatch;
/* A request's conditioning options on a COND pass (RadGenBatch::cond_opts). */
enum {
RAD_GEN_COND_REBALANCE = 1 /* Krea 2: the text taps at the plugin's fixed rebalance gains */
};
/* An entry's flags on a DENOISE pass. */
enum {
RAD_GEN_F_FIRST = 1, /* the image's first step: its latent is the noise its seed draws */
@@ -461,7 +532,8 @@ typedef struct RadVideoGenBatch {
/* f32 [6]: the video's timestep, sigma and next sigma, then the soundtrack's. */
const float* sched;
const float* pos; /* f32 [3, n_tok]: RAD_VPOS_STEP */
/* u32 [2, 2]: the video's noise seed and the soundtrack's, low word first. */
/* u32 [2, 2]: the video's noise seed and the soundtrack's, low word first (VSTEP, VUPSCALE and
* VDECODE passes; a decoder that denoises draws from it). */
const uint32_t* seed;
/* ---- VDECODE */
@@ -530,6 +602,23 @@ typedef struct RadVideoGenBatch {
/* ---- The sampler that advances the latents: RAD_SAMPLER_* above. Trailing since ABI 24. */
int32_t sampler;
/* ---- appended in ABI 24 */
/* VCOND with a negative prompt: `n_neg` of the pass's tokens, after the prompt's. */
int32_t n_neg;
/* The request's guidance, f32 [8] host: the video's scale, its spatio-temporal scale, its
* modality scale and its rescale, then the soundtrack's four; a model's own defaults where
* the request named none. */
const float* guidance_h;
/* VCOND with a first frame (RadVideoGenDecl::image_cond): `image` [height, width, 3] bf16 in
* [-1, 1], device; null without one. Every later pass carries `has_image` 1 for such a
* request. */
const uint16_t* image;
int32_t has_image;
/* guidance_h on the device, f32 [8], for ops that read the terms. */
const float* guidance;
/* VDECODE: the decoder the request named (RadVideoGenDecl::decoders), its index; 0 the
* default. */
int32_t decoder;
} RadVideoGenBatch;
/* RadVideoGenBatch::enc_kind: which reference media an encode pass carries. A plugin's latent
@@ -556,7 +645,11 @@ enum {
* first three are also the source volume; (frames, H, W) the target volume; then both in
* patches, (frames, h / patch, w / patch) and (frames, H / patch, W / patch). */
RAD_VGEOM_UP_SRC = 16, RAD_VGEOM_UP_DST = 21, RAD_VGEOM_UP_PSRC = 24, RAD_VGEOM_UP_PDST = 27,
RAD_VGEOM_N = 32
/* The soundtrack's latents as a volume of single latents, (n_audio, 1, 1); and the video's
* rows cut at its first latent frame, {0, that frame's patches, every patch} (a first frame
* a model conditions on at its own timestep). */
RAD_VGEOM_AUDIO_VOL = 32, RAD_VGEOM_FIRST_CU = 35,
RAD_VGEOM_N = 40
};
/* ================================================================== operands */
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/anima -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(anima LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(anima architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/anima.cpp)
+1367
View File
File diff suppressed because it is too large. Load diff
+109 -11
View File
@@ -432,6 +432,28 @@ inline int map_rows(RadBuilder* b, const char* declared, std::initializer_list<R
return rad_decl_name_map(b, &m);
}
/* How adapter files name a generator's modules (rad_lora_root, rad_lora_alias): one network
* under the checkpoint prefix `native`, the prefixes adapter keys use for it, and the module paths
* that differ, '#' standing for a block index. */
struct LoraName {
std::string from, to;
int64_t from_lo = 0, from_hi = 0, to_lo = 0;
};
inline int lora_names(RadBuilder* b, const char* native, const char* spellings,
const std::vector<LoraName>& names) {
const int s = rad_lora_root(b, native, spellings);
if (s < 0) return s;
for (const LoraName& n : names) {
const int a = rad_lora_alias(b, native, n.from.c_str(), n.to.c_str(), n.from_lo, n.from_hi,
n.to_lo);
if (a < 0) return a;
}
return RAD_OK;
}
/* The prefixes ComfyUI, kohya and bare-key adapter files put before a diffusion model's modules. */
inline const char* kLoraDiffusionSpellings = "diffusion_model. model.diffusion_model. lora_unet_ "
"base_model.model. -";
/* A weight-normalised checkpoint tensor folded into its plain weight (RAD_MAP_WNORM). */
inline int map_wnorm(RadBuilder* b, const char* declared, const char* g, const char* v) {
RadNameMap m = map_base(declared, RAD_MAP_WNORM);
@@ -450,6 +472,17 @@ inline int map_transpose(RadBuilder* b, const char* declared, const char* src) {
return rad_decl_name_map(b, &m);
}
/* One index of one dimension of a checkpoint tensor (RAD_MAP_TAP): a causal 3-D convolution's
* last temporal tap is map_tap(b, name, src, 2, -1). */
inline int map_tap(RadBuilder* b, const char* declared, const char* src, int dim, int index) {
RadNameMap m = map_base(declared, RAD_MAP_TAP);
m.n_src = 1;
m.src[0] = src;
m.src_index[0] = index;
m.concat_dim = dim;
return rad_decl_name_map(b, &m);
}
/* An EMA codebook: the embedding sums over max(cluster usage, 1e-5), row by row (RAD_MAP_EMA). */
inline int map_ema(RadBuilder* b, const char* declared, const char* sums, const char* usage) {
RadNameMap m = map_base(declared, RAD_MAP_EMA);
@@ -554,6 +587,53 @@ inline rad_op rw(RadBuilder* b, rad_op h,
return h;
}
/* ---- A weight read into the on-die cache beside a collective (libr4d `prefetch`, docs/OPS.md).
* At decode heights a GEMM streams its weight once from memory, and a collective in front of it
* leaves the card's memory idle for its round trip. prefetch_beside issues `op`, a `prefetch` of
* the next GEMM's weight `w`, behind the GEMM before the collective, so the two do not share the
* memory, and the next GEMM finds its leading bytes in the cache. Nothing it reads or writes is a
* model value, so on the second lane it keeps that lane's rules with no buffer named
* (core/runtime/ctx.h): it is no collective, keeps no counter and touches no arena byte.
*
* Only at decode and verify heights, up to kPrefetchRows rows: a DFlash2 verify's 8 a sequence, a
* z-lab DFlash verify's 16, a plain decode's one. With the ceiling at 64, a prompt's prefill steps
* (40 rows on the 31B's test prompt) took the reads too, and a freshly started 31B server's first
* greedy reply then differed on 4 of 6 starts (4x R9700, the cards' memory scribbled before each
* start); at 16, and with no reads at all, 0 of 6. Per-op output hashes later located that
* divergence at the prefill all-reduce's first reuse of a double-buffered slot: a race in the
* all-reduce, which its full fence on prefill-sized messages (libr4d) cures, not in anything the
* reads touch. The reads stay off prompt steps all the same. */
constexpr int64_t kPrefetchRows = 16;
/* The read goes on lane 0 itself, right after the GEMM, where its chained form (libr4d
* r4dchain_prefetch) waits for that GEMM and then reads beside the collective after it without
* holding the collective: no join between the lanes, so no record on the GEMM and no barrier bit
* on it, and the read starts as the GEMM's last block ends rather than ~10 us later on lane 1. On
* 4x R9700 (31B DFlash2, three rounds, every reply identical): code 385-386 tok/s against 363-365,
* prose 284-286 against 269-270, decode after a 6.4k prompt 580-583 against 538-541. Only where
* launches chain (rad_chain_on, the core's decision), since a plain launch would read in series
* there; elsewhere the read goes on lane 1, behind a join from lane 0. */
inline bool prefetch_lane0() { return rad_chain_on() != 0; }
inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
if (!op || T > kPrefetchRows) return;
if (prefetch_lane0()) {
RAD_ISSUE(c, op, RAD_W(w));
return;
}
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) RAD_ISSUE(c, op, RAD_W(w));
rad_lane(c, 0);
}
/* RADIANCE_PREFETCH=0 declares no reads at all (docs/GUIDE.md); read at declare. */
inline bool prefetch_enabled() {
const char* e = std::getenv("RADIANCE_PREFETCH");
return !(e && !std::strcmp(e, "0"));
}
/* The `prefetch` of `w`'s first `bytes`, where a library serves it and the reads are on; 0
* otherwise. */
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) {
if (!w || bytes <= 0 || !prefetch_enabled() || !rad_op_declared(b, "prefetch")) return 0;
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w));
}
/* ================================================================== geometry */
/* Dimensions come from model metadata, so one plugin covers every size in a family. Sharded
* dimensions are already divided by world_size: the plugin declares divided dimensions and emits
@@ -1229,17 +1309,30 @@ inline const RadKVGroupBatch* kv_batch(const RadBatch* b, rad_kvgroup group) {
* layer, head, feed-forward, norm and rotary geometry of the container's `draft.` config, split
* over the ranks, and a plain RMS norm. A drafter is a second model, so nothing is defaulted: a
* config that does not describe one is refused, naming `what` (spec §17). So is a vocabulary
* other than the target's, since a drafter reads the target's embedding and lm_head. */
* other than the target's, since a drafter reads the target's embedding and lm_head.
*
* The layer config sits at the top of `draft.` in z-lab's and SpecForge's checkpoints, and under
* `draft.transformer_layer_config.` in vLLM's speculators format (RedHatAI's DFlash2 drafters),
* whose top level holds the speculator's own keys instead (drafter_layer_prefix). */
inline const char* drafter_layer_prefix(const RadModelMeta* meta) {
if (rad_meta_geti(meta, "draft.num_hidden_layers", 0) > 0) return "draft.";
if (rad_meta_geti(meta, "draft.transformer_layer_config.num_hidden_layers", 0) > 0)
return "draft.transformer_layer_config.";
return "draft.";
}
inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what) {
dg = target;
dg.n_layer = rad_meta_geti(meta, "draft.num_hidden_layers", 0);
dg.head_dim = rad_meta_geti(meta, "draft.head_dim", 0);
dg.n_head_all = rad_meta_geti(meta, "draft.num_attention_heads", 0);
dg.n_head_kv_all = rad_meta_geti(meta, "draft.num_key_value_heads", 0);
dg.n_ff_all = rad_meta_geti(meta, "draft.intermediate_size", 0);
dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
rad_meta_getf(meta, "draft.rope_theta", 0.0));
const char* pre = drafter_layer_prefix(meta);
char key[160];
auto k = [&](const char* name) { std::snprintf(key, sizeof key, "%s%s", pre, name); return key; };
dg.n_layer = rad_meta_geti(meta, k("num_hidden_layers"), 0);
dg.head_dim = rad_meta_geti(meta, k("head_dim"), 0);
dg.n_head_all = rad_meta_geti(meta, k("num_attention_heads"), 0);
dg.n_head_kv_all = rad_meta_geti(meta, k("num_key_value_heads"), 0);
dg.n_ff_all = rad_meta_geti(meta, k("intermediate_size"), 0);
dg.eps = (float)rad_meta_getf(meta, k("rms_norm_eps"), 0.0);
const double th = rad_meta_getf(meta, k("rope_theta"), 0.0);
dg.theta = (float)rad_meta_getf(meta, k("rope_parameters.rope_theta"), th);
dg.wadd = dg.wadd_qk = 0.0f;
if (dg.n_layer <= 0 || dg.head_dim <= 0 || dg.n_head_all <= 0 || dg.n_head_kv_all <= 0 ||
dg.n_ff_all <= 0 || !(dg.eps > 0.0f) || !(dg.theta > 0.0f)) {
@@ -1250,11 +1343,11 @@ inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta,
(long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta);
return RAD_E_INVAL;
}
RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", 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_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv));
RAD_ARCH_TRY(divide_or_fail(dg.n_ff_all, dg.world, "draft intermediate_size", &dg.n_ff));
const long long dvocab = rad_meta_geti(meta, "draft.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) {
fprintf(stderr, "radiance: the %s drafter claims a %lld-token vocabulary and the target "
"has %lld; it reads the target's embedding and lm_head\n",
@@ -1331,6 +1424,11 @@ inline int drafter_kv_group(RadBuilder* b, Names& nm, const RadBuildCtx* ctx, Ge
return NS::audio_format(m); \
}
/* Optional: RAD_ARCH_SERVES_IMPORTS(0) keeps a family's second quantised plugin out of the pick for
* an imported checkpoint (rad_builder.h, rad_arch_serves_imports). */
#define RAD_ARCH_SERVES_IMPORTS(V) \
extern "C" int rad_arch_serves_imports(void) { return V; }
} /* namespace arch */
} /* namespace rad */
+294 -39
View File
@@ -69,10 +69,21 @@
* 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.
*
* 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
* kept bit for bit. Each rank hands over an equal share of c's columns
* (n_embd / world) and computes the fewest whole 128-row scale blocks that cover
* it (the 31B at tp 4: 1344 columns a rank inside 11 blocks, 1408 rows, against
* 42 blocks whole), a row span of the one stored weight
* (DenseFP8::declare_slice), so no reconvert. The GEMM takes its K split from
* the whole width (OPS.md's `split_n`), so each output is summed as the unsplit
* fc sums it, and the all-gather reads each rank's window out of its wider rows
* (an input pitch) and writes c whole. A GEMM cannot write a column slice (the
* narrow fp8 kernel's store is tight), which is why the windows are the
* gather's to cut. One rank, or an fc off block fp8, keeps it whole.
*
* Replicated:
*
* fc [n_embd, n_taps*n_embd], 262 MiB. Column-sharding would halve it but add an
* all-reduce to the prefill path.
* conv weights projection and base kernel, 26 MiB a layer. The convolution spans the whole
* replicated hidden row, so every rank needs every coefficient.
* codebooks [n_vocab, 256], 127 MiB each, gathered by global token id. Only 128 rows are
@@ -113,6 +124,12 @@ struct Dflash2 {
int64_t sel_topk = 16; /* candidates kept per position */
int64_t window = 0; /* sliding attention width, 0 for none */
int causal = 0;
/* The target's embedding scale, applied to the query block as the drafter was trained
* (dflash_config.input_embedding_scale): 1 for Qwen, sqrt(hidden) in bf16 for Gemma. */
double escale = 1.0;
/* Bytes of the next GEMM's weight read into the cache beside each all-reduce of the query
* pass (prefetch_beside, rad_arch.h); 0 reads none. */
int64_t prefetch = 0;
int64_t steps() const { return block - 1; }
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
/* The kernel projection emits [2, taps, NG] per token (prepare's set, then finish's);
@@ -124,6 +141,10 @@ struct Dflash2 {
/* the context pass */
rad_buf src = 0; /* [max_tok, n_taps * n_embd] the trunk's taps, read only */
rad_buf c = 0; /* [max_tok, n_embd] fc's output, then normed in place */
/* [max_tok, fc_rows] the block-aligned rows of a split fc this rank computes, whose
* fc_share-wide window at fc_off is gathered into c. The block declares it (only when it
* splits fc); leave it 0. */
rad_buf cpart = 0;
/* K and V are separate buffers because of the per-head k norm: `rmsnorm` takes one row
* pitch, and K heads inside a fused [K|V] row are head_dim apart within a token but
* 2*kv_dim apart between tokens. libr4d refuses such an operand (libr4d/r4d_model.cpp,
@@ -188,10 +209,17 @@ struct Dflash2 {
* MXFP4 accepts ~1% fewer tokens per step than fp8 and saves ~1.5 ms of a ~34 ms step.
* Quantisation can only change acceptance, since every draft is verified. */
DenseFP8 w_fc{};
/* fc split by rows (see SHARDING): w_fc is this rank's fc_rows block-aligned rows, holding its
* fc_share output columns at row fc_off. fc_rows 0: w_fc is the whole fc, replicated. */
int64_t fc_share = 0, fc_rows = 0, fc_off = 0;
rad_weight w_hnorm = 0, w_norm = 0;
rad_weight w_selp = 0, w_pred = 0, w_succ = 0;
rad_weight w_tok = 0; /* the target's embedding table */
rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit copy of the target's lm_head */
rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit (or 8-bit) copy of the target's lm_head */
/* The copy is int8 with an f16 scale per (row, 128 of K) where the recipe made it so (the
* 31B's: the head read at w8a8, so the selector sees the candidates an 8-bit head ranks), and
* the 2-bit grid otherwise. Set by declare from the copy's encoding. */
bool head_i8 = false;
/* per-layer weights */
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
@@ -206,7 +234,11 @@ struct Dflash2 {
/* context-pass ops */
rad_op op_cfc = 0, op_cnorm = 0, op_crope = 0, op_cstore = 0;
rad_op op_cgath = 0; /* the split fc's all-gather */
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
/* The k norm, the k rotary and the cache store as one launch a layer (qkv_norm_rope_kv_store
* with n_head 0 and v_norm 0), issued in place of those three where it resolves. */
rad_op op_cqkr[MAX_LAYERS] = {};
/* Activation quantisers, one per activation that feeds a linear. Weightless, so one declaration
* serves every layer; ops with weights are per layer because a weight's prefetch interval
@@ -222,11 +254,26 @@ struct Dflash2 {
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
rad_op op_op[MAX_LAYERS] = {};
rad_op op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {};
/* The q and k norms, both rotaries and the cache store as one launch a layer
* (qkv_norm_rope_kv_store with v_norm 0), issued in place of those five where it resolves. */
rad_op op_qkr[MAX_LAYERS] = {};
rad_op op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
rad_op op_gug[MAX_LAYERS] = {}; /* the gate_up|silu|quant fold; 0 when nothing serves it */
rad_op op_aconv[MAX_LAYERS] = {}, op_fconv[MAX_LAYERS] = {};
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
/* 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),
* op_aan[i] after layer i-1's feed-forward (layer i's attention norm, i >= 1), op_afinal after
* the last layer's (the final norm). All or none. */
rad_op op_afn[MAX_LAYERS] = {}, op_aan[MAX_LAYERS] = {}, op_afinal = 0;
/* The reads beside the query pass's all-reduces (cfg.prefetch), each the GEMMs that follow
* in their order: beside the attention's, the feed-forward's coefficient projection, then
* gate_up; beside the feed-forward's, the next layer's attention coefficient projection, then
* its q -- after the last layer, the draft head; and o's beside the attention itself. 0 where
* none is declared. */
rad_op op_pfa[MAX_LAYERS][2] = {}, op_pff[MAX_LAYERS][2] = {}, op_pfo[MAX_LAYERS] = {};
rad_weight pfa_w[MAX_LAYERS][2] = {}, pff_w[MAX_LAYERS][2] = {}, pfo_w[MAX_LAYERS] = {};
/* head and selector */
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
@@ -281,9 +328,38 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
/* ---------------------------------------------------------------- model-scope weights */
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, cfg.n_taps * g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
{ nm.ckpt("%s.fc.weight", ck) }));
{
const int64_t K = cfg.n_taps * g.n_embd;
const char* fwn = nm.f("dflash.fc.weight");
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
/* Split only block fp8 (an MXFP4 GEMM's K split is its own), into equal shares of whole
* 16-byte words (the gather's unit). */
RadEncoding fe{};
const RadEncPlane* fsc = nullptr;
const bool fp8 = weight_enc(b, fwn, &fe) && rad_enc_is(&fe, "affine") && fe.n_planes == 2 &&
!fe.transform[0] && fe.plane[0].dtype == RAD_F8E4M3 &&
(fsc = rad_enc_plane(&fe, "scale")) && fsc->block[0] == RAD_FP8_BLOCK &&
fsc->block[1] == RAD_FP8_BLOCK;
const int64_t share = (g.world > 1 && g.n_embd % RAD_FP8_BLOCK == 0 &&
g.n_embd % g.world == 0 && (g.n_embd / g.world) % 8 == 0)
? g.n_embd / g.world : 0;
if (fp8 && share > 0) {
const int64_t B = RAD_FP8_BLOCK;
const int64_t lo = share * g.rank / B * B;
const int64_t hi = (share * (g.rank + 1) + B - 1) / B * B;
fc_share = share;
fc_rows = hi - lo;
fc_off = share * g.rank - lo;
RAD_ARCH_TRY(w_fc.declare_slice(b, nm, nm.f("dflash.fc"), fwn, lo, hi, K,
RAD_ACCESS_PER_TOKEN, grp_model()));
if (!w.cpart)
w.cpart = decl_b(b, nm.f("df_cpart"), g.act_dtype, { g.max_tok, fc_rows });
} else {
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, K, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_model(), { nm.ckpt("%s.fc.weight", ck) },
{}, true));
}
}
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_proj.weight"),
@@ -318,10 +394,28 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
const char* dhn = nm.f("dflash.draft_head.weight");
RAD_ARCH_TRY(map_copy(b, dhn, ck_lm));
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16,
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
/* 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;
/* ---------------------------------------------------------------- per-layer weights */
@@ -419,7 +513,21 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.src}, {w.srcq, w.srcs});
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
if (fc_rows) {
/* The split (SHARDING above): this rank's block-aligned rows into `cpart`, its window of
* them gathered into `c`. The GEMM takes its K split from the whole width. The gather
* rides the trunk's all-reduce instance (the same numel bound, so the same instance). */
op_cfc = w_fc.gemm(b, crows, fc_rows, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.cpart},
g.n_embd);
op_cgath = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", crows * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("row", fc_share)),
RAD_NOWEIGHTS),
{w.cpart}, {w.c});
} else {
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
}
/* In place, like the per-head q/k norms below: a row's scale is computed before the row is
* written. */
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
@@ -468,12 +576,22 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
{w.ck, w.cv}, {});
/* ---------------------------------------------------------------- the query pass */
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w_tok)),
{}, {w.x});
/* An unscaled lookup is declared exactly as before the scale existed, so a Qwen container
* resolves the same op. */
if (cfg.escale != 1.0)
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
RAD_INT("vocab_offset", g.vocab_off), RAD_F64("mult", cfg.escale)),
RAD_WEIGHTS(w_tok)),
{}, {w.x});
else
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w_tok)),
{}, {w.x});
/* The trunk's embedding is vocab-sharded, so the lookup is partial and needs an exact
* all-reduce. */
if (g.world > 1)
@@ -587,6 +705,62 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.k, w.v}, {});
/* The query pass's q/k norms, rotaries and store as one launch a layer where a library
* serves it: qkv_norm_rope_kv_store with v_norm 0 (v stored as it is), byte-identical to the
* two rmsnorms, the two ropes and kv_store (docs/OPS.md), which stay declared beside it for
* a library that does not. No YaRN (the fold takes none). */
{
/* Only for a shape a library serves: an op declared for one that resolves to no device
* kernel is a hole that refuses startup (Program::device_holes), whether or not it is
* issued, so the block asks within libr4d's span for the fold (head_dim 256 to 512 in
* steps of 256, bf16 rows, an fp8 or bf16 cache). Qwen3.8's DFlash2 drafter (head_dim
* 128) keeps the chain. */
const bool fold_shape = g.head_dim >= 256 && g.head_dim <= 512 && g.head_dim % 256 == 0 &&
!std::strcmp(g.dtype, "bf16") &&
(!std::strcmp(g.kv_dtype, "fp8_e4m3") ||
!std::strcmp(g.kv_dtype, "bf16"));
if (fold_shape && g.yarn.factor == 0.0f &&
rad_op_declared(b, "qkv_norm_rope_kv_store")) {
const int64_t bsz = rad_kv_block_size(b, kv);
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_qkr[i] = RAD_OP(b, "qkv_norm_rope_kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_F64("theta", g.theta), RAD_F64("eps", g.eps),
RAD_F64("scale", g.rope_scale), RAD_STR("mode", "neox"),
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype),
RAD_INT("v_norm", 0), RAD_INT("block_size", bsz),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_WEIGHTS(w_qn[i], w_kn[i]));
if (!op_qkr[i] || !rad_op_resolved(b, op_qkr[i])) {
for (int j = 0; j <= i; ++j) op_qkr[j] = 0;
break;
}
op_qkr[i] = rw(b, op_qkr[i], {w.q, w.k, w.v}, {w.q, w.k, w.v});
}
/* The context pass's keys the same way: no q (n_head 0, `q` passed as k's buffer and
* `q_w` as k's norm, neither read), the context rows' slots. */
for (int64_t l = 0; op_qkr[0] && l < g.n_layer; ++l) {
const int i = (int)l;
op_cqkr[i] = RAD_OP(b, "qkv_norm_rope_kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", 0), RAD_INT("n_head_kv", g.n_head_kv),
RAD_F64("theta", g.theta), RAD_F64("eps", g.eps),
RAD_F64("scale", g.rope_scale), RAD_STR("mode", "neox"),
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype),
RAD_INT("v_norm", 0), RAD_INT("block_size", bsz),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_WEIGHTS(w_kn[i], w_kn[i]));
if (!op_cqkr[i] || !rad_op_resolved(b, op_cqkr[i])) {
for (int j = 0; j <= i; ++j) op_cqkr[j] = 0;
break;
}
op_cqkr[i] = rw(b, op_cqkr[i], {w.ck, w.cv}, {w.ck});
}
}
}
op_act = rw(b, RAD_OP(b, "silu_mul",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_STR("dtype", g.dtype)),
@@ -611,6 +785,30 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h});
/* Each residual add and the norm after it as one launch where a library serves add_rmsnorm
* (byte-identical to the pair: the norm is taken over the bf16 sum it stores), taken only
* where every handle resolves (rad_op_resolved), all or none; the pairs declared beside it run
* otherwise. */
if (rad_op_declared(b, "add_rmsnorm")) {
auto an = [&](rad_weight wt) -> rad_op {
const rad_op h = RAD_OP(b, "add_rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(wt));
return h && rad_op_resolved(b, h) ? rw(b, h, {w.x, w.h2}, {w.x, w.h}) : (rad_op)0;
};
bool all = true;
for (int64_t l = 0; all && l < g.n_layer; ++l) {
const int i = (int)l;
op_afn[i] = an(w_fnorm[i]);
if (l > 0) op_aan[i] = an(w_anorm[i]);
all = op_afn[i] && (l == 0 || op_aan[i]);
}
op_afinal = all ? an(w_norm) : 0;
if (!op_afinal)
for (int i = 0; i < MAX_LAYERS; ++i) op_afn[i] = op_aan[i] = 0;
}
/* ---------------------------------------------------------------- the head and the selector
*
@@ -630,12 +828,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.sel_h}, {w.dq, w.ds, w.dsum});
op_dlogits = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP),
RAD_STR("dtype", "w2a8")),
RAD_WEIGHTS(w_dh, w_dhs)),
{w.dq, w.ds, w.dsum}, {w.dlog});
op_dlogits = head_i8
? rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP),
RAD_STR("dtype", "w8a8")),
RAD_WEIGHTS(w_dh, w_dhs)),
{w.dq, w.ds}, {w.dlog})
: rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP),
RAD_STR("dtype", "w2a8")),
RAD_WEIGHTS(w_dh, w_dhs)),
{w.dq, w.ds, w.dsum}, {w.dlog});
/* Sharded, the top-R runs over this rank's plane, reports global ids and also writes the pair
* plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter present
* with value 0 is a different declaration from an absent one. */
@@ -705,6 +910,22 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_WEIGHTS(w_pred, w_succ)),
{w.cand, w.unary, w.hp}, {w.tokens});
/* The reads beside the all-reduces, after every weight they read is declared. */
if (op_ar && cfg.prefetch > 0)
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
pfa_w[i][0] = w_fcp[i];
pfa_w[i][1] = w_gu[i].w;
pff_w[i][0] = l + 1 < g.n_layer ? w_acp[i + 1] : w_dh;
pff_w[i][1] = l + 1 < g.n_layer ? w_q[i + 1].w : 0;
for (int j = 0; j < 2; ++j) {
op_pfa[i][j] = decl_prefetch(b, pfa_w[i][j], cfg.prefetch);
op_pff[i][j] = decl_prefetch(b, pff_w[i][j], cfg.prefetch);
}
pfo_w[i] = w_o[i].w;
op_pfo[i] = decl_prefetch(b, pfo_w[i], cfg.prefetch);
}
return RAD_OK;
}
@@ -718,8 +939,14 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
/* As wide as the prefill chunk, one launch per op (the fp8a8 pair covers every M). */
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
brows(w.c, T), RAD_NONE, w_fc.bref());
if (fc_rows) {
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
brows(w.cpart, T), RAD_NONE, w_fc.bref());
RAD_ISSUE_N(c, op_cgath, T, bcol(w.cpart, fc_off, fc_share, T), brows(w.c, T));
} else {
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
brows(w.c, T), RAD_NONE, w_fc.bref());
}
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
@@ -729,6 +956,12 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref());
if (op_cqkr[i]) {
RAD_ISSUE_N(c, op_cqkr[i], T, brows(w.ck, T), brows(w.ck, T), brows(w.cv, T),
praw(batch->positions, RAD_I32, T), RAD_W(w_kn[i]), RAD_W(w_kn[i]),
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
continue;
}
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv,
brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T));
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
@@ -754,11 +987,23 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
if (op_embed_ar)
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE);
/* x += h2 waits for the norm after it, which takes it in (add_rmsnorm) where declared */
bool add_pending = false;
auto norm = [&](rad_op plain, rad_op folded, rad_weight wt) {
if (add_pending && folded) {
RAD_ISSUE_N(c, folded, T, brows(w.x, T), brows(w.h2, T), RAD_W(wt), brows(w.h, T));
} else {
if (add_pending) RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h2, T), brows(w.x, T));
RAD_ISSUE_N(c, plain, T, brows(w.x, T), RAD_W(wt), brows(w.h, T));
}
add_pending = false;
};
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
/* ---- attention, wrapped in the two halves of one convolution */
RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T));
norm(op_anorm[i], op_aan[i], w_anorm[i]);
RAD_ISSUE_N(c, op_acoef[i], T, brows(w.h, T), RAD_W(w_acp[i]), brows(w.coef, T));
RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
wrow_slice(w_acb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T));
@@ -770,13 +1015,20 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h2q, T), brows(w.h2s, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv,
brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T),
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
prefetch_beside(c, op_pfo[i], pfo_w[i], T);
if (op_qkr[i]) {
RAD_ISSUE_N(c, op_qkr[i], T, brows(w.q, T), brows(w.k, T), brows(w.v, T),
praw(batch->positions, RAD_I32, T), RAD_W(w_qn[i]), RAD_W(w_kn[i]),
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
} else {
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv,
brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T),
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
}
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
brows(w.q, T), kv_cache(kv, first_layer + i),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
@@ -787,16 +1039,17 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref());
for (int j = 0; j < 2; ++j) prefetch_beside(c, op_pfa[i][j], pfa_w[i][j], T);
/* Reduce before the closing convolution. It is linear with coefficients from the
* replicated norm, so either order gives the same result; reducing first keeps x's
* update agreed across ranks. */
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
wrow_slice(w_acb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h2, T), brows(w.x, T));
add_pending = true;
/* ---- the feed-forward, wrapped in the other convolution */
RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T));
norm(op_fnorm[i], op_afn[i], w_fnorm[i]);
RAD_ISSUE_N(c, op_fcoef[i], T, brows(w.h, T), RAD_W(w_fcp[i]), brows(w.coef, T));
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
wrow_slice(w_fcb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T));
@@ -813,13 +1066,14 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
}
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T),
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
for (int j = 0; j < 2; ++j) prefetch_beside(c, op_pff[i][j], pff_w[i][j], T);
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
wrow_slice(w_fcb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h2, T), brows(w.x, T));
add_pending = true;
}
RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
norm(op_final, op_afinal, w_norm);
/* The predicting rows, `steps` per sequence, named by the scheduler through out_ids. */
const int64_t S = batch->n_out;
@@ -830,9 +1084,10 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
* whole. */
RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S), RAD_B(w.dsum));
/* The trailing operand is mxfp4's optional reference, absent here. Operands are positional,
* so an absent optional one is RAD_NONE, not a shorter list. */
* so an absent optional one is RAD_NONE, not a shorter list. The 8-bit head is symmetric and
* takes no asum. */
RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs),
brows(w.dlog, S), RAD_B(w.dsum), RAD_NONE);
brows(w.dlog, S), head_i8 ? RAD_NONE : RAD_B(w.dsum), RAD_NONE);
/* RAD_NONE fills the unused `pairs` slot. Sharded, this rank's top-R are only candidates and
* the merge overwrites `cand`/`unary`. */
if (op_dmerge) {
+370
View File
@@ -0,0 +1,370 @@
/* GLM-5.3's DSA indexer: the stateful compressed-index core over its paged key cache (DsaCache),
* which scores every complete block of a sequence's history against each query and selects the
* 512 the MLA attends to, and the front end around it (GlmIndexer), whose casts bridge ordinary
* linear rows to the flattened per-head quantiser and join normalized keys with learned pool
* gates. No RoPE; the only rotation is the Hadamard inside dsa_query. Selected pages belong to
* the MLA.
*
* Under tensor parallelism the key side stays replicated (every rank pools into the whole index
* cache and scores against it), but from GlmTp::kSplitRows rows, or a smaller step whose rows x
* live blocks reach GlmTp::kSplitWork, each rank scores and selects for its own run of query rows
* (GlmTp::run_of) and two all_gathers join the runs' page tables and lengths: every row's
* selection is computed by the same kernels from the same operands as on one rank, so the joined
* table is the replicated one's bits. The query side (projection, head gates, quantiser) then runs
* on this rank's run of rows only, since no other rank reads them. */
#ifndef RAD_BLOCK_GLM_INDEXER_H
#define RAD_BLOCK_GLM_INDEXER_H
#include "rad_fp8.h"
#include "rad_glm_tp.h"
namespace rad {
namespace arch {
struct DsaCache {
struct Config {
int64_t blocks = 0, work = 0, ring = 0, topk = 512;
};
struct Wire {
rad_buf query = 0, codes = 0, scales = 0, gate = 0, kg = 0;
rad_buf stage = 0, page = 0, bpos = 0, nc = 0, pooled = 0, pool_scale = 0;
rad_buf score = 0, selected = 0, nsel = 0, length = 0;
/* 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;
};
/* The narrower of the two gathered rows, one i32 length a query row (the page table's 513 a
* row is a multiple of it), so a run is whole 16-byte words of both: a multiple of four rows.
* The query and output planes hold world times this. */
static constexpr int64_t kGatherRowBytes = 4;
static int64_t part_rows(int64_t rows, int world) {
return GlmTp::run_rows(rows, world, kGatherRowBytes);
}
Geom g{};
Config c{};
Wire w{};
int layer = 0;
rad_kvgroup index = 0, tail = 0, attention = 0;
rad_weight ape = 0;
rad_op op_query = 0, op_work = 0, op_pool = 0, op_tail = 0, op_score = 0, op_select = 0;
rad_op op_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,
const Wire& wire, rad_kvgroup attn, rad_kvgroup tail_group,
rad_kvgroup* index_group, const char* ape_source) {
g = geom;
c = cfg;
w = wire;
layer = l;
attention = attn;
tail = tail_group;
if (!b || !index_group || !ape_source || !attention || !tail || c.blocks < 1 ||
c.work < (g.max_tok + 3) / 4 + g.max_seqs || c.ring < 4 + g.max_spec || c.topk != 512 ||
!w.query || !w.codes || !w.scales || !w.gate || !w.kg || !w.stage || !w.page ||
!w.bpos || !w.nc || !w.pooled || !w.pool_scale || !w.score || !w.selected || !w.nsel ||
!w.length)
return RAD_E_INVAL;
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, tail));
const char* name = nm.f("blk.%d.index_ape", l);
RAD_ARCH_TRY(map_copy(b, name, ape_source));
ape = decl_w(b, name, RAD_F32, { 4, 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
if (!ape) return RAD_E_INVAL;
// Query buffers are [tokens*32,128]; scoring uses their rank-three view.
op_query = rw(b,
RAD_OP(b, "dsa_query",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * 32), RAD_INT("n", 128),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.query }, { w.codes, w.scales });
op_work = rw(
b,
RAD_OP(b, "qsa_work",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 256), RAD_INT("ratio", 4),
RAD_INT("ring", c.ring), RAD_INT("seqs", g.max_seqs),
RAD_INT("work", c.work), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.kg }, { w.stage, w.page, w.bpos, w.nc });
// Declare immediately before the cache consumer: page size comes from that op.
if (!*index_group) {
RadKVGroupDecl d{};
d.kind = RAD_KV_FULL;
d.dtype = RAD_U8;
d.n_head_kv = 1;
d.head_dim = 17;
*index_group = rad_decl_kv_group(b, nm.f("kv_dsa_index"), &d);
}
index = *index_group;
if (!index) return RAD_E_INVAL;
op_pool =
rw(b,
RAD_OP(b, "dsa_pool",
RAD_PARAMS(RAD_RANGE("M", 1, c.work), RAD_INT("n", 128), RAD_INT("ratio", 4),
RAD_INT("block_size", 4), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(ape)),
{ w.stage, w.page }, { w.pooled, w.pool_scale });
if (!op_pool || rad_kv_block_size(b, index) != 4) return RAD_E_INVAL;
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, index));
op_tail = rw(b,
RAD_OP(b, "qsa_tail_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 256),
RAD_INT("ratio", 4), RAD_INT("ring", c.ring),
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.kg }, {});
op_score = rw(b,
RAD_OP(b, "dsa_score",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
RAD_INT("heads", 32), RAD_INT("blocks", c.blocks),
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "fp8_e4m3")),
RAD_NOWEIGHTS),
{ w.codes, w.scales, w.gate, w.nc }, { w.score });
const bool split = g.world > 1;
const int64_t part = split ? part_rows(g.max_tok, g.world) : 0;
if (split && (!w.cu_part || !w.sel_part || !w.len_part)) return RAD_E_INVAL;
if (split)
op_score_part =
rw(b,
RAD_OP(b, "dsa_score",
RAD_PARAMS(RAD_RANGE("M", 1, part), RAD_INT("n", 128),
RAD_INT("heads", 32), RAD_INT("blocks", c.blocks),
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "fp8_e4m3"),
RAD_INT("row_part", g.rank)),
RAD_NOWEIGHTS),
{ w.codes, w.scales, w.gate, w.nc }, { w.score, w.cu_part });
op_select = rw(b,
RAD_OP(b, "qsa_select",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("blocks", c.blocks),
RAD_INT("topk", 512), RAD_INT("ratio", 4),
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
RAD_NOWEIGHTS),
{ w.score, w.nc }, { w.selected, w.nsel, w.length });
if (split) {
op_select_part = rw(
b,
RAD_OP(b, "qsa_select",
RAD_PARAMS(RAD_RANGE("M", 1, part), RAD_INT("blocks", c.blocks),
RAD_INT("topk", 512), RAD_INT("ratio", 4),
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
RAD_NOWEIGHTS),
{ w.score, w.nc, w.cu_part }, { w.sel_part, w.nsel, w.len_part });
op_gather_sel = rw(b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", 4 * 513, part * 513),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{ w.sel_part }, { w.selected });
op_gather_len = rw(b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", 4, part),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{ w.len_part }, { w.length });
if (!op_score_part || !op_select_part || !op_gather_sel || !op_gather_len)
return RAD_E_INVAL;
}
return op_query && op_work && op_tail && op_score && op_select ? RAD_OK : RAD_E_INVAL;
}
/* The columns a step scores: the live reach the batch bounds on the host. */
int64_t live_blocks(const RadBatch* batch) const {
const auto* ib = kv_batch(batch, index);
int64_t live = ((int64_t)batch->max_ctx_len + batch->n_tok + batch->n_spec + 4) / 4 + 1;
if (live > c.blocks) live = c.blocks;
// T is the total across sequences, so the conservative bound can exceed the
// per-sequence page table. Columns without a table entry cannot be scored.
if (ib && live > ib->block_table_pitch) live = ib->block_table_pitch;
return live < 1 ? 1 : live;
}
/* The decision reads the same host bound as the score plane's width (max_ctx_len, rounded by
* the core), so every rank takes the same path and a recorded decode pass changes it only when
* that bound moves. */
bool splits(const RadBatch* batch) const {
const int64_t T = batch->n_tok;
return op_score_part && (GlmTp::splits(T, g.world) ||
(T >= GlmTp::kSplitWorkRows &&
T * live_blocks(batch) >= GlmTp::kSplitWork));
}
/* The query rows this rank runs: the whole step, or its run of a split step (GlmTp::run_of).
* A rank whose run lies wholly past a small step runs the step's first R rows instead: no
* sequence holds its run, so its scores are -inf, and its answers land past T. The caller's
* projections into `query` and `gate` cover the same rows. */
void query_rows(const RadBatch* batch, int64_t* r0, int64_t* rows) const {
const int64_t T = batch->n_tok;
*r0 = 0;
*rows = T;
if (!splits(batch)) return;
const GlmTp::Run run = GlmTp::run_of(T, g.world, g.rank, kGatherRowBytes);
*r0 = run.first;
*rows = run.rows;
}
void step(RadCtx* ctx, const RadBatch* batch) const {
const auto* ib = kv_batch(batch, index);
const auto* tb = kv_batch(batch, tail);
const auto* ab = kv_batch(batch, attention);
if (!ib || !tb || !ab || !ib->block_table || !ab->block_table || !tb->state_index) {
rad_step_fail(ctx, "DSA requires index/attention block tables and tail state indices");
return;
}
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t work = (T + 3) / 4 + S,
pitch = tb->state_index_pitch > 0 ? tb->state_index_pitch : 1;
int64_t q0 = 0, qn = T;
query_rows(batch, &q0, &qn);
RAD_ISSUE_N(ctx, op_query, qn * 32, brow_slice(w.query, q0 * 32, qn * 32, 128),
brow_slice(w.codes, q0 * 32, qn * 32, 128),
brow_slice(w.scales, q0 * 32, qn * 32, 1));
RAD_ISSUE_N(ctx, op_work, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer),
praw2(tb->state_index, RAD_I32, S, pitch),
praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch), RAD_NONE,
brows(w.stage, work * 4), brows(w.page, work), brows(w.bpos, work),
brows(w.nc, S));
RAD_ISSUE_N(ctx, op_pool, work, brows(w.stage, work * 4), RAD_W(ape), brows(w.pooled, work),
brows(w.pool_scale, work), brows(w.page, work), kv_cache(index, layer));
// Gather before overwriting the tail; the wider ring preserves rejected-token rollback.
RAD_ISSUE_N(ctx, op_tail, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer),
praw2(tb->state_index, RAD_I32, S, pitch));
const int64_t live = live_blocks(batch);
if (splits(batch)) {
step_split(ctx, batch, live);
return;
}
// dsa_score declares ten operands, cu_part the optional tenth; the engine counts them.
RAD_ISSUE_N(ctx, op_score, T, brows(w.codes, T * 32), brows(w.scales, T * 32),
brows(w.gate, T), kv_cache(index, layer), RAD_NONE,
praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch),
praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.nc, S),
bcol_at(w.score, 0, c.blocks, 0, live, T), RAD_NONE);
RAD_ISSUE_N(ctx, op_select, T, bcol_at(w.score, 0, c.blocks, 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));
}
/* Rank r scores rows [r R, r R + R) (rows past the step score -inf) and selects for those
* that exist (query_rows), against the bounds the scorer rebased to its first row. The
* gathers lay the runs end to end, so rows past the step land past T, where nothing reads
* them. */
void step_split(RadCtx* ctx, const RadBatch* batch, int64_t live) const {
const auto* ib = kv_batch(batch, index);
const auto* ab = kv_batch(batch, attention);
const int64_t T = batch->n_tok, S = batch->n_seq, W = g.world;
const int64_t R = part_rows(T, g.world);
int64_t p0 = 0, rows = 0;
query_rows(batch, &p0, &rows);
RAD_ISSUE_N(ctx, op_score_part, R, brows(w.codes, W * R * 32),
brows(w.scales, W * R * 32), brows(w.gate, W * R), kv_cache(index, layer),
RAD_NONE, praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch),
praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.nc, S),
bcol_at(w.score, 0, c.blocks, 0, live, R), brows(w.cu_part, S + 1));
RAD_ISSUE_N(ctx, op_select_part, rows, bcol_at(w.score, 0, c.blocks, 0, live, rows),
praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch), brows(w.nc, S),
praw(batch->positions + p0, RAD_I32, rows), brows(w.cu_part, S + 1),
brows(w.sel_part, rows), brows(w.nsel, rows), brows(w.len_part, rows));
RAD_ISSUE_N(ctx, op_gather_sel, R * 513, brows(w.sel_part, R), brows(w.selected, W * R));
RAD_ISSUE_N(ctx, op_gather_len, R, brows(w.len_part, R), brows(w.length, W * R));
}
};
struct GlmIndexer {
struct Wire {
rad_buf input = 0, q_low = 0, q_wide = 0, kg_raw = 0;
DsaCache::Wire cache{};
};
Geom g{};
Wire w{};
LinearFP8 query{}, key_gate{};
DsaCache cache{};
rad_weight gain = 0, bias = 0, head_weight = 0;
rad_op op_norm = 0, op_query_copy = 0, op_gate_copy = 0, op_head = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const char* prefix, const DsaCache::Config& cfg, rad_kvgroup attention,
rad_kvgroup tail, rad_kvgroup* index) {
g = geom;
w = wire;
if (!b || !prefix || g.n_embd != 4096 || !w.input || !w.q_low || !w.q_wide || !w.kg_raw)
return RAD_E_INVAL;
Geom bg = g;
bg.w_bf16 = true;
auto act = [](rad_buf x) {
ActFP8 a{};
a.x = x;
return a;
};
RAD_ARCH_TRY(query.declare(b, nm, bg, nm.f("blk.%d.index_query", l), 4096, 1536,
RAD_SHARD_NONE, grp_layer(l),
{ nm.ckpt("%s.wq_b.weight", prefix) }, act(w.q_low), w.q_wide));
RAD_ARCH_TRY(key_gate.declare(
b, nm, bg, nm.f("blk.%d.index_key_gate", l), 256, 4096, RAD_SHARD_NONE, grp_layer(l),
{ nm.ckpt("%s.wk.weight", prefix), nm.ckpt("%s.index_kpool_compress_gate", prefix) },
act(w.input), w.kg_raw, 0, { 128, 128 }));
const char *gn = nm.f("blk.%d.index_norm.weight", l),
*bn = nm.f("blk.%d.index_norm.bias", l),
*hn = nm.f("blk.%d.index_head.weight", l);
RAD_ARCH_TRY(map_copy(b, gn, nm.ckpt("%s.k_norm.weight", prefix)));
RAD_ARCH_TRY(map_copy(b, bn, nm.ckpt("%s.k_norm.bias", prefix)));
RAD_ARCH_TRY(map_copy(b, hn, nm.ckpt("%s.weights_proj.weight", prefix)));
gain = decl_w(b, gn, RAD_F32, { 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
bias = decl_w(b, bn, RAD_F32, { 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
head_weight = decl_w(b, hn, RAD_F32, { 32, 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
if (!gain || !bias || !head_weight) return RAD_E_INVAL;
op_norm = rw(b,
RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
RAD_F64("eps", 1e-6), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(gain, bias)),
{ w.kg_raw }, { w.cache.kg });
op_query_copy = rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * 32), RAD_INT("n", 128),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{ w.q_wide }, { w.cache.query });
op_gate_copy = rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{ w.kg_raw }, { w.cache.kg });
op_head = rw(b,
RAD_OP(b, "gemm_nt_f32",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 32),
RAD_INT("K", 4096), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(head_weight)),
{ w.input }, { w.cache.gate });
RAD_ARCH_TRY(cache.declare(b, nm, g, l, cfg, w.cache, attention, tail, index,
nm.ckpt("%s.index_kpool_compress_ape", prefix)));
return op_norm && op_query_copy && op_gate_copy && op_head ? RAD_OK : RAD_E_INVAL;
}
void step(RadCtx* ctx, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
auto act = [](rad_buf x) {
ActFP8 a{};
a.x = x;
return a;
};
int64_t r0 = 0, rows = T;
cache.query_rows(batch, &r0, &rows);
/* Every output row of these ops is independent of the others and of how many there are,
* except the bf16 projection's at 64 rows and under, a band whose split count a tuned
* configuration may set: it stays on the step's rows unless every run is wider. */
const bool runs = cache.splits(batch);
if (runs && T - (g.world - 1) * DsaCache::part_rows(T, g.world) > 64)
query.step(ctx, act(w.q_low), w.q_wide, T, r0, rows);
else
query.step(ctx, act(w.q_low), w.q_wide, T);
RAD_ISSUE_N(ctx, op_query_copy, rows * 32, brow_slice(w.q_wide, r0, rows, 4096),
brow_slice(w.cache.query, r0 * 32, rows * 32, 128));
key_gate.step(ctx, act(w.input), w.kg_raw, T);
RAD_ISSUE_N(ctx, op_norm, T, bcol(w.kg_raw, 0, 128, T), RAD_W(gain), RAD_W(bias),
bcol(w.cache.kg, 0, 128, T));
RAD_ISSUE_N(ctx, op_gate_copy, T, bcol(w.kg_raw, 128, 128, T),
bcol(w.cache.kg, 128, 128, T));
RAD_ISSUE_N(ctx, op_head, rows, brow_slice(w.input, r0, rows, 4096), RAD_W(head_weight),
brow_slice(w.cache.gate, r0, rows, 32));
cache.step(ctx, batch);
}
};
}
} // namespace rad::arch
#endif
+223
View File
@@ -0,0 +1,223 @@
/* GLM-5.3's KDA layer: the seven bf16 projections around the recurrent core (GlmKda), and the
* core itself over already projected inputs (KdaState), whose ple_conv supplies exactly causal
* depthwise convolution + SiLU, cold start and accepted-history rollback included. The two
* low-rank gate paths have no intervening activation. The caller supplies the normalized input
* and owns the mHC residual connection.
*
* Under tensor parallelism the heads split (GlmTp::heads), and with them the q/k/v rows, the
* convolution taps, the state and the output projection's columns; the two rank-128 projections
* into the gates are replicated. The block's all_reduce sums the output. */
#ifndef RAD_BLOCK_GLM_KDA_H
#define RAD_BLOCK_GLM_KDA_H
#include "rad_fp8.h"
#include "rad_glm_tp.h"
#include <cmath>
namespace rad {
namespace arch {
struct KdaState {
struct Config {
int64_t heads = 16, dim = 128, width = 4;
double lower = -5;
};
struct Src {
const char *q_conv = nullptr, *k_conv = nullptr, *v_conv = nullptr, *alog = nullptr,
*bias = nullptr, *norm = nullptr;
};
struct Wire {
rad_buf qkv = 0, conv = 0, a = 0, beta = 0, gate = 0, out = 0;
};
Geom g{};
Config c{};
Wire w{};
int layer = 0;
rad_kvgroup state = 0, history = 0;
rad_weight taps = 0, alog = 0, bias = 0, norm = 0;
rad_op op_conv = 0, op_verify = 0, op_prefill = 0, op_norm = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup st, rad_kvgroup cv,
const Config& cfg, const Wire& wire, const Src& src) {
g = geom;
c = cfg;
w = wire;
layer = l;
state = st;
history = cv;
if (!b || !st || !cv || c.heads < 1 || c.dim != 128 || c.width != 4 || g.max_spec > 31 ||
!std::isfinite(c.lower) || c.lower >= 0 || !w.qkv || !w.conv || !w.a || !w.beta ||
!w.gate || !w.out || w.qkv == w.conv || !src.q_conv || !src.k_conv || !src.v_conv ||
!src.alog || !src.bias || !src.norm)
return RAD_E_INVAL;
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, st));
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, cv));
const int64_t width = c.heads * c.dim;
const char *tn = nm.f("blk.%d.ssm_conv.weight", l), *an = nm.f("blk.%d.ssm_a", l),
*bn = nm.f("blk.%d.ssm_dt_bias", l), *nn = nm.f("blk.%d.ssm_norm.weight", l);
RAD_ARCH_TRY(map_concat(b, tn, { src.q_conv, src.k_conv, src.v_conv }));
RAD_ARCH_TRY(map_copy(b, an, src.alog));
RAD_ARCH_TRY(map_copy(b, bn, src.bias));
RAD_ARCH_TRY(map_copy(b, nn, src.norm));
taps = decl_w(b, tn, RAD_BF16, { 3 * width, c.width }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,
grp_layer(l), 0, { width, width, width });
alog =
decl_w(b, an, RAD_F32, { c.heads }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
bias = decl_w(b, bn, RAD_F32, { width }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
norm =
decl_w(b, nn, RAD_F32, { c.dim }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
if (!taps || !alog || !bias || !norm) return RAD_E_INVAL;
op_conv = rw(b,
RAD_OP(b, "ple_conv",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 3 * width),
RAD_INT("width", c.width), RAD_INT("dilation", 1),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(taps)),
{ w.qkv }, { w.conv });
for (int verify = 0; verify < 2; ++verify) {
const rad_op op = rw(
b,
RAD_OP(b, "kda_update",
RAD_PARAMS(
RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads),
RAD_INT("head_k", c.dim), RAD_INT("head_v", c.dim),
RAD_F64("lower_bound", c.lower),
RAD_F64("scale", 1.0 / std::sqrt((double)c.dim)),
RAD_F64("l2_eps", 1e-6), RAD_STR("mode", verify ? "verify" : "prefill"),
RAD_STR("dtype", "bf16"),
RAD_STR("state_form", g.max_spec > 0 ? "anchor" : "per_candidate")),
RAD_WEIGHTS(alog, bias)),
{ w.conv, w.a, w.beta }, { w.out });
if (verify)
op_verify = op;
else
op_prefill = op;
}
op_norm = rw(b,
RAD_OP(b, "gdn_gated_rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("channels", c.dim),
RAD_F64("eps", g.eps), RAD_STR("act", "sigmoid")),
RAD_WEIGHTS(norm)),
{ w.out, w.gate }, { w.out });
return op_conv && op_verify && op_prefill && op_norm ? RAD_OK : RAD_E_INVAL;
}
void step(RadCtx* ctx, const RadBatch* batch) const {
const auto *st = kv_batch(batch, state), *cv = kv_batch(batch, history);
if (!st || !cv || !st->state_index || !cv->state_index) {
rad_step_fail(ctx, "KDA requires recurrent and convolution state indices");
return;
}
const int64_t T = batch->n_tok, S = batch->n_seq, width = c.heads * c.dim;
const int64_t pitch = st->state_index_pitch > 0 ? st->state_index_pitch : 1;
int64_t D = 0, DT = 0;
batch_split(batch, &D, &DT);
for (int verify = 1; verify >= 0; --verify) {
const int64_t seq0 = verify ? 0 : D, seqs = verify ? D : S - D, rows = verify ? DT : T;
if (!seqs) continue;
const RadOperand cu = praw(batch->cu_seqlens + seq0, RAD_I32, seqs + 1);
const RadOperand init = praw(batch->ctx_lens + seq0, RAD_I32, seqs);
const RadOperand accepted =
verify ? praw(batch->num_accepted, RAD_I32, seqs) : RAD_NONE;
RAD_ISSUE_N(ctx, op_conv, rows, brows(w.qkv, rows), RAD_W(taps),
kv_cache(history, layer), cu, RAD_NONE,
praw(cv->state_index + seq0, RAD_I32, seqs), init, accepted,
brows(w.conv, rows));
RAD_ISSUE_N(ctx, verify ? op_verify : op_prefill, rows, bcol(w.conv, 0, width, rows),
bcol(w.conv, width, width, rows), bcol(w.conv, 2 * width, width, rows),
brows(w.a, rows), brows(w.beta, rows), RAD_W(alog), RAD_W(bias),
kv_cache(state, layer),
praw2(st->state_index + seq0 * pitch, RAD_I32, seqs, pitch), cu, accepted,
init, brows(w.out, rows));
}
RAD_ISSUE_N(ctx, op_norm, T, brows(w.out, T), brows(w.gate, T), RAD_W(norm),
brows(w.out, T));
}
};
struct GlmKda {
struct Wire {
rad_buf input = 0, forget_low = 0, gate_low = 0, out = 0;
KdaState::Wire core{};
};
Geom g{};
Wire w{};
KdaState core{};
LinearFP8 qkv{}, beta{}, forget_a{}, forget_b{}, gate_a{}, gate_b{}, output{};
rad_op op_ar = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const Wire& wire,
const char* prefix, const KdaState::Src& src, rad_kvgroup state,
rad_kvgroup history, bool reduce = true) {
g = geom;
w = wire;
if (!b || !prefix || g.n_embd != 4096 || g.world < 1 || GlmTp::kHeads % g.world ||
!w.input || !w.forget_low || !w.gate_low || !w.out || w.input == w.out ||
w.forget_low == w.gate_low)
return RAD_E_INVAL;
// All seven projections are plain BF16 in the pinned checkpoint.
Geom bg = g;
bg.w_bf16 = true;
const int64_t width = GlmTp::kda_width(g.world), heads = GlmTp::heads(g.world);
const auto group = grp_layer(layer);
auto act = [](rad_buf x) {
ActFP8 a{};
a.x = x;
return a;
};
const auto input = act(w.input);
RAD_ARCH_TRY(qkv.declare(
b, nm, bg, nm.f("blk.%d.attn_qkv", layer), 3 * width, 4096, RAD_SHARD_ROW, group,
{ nm.ckpt("%s.q_proj.weight", prefix), nm.ckpt("%s.k_proj.weight", prefix),
nm.ckpt("%s.v_proj.weight", prefix) },
input, w.core.qkv, 0, { width, width, width }));
RAD_ARCH_TRY(beta.declare(b, nm, bg, nm.f("blk.%d.attn_beta", layer), heads, 4096,
RAD_SHARD_ROW, group, { nm.ckpt("%s.b_proj.weight", prefix) },
input, w.core.beta));
/* Both low-rank down-projections before either up-projection, in step() as here: the
* four reads of the input then share one ordered point of a recorded pass and the two
* up-projections the next, where forget_b between them cost a third. Declared in the
* issue order because the buffer plan takes lifetimes from this list, and forget_low and
* gate_low must not share bytes while both are live. */
RAD_ARCH_TRY(forget_a.declare(
b, nm, bg, nm.f("blk.%d.attn_forget_a", layer), 128, 4096, RAD_SHARD_NONE, group,
{ nm.ckpt("%s.f_a_proj.weight", prefix) }, input, w.forget_low));
RAD_ARCH_TRY(gate_a.declare(b, nm, bg, nm.f("blk.%d.attn_gate_a", layer), 128, 4096,
RAD_SHARD_NONE, group,
{ nm.ckpt("%s.g_a_proj.weight", prefix) }, input, w.gate_low));
RAD_ARCH_TRY(forget_b.declare(
b, nm, bg, nm.f("blk.%d.attn_forget_b", layer), width, 128, RAD_SHARD_ROW, group,
{ nm.ckpt("%s.f_b_proj.weight", prefix) }, act(w.forget_low), w.core.a));
RAD_ARCH_TRY(gate_b.declare(b, nm, bg, nm.f("blk.%d.attn_gate_b", layer), width, 128,
RAD_SHARD_ROW, group, { nm.ckpt("%s.g_b_proj.weight", prefix) },
act(w.gate_low), w.core.gate));
KdaState::Config cfg;
cfg.heads = heads;
RAD_ARCH_TRY(core.declare(b, nm, bg, layer, state, history, cfg, w.core, src));
RAD_ARCH_TRY(output.declare(b, nm, bg, nm.f("blk.%d.attn_output", layer), 4096, width,
RAD_SHARD_COL, group, { nm.ckpt("%s.o_proj.weight", prefix) },
act(w.core.out), w.out));
if (!qkv.bf16 || !beta.bf16 || !forget_a.bf16 || !forget_b.bf16 || !gate_a.bf16 ||
!gate_b.bf16 || !output.bf16)
return RAD_E_UNSUPPORTED;
if (reduce) op_ar = GlmTp::reduce(b, g, w.out);
return reduce && g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
}
void step(RadCtx* ctx, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
auto act = [](rad_buf x) {
ActFP8 a{};
a.x = x;
return a;
};
const auto input = act(w.input);
qkv.step(ctx, input, w.core.qkv, T);
beta.step(ctx, input, w.core.beta, T);
forget_a.step(ctx, input, w.forget_low, T);
gate_a.step(ctx, input, w.gate_low, T);
forget_b.step(ctx, act(w.forget_low), w.core.a, T);
gate_b.step(ctx, act(w.gate_low), w.core.gate, T);
core.step(ctx, batch);
output.step(ctx, act(w.core.out), w.out, T);
if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE);
}
};
}
} // namespace rad::arch
#endif
+138
View File
@@ -0,0 +1,138 @@
/* GLM-5.3's manifold-constrained residual connections (mHC): four residual streams in one
* 16384-wide row. read() mixes them down to the block's 4096-wide input and saves the mixing
* coefficients; write() adds the block's output back into every stream. The mixed residual must
* have a separate destination: each output stream reads every original input stream. */
#ifndef RAD_BLOCK_GLM_MHC_H
#define RAD_BLOCK_GLM_MHC_H
#include "rad_glm_tp.h"
#include <cmath>
namespace rad {
namespace arch {
struct ManifoldConn {
struct Config {
int64_t hc = 4, iterations = 20;
double eps = 1e-6, hc_eps = 1e-6;
};
struct Src {
const char *fn = nullptr, *scale = nullptr, *base = nullptr;
};
struct Wire {
rad_buf h = 0, x = 0, y = 0, out = 0;
// Saved by read(), consumed by write() after the block produces y.
rad_buf post = 0, comb = 0;
};
Geom g{};
Config c{};
Wire w{};
rad_weight w_fn = 0, w_scale = 0, w_base = 0;
rad_op op_pre = 0, op_post = 0;
/* Above the split threshold under TP, GLM's projection is split by residual chunks: each rank
* computes the partials of its chunks with mhc_pre's own kernels, an all_gather joins them,
* and mhc_pre_finish completes the read on every rank (rad_glm_tp.h). */
static constexpr int64_t kChunk = 2048, kPartStride = 28;
rad_buf part = 0, parts = 0;
rad_op op_partial = 0, op_gather = 0, op_finish = 0;
int64_t split_rows = 0, part_row = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const char* name,
const Config& cfg, const Wire& wire, const Src& src, bool defer_post = false) {
g = geom;
c = cfg;
w = wire;
if (!b || !name || !src.fn || !src.scale || !src.base || g.n_embd < 1 || g.max_tok < 1 ||
c.hc < 2 || c.hc > 8 || c.iterations < 1 || c.iterations > 256 ||
!std::isfinite(c.eps) || !std::isfinite(c.hc_eps) || c.eps <= 0 || c.hc_eps < 0 ||
!w.h || !w.x || !w.y || !w.out || !w.post || !w.comb || w.h == w.out || w.h == w.x ||
w.h == w.y || w.x == w.out || w.y == w.out || w.post == w.comb)
return RAD_E_INVAL;
const int64_t width = c.hc * g.n_embd, mix = c.hc * (c.hc + 2);
const char *fn = nm.f("%s.fn", name), *scale = nm.f("%s.scale", name),
*base = nm.f("%s.base", name);
RAD_ARCH_TRY(map_copy(b, fn, src.fn));
RAD_ARCH_TRY(map_copy(b, scale, src.scale));
RAD_ARCH_TRY(map_copy(b, base, src.base));
// Mixing coefficients are F32 in the checkpoint; keep them replicated under TP.
const rad_weight wf = w_fn = decl_w(b, fn, RAD_F32, { mix, width }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
const rad_weight ws = w_scale = decl_w(b, scale, RAD_F32, { 3 }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
const rad_weight wb = w_base = decl_w(b, base, RAD_F32, { mix }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
if (!wf || !ws || !wb) return RAD_E_INVAL;
op_pre = rw(b,
RAD_OP(b, "mhc_pre",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_INT("iterations", c.iterations),
RAD_F64("eps", c.eps), RAD_F64("hc_eps", c.hc_eps),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(wf, ws, wb)),
{ w.h }, { w.x, w.post, w.comb });
if (!op_pre) return RAD_E_INVAL;
RAD_ARCH_TRY(declare_split(b, nm, name));
return defer_post ? RAD_OK : declare_post(b);
}
int declare_split(RadBuilder* b, Names& nm, const char* name) {
const int64_t total = c.hc * g.n_embd / kChunk;
split_rows = GlmTp::kSplitRows;
if (g.world < 2 || g.n_embd != 4096 || c.hc != 4 || total % g.world) {
split_rows = 0;
return RAD_OK;
}
const int64_t mine = total / g.world, T = g.max_tok;
part_row = mine * kPartStride;
part = decl_b(b, nm.f("%s.part", name), RAD_F32, { T, part_row });
parts = decl_b(b, nm.f("%s.parts", name), RAD_F32, { T, total * kPartStride });
op_partial =
rw(b,
RAD_OP(b, "mhc_pre_partial",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), RAD_INT("hc", c.hc),
RAD_INT("chunk", kChunk), RAD_INT("first", g.rank * mine),
RAD_INT("chunks", mine), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_fn)),
{ w.h }, { part });
op_gather = rw(b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", part_row, T * part_row),
RAD_STR("dtype", "f32"), RAD_INT("row", part_row)),
RAD_NOWEIGHTS),
{ part }, { parts });
op_finish = rw(b,
RAD_OP(b, "mhc_pre_finish",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_INT("iterations", c.iterations),
RAD_F64("eps", c.eps), RAD_F64("hc_eps", c.hc_eps),
RAD_INT("chunk", kChunk), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_scale, w_base)),
{ parts, w.h }, { w.x, w.post, w.comb });
return part && parts && op_partial && op_gather && op_finish ? RAD_OK : RAD_E_INVAL;
}
int declare_post(RadBuilder* b) {
op_post = rw(b,
RAD_OP(b, "mhc_post",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ w.y, w.h, w.post, w.comb }, { w.out });
return op_post ? RAD_OK : RAD_E_INVAL;
}
void read(RadCtx* ctx, int64_t rows) const {
if (split_rows && rows >= split_rows) {
RAD_ISSUE_N(ctx, op_partial, rows, brows(w.h, rows), RAD_W(w_fn), brows(part, rows));
RAD_ISSUE_N(ctx, op_gather, rows * part_row, brows(part, rows), brows(parts, rows));
RAD_ISSUE_N(ctx, op_finish, rows, brows(parts, rows), brows(w.h, rows), RAD_W(w_scale),
RAD_W(w_base), brows(w.x, rows), brows(w.post, rows), brows(w.comb, rows));
return;
}
RAD_ISSUE_N(ctx, op_pre, rows, brows(w.h, rows), RAD_W(w_fn), RAD_W(w_scale), RAD_W(w_base),
brows(w.x, rows), brows(w.post, rows), brows(w.comb, rows));
}
void write(RadCtx* ctx, int64_t rows) const {
RAD_ISSUE_N(ctx, op_post, rows, brows(w.y, rows), brows(w.h, rows), brows(w.post, rows),
brows(w.comb, rows), brows(w.out, rows));
}
};
}
} // namespace rad::arch
#endif
+190
View File
@@ -0,0 +1,190 @@
/* GLM-5.3's sparse latent attention (MLA, no RoPE): the projections and the latent cache store
* around the absorbed core (GlmMla), and the core itself over the latent cache (MlaLatent), whose
* complete heads shard as rows of the shared K/V weight. prepare() exposes the normalized q latent
* for the indexer; finish() consumes the indexer's selection. The caller owns the mHC residual.
*
* Under tensor parallelism the 64 heads split over the ranks (GlmTp::heads): the rows of q_b and
* kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent cache are
* replicated. */
#ifndef RAD_BLOCK_GLM_MLA_H
#define RAD_BLOCK_GLM_MLA_H
#include "rad_fp8.h"
#include "rad_glm_tp.h"
#include <cmath>
namespace rad {
namespace arch {
struct MlaLatent {
struct Config {
int64_t heads = 16, head_dim = 256, latent_dim = 512, blocks = 513;
};
struct Wire {
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0;
};
Geom g{};
Config c{};
Wire w{};
int layer = 0;
rad_kvgroup kv = 0;
rad_weight projection = 0;
rad_op op_absorb = 0, op_attn = 0, op_expand = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
const Config& cfg, const Wire& wire, const char* source) {
g = geom;
c = cfg;
w = wire;
layer = l;
kv = group;
if (!b || !source || !group || c.heads < 1 || c.blocks < 1 || !w.q || !w.q_latent ||
!w.attn_latent || !w.out || !w.selected || !w.length || w.q == w.q_latent ||
w.q_latent == w.attn_latent || w.attn_latent == w.out || c.latent_dim != 512 ||
c.head_dim != 256)
return RAD_E_INVAL;
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, group));
const char* name = nm.f("blk.%d.attn_kv_b.weight", l);
RAD_ARCH_TRY(map_copy(b, name, source));
// The conversion recipe decodes this small projection only.
projection = decl_w(b, name, RAD_BF16, { c.heads * 2 * c.head_dim, c.latent_dim },
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
if (!projection) 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", c.heads),
RAD_INT("head_dim", c.head_dim), RAD_INT("latent_dim", c.latent_dim),
RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(projection)),
{ w.q }, { w.q_latent });
op_attn =
rw(b,
RAD_OP(b, "mla_attn",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("latent_dim", c.latent_dim),
RAD_INT("heads", c.heads), RAD_INT("blocks", c.blocks),
RAD_INT("block_size", 4),
RAD_F64("scale", 1.0 / std::sqrt((double)c.head_dim)),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.q_latent, w.selected, w.length }, { w.attn_latent });
if (!op_attn || rad_kv_block_size(b, group) != 4) return RAD_E_INVAL;
op_expand = rw(
b,
RAD_OP(b, "mla_project",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads),
RAD_INT("head_dim", c.head_dim), RAD_INT("latent_dim", c.latent_dim),
RAD_STR("mode", "expand"), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(projection)),
{ w.attn_latent }, { w.out });
return op_absorb && op_attn && op_expand ? RAD_OK : RAD_E_INVAL;
}
void step(RadCtx* ctx, int64_t rows) const {
RAD_ISSUE_N(ctx, op_absorb, rows, brows(w.q, rows), RAD_W(projection),
brows(w.q_latent, rows));
RAD_ISSUE_N(ctx, op_attn, rows, brows(w.q_latent, rows), kv_cache(kv, layer),
brows(w.selected, rows), brows(w.length, rows), brows(w.attn_latent, rows));
RAD_ISSUE_N(ctx, op_expand, rows, brows(w.attn_latent, rows), RAD_W(projection),
brows(w.out, rows));
}
};
struct GlmMla {
struct Wire {
ActFP8 input{}, q_low{}, attn{};
rad_buf q_raw = 0, kv_raw = 0, latent = 0, out = 0;
MlaLatent::Wire core{};
};
Geom g{};
Wire w{};
int layer = 0;
rad_kvgroup kv = 0;
LinearFP8 q_a{}, kv_a{}, q_b{}, output{};
NormQuantFP8 q_norm{};
QuantFP8 attn_quant{};
MlaLatent core{};
rad_weight q_gain = 0, kv_gain = 0;
rad_op op_kv_norm = 0, op_store = 0, op_ar = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const char* prefix, rad_kvgroup group, bool reduce = true,
bool defer_finish = false) {
g = geom;
w = wire;
layer = l;
kv = group;
if (!b || !prefix || !kv || g.n_embd != 4096 || g.world < 1 || GlmTp::kHeads % g.world ||
!w.input.x || !w.q_raw || !w.kv_raw || !w.latent || !w.out || !w.q_low.x || !w.attn.x ||
w.attn.x != w.core.out)
return RAD_E_INVAL;
const auto wg = grp_layer(l);
RAD_ARCH_TRY(q_a.declare(b, nm, g, nm.f("blk.%d.attn_q_a", l), 1536, 4096, RAD_SHARD_NONE,
wg, { nm.ckpt("%s.q_a_proj.weight", prefix) }, w.input, w.q_raw));
RAD_ARCH_TRY(kv_a.declare(b, nm, g, nm.f("blk.%d.attn_kv_a", l), 512, 4096, RAD_SHARD_NONE,
wg, { nm.ckpt("%s.kv_a_proj_with_mqa.weight", prefix) }, w.input,
w.kv_raw));
const char* qn = nm.f("blk.%d.attn_q_a_norm.weight", l);
const char* kn = nm.f("blk.%d.attn_kv_a_norm.weight", l);
RAD_ARCH_TRY(map_copy(b, qn, nm.ckpt("%s.q_a_layernorm.weight", prefix)));
RAD_ARCH_TRY(map_copy(b, kn, nm.ckpt("%s.kv_a_layernorm.weight", prefix)));
q_gain = decl_w(b, qn, RAD_F32, { 1536 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
kv_gain = decl_w(b, kn, RAD_F32, { 512 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
if (!q_gain || !kv_gain) return RAD_E_INVAL;
RAD_ARCH_TRY(q_norm.declare(b, g, q_gain, w.q_raw, w.q_low, 1536));
op_kv_norm = rw(b,
RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 512),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(kv_gain)),
{ w.kv_raw }, { w.latent });
if (!op_kv_norm) return RAD_E_INVAL;
RAD_ARCH_TRY(q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b", l), GlmTp::mla_width(g.world),
1536, RAD_SHARD_ROW, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) },
w.q_low, w.core.q));
// Cache stores contiguous halves of the normalized latent, with no duplicated K/V.
op_store = rw(b,
RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", 256),
RAD_INT("n_head_kv", 1), RAD_INT("block_size", 4),
RAD_STR("kv_dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.latent }, {});
if (!op_store) return RAD_E_INVAL;
return defer_finish ? RAD_OK : declare_finish(b, nm, prefix, reduce);
}
int declare_finish(RadBuilder* b, Names& nm, const char* prefix, bool reduce = true) {
MlaLatent::Config cfg;
cfg.heads = GlmTp::heads(g.world);
RAD_ARCH_TRY(
core.declare(b, nm, g, layer, kv, cfg, w.core, nm.ckpt("%s.kv_b_proj.weight", prefix)));
RAD_ARCH_TRY(attn_quant.declare(b, g, w.attn, GlmTp::mla_width(g.world)));
RAD_ARCH_TRY(output.declare(b, nm, g, nm.f("blk.%d.attn_output", layer), 4096,
GlmTp::mla_width(g.world), RAD_SHARD_COL, grp_layer(layer),
{ nm.ckpt("%s.o_proj.weight", prefix) }, w.attn, w.out));
if (reduce) op_ar = GlmTp::reduce(b, g, w.out);
return op_store && (!(reduce && g.world > 1) || op_ar) ? RAD_OK : RAD_E_INVAL;
}
void prepare(RadCtx* ctx, const RadBatch* batch) const {
const auto* kb = kv_batch(batch, kv);
if (!kb || !kb->slot_mapping) {
rad_step_fail(ctx, "GLM MLA requires latent cache slot mapping");
return;
}
const int64_t T = batch->n_tok;
q_a.step(ctx, w.input, w.q_raw, T);
kv_a.step(ctx, w.input, w.kv_raw, T);
q_norm.step(ctx, T);
RAD_ISSUE_N(ctx, op_kv_norm, T, brows(w.kv_raw, T), RAD_W(kv_gain), brows(w.latent, T));
q_b.step(ctx, w.q_low, w.core.q, T);
RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T),
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
}
void finish(RadCtx* ctx, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
core.step(ctx, T);
attn_quant.step(ctx, T);
output.step(ctx, w.attn, w.out, T);
if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE);
}
};
}
} // namespace rad::arch
#endif
+194
View File
@@ -0,0 +1,194 @@
/* GLM-5.3's draft head: checkpoint layer 45 as a serial drafter (RAD_DRAFT_SERIAL), around the
* one MLA + indexer + MoE layer the plugin declares and steps itself.
*
* h = gather(the trunk's final hidden states, at the rows this pass continues from)
* e = embed(the token one position on), the encoder's rows over its placeholders
* x = eh_proj( concat( enorm(e), hnorm(h) ) ) the normalized embedding first
* x += attention(norm(x)); the proposal rows: x += moe(norm(x)) <- the plugin's layer
* h' = shared_head.norm(x); logits = the trunk's lm_head over h'
*
* h' is both the logits input and the next round's `h`. No mHC: the layer's residual is a plain
* add. By the sign of RadBatch::draft_pass a history pass (< 0) covers every row the trunk step
* had, fills the draft layer's latent, index and tail for all of them and runs the MoE and the
* head on the proposal rows only (draft_out_ids); a draft round (> 1) is one row a sequence.
*
* The block is declared and stepped in three parts around the layer, in this order: `inputs`
* before the layer's attention, `join` (the residual add and the proposal rows' selection) between
* its attention and its feed-forward, `head` after it. The embedding and lm_head are the trunk's.
* Its names live under the `mtp.` scope (Names), its weights in layer 45's group. eh_proj
* (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass. */
#ifndef RAD_BLOCK_GLM_MTP_H
#define RAD_BLOCK_GLM_MTP_H
#include "rad_glm_tp.h"
#include "rad_block_vit.h"
namespace rad {
namespace arch {
struct GlmMtp {
/* The trunk's: its final hidden states, its logits, its embedding and head. */
struct Wire {
rad_buf final_hidden = 0, logits = 0;
rad_weight token = 0, head = 0;
};
static constexpr int kDepth = 3; /* --num-speculative-tokens auto */
Names nm{ "mtp" };
Geom g{};
Wire w{};
rad_buf x = 0, hidden = 0, embedding = 0, concat = 0, out = 0;
rad_weight en = 0, hn = 0, eh = 0, norm = 0;
rad_op op_prev = 0, op_embed = 0, op_embed_ar = 0, op_en = 0, op_hn = 0, op_eh = 0;
rad_op op_residual = 0, op_select = 0, op_back = 0;
rad_op op_norm = 0, op_copy = 0, op_head = 0;
MediaRows mrows{};
/* The buffers, the weights, and the ops up to the layer's input. `media`: the encoder's rows
* replace the placeholders' embeddings, as the target's do (SGLang feeds its draft model the
* target's image rows); without them the drafts read the placeholder's embedding and
* acceptance falls on a prompt with a picture. */
int declare_inputs(RadBuilder* b, const Geom& geom, const Wire& wire, bool media) {
g = geom;
w = wire;
if (!b || !w.final_hidden || !w.logits || !w.token || !w.head || g.max_spec < 1)
return RAD_E_INVAL;
x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, 4096 });
hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, 4096 }, RAD_BUF_PERSIST);
embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, 4096 });
concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 8192 });
out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, 4096 });
const char* pre = "model.language_model.layers.45";
auto gain = [&](const char* n, const char* src) {
const char* name = nm.f("%s", n);
if (map_copy(b, name, nm.ckpt("%s.%s", pre, src)) < 0) return (rad_weight)0;
return decl_w(b, name, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(45));
};
en = gain("enorm.weight", "enorm.weight");
hn = gain("hnorm.weight", "hnorm.weight");
norm = gain("output_norm.weight", "shared_head.norm.weight");
RAD_ARCH_TRY(map_copy(b, nm.f("eh_proj.weight"), nm.ckpt("%s.eh_proj.weight", pre)));
eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { 4096, 8192 }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(45));
if (!x || !hidden || !embedding || !concat || !out || !en || !hn || !norm || !eh)
return RAD_E_INVAL;
op_prev = rw(b,
RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.final_hidden }, { hidden });
op_embed = rw(b,
RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", 4096),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w.token)),
{}, { embedding });
if (media) RAD_ARCH_TRY(mrows.declare(b, g.max_tok, 4096, embedding));
op_embed_ar = GlmTp::reduce(b, g, embedding, true);
op_en = rmsnorm(b, en, embedding, concat);
op_hn = rmsnorm(b, hn, hidden, concat);
op_eh = rw(b,
RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 4096),
RAD_INT("K", 8192), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(eh)),
{ concat }, { x });
return op_prev && op_embed && op_en && op_hn && op_eh && (g.world == 1 || op_embed_ar)
? RAD_OK
: RAD_E_INVAL;
}
/* Between the layer's attention and its feed-forward: the residual add of the attention's
* output `y`, and on a history pass the proposal rows gathered to the head of `x`. */
int declare_join(RadBuilder* b, rad_buf y) {
op_residual = rw(b,
RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x, y }, { x });
// All history rows fill the draft cache; only proposal rows need its FFN.
op_select = rw(b,
RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x }, { hidden });
op_back = cast(b, hidden, x);
return op_residual && op_select && op_back ? RAD_OK : RAD_E_INVAL;
}
/* After the layer: the head's norm, its output kept as the next round's hidden, the logits,
* and the drafter's declaration. */
int declare_head(RadBuilder* b) {
op_norm = rmsnorm(b, norm, x, out);
op_copy = cast(b, out, hidden);
op_head = rw(b,
RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", 4096),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w.head)),
{ hidden }, { w.logits });
if (!op_norm || !op_copy || !op_head) return RAD_E_INVAL;
RadDrafterDecl dd{};
dd.name = "mtp";
dd.kind = RAD_DRAFT_SERIAL;
dd.depth = g.max_spec;
dd.mask_token = -1;
return rad_declare_drafter(b, &dd);
}
/* The rows a pass runs its feed-forward and head on: the proposal rows of a history pass,
* every row of a draft round. */
static int64_t head_rows(const RadBatch* batch) {
return batch->draft_pass < 0 ? batch->n_draft_out : batch->n_tok;
}
void step_inputs(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (batch->draft_pass < 0 && batch->n_out > 0)
RAD_ISSUE_N(c, op_prev, batch->n_out, RAD_B(w.final_hidden),
praw(batch->out_ids, RAD_I32, batch->n_out), brows(hidden, batch->n_out));
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w.token),
brows(embedding, T));
mrows.step(c, batch, embedding, T);
if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * 4096, brows(embedding, T), RAD_NONE);
RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, 4096, T));
RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, 4096, 4096, T));
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 {
const int64_t T = batch->n_tok, L = head_rows(batch);
RAD_ISSUE_N(c, op_residual, T, brows(x, T), brows(y, T), brows(x, T));
if (batch->draft_pass < 0) {
RAD_ISSUE_N(c, op_select, L, RAD_B(x), praw(batch->draft_out_ids, RAD_I32, L),
brows(hidden, L));
RAD_ISSUE_N(c, op_back, L, brows(hidden, L), brows(x, L));
}
}
void step_head(RadCtx* c, const RadBatch* batch) const {
const int64_t L = head_rows(batch);
RAD_ISSUE_N(c, op_norm, L, brows(x, L), RAD_W(norm), brows(out, L));
RAD_ISSUE_N(c, op_copy, L, brows(out, L), brows(hidden, L));
RAD_ISSUE_N(c, op_head, L, brows(hidden, L), RAD_W(w.head), brows(w.logits, L));
}
private:
rad_op rmsnorm(RadBuilder* b, rad_weight gain, rad_buf in, rad_buf out) const {
return rw(b,
RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(gain)),
{ in }, { out });
}
rad_op cast(RadBuilder* b, rad_buf in, rad_buf out) const {
return rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{ in }, { out });
}
};
}
} // namespace rad::arch
#endif
+82
View File
@@ -0,0 +1,82 @@
/* GLM noaux_tc router. Correction bias changes selection only; mixture weights
* come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. */
#ifndef RAD_BLOCK_GLM_ROUTER_H
#define RAD_BLOCK_GLM_ROUTER_H
#include "rad_glm_tp.h"
#include <cmath>
namespace rad {
namespace arch {
struct GlmRouter {
struct Config {
int64_t experts = 288, top_k = 8, rows = 32;
int norm = 1;
double route_scale = 2.5;
};
struct Src {
const char *weight = nullptr, *correction = nullptr;
};
struct Wire {
rad_buf input = 0, logits = 0, ids = 0, weights = 0;
};
Geom g{};
Config c{};
Wire w{};
rad_weight projection = 0, correction = 0;
rad_op op_project = 0, op_select = 0;
SplitF32Proj split{};
int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const char* name,
const Config& cfg, const Wire& wire, const Src& src) {
g = geom;
c = cfg;
w = wire;
if (!b || !name || !src.weight || !src.correction || g.n_embd < 1 || c.experts < 1 ||
c.experts > 512 || c.top_k < 1 || c.top_k > c.experts || c.rows < 1 ||
c.rows > g.max_tok || !std::isfinite(c.route_scale) || c.route_scale <= 0 || !w.input ||
!w.logits || !w.ids || !w.weights || w.logits == w.weights)
return RAD_E_INVAL;
const char *pn = nm.f("%s.weight", name), *cn = nm.f("%s.correction", name);
RAD_ARCH_TRY(map_copy(b, pn, src.weight));
RAD_ARCH_TRY(map_copy(b, cn, src.correction));
projection = decl_w(b, pn, RAD_F32, { c.experts, g.n_embd }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
correction = decl_w(b, cn, RAD_F32, { c.experts }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(layer));
if (!projection || !correction) return RAD_E_INVAL;
op_project = rw(b,
RAD_OP(b, "gemm_nt_f32",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", c.experts),
RAD_INT("K", g.n_embd), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(projection)),
{ w.input }, { w.logits });
RAD_ARCH_TRY(split.declare(b, nm, g, name, c.rows, c.experts, g.n_embd, projection, w.input,
w.logits));
op_select =
rw(b,
RAD_OP(b, "router_sigmoid_topk",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm),
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
RAD_WEIGHTS(correction)),
{ w.logits }, { w.ids, w.weights });
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 {
if (split.takes(rows))
split.step(ctx, rows, brow_slice(w.input, first, rows, g.n_embd), projection,
brow_slice(w.logits, output_first, rows, c.experts));
else
RAD_ISSUE_N(ctx, op_project, rows, brow_slice(w.input, first, rows, g.n_embd),
RAD_W(projection), brow_slice(w.logits, output_first, rows, c.experts));
}
void step(RadCtx* ctx, int64_t first, int64_t rows, int64_t output_first = 0) const {
project(ctx, first, rows, output_first);
RAD_ISSUE_N(ctx, op_select, rows, brow_slice(w.logits, output_first, rows, c.experts),
RAD_W(correction), brow_slice(w.ids, output_first, rows, c.top_k),
brow_slice(w.weights, output_first, rows, c.top_k));
}
};
}
} // namespace rad::arch
#endif
+379
View File
@@ -0,0 +1,379 @@
/* rad_block_glm_vision.h -- GLM-5.3's vision tower (transformers' Glm5NextVisionModel), served by
* glm5next.
*
* WHAT IT COMPUTES, per encoder pass (RadBatch::enc):
*
* x = patches @ Wp^T + bp the Conv3d patch embedding as a linear layer; a
* patch row is (channel, frame, y, x), no position
* table
* depth times:
* h = RMS(x) gain only
* q, k, v = qkv(h) with bias; q and k RMS-normed per head with a
* gain, then a 2-D rotary over (row, column):
* `axial` over NeoX pairs (i, i + head_dim / 2),
* the row on the first head_dim / 4 frequencies and
* the column on the next, each on its own ladder
* x += proj(attn(q, k, v)) full attention within a segment (one picture)
* x += down(silu(min(g, L)) * clamp(u, -L, L)), g | u = gate_up(RMS(x)) all with bias
* y = RMS(x) post_layernorm
* d = conv2d(y viewed [rows / 2, 2, 2, width], 2 x 2, stride 2) + bd the downsample: one row
* a merged block of merge x merge patches
* out = down'(silu(min(g', L)) * clamp(u', -L, L)), g' | u' = gate_up'(gelu(LN(proj'(d))))
* the merger: no biases but the LayerNorm's, exact
* GELU, the clip of the blocks
*
* which is the reference module for module. The processor stages patches in merge-block order (the
* merge x merge patches of one output row consecutive), so the downsample's input view is the
* reference's own: `conv2d_unfold` writes each merged block's receptive field as one row, its
* columns in the checkpoint weight's order (channel, kernel row, kernel column), and the weight is
* read as stored. Every linear with a bias is `gemm_nt_bias`, its residual in the epilogue.
*
* Every rank runs the whole tower with replicated weights, as rad_block_vit.h's does, and the
* weights are RAD_ACCESS_PER_REQUEST. Activations are sized by the pass (RadBuildCtx::
* max_enc_patches rows), except in a sizing declare (shape_probe), where rows follow the probe's
* step and nothing is declared to the core. */
#ifndef RAD_BLOCK_GLM_VISION_H
#define RAD_BLOCK_GLM_VISION_H
#include "rad_arch.h"
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace rad {
namespace arch {
struct GlmVision {
/* Geometry, from the container's vision_config. */
int64_t depth = 0, width = 0, heads = 0, head_dim = 0, ff = 0, patch = 0, temporal = 0;
int64_t chans = 0, merge = 0, n_embd = 0, proj_ff = 0, patch_dim = 0, P = 0;
double eps = 1e-5, theta = 10000.0, limit = 0.0;
bool on = false;
struct Layer {
rad_weight n1 = 0, qkv_w = 0, qkv_b = 0, q_norm = 0, k_norm = 0, out_w = 0, out_b = 0;
rad_weight n2 = 0, gu_w = 0, gu_b = 0, down_w = 0, down_b = 0;
rad_op op_n1 = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_proj = 0, op_n2 = 0, op_gu = 0;
rad_op op_act = 0, op_down = 0;
};
std::vector<Layer> L;
rad_weight w_patch = 0, b_patch = 0, w_post = 0, w_ds = 0, b_ds = 0;
rad_weight w_mproj = 0, w_mln = 0, b_mln = 0, w_mgu = 0, w_mdown = 0;
rad_op op_patch = 0, op_post = 0, op_unfold = 0, op_ds = 0, op_mproj = 0, op_mln = 0;
rad_op op_gelu = 0, op_mgu = 0, op_mact = 0, op_mdown = 0;
rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_gu = 0, b_ff = 0, b_post = 0, b_unf = 0;
rad_buf b_d = 0, b_m = 0, b_mgu = 0, b_mff = 0, b_out = 0;
char sec[48] = {};
/* Whether the container carries GLM-5.3's tower. */
static bool present(const RadModelMeta* m) {
const char* t = rad_meta_gets(m, "vision_config.model_type", "");
return t && !std::strcmp(t, "glm5_next_vision");
}
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 GlmVision::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.depth", 0);
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
heads = rad_meta_geti(m, "vision_config.num_heads", 0);
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
patch = rad_meta_geti(m, "vision_config.patch_size", 0);
temporal = rad_meta_geti(m, "vision_config.temporal_patch_size", 0);
chans = rad_meta_geti(m, "vision_config.in_channels", 3);
merge = rad_meta_geti(m, "vision_config.spatial_merge_size", 0);
n_embd = rad_meta_geti(m, "vision_config.out_hidden_size", 0);
proj_ff = rad_meta_geti(m, "vision_config.projection_intermediate_size", 0);
eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-5);
limit = rad_meta_getf(m, "vision_config.swiglu_limit", 0.0);
/* The checkpoint states no rotary; the reference's default is axial at 10000. */
theta = rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 10000.0);
const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", "axial");
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "");
const bool bias = rad_meta_geti(m, "vision_config.attention_bias", 1) != 0;
if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || temporal <= 0 ||
chans <= 0 || merge <= 0 || n_embd <= 0 || proj_ff <= 0 || width % heads ||
(width / heads) % 4 || !(eps > 0) || !(theta > 0)) {
fprintf(stderr, "radiance: glm5next: the container's vision_config is incomplete or "
"inconsistent (depth %lld, hidden %lld, heads %lld, ff %lld, patch %lld, "
"merge %lld, out %lld, projection %lld)\n", (long long)depth,
(long long)width, (long long)heads, (long long)ff, (long long)patch,
(long long)merge, (long long)n_embd, (long long)proj_ff);
return RAD_E_INVAL;
}
/* The clipped SwiGLU, the axial rotary and the biased linears are what this tower is; a
* checkpoint that turns one of them off is another tower. */
if (std::strcmp(act, "silu") || !(limit > 0) || !std::isfinite(limit) ||
std::strcmp(rt, "axial") || !bias) {
fprintf(stderr, "radiance: glm5next: this vision tower has a '%s' activation, swiglu_limit "
"%g, a '%s' rotary or no attention bias; it serves silu, a positive "
"limit, axial and biased linears\n", act, limit, rt);
return RAD_E_UNSUPPORTED;
}
/* The merger's rows replace token embeddings, so they must be the model's width. */
if (n_embd != model_embd) {
fprintf(stderr, "radiance: glm5next: the vision tower emits %lld-wide rows and the model "
"embeds %lld-wide tokens\n", (long long)n_embd, (long long)model_embd);
return RAD_E_INVAL;
}
head_dim = width / heads;
patch_dim = chans * temporal * patch * patch;
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(head_dim / 4),
(long long)(head_dim / 4));
const int64_t mm = merge * merge;
P = ctx->max_enc_patches;
/* The longest segment attention may see: the real pass size, even in a sizing declare (see
* rad_block_vit.h). */
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);
}
if (P % mm) return RAD_E_SHAPE;
const int64_t R = P / mm;
const int ACC = RAD_ACCESS_PER_REQUEST;
/* ---- weights, replicated: model-level groups for the stem, downsample and merger, one group
* a block from `first_group` on. gate and up are joined into one GEMM, gate first, as
* swiglu_clamped splits its operand. */
auto copy = [&](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);
};
auto join = [&](const char* dn, const char* gate, const char* up,
std::initializer_list<int64_t> shp, RadWeightGroup g) -> rad_weight {
if (map_concat(b, dn, { gate, up }) < 0) return 0;
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g);
};
const char* V = "model.visual";
w_patch = copy(nm.f("v.patch.weight"), nm.ckpt("%s.patch_embed.proj.weight", V),
{ width, patch_dim }, grp_model());
b_patch = copy(nm.f("v.patch.bias"), nm.ckpt("%s.patch_embed.proj.bias", V), { width },
grp_model());
L.assign((size_t)depth, Layer{});
for (int64_t i = 0; i < depth; ++i) {
Layer& l = L[(size_t)i];
const RadWeightGroup g = grp_layer(first_group + (int)i);
const int li = (int)i;
auto src = [&](const char* s) { return nm.ckpt("%s.blocks.%d.%s", V, li, s); };
auto dn = [&](const char* s) { return nm.f("v.blk.%d.%s", li, s); };
l.n1 = copy(dn("norm1.weight"), src("norm1.weight"), { width }, g);
l.qkv_w = copy(dn("qkv.weight"), src("attn.qkv.weight"), { 3 * width, width }, g);
l.qkv_b = copy(dn("qkv.bias"), src("attn.qkv.bias"), { 3 * width }, g);
l.q_norm = copy(dn("q_norm.weight"), src("attn.q_norm.weight"), { head_dim }, g);
l.k_norm = copy(dn("k_norm.weight"), src("attn.k_norm.weight"), { head_dim }, g);
l.out_w = copy(dn("proj.weight"), src("attn.proj.weight"), { width, width }, g);
l.out_b = copy(dn("proj.bias"), src("attn.proj.bias"), { width }, g);
l.n2 = copy(dn("norm2.weight"), src("norm2.weight"), { width }, g);
l.gu_w = join(dn("gate_up.weight"), src("mlp.gate_proj.weight"), src("mlp.up_proj.weight"),
{ 2 * ff, width }, g);
l.gu_b = join(dn("gate_up.bias"), src("mlp.gate_proj.bias"), src("mlp.up_proj.bias"),
{ 2 * ff }, g);
l.down_w = copy(dn("down.weight"), src("mlp.down_proj.weight"), { width, ff }, g);
l.down_b = copy(dn("down.bias"), src("mlp.down_proj.bias"), { width }, g);
if (!l.n1 || !l.qkv_w || !l.qkv_b || !l.q_norm || !l.k_norm || !l.out_w || !l.out_b ||
!l.n2 || !l.gu_w || !l.gu_b || !l.down_w || !l.down_b)
return RAD_E_INVAL;
}
w_post = copy(nm.f("v.post_norm.weight"), nm.ckpt("%s.post_layernorm.weight", V), { width },
grp_model());
/* [out, width, merge, merge] read as [out, width * merge^2]: conv2d_unfold's column order. */
w_ds = copy(nm.f("v.downsample.weight"), nm.ckpt("%s.downsample.weight", V),
{ n_embd, mm * width }, grp_model());
b_ds = copy(nm.f("v.downsample.bias"), nm.ckpt("%s.downsample.bias", V), { n_embd },
grp_model());
w_mproj = copy(nm.f("v.merger.proj.weight"), nm.ckpt("%s.merger.proj.weight", V),
{ n_embd, n_embd }, grp_model());
w_mln = copy(nm.f("v.merger.norm.weight"),
nm.ckpt("%s.merger.post_projection_norm.weight", V), { n_embd }, grp_model());
b_mln = copy(nm.f("v.merger.norm.bias"), nm.ckpt("%s.merger.post_projection_norm.bias", V),
{ n_embd }, grp_model());
w_mgu = join(nm.f("v.merger.gate_up.weight"), nm.ckpt("%s.merger.gate_proj.weight", V),
nm.ckpt("%s.merger.up_proj.weight", V), { 2 * proj_ff, n_embd }, grp_model());
w_mdown = copy(nm.f("v.merger.down.weight"), nm.ckpt("%s.merger.down_proj.weight", V),
{ n_embd, proj_ff }, grp_model());
if (!w_patch || !b_patch || !w_post || !w_ds || !b_ds || !w_mproj || !w_mln || !b_mln ||
!w_mgu || !w_mdown)
return RAD_E_INVAL;
/* ---- activations. `post` is declared at merge x width: the norm writes P rows of `width`
* and conv2d_unfold reads the same bytes as P / merge rows of `merge` columns (dh rows of dw
* columns), the reference's view() with 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_gu = decl_b(b, nm.f("v.gu"), RAD_BF16, { P, 2 * ff });
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff });
b_post = decl_b(b, nm.f("v.post"), RAD_BF16, { P / merge, merge * width });
b_unf = decl_b(b, nm.f("v.unf"), RAD_BF16, { R, mm * width });
b_d = decl_b(b, nm.f("v.d"), RAD_BF16, { R, n_embd });
b_m = decl_b(b, nm.f("v.m"), RAD_BF16, { R, n_embd });
b_mgu = decl_b(b, nm.f("v.mgu"), RAD_BF16, { R, 2 * proj_ff });
b_mff = decl_b(b, nm.f("v.mff"), RAD_BF16, { R, proj_ff });
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
if (!b_x || !b_h || !b_qkv || !b_att || !b_gu || !b_ff || !b_post || !b_unf || !b_d || !b_m ||
!b_mgu || !b_mff || !b_out)
return RAD_E_INVAL;
auto gemm_b = [&](int64_t rows, int64_t N, int64_t K, rad_weight w, rad_weight bw) -> 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", "none")),
RAD_WEIGHTS(w, bw));
};
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 rms = [&](int64_t rows, rad_weight w) -> rad_op {
return RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto swiglu = [&](int64_t rows, int64_t n) -> rad_op {
return RAD_OP(b, "swiglu_clamped",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_F64("limit", limit), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
op_patch = rw(b, gemm_b(P, width, patch_dim, w_patch, b_patch), {}, { b_x });
for (Layer& l : L) {
l.op_n1 = rw(b, rms(P, l.n1), { b_x }, { b_h });
l.op_qkv = rw(b, gemm_b(P, 3 * width, width, l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
l.op_qk = rw(b, RAD_OP(b, "qk_norm_rope",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads),
RAD_F64("theta", theta), RAD_F64("eps", eps),
RAD_STR("mode", "axial"),
RAD_INT("rotary_dim", head_dim),
RAD_STR("sections", sec)),
RAD_WEIGHTS(l.q_norm, l.k_norm)),
{ b_qkv }, { b_qkv });
l.op_attn = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", 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.op_proj = rw(b, gemm_b(P, width, width, l.out_w, l.out_b), { b_att, b_x }, { b_x });
l.op_n2 = rw(b, rms(P, l.n2), { b_x }, { b_h });
l.op_gu = rw(b, gemm_b(P, 2 * ff, width, l.gu_w, l.gu_b), { b_h }, { b_gu });
l.op_act = rw(b, swiglu(P, ff), { b_gu }, { b_ff });
l.op_down = rw(b, gemm_b(P, width, ff, l.down_w, l.down_b), { b_ff, b_x }, { b_x });
}
op_post = rw(b, rms(P, w_post), { b_x }, { b_post });
/* Input rows are P / merge (one kernel row of merge patches each) and a segment's rows are its
* patches over merge, so a picture of whole merged blocks starts on an even row. */
op_unfold = rw(b, RAD_OP(b, "conv2d_unfold",
RAD_PARAMS(RAD_RANGE("M", 1, P / merge), RAD_INT("width", merge),
RAD_INT("cin", width), RAD_INT("kh", merge),
RAD_INT("kw", merge), RAD_INT("stride", merge),
RAD_INT("pad", 0), RAD_INT("cu_div", merge),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_post }, { b_unf });
op_ds = rw(b, gemm_b(R, n_embd, mm * width, w_ds, b_ds), { b_unf }, { b_d });
op_mproj = rw(b, gemm(R, n_embd, n_embd, w_mproj), { b_d }, { b_m });
/* torch.nn.LayerNorm's default eps: the merger states none. */
op_mln = rw(b, RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", n_embd),
RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_mln, b_mln)),
{ b_m }, { b_d });
op_gelu = rw(b, RAD_OP(b, "gelu",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", n_embd),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_d }, { b_m });
op_mgu = rw(b, gemm(R, 2 * proj_ff, n_embd, w_mgu), { b_m }, { b_mgu });
op_mact = rw(b, swiglu(R, proj_ff), { b_mgu }, { b_mff });
op_mdown = rw(b, gemm(R, n_embd, proj_ff, w_mdown), { b_mff }, { b_out });
if (!ctx->shape_probe) {
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE;
e.patch_dim = patch_dim;
e.merge = mm;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "vision tower: %lld blocks of %lld (%lld heads x %lld), ff %lld clipped at %g, "
"patch %lld x %lld x %lld, %lld x %lld downsample, merger %lld; %lld patches a "
"pass -> %lld rows of %lld", (long long)depth, (long long)width,
(long long)heads, (long long)head_dim, (long long)ff, limit, (long long)temporal,
(long long)patch, (long long)patch, (long long)merge, (long long)merge,
(long long)proj_ff, (long long)P, (long long)R, (long long)n_embd);
}
on = true;
return RAD_OK;
}
inline void GlmVision::step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
const int64_t mm = merge * merge, Rn = Pn / mm;
if (!on || Pn <= 0 || Pn > P || Pn % mm || S <= 0) {
rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, or "
"more patches than it was declared for, or not whole merged rows");
return;
}
/* Patches, coordinates (planes 0-1 a dense [2, P] of (row, column)) and segment boundaries,
* staged by the core. */
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
const RadOperand rc = praw2(batch->enc_coord, RAD_I32, 2, Pn);
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), RAD_W(b_patch), RAD_NONE, brows(b_x, Pn));
for (const Layer& l : L) {
RAD_ISSUE_N(c, l.op_n1, Pn, brows(b_x, Pn), RAD_W(l.n1), brows(b_h, Pn));
RAD_ISSUE_N(c, l.op_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.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm));
RAD_ISSUE_N(c, l.op_attn, Pn, bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
RAD_ISSUE_N(c, l.op_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.op_n2, Pn, brows(b_x, Pn), RAD_W(l.n2), brows(b_h, Pn));
RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gu_w), RAD_W(l.gu_b), RAD_NONE,
brows(b_gu, Pn));
RAD_ISSUE_N(c, l.op_act, Pn, brows(b_gu, Pn), brows(b_ff, Pn));
RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
brows(b_x, Pn), brows(b_x, Pn));
}
/* The norm writes Pn rows of `width`; the unfold reads them as Pn / merge rows. */
RAD_ISSUE_N(c, op_post, Pn, brows(b_x, Pn), RAD_W(w_post), brows(b_post, Pn / merge));
RAD_ISSUE_N(c, op_unfold, Pn / merge, brows(b_post, Pn / merge), cu, RAD_NONE,
brows(b_unf, Rn));
RAD_ISSUE_N(c, op_ds, Rn, brows(b_unf, Rn), RAD_W(w_ds), RAD_W(b_ds), RAD_NONE,
brows(b_d, Rn));
RAD_ISSUE_N(c, op_mproj, Rn, brows(b_d, Rn), RAD_W(w_mproj), brows(b_m, Rn));
RAD_ISSUE_N(c, op_mln, Rn, brows(b_m, Rn), RAD_W(w_mln), RAD_W(b_mln), brows(b_d, Rn));
RAD_ISSUE_N(c, op_gelu, Rn, brows(b_d, Rn), brows(b_m, Rn));
RAD_ISSUE_N(c, op_mgu, Rn, brows(b_m, Rn), RAD_W(w_mgu), brows(b_mgu, Rn));
RAD_ISSUE_N(c, op_mact, Rn, brows(b_mgu, Rn), brows(b_mff, Rn));
RAD_ISSUE_N(c, op_mdown, Rn, brows(b_mff, Rn), RAD_W(w_mdown), brows(b_out, Rn));
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_GLM_VISION_H */
+98
View File
@@ -368,6 +368,104 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
/* The block's output `y` is read from `w.x.x`, the buffer the read wrote the block's input to:
* every block leaves its delta in the activation its norm produced, and the input is dead by
* then. */
/* ================================================================== the control-vector projection
*
* A control vector is one unit direction per layer (a `controlvector` GGUF, core/cvec.h). Turned on
* for a request, a steered layer's wide stream is projected off that layer's direction right after
* the feed-forward's write:
*
* h[s] -= scale * (h[s] . v) * v for each of the hc streams s
*
* which is llama.cpp's `--cvec-mode project` and the operation the Qwen3.8-Flash-Next package
* documents. The dot is per stream, not on the stream mean: the patch applies it to the
* [n_embd, hc, tokens] view where `mul_mat(v, cur)` reduces over dim 0 alone.
*
* Two properties the architecture plugin does not have to think about, both here:
*
* - **the switch is per request.** `on` is a derived buffer of one int32 per token row
* (core/sched/derive.cpp's `projection_on_rows`), so a step that mixes a projected
* conversation with a stock one projects exactly the rows that asked for it. All zeros is the
* stock model: the kernel skips a zero row without reading or writing it, so an unprojected
* request's stream is the one the stock model computes. (The *deployment* is not bit-identical
* to one with no vector: the direction table's VRAM can move an expert or a KV block, which is
* the tie-level variance radiance documents elsewhere. Measured, docs/GUIDE.md 4.10.)
* - **the parameters travel with the file.** `scale` is the norm the file stored for that layer
* (times the package's own `scale`, read from its JSON), and the direction row is sliced from
* the table at issue, so nothing is configured per deployment or scanned per layer.
*
* One instance per layer: `declare` emits an op only when the vector steers that layer, so a
* deployment without a vector declares no op, no buffer and no branch in the step. */
struct HcProject {
rad_op op = 0; /* 0: this layer is not steered (or there is no vector) */
const float* dir = nullptr; /* this layer's row of the device direction table */
rad_buf on = 0; /* [rows] int32: 1 = project this row */
rad_buf h = 0; /* the model's wide stream */
int64_t n = 0, hc = 0;
bool steered() const { return op != 0; }
/* The per-token switch, declared once per model as a derived buffer. 0 when the deployment has
* no vector (or one of another width), which leaves every layer unsteered. */
static rad_buf declare_mask(RadBuilder* b, const char* name, const Geom& g,
const RadControlVector* cv) {
if (!b || g.n_embd <= 0 || g.max_tok <= 0) return 0;
if (!cv || !cv->dir || cv->n_layers <= 0) return 0;
if (cv->n_embd != g.n_embd) {
fprintf(stderr, "radiance: %s: the control vector is %lld wide and this model's "
"residual streams are %lld; not steering it\n",
name, (long long) cv->n_embd, (long long) g.n_embd);
return 0;
}
RadBufDecl d{};
d.dtype = RAD_I32;
d.rank = 1;
d.shape[0] = g.max_tok;
d.kind = RAD_BUF_DERIVED;
d.domain = RAD_DOMAIN_DEVICE;
d.derive = "projection_on_rows";
return rad_decl_buffer(b, name, &d);
}
/* `layer`'s projection, when the vector steers it. Called for every layer; the unsteered ones
* (outside the file, outside the range, or no vector at all) declare nothing. */
int declare(RadBuilder* b, const char* name, const Geom& g, int64_t layer,
const RadControlVector* cv, rad_buf mask, rad_buf stream, int64_t hc_streams) {
if (!b || !mask || !stream || !cv || !cv->dir || hc_streams <= 1) return RAD_OK;
if (layer <= 0 || layer >= cv->n_layers || layer >= g.n_layer) return RAD_OK;
const float scale = cv->scales ? cv->scales[(size_t) layer] : 0.0f;
if (scale == 0.0f) return RAD_OK;
n = g.n_embd;
hc = hc_streams;
on = mask;
h = stream;
dir = cv->dir + (size_t) layer * (size_t) n;
op = rw(b, RAD_OP(b, "hc_project",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), RAD_INT("hc", hc),
RAD_F64("scale", (double) scale), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{h, mask}, {h});
if (!op) {
fprintf(stderr, "radiance: %s: hc_project resolves to no kernel at n %lld, hc %lld -- "
"this rank cannot serve the control vector\n",
name, (long long) n, (long long) hc);
return RAD_E_INVAL;
}
return RAD_OK;
}
/* Rows [r0, r0 + rows) of the stream. The whole step is r0 = 0; the pipelined step issues one
* call per piece, in the same place in the graph. */
void step(RadCtx* c_, int64_t r0, int64_t rows) const {
if (!op) return;
RAD_ISSUE_N(c_, op, rows,
brow_slice(h, r0, rows, hc * n),
praw(dir, RAD_F32, n),
praw((const int32_t*) rad_buf_ptr(c_, on) + r0, RAD_I32, rows));
}
};
inline void HyperConn::write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const {
if (!op_write) return;
if (takes_gather(T)) {
+17 -7
View File
@@ -60,13 +60,16 @@ struct MlpFP8 {
/* The next block absorbs this block's closing all-reduce, so this one must not issue it.
* Counterpart of `ar_in`; both sides ask ar_fused_ok(g, T), so they agree. */
bool ar_out = false;
/* Set before declare: a clamped product (`swiglu_limit`) and its quantiser as one launch
* (GateQuantFP8::fuse_clamped). */
bool swiglu_quant = false;
/* `fold`: a predecessor's delta is still in `w.h.x` and this norm does its residual add
* (false for the first block of a chain). `add_out`: issue the trailing add here. See
* rad_fp8.h. */
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const Src& src, bool fold = false, bool add_out = true,
int ar_in = kArNone, bool ar_out_ = false);
int ar_in = kArNone, bool ar_out_ = false, double swiglu_limit = 0);
void step(RadCtx* c, const RadBatch* batch) const;
/* The block over the first `T` rows of its buffers (see MoeFP8::step_rows). */
void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); }
@@ -76,7 +79,7 @@ struct MlpFP8 {
inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const Src& src, bool fold, bool add_out,
int ar_in, bool ar_out_) {
int ar_in, bool ar_out_, double swiglu_limit) {
g = geom; w = wire; layer = l;
ar_out = ar_out_;
@@ -93,14 +96,21 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
{ src.gate, src.up }, w.h, w.gate_up, 0, { g.n_ff, g.n_ff }));
/* The bf16 silu product is written only if the down projection reads the bf16 plane
* (LinearFP8::reads_x); a block-fp8 down_proj reads only codes and scales. */
* (LinearFP8::reads_x); a block-fp8 down_proj reads only codes and scales, and so does an
* int8 one fed its codes (ActFP8::q8_fed). */
const char* down_base = nm.f("blk.%d.ffn_down", l);
RAD_ARCH_TRY(down.probe(b, nm, g, down_base, { src.down }));
RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0, down.reads_x));
gq_ffn.fuse_clamped = swiglu_quant;
RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0,
down.reads_x && !(w.ffn.q8_fed && down.probed_i8), false, false,
swiglu_limit));
/* The fold (decl_gated_fold), an fp8a8 tile, so bf16, MXFP4, rotated 5-bit and 4-bit gate_up
* weights take the pair. */
if (!gate_up.bf16 && !gate_up.mx && !gate_up.paro5 && !gate_up.w4)
/* The fold (decl_gated_fold), an fp8a8 tile, so bf16, f32-scaled, MXFP4, rotated 5-bit, 4-bit
* and int8 gate_up weights take the pair, and so does a clamped (swiglu_limit) product.
* Declared over int8 codes, only a host kernel would take it, and that would pin the layer's
* weights to the host. */
if (swiglu_limit <= 0 && !gate_up.bf16 && !gate_up.f32_scale && !gate_up.mx &&
!gate_up.paro5 && !gate_up.w4 && !gate_up.i8)
op_gated = decl_gated_fold(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
{ w.h.q, w.h.s },
gq_ffn.want_x
+205 -47
View File
@@ -48,6 +48,7 @@
#define RAD_BLOCK_MOE_FP8_H
#include "rad_fp8.h"
#include "rad_block_glm_router.h"
#include "rad_device.h"
#include <cstdio>
@@ -72,8 +73,10 @@ static const int64_t kMoeRouterFusedRows = 64;
*
* The core's histogram (core/runtime/ctx.cpp) shows which experts were chosen and dbg_resid shows
* each arm's magnitude; neither shows the weights, so a top-k that sums to 0.4 instead of 1 would
* go unnoticed. Synchronises the stream. Off unless set: a layer number, or negative for all. */
inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids, rad_buf ew) {
* go unnoticed. Synchronises the stream. Off unless set: a layer number, or negative for all.
* `f32`: the weights are f32 rather than bf16 (the sigmoid router). */
inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids, rad_buf ew,
bool f32 = false) {
static const char* dbg = std::getenv("RADIANCE_DEBUG_ROUTING");
if (!dbg || !ids || !ew) return;
static const int want = (int)std::strtol(dbg, nullptr, 10);
@@ -85,8 +88,9 @@ inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids,
RadStream s = rad_stream(c_);
std::vector<int32_t> vi((size_t)top_k);
std::vector<uint16_t> vw((size_t)top_k);
std::vector<float> vf((size_t)top_k);
rad_memcpy_async(vi.data(), pi, top_k * 4, s);
rad_memcpy_async(vw.data(), pw, top_k * 2, s);
rad_memcpy_async(f32?(void*)vf.data():(void*)vw.data(), pw, top_k * (f32?4:2), s);
rad_stream_sync(s);
std::string line;
@@ -95,6 +99,7 @@ inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids,
const uint32_t u = (uint32_t)vw[(size_t)r] << 16;
float f;
std::memcpy(&f, &u, 4);
if (f32) f = vf[(size_t)r];
sum += f;
char b[48];
std::snprintf(b, sizeof b, "%s%d:%.4f", r ? " " : "", vi[(size_t)r], f);
@@ -167,6 +172,23 @@ struct MoeFP8 {
* units a routed GEMM's tail leaves idle. */
int64_t shared_lo = 0, shared_hi = 0;
int norm_topk = 1; /* renormalise the kept routing weights to sum to one */
/* GLM routing (GlmRouter): sigmoid scores with a correction bias, top-k, `route_scale` on
* the kept weights, which are then f32 in `ew`. */
int sigmoid_router = 0;
/* With `sigmoid_router`: the selection, the scatter and an ungated shared arm's gate fill in
* one launch (`router_sigmoid_topk_scatter`) wherever the pass fits the sort's one
* workgroup; the separate ops otherwise. Byte-identical either way. */
int router_fuse = 0;
/* Block-fp8 experts whose scale plane is f32 (format 9, dtype fp8a8f32). */
int expert_f32_scale = 0;
double route_scale = 1.0;
/* Clamp of the SwiGLU product (swiglu_clamped); 0 is none. */
double swiglu_limit = 0.0;
/* With `swiglu_limit`: the clamped product and its quantiser as one launch
* (GateQuantFP8::fuse_clamped), for the routed and the shared arm. */
int swiglu_quant = 0;
/* A shared arm without its sigmoid gate: the gate plane is filled with 1. */
int shared_ungated = 0;
/* 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`
* registry row). It is the stored encoding: probe() reads it from the first expert's
@@ -176,6 +198,8 @@ struct MoeFP8 {
* A packed 4-bit row is K/2 bytes, so a width shard must fall on a scale group; declare()
* checks this per rank. */
int expert_w4 = 0;
/* OCP E2M1 codes with E8M0 scales per 32 of K; kept canonical for host-tier reads. */
int expert_mx = 0;
/* Rotated: a 128-wide Walsh-Hadamard along K baked into the stored expert weight and the
* activation meeting it (the encoding's `fwht128` transform, dtype `w4a8h`; only with
* `expert_w4`).
@@ -242,11 +266,14 @@ struct MoeFP8 {
/* the routing, one row per token */
rad_buf logits = 0; /* [max_tok, n_expert_all] bf16, the model's expert count */
rad_buf ids = 0; /* [max_tok, top_k] i32 */
rad_buf ew = 0; /* [max_tok, top_k] bf16 */
rad_buf ew = 0; /* [max_tok, top_k] F32 for sigmoid_router, BF16 otherwise */
rad_buf eoff = 0; /* [n_expert + 1] i32 */
rad_buf ecnt = 0; /* [n_expert] i32 */
/* the expert planes, one row per (token, slot), a pass tall */
rad_buf sorted = 0; /* [rows * top_k] i32, pass-relative slot indices */
/* Each slot's row in `sorted`, -1 when dropped; with it the sort writes the gather's slot
* table (moe_scatter_inv, moe_gather_inv). Optional. */
rad_buf inv = 0; /* [rows * top_k] i32 */
rad_buf egu = 0; /* [rows * top_k, 2 * n_ff_exp] bf16 */
ActFP8 eff{}; /* [rows * top_k, n_ff_exp] */
rad_buf edn = 0; /* [rows * top_k, n_embd] bf16, in sorted order */
@@ -268,6 +295,7 @@ struct MoeFP8 {
Config cfg{};
const char* norm = nullptr;
const char* router = nullptr; /* mlp.gate.weight, [n_expert, n_embd] bf16 */
const char* router_bias = nullptr; /* GLM noaux_tc correction bias */
const char* experts = nullptr; /* prefix; ".<e>.{gate,up,down}_proj.weight" */
const char* shared = nullptr; /* prefix; ".{gate,up,down}_proj.weight" */
/* Stacked checkpoints (recent releases) store all experts in two tensors:
@@ -287,6 +315,7 @@ struct MoeFP8 {
int layer = 0;
rad_weight w_norm = 0, w_router = 0, w_sgate = 0;
GlmRouter glm_router{};
/* The input was normed and quantised by the caller; this block declares no norm. */
bool ext_in = false;
/* The weight runs. Only the first handle and the count reach an issue (RAD_WTAB); the rest are
@@ -297,6 +326,9 @@ struct MoeFP8 {
GateQuantFP8 gq_exp{}, gq_sh{};
LinearFP8 sh_gate_up{}, sh_down{};
rad_op op_router = 0, op_topk = 0, op_scatter = 0;
/* `op_scatter` is moe_scatter_inv and `op_gather` moe_gather_inv: the sort writes `w.inv` and
* the gather reads it (Wire::inv). */
bool scatter_inv = false, gather_inv = false;
/* `router_topk_scatter`, if it resolves: topk and scatter in one launch. The pair is declared
* either way, since the fused form is bounded by the sort's single workgroup and a prefill
* chunk exceeds it. */
@@ -308,6 +340,11 @@ struct MoeFP8 {
rad_op op_router_fused = 0;
int64_t router_fused_rows = 0;
bool router_fused_gate = false;
/* `router_sigmoid_topk_scatter` (Config::router_fuse), up to `sigmoid_scatter_rows` tokens,
* writing the shared gate's fill too when `sigmoid_scatter_gate`. */
rad_op op_sigmoid_scatter = 0;
int64_t sigmoid_scatter_rows = 0;
bool sigmoid_scatter_gate = false;
/* The rotated re-quantisation of the block input, declared only when `expert_rot` is set and
* the caller does not already write `w.hr`. */
rad_op op_hq = 0;
@@ -390,11 +427,11 @@ struct MoeFP8 {
static int probe(RadBuilder* b, Names& nm, int l, const Src& src, Config* cfg);
/* The format `e` names: 0 block fp8, 1 four-bit, 2 four-bit rotated, 3 plain bf16, 4 the
* rotated w4nl codebook, 5 and 6 that codebook at E4M3 scales per 64 and 32 of K, 7 its
* five-bit form per 64; RAD_E_DTYPE otherwise. */
* five-bit form per 64, 8 OCP MXFP4, 9 block fp8 at f32 scales; RAD_E_DTYPE otherwise. */
static int format_of(const RadEncoding& e);
/* format_of's numbers as the grouped GEMMs' dtype strings. */
static constexpr const char* kServed[8] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h" };
static constexpr const char* kServed[10] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h", "mxfp4a8", "fp8a8f32" };
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const Wire& wire, const Src& src, bool fold = false, bool add_out = true,
@@ -424,6 +461,7 @@ struct MoeFP8 {
};
inline int MoeFP8::format_of(const RadEncoding& e) {
if (linear_is_mxfp4(e)) return 8;
if (rad_enc_is(&e, "plain") && e.n_planes == 1 && e.plane[0].dtype == RAD_BF16) return 3;
if (!rad_enc_is(&e, "affine")) return RAD_E_DTYPE;
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
@@ -443,7 +481,11 @@ inline int MoeFP8::format_of(const RadEncoding& e) {
return 7;
return RAD_E_DTYPE;
}
if (!sc || sc->dtype != RAD_BF16) return RAD_E_DTYPE;
if (!sc) return RAD_E_DTYPE;
if (e.n_planes == 2 && e.plane[0].dtype == RAD_F8E4M3 && sc->dtype == RAD_F32 &&
!e.transform[0] && sc->block[0] == 128 && sc->block[1] == 128)
return 9;
if (sc->dtype != RAD_BF16) return RAD_E_DTYPE;
if (e.n_planes == 3) {
const RadEncPlane* t = rad_enc_plane(&e, "table");
if (t && t->kind == RAD_PLANE_TABLE && t->dtype == RAD_F32 && t->extent[0] == 1 &&
@@ -530,7 +572,8 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
"(fp8_e4m3*bf16[128x128]), four-bit (i4*bf16[1x128], optionally "
"/fwht128; or u4 codes into a 16-entry f32 table, /fwht128) or plain "
"bf16; or the codebook at E4M3 scales a 64 or 32 of K under a fixed "
"f32, or its 32-entry five-bit form at a 64. "
"f32, or its 32-entry five-bit form at a 64, or OCP MXFP4 "
"(fp4_e2m1*e8m0[1x32]). "
"Convert it with a recipe that makes one of them.\n", guw, en);
return RAD_E_DTYPE;
}
@@ -542,6 +585,8 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
cfg->expert_g64 = (f == 5 || f == 7) ? 2 : f == 6 ? 4 : 0;
cfg->expert_w5 = f == 7 ? 1 : 0;
cfg->expert_bf16 = f == 3 ? 1 : 0;
cfg->expert_mx = f == 8 ? 1 : 0;
cfg->expert_f32_scale = f == 9 ? 1 : 0;
return RAD_OK;
}
@@ -560,6 +605,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* A rank whose slice of the shared arm is empty (see Config) declares no arm, and the
* all-reduce carries the others' share. */
const bool shared = c.n_ff_shared > 0 && src.shared;
if (shared && c.shared_ungated && src.shared_gate) return RAD_E_INVAL;
/* Whether `w.sgate` is excluded from buffer sharing; set with the shared arm and required by
* the fused router's gate write (see there). */
bool sgate_concurrent = false;
@@ -592,7 +638,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
}
prot.clear();
{
const int want = c.expert_bf16 ? 3 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6
const int want = c.expert_f32_scale ? 9 : c.expert_mx ? 8 : c.expert_bf16 ? 3 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6
: c.expert_g64 ? 5 : c.expert_nl ? 4
: c.expert_w4 ? (c.expert_rot ? 2 : 1) : 0;
auto fmt_of = [&](int64_t e, RadEncoding (&enc)[2], int (&fe)[2], const char* (&nmv)[2]) {
@@ -665,16 +711,33 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* The router is replicated (see Config::n_expert_all): every rank computes the same routing
* from the full residual stream, so `sorted_tok` and `expert_offset` agree across ranks
* without a collective. */
* without a collective. The sigmoid router (GlmRouter) declares its own projection. */
if (!c.sigmoid_router) {
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_gate_inp.weight", l), src.router));
w_router = decl_w(b, nm.f("blk.%d.ffn_gate_inp.weight", l), RAD_BF16,
{c.n_expert_all, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
}
if (!ext_in)
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
fold ? w.x : 0, 0, ar_in));
if (c.sigmoid_router) {
if (!src.router_bias) return RAD_E_INVAL;
GlmRouter::Config rc;
rc.experts = c.n_expert_all;
rc.top_k = c.top_k;
rc.rows = c.rows;
rc.norm = c.norm_topk;
rc.route_scale = c.route_scale;
const GlmRouter::Wire wire{ w.h.x, w.logits, w.ids, w.ew };
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));
w_router = glm_router.projection;
op_router = glm_router.op_project;
op_topk = glm_router.op_select;
} else {
op_router = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", c.n_expert_all),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
@@ -686,6 +749,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.logits}, {w.ids, w.ew});
}
/* Protected experts are sorted last (`protect`); layers without them declare no protect
* list, so it is the last parameter and cut off. */
const int n_prot = prot_list ? 1 : 0;
@@ -693,8 +757,15 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const RadParam ps[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.n_expert),
RAD_INT("top_k", c.top_k), RAD_INT("expert_base", c.expert_base),
RAD_STR("protect", prot_list) };
op_scatter = rw(b, rad_decl_op(b, "moe_scatter", ps, 4 + n_prot, RAD_NOWEIGHTS),
{w.ids}, {w.sorted, w.eoff, w.ecnt});
/* With `w.inv` the sort also writes the gather's slot table. It writes everything
* moe_scatter does, so a moe_gather_inv that does not resolve leaves moe_gather to serve. */
if (w.inv && rad_op_declared(b, "moe_scatter_inv") && rad_op_declared(b, "moe_gather_inv"))
op_scatter = rw(b, rad_decl_op(b, "moe_scatter_inv", ps, 4 + n_prot, RAD_NOWEIGHTS),
{w.ids}, {w.sorted, w.eoff, w.ecnt, w.inv});
scatter_inv = op_scatter != 0;
if (!op_scatter)
op_scatter = rw(b, rad_decl_op(b, "moe_scatter", ps, 4 + n_prot, RAD_NOWEIGHTS),
{w.ids}, {w.sorted, w.eoff, w.ecnt});
}
/* topk and scatter in one launch. At decode each is a single 256-thread workgroup ranking
@@ -705,9 +776,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* M*top_k <= 1024 and three above (for a stable sort without atomics), and only the first is
* fusible. That covers decode (eight sequences at depth 3 and top_k 10 is 320); prefill
* chunks exceed it. The pair is declared either way, so the graph and buffer plan do not
* depend on it. */
* depend on it. The sigmoid router selects in its own op and takes no fused pair. */
topk_scatter_rows = (int64_t)c.rows * c.top_k <= kMoeSortRows ? c.rows
: kMoeSortRows / c.top_k;
if (c.sigmoid_router || scatter_inv) topk_scatter_rows = 0;
/* Asked for only where a loaded library declares it: a CPU-only engine would refuse the
* declare, and the two separate ops serve without it. */
if (topk_scatter_rows > 0 && rad_op_declared(b, "router_topk_scatter")) {
@@ -752,6 +824,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* the parity classes. */
const bool split = c.ff_hi[0] > 0 || c.ff_hi4[0] > 0;
ncls = c.ff_hi4[0] > 0 ? 4 : 2;
if (c.expert_mx && ncls == 4) {
fprintf(stderr, "radiance: MXFP4 experts use two parity tables; use equal TP width slices\n");
return RAD_E_UNSUPPORTED;
}
if (ncls == 4 && n_reg < 4) {
fprintf(stderr, "radiance: layer %d serves %lld quantised experts on this rank; four "
"classes need at least one each\n", l, (long long)n_reg);
@@ -791,7 +867,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* The codes view's dtype and planes; a codebook's table is selected with its codes so the
* relayout sees it. */
auto edt_of = [&](int f) {
return f == 7 ? (uint32_t)RAD_U5 : c.expert_nl ? (uint32_t)RAD_U4
return f == 8 ? (uint32_t)RAD_FP4E2M1 : f == 7 ? (uint32_t)RAD_U5 : c.expert_nl ? (uint32_t)RAD_U4
: c.expert_w4 ? (uint32_t)RAD_I4 : (uint32_t)RAD_F8E4M3;
};
const uint32_t edt[2] = { edt_of(fmt[0]), edt_of(fmt[1]) };
@@ -819,19 +895,23 @@ 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_col = ep ? RAD_SHARD_NONE : RAD_SHARD_COL;
const int n_parts = ep ? 0 : 2;
/* The scale grid: one per 128x128 tile for E4M3, one per row per 128 of K for 4-bit. `sdiv` is
* how many weight rows or columns one scale covers along the split dimension. */
const int64_t sdiv = c.expert_w4 ? 1 : RAD_FP8_BLOCK;
/* 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
* dimension. */
const int64_t sdiv = (c.expert_w4 || c.expert_mx) ? 1 : RAD_FP8_BLOCK;
/* The dtype string per projection selects the grouped GEMM; its layout hook then accepts the
* experts' encoding or the kernel is not a candidate. */
const char* const edtype[2] = { kServed[fmt[0]], kServed[fmt[1]] };
/* The scale views: bf16 per (row, 128 of K) or per 128x128 tile for E4M3, or for the 64-group
* forms E4M3 per (row, 64 of K) selected with the fixed second level. With two planes it is a
* forms E4M3 per (row, 64 of K) selected with the fixed second level; f32 per 128x128 tile
* (expert_f32_scale) or E8M0 per (row, 32 of K) for MXFP4. With two planes it is a
* view of the logical weight, like the codes view (rad_builder.cpp): declared at the weight's
* extents and sliced in its columns, with the stored [rows, K/64] plane left to the layout
* hook. `sgk` is the K one declared scale column covers. */
const uint32_t sdt = c.expert_g64 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16;
const int64_t sgk = c.expert_g64 ? 1 : RAD_FP8_BLOCK;
const uint32_t sdt = c.expert_f32_scale ? (uint32_t)RAD_F32
: c.expert_mx ? (uint32_t)RAD_E8M0
: c.expert_g64 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16;
const int64_t sgk = c.expert_mx ? RAD_MX_GROUP : c.expert_g64 ? 1 : RAD_FP8_BLOCK;
const char* escale = c.expert_g64 ? "scale,scale.1" : "scale";
/* This class's slice of each expert: gate and up rows [lo, hi), down columns [lo, hi), scale
* planes the same in their own units. */
@@ -880,7 +960,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
Geom gx = g;
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,
true, false));
true, false, false, c.swiglu_limit));
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_INT("K", c.n_ff_exp), RAD_INT("n_expert", ne),
@@ -914,8 +994,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
(long long)(c.expert_base + e)),
escale, sdt,
{c.expert_w4 ? 2 * wq[q] : fp8_blocks(2 * wq[q]),
c.expert_w4 ? g.n_embd / sgk : fp8_blocks(g.n_embd)},
{(c.expert_w4 || c.expert_mx) ? 2 * wq[q] : fp8_blocks(2 * wq[q]),
(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),
parts, n_parts);
if (!h) return RAD_E_INVAL;
@@ -941,7 +1021,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
(long long)(c.expert_base + e)),
escale, sdt,
{c.expert_w4 ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / sgk},
{(c.expert_w4 || c.expert_mx) ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / sgk},
RAD_ACCESS_CONDITIONAL, sh_col, grp_expert_slot(l, (int)s, 1));
if (!h) return RAD_E_INVAL;
RAD_ARCH_TRY(span(h, q, sgk));
@@ -1012,8 +1092,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* The down projection's input can be rotated in place: `w.eff` is read only by the down GEMM,
* which takes the codes alone (no bf16 product is written), so the gated quantiser resolves to
* the rotated op at no extra launch. */
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,
false, rot));
false, rot, false, c.swiglu_limit));
{
const std::vector<rad_weight> tab = tables(w_dn, w_dns);
rad_op h = ncls == 4
@@ -1116,7 +1197,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
Geom gx = g;
gx.w_bf16 = true;
RAD_ARCH_TRY(gq_prot.declare(b, gx, b_pgu, pff, wp, "silu", c.rows * c.top_k, true,
false));
false, false, c.swiglu_limit));
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_INT("K", wp), RAD_INT("n_expert", np),
@@ -1209,18 +1290,20 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* The gather folds the shared arm in, so `w.moe` is never written; `scale_rows` plus a
* separate gather would be two dispatches per layer and a 160 KiB round trip. */
gfold = shared;
{
rad_buf grd[5] = { w.edn, w.ew, w.sorted, w.sout, w.sgate };
for (int form = scatter_inv ? 0 : 1; form < 2 && !op_gather; ++form) {
rad_buf grd[5] = { w.edn, w.ew, form ? w.sorted : w.inv, w.sout, w.sgate };
rad_buf gwr[1] = { w.h.x };
op_gather = RAD_OP(b, "moe_gather",
op_gather = RAD_OP(b, form ? "moe_gather" : "moe_gather_inv",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd),
RAD_INT("top_k", c.top_k), RAD_STR("dtype", g.dtype),
RAD_STR("act", gfold ? "sigmoid" : "none")),
RAD_STR("act", gfold && !c.shared_ungated ? "sigmoid" : "none")),
RAD_NOWEIGHTS);
if (!op_gather) return RAD_E_INVAL;
if (!op_gather) continue;
gather_inv = !form;
rad_op_reads (b, op_gather, grd, gfold ? 5 : 3);
rad_op_writes(b, op_gather, gwr, 1);
}
if (!op_gather) return RAD_E_INVAL;
/* ---- the shared expert. Ordinary dense linears over the same normed input. */
if (shared) {
@@ -1243,7 +1326,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.s8));
}
if (!w.sff.q || (sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8)))
if (!w.sff.q || c.swiglu_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.sout));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sgate));
@@ -1258,8 +1341,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
{ c.n_ff_shared, c.n_ff_shared },
c.shared_lo, c.shared_hi));
/* An int8 down projection fed the int8 pair reads no bf16 plane, so none is written. */
gq_sh.fuse_clamped = c.swiglu_quant != 0;
RAD_ARCH_TRY(gq_sh.declare(b, g, w.sgu, w.sff, c.n_ff_shared, "silu", c.rows,
sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8)));
sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8), false,
false, c.swiglu_limit));
RAD_ARCH_TRY(sh_down.declare(b, nm, g, down_base,
g.n_embd, c.n_ff_shared, RAD_SHARD_COL, grp_layer(l),
{ nm.ckpt("%s.down_proj.weight", src.shared) },
@@ -1267,7 +1352,14 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
c.shared_lo, c.shared_hi));
/* The shared gate, replicated like the router so every rank computes the same gate. One
* output column: the skinny GEMM kernel clamps its N tile rather than masking, so N = 1 is
* legal. */
* legal. An ungated arm (shared_ungated) fills the gate with 1 instead. */
if (c.shared_ungated) {
op_sgate = rw(b, RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", 1),
RAD_STR("dtype", g.dtype), RAD_F64("value", 1.0)),
RAD_NOWEIGHTS),
{}, {w.sgate});
} else {
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_gate_shexp.weight", l), src.shared_gate));
w_sgate = decl_w(b, nm.f("blk.%d.ffn_gate_shexp.weight", l), RAD_BF16, {1, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
@@ -1276,6 +1368,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_sgate)),
{w.h.x}, {w.sgate});
}
}
/* ---- The router GEMM and `router_topk_scatter` as one op, plus the shared gate when the
@@ -1290,7 +1383,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
*
* The parameter list, weights and write set are conditional, so each is an array cut to
* length. */
if (op_topk_scatter && rad_op_declared(b, "router_gemm_topk_scatter")) {
if (op_topk_scatter && !c.shared_ungated && rad_op_declared(b, "router_gemm_topk_scatter")) {
router_fused_rows = topk_scatter_rows < kMoeRouterFusedRows ? topk_scatter_rows
: kMoeRouterFusedRows;
const bool gate = op_sgate != 0;
@@ -1319,6 +1412,50 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
router_fused_gate = op_router_fused && gate;
}
/* GLM's selection and the sort as one op, plus the ungated shared arm's gate fill. Declared
* here for the reason the fused router above is: it writes `w.sgate` ahead of `op_sgate`'s
* declared index, which is safe only with `sgate` out of the sharing pool. Its other outputs
* and its input are also declared by the ops it replaces, so their planned lifetimes cover it.
* Undeclared or unresolved, the separate ops serve. */
if (c.sigmoid_router && c.router_fuse) {
if (!rad_op_declared(b, "router_sigmoid_topk_scatter")) {
static bool told = false;
if (!told) rad_note(b, "no loaded library declares router_sigmoid_topk_scatter; the "
"selection and the sort stay separate launches");
told = true;
} else {
sigmoid_scatter_rows = (int64_t)c.rows * c.top_k <= kMoeSortRows
? c.rows : kMoeSortRows / c.top_k;
const bool gate = op_sgate != 0 && c.shared_ungated;
if (gate && !sgate_concurrent) {
fprintf(stderr, "radiance: layer %d: the fused selection writes the shared gate "
"ahead of its declared writer, which needs `sgate` out of the "
"sharing pool, and it is not\n", l);
return RAD_E_STATE;
}
const RadParam sp[] = {
RAD_RANGE("M", 1, sigmoid_scatter_rows), RAD_INT("n_expert", c.n_expert_all),
RAD_INT("n_local", c.n_expert), RAD_INT("top_k", c.top_k),
RAD_INT("norm", c.norm_topk), RAD_F64("route_scale", c.route_scale),
RAD_STR("dtype", "f32"), RAD_INT("expert_base", c.expert_base),
RAD_STR("protect", prot_list),
};
const int n_sp = (int)(sizeof(sp) / sizeof(sp[0])) - (prot_list ? 0 : 1);
op_sigmoid_scatter = rad_decl_op(b, "router_sigmoid_topk_scatter", sp, n_sp,
&glm_router.correction, 1);
if (op_sigmoid_scatter) {
const rad_buf rd[1] = { w.logits };
rad_buf wr[7] = { w.ids, w.ew, w.sorted, w.eoff, w.ecnt };
int n_wr = 5;
if (gate) wr[n_wr++] = w.sgate;
if (scatter_inv) wr[n_wr++] = w.inv;
rad_op_reads (b, op_sigmoid_scatter, rd, 1);
rad_op_writes(b, op_sigmoid_scatter, wr, n_wr);
}
sigmoid_scatter_gate = op_sigmoid_scatter && gate;
}
}
if (g.world > 1)
op_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -1347,7 +1484,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
{w.x, w.h.x}, {w.x});
/* The layer as the prefetch sees it, indexed by model expert number (what the router ranks). */
if (!c.expert_bf16 && c.n_expert_all > 0 && n_reg > 0) {
if (!c.sigmoid_router && !c.expert_bf16 && c.n_expert_all > 0 && n_reg > 0) {
const int64_t na = c.n_expert_all;
xp_parts.assign((size_t)(na * 4), 0);
xp_count_at.assign((size_t)na, -1);
@@ -1376,7 +1513,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows,
bool gate_done) const {
/* `gate_done`: the fused router already wrote this pass's gate. */
if (!gate_done)
if (!gate_done && c.shared_ungated)
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.sgate, r0, rows, 1));
else if (!gate_done)
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_sgate),
brow_slice(w.sgate, r0, rows, 1));
sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows);
@@ -1415,7 +1554,18 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
/* The fused router when it resolved and the pass fits: router, topk + scatter and (with
* `router_fused_gate`) the shared gate in one launch. Otherwise the separate ops. */
const bool rfused = op_router_fused && rows <= router_fused_rows;
if (rfused)
const bool sfused = op_sigmoid_scatter && rows <= sigmoid_scatter_rows;
if (sfused) {
glm_router.project(c_, r0, rows, r0);
RAD_ISSUE_N(c_, op_sigmoid_scatter, rows, brow_slice(w.logits, r0, rows, ne_all),
RAD_W(glm_router.correction), brow_slice(w.ids, r0, rows, k),
brow_slice(w.ew, r0, rows, k), brows(w.sorted, rows * k),
brows(w.eoff, ne + 1), ecnt,
sigmoid_scatter_gate ? brow_slice(w.sgate, r0, rows, 1) : RAD_NONE,
scatter_inv ? brows(w.inv, rows * k) : RAD_NONE);
} else if (c.sigmoid_router) {
glm_router.step(c_, r0, rows, r0);
} else if (rfused)
RAD_ISSUE_N(c_, op_router_fused, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
RAD_W(w_router), router_fused_gate ? RAD_W(w_sgate) : RAD_NONE,
brow_slice(w.logits, r0, rows, ne_all),
@@ -1426,17 +1576,23 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
RAD_ISSUE_N(c_, op_router, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_router),
brow_slice(w.logits, r0, rows, ne_all));
/* topk + scatter fused, or the pair. In the fused op `w.ids` is an output. */
if (rfused) {
if (rfused || sfused) {
/* the fused router wrote all five */
} else if (op_topk_scatter && rows <= topk_scatter_rows) {
RAD_ISSUE_N(c_, op_topk_scatter, rows, brow_slice(w.logits, r0, rows, ne_all),
brow_slice(w.ids, r0, rows, k), brow_slice(w.ew, r0, rows, k),
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt);
} else {
if (!c.sigmoid_router)
RAD_ISSUE_N(c_, op_topk, rows, brow_slice(w.logits, r0, rows, ne_all),
brow_slice(w.ids, r0, rows, k), brow_slice(w.ew, r0, rows, k));
RAD_ISSUE_N(c_, op_scatter, rows, brow_slice(w.ids, r0, rows, k),
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt);
if (scatter_inv)
RAD_ISSUE_N(c_, op_scatter, rows, brow_slice(w.ids, r0, rows, k),
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt,
brows(w.inv, rows * k));
else
RAD_ISSUE_N(c_, op_scatter, rows, brow_slice(w.ids, r0, rows, k),
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt);
}
/* The rotated quantisation of the input, when the experts are rotated and the caller did not
@@ -1476,7 +1632,8 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
RAD_WTAB(w_gu[1], n_reg / 2), RAD_WTAB(w_gus[1], n_reg / 2),
brows(w.egu, rows * k));
if (shared) shared_up(c_, T, r0, rows, rfused && router_fused_gate);
if (shared) shared_up(c_, T, r0, rows,
(rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate));
gq_exp.step(c_, w.egu, rows * k, 0, rows * k);
if (shared) gq_sh.step(c_, w.sgu, T, r0, rows);
if (c.expert_bf16)
@@ -1562,7 +1719,7 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
* the block's delta into `h.x`. */
if (!gather_taken(g, T, gather_out_rows, gather_out_rows6))
RAD_ISSUE_N(c_, op_gather, rows, brows(w.edn, rows * k), brow_slice(w.ew, r0, rows, k),
brows(w.sorted, rows * k),
brows(gather_inv ? w.inv : w.sorted, rows * k),
gfold ? brow_slice(w.sout, r0, rows, g.n_embd) : RAD_NONE,
gfold ? brow_slice(w.sgate, r0, rows, 1) : RAD_NONE,
brow_slice(w.h.x, r0, rows, g.n_embd));
@@ -1640,9 +1797,10 @@ inline void MoeFP8::route_report(RadCtx* c_) const {
* It reports the last pass, which is the whole step by default (`c.rows` is the prefill
* chunk). With more passes it is a sample, adequate for a popularity estimate.
*
* `expert_w` stays null: RadRouting declares it `const float*` but these weights are bf16.
* Nothing in the core reads it (the heat engine uses `expert_count`). */
moe_debug_weights(c_, layer, c.top_k, w.ids, w.ew);
* `expert_w` stays null: RadRouting declares it `const float*` but these weights are bf16
* (f32 under the sigmoid router). Nothing in the core reads it (the heat engine uses
* `expert_count`). */
moe_debug_weights(c_, layer, c.top_k, w.ids, w.ew, c.sigmoid_router != 0);
RadRouting r{};
r.expert_ids = (const int32_t*)rad_buf_ptr(c_, w.ids);
r.expert_w = nullptr;
+174 -25
View File
@@ -68,6 +68,10 @@ struct ActFP8 {
* epilogue), so an int8 linear reading it declares no quantiser. Set by the model when it
* declares the pair, before the wires are copied. */
bool q8_fed = false;
/* With q8_fed: the producer's int8 codes are rotated, had_quant_act_i8g's (a `_had_quant_i8g`
* producer), so only a weight stored rotated (LinearFP8 at i8a8h) reads them, and it declares
* no quantiser of its own. Set by the model with q8_fed. */
bool q8_rot = false;
/* The code pair the producer writes: int8 when the model fed it, E4M3 otherwise. */
rad_buf cq() const { return q8_fed ? q8 : q; }
@@ -374,6 +378,8 @@ struct NormQuantFP8 {
* (the T * n_embd * 2-byte message then crosses --tp-wire-min-kb). The wire is a declare-time
* parameter, hence a separate op. */
rad_op op_arn6 = 0;
/* The ops write had_quant_act_i8g's rotated int8 codes into the int8 pair (ActFP8::q8_rot). */
bool hi8 = false;
Geom gm{};
/* The row width, for turning a row slice into element offsets. */
int64_t n = 0;
@@ -407,8 +413,12 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
"linears are bf16; its blocks take a prepared input instead\n");
return RAD_E_UNSUPPORTED;
}
if (!src || !a.x || !a.q || !a.s || !w || n <= 0) return RAD_E_INVAL;
op = RAD_OP(b, "rmsnorm_quant_fp8",
/* Rotated int8 codes (ActFP8::q8_rot) come from the `_had_quant_i8g` twins, into the int8
* pair; the model checked they are declared before feeding. Otherwise E4M3, as always. */
hi8 = a.q8_fed && a.q8_rot;
const rad_buf cq = hi8 ? a.q8 : a.q, cs = hi8 ? a.s8 : a.s;
if (!src || !a.x || !cq || !cs || !w || n <= 0) return RAD_E_INVAL;
op = RAD_OP(b, hi8 ? "rmsnorm_had_quant_i8g" : "rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype),
@@ -419,7 +429,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
* lifetime-extended. `residual` is INOUT, so it is in both sets; otherwise the planner could
* reorder a reader around it. */
rad_buf rd[2] = { src, res };
rad_buf wr[4] = { a.q, a.s, a.x, res };
rad_buf wr[4] = { cq, cs, a.x, res };
rad_op_reads (b, op, rd, res ? 2 : 1);
rad_op_writes(b, op, wr, res ? 4 : 3);
@@ -431,7 +441,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
* with `x` the stream and no residual. The kernel supports it (r4d_fused_quant_fp8.hip) and the
* schema marks `residual` optional. */
if (fuse_ar && g.world == 2) {
op_arn = RAD_OP(b, "ar_rmsnorm_quant_fp8",
op_arn = RAD_OP(b, hi8 ? "ar_rmsnorm_had_quant_i8g" : "ar_rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_INT("group", RAD_FP8_BLOCK),
@@ -439,14 +449,14 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
RAD_WEIGHTS(w));
if (!op_arn) return RAD_E_INVAL;
rad_buf wr_ar[4] = { a.q, a.s, a.x, res ? res : src };
rad_buf wr_ar[4] = { cq, cs, a.x, res ? res : src };
rad_op_reads (b, op_arn, rd, res ? 2 : 1);
rad_op_writes(b, op_arn, wr_ar, 4);
/* Only where the compressed wire is reachable and servable: a lossy payload accepted, and
* the width tiled by the chunk (otherwise a fatal step-time shape refusal). */
if (fuse_ar != kArExact && !g.wire_exact && (n % kArWire6Chunk) == 0) {
op_arn6 = RAD_OP(b, "ar_rmsnorm_quant_fp8",
op_arn6 = RAD_OP(b, hi8 ? "ar_rmsnorm_had_quant_i8g" : "ar_rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_INT("group", RAD_FP8_BLOCK),
@@ -470,8 +480,8 @@ inline void NormQuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) c
if (rows <= 0) rows = T - r0;
RAD_ISSUE_N(c, pick(rows), rows, brow_slice(src, r0, rows, n),
res ? brow_slice(res, r0, rows, n) : RAD_NONE, RAD_W(w),
brow_slice(a.q, r0, rows, n),
brow_slice(a.s, r0, rows, n / RAD_FP8_BLOCK),
brow_slice(hi8 ? a.q8 : a.q, r0, rows, n),
brow_slice(hi8 ? a.s8 : a.s, r0, rows, n / RAD_FP8_BLOCK),
brow_slice(a.x, r0, rows, n));
}
@@ -480,6 +490,15 @@ inline void NormQuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) c
struct GateQuantFP8 {
ActFP8 a{};
rad_op op = 0;
/* The swiglu_clamped path (`limit` > 0): `op` writes the clamped bf16 product and `op_quant`
* quantises it into the codes; with `clamped_fused`, `op` is `swiglu_clamped_quant_fp8` doing
* both and `op_quant` is unset. */
rad_op op_quant = 0;
bool clipped = false;
/* Set before declare: serve the clamped path as one `swiglu_clamped_quant_fp8` where a loaded
* library declares it and it resolves (E4M3 codes only). Byte-identical to the pair. */
bool fuse_clamped = false;
bool clamped_fused = false;
/* Whether the bf16 product is written. A consumer of the bf16 value must request it
* (docs/OPS.md), but a block-fp8 down_proj reads only codes and scales; only one that reads
* the bf16 plane (LinearFP8::reads_x) needs it. Skipping it saves [T, n_ff] per layer (18.2 GB
@@ -500,7 +519,7 @@ struct GateQuantFP8 {
* and `gated_quant_fp8` cannot supply it alone (its code and scale outputs are mandatory). */
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,
bool rot = false, bool silu_only = false);
bool rot = false, bool silu_only = false, double limit = 0);
void step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0 = 0, int64_t rows = 0) const;
};
@@ -509,13 +528,59 @@ struct GateQuantFP8 {
* bf16 output is unrotated either way. */
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,
bool bf16_out, bool rot, bool silu_only) {
bool bf16_out, bool rot, bool silu_only, double limit) {
a = act;
want_x = bf16_out;
op_quant = 0;
this->n = n;
/* bf16 linears read the product itself, and an int8 trunk's down projection quantises its own
* input (`silu_only`): `silu_mul` into the bf16 plane only, and no rotation. */
bf16 = g.w_bf16 || silu_only;
clipped = limit > 0;
clamped_fused = false;
if (!std::isfinite(limit) || limit < 0) return RAD_E_INVAL;
if (clipped) {
/* No rotated int8 form: its quantiser would be quant_act_i8g, unrotated. A `silu_only`
* linear quantises its output through its consumer, so it carries no clamp. */
if (!gate_up || !a.x || n <= 0 || rot || silu_only || (a.q8_fed && a.q8_rot) ||
std::strcmp(act_name, "silu"))
return RAD_E_INVAL;
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
if (fuse_clamped && !bf16 && !a.q8_fed && a.cq() && a.cs() &&
rad_op_declared(b, "swiglu_clamped_quant_fp8")) {
op =
RAD_OP(b, "swiglu_clamped_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("limit", limit),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS);
if (op) {
const rad_buf wr[3] = { a.cq(), a.cs(), a.x };
rad_op_reads(b, op, &gate_up, 1);
rad_op_writes(b, op, wr, want_x ? 3 : 2);
clamped_fused = true;
return RAD_OK;
}
}
want_x = true;
op = rw(b,
RAD_OP(b, "swiglu_clamped",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("limit", limit),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ gate_up }, { a.x });
if (!bf16) {
if (!a.cq() || !a.cs()) return RAD_E_INVAL;
op_quant =
rw(b,
RAD_OP(b, a.q8_fed ? "quant_act_i8g" : "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ a.x }, { a.cq(), a.cs() });
if (!op_quant) return RAD_E_INVAL;
}
return op?RAD_OK:RAD_E_INVAL;
}
if (bf16) {
if (!gate_up || !a.x || n <= 0 || rot || std::strcmp(act_name, "silu") != 0) {
fprintf(stderr, "radiance: a bf16 gate is silu over [gate|up] into a bf16 plane; "
@@ -533,9 +598,13 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
if (!gate_up || !a.x || !a.cq() || !a.cs() || n <= 0) return RAD_E_INVAL;
/* Rotated codes feed a four-bit expert, which reads E4M3 only. */
if (rot && a.q8_fed) return RAD_E_INVAL;
/* Rotated int8 codes (ActFP8::q8_rot) feed a down projection stored at i8a8h:
* gated_had_quant_i8g, which the model checked is declared before feeding. */
const bool hi8 = a.q8_fed && a.q8_rot;
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
const char* gq = hi8 ? "gated_had_quant_i8g" : rot ? "gated_had_quant_fp8" : "gated_quant_fp8";
if (!rot || rad_op_declared(b, "gated_had_quant_fp8"))
op = RAD_OP(b, rot ? "gated_had_quant_fp8" : "gated_quant_fp8",
op = RAD_OP(b, gq,
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype),
RAD_STR("act", act_name)),
@@ -564,6 +633,22 @@ 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,
int64_t rows) const {
if (rows <= 0) rows = T - r0;
if (clamped_fused) {
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n),
brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK),
want_x ? brow_slice(a.x, r0, rows, n) : RAD_NONE);
return;
}
if (clipped) {
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n),
brow_slice(a.x, r0, rows, n));
if (op_quant)
RAD_ISSUE_N(c, op_quant, 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 (bf16 || op_q) {
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n), brow_slice(a.x, r0, rows, n));
if (op_q)
@@ -616,6 +701,9 @@ struct LinearFP8 {
/* Plain bf16 weight read by `gemm_nt` over the bf16 activation (Geom::w_bf16): no scale plane,
* no quantiser. */
bool bf16 = false;
/* Block-fp8 weight whose scale plane is f32 rather than bf16 (GLM's checkpoints), read by
* `gemm_nt_q` at dtype fp8a8f32. Read from the weight's encoding. */
bool f32_scale = false;
/* Int8 weight read by `gemm_nt_q` at dtype i8a8: i8 codes with a bf16 scale per row per 128 of
* K (libquant `codes=i8 group=128 scale=bf16`), against an i8 activation with an f32 scale per
* (row, 128). A quarter of E4M3's error at the same bytes, and iu8 WMMA runs at the fp8 rate.
@@ -771,6 +859,17 @@ inline bool linear_is_w8(const RadEncoding& e) {
sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK;
}
/* The same planes rotated by the unnormalised 128-wide Hadamard along K, the 1/128 in the scale
* (libquant's `transform=fwht128`), served at i8a8h behind had_quant_act_i8g. */
inline bool linear_is_w8h(const RadEncoding& e) {
if (!rad_enc_is(&e, "affine") || e.n_planes != 2 ||
std::strncmp(e.transform, "fwht128", RAD_ENC_STR) != 0)
return false;
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
return e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 && sc && sc->dtype == RAD_BF16 &&
sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK;
}
/* The OCP-MXFP4 weight LinearFP8 serves at mxfp4a8: e2m1 codes and an E8M0 exponent per [1 x 32],
* no transform (libr4d's MXFP4 layout hook). */
enum { RAD_MX_GROUP = 32 };
@@ -832,7 +931,7 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char*
const bool known = weight_enc(b, wn, &enc);
const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
enc.plane[0].dtype == RAD_BF16;
probed_i8 = known && linear_is_w8(enc);
probed_i8 = known && (linear_is_w8(enc) || linear_is_w8h(enc));
/* A rotated weight rotates and quantises the bf16 plane itself; a 4-bit one casts or
* quantises it. */
const bool rotated = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc));
@@ -990,9 +1089,21 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
/* ---- int8 weight, `gemm_nt_q` at i8a8 over the input's `a.q8` / `a.s8`. The scale plane is
* one bf16 per row per 128 of K: row parts and row slices apply as is, column slices in groups
* of 128. The codes come from the producer (ActFP8::q8_fed) or from op_q over `a.x` (probe()
* set reads_x). The model must have declared the pair (ActFP8::declare_qs's `i8`). */
i8 = known && linear_is_w8(enc);
* set reads_x). The model must have declared the pair (ActFP8::declare_qs's `i8`).
*
* A rotated weight (i8a8h) takes had_quant_act_i8g instead. It reads a producer's codes only
* when they are rotated too (ActFP8::q8_rot, a `_had_quant_i8g` producer); a plain int8 weight
* only when they are not. */
const bool rot8 = known && linear_is_w8h(enc);
i8 = known && (linear_is_w8(enc) || rot8);
if (i8) {
/* Upstream's rot guard: fed codes must match the weight's rotation form. */
if (a.q8_fed && rot8 != a.q8_rot) {
fprintf(stderr, "radiance: '%s' is a%s int8 weight and its input is fed codes its "
"producer wrote %s\n", wn, rot8 ? " rotated" : " plain",
rot8 ? "unrotated" : "rotated");
return RAD_E_DTYPE;
}
/* The codes come from the producer (`q8_fed`, which declares no `op_q` and so needs no bf16
* plane) or from this linear's own `op_q` over `a.x`. Either way the int8 pair must exist;
* the bf16 plane is required only when this linear quantises, exactly as the fp8 branch
@@ -1031,14 +1142,15 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
}
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
if (!a.q8_fed)
op_q = rw(b, RAD_OP(b, "quant_act_i8g",
op_q = rw(b, RAD_OP(b, rot8 ? "had_quant_act_i8g" : "quant_act_i8g",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("n", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ a.x }, { a.q8, a.s8 });
op = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "i8a8")),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", rot8 ? "i8a8h" : "i8a8")),
RAD_WEIGHTS(w, ws)),
{ a.q8, a.s8 }, { y });
return (op_q || a.q8_fed) && op ? RAD_OK : RAD_E_INVAL;
@@ -1260,12 +1372,13 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
if (known) {
const RadEncPlane* sc = rad_enc_plane(&enc, "scale");
if (!rad_enc_is(&enc, "affine") || enc.n_planes != 2 || enc.transform[0] ||
enc.plane[0].dtype != RAD_F8E4M3 || !sc || sc->dtype != RAD_BF16 ||
enc.plane[0].dtype != RAD_F8E4M3 || !sc ||
(sc->dtype != RAD_BF16 && sc->dtype != RAD_F32) ||
sc->block[0] != RAD_FP8_BLOCK || sc->block[1] != RAD_FP8_BLOCK) {
char en[256];
rad_enc_format(&enc, en, sizeof en);
fprintf(stderr, "radiance: '%s' is %s, which this model's linears do not read; they "
"read bf16, fp8_e4m3*bf16[128x128], i8*bf16[1x128], "
"read bf16, fp8_e4m3*bf16[128x128] or *f32[128x128], i8*bf16[1x128], "
"fp4_e2m1*e8m0[1x32], u4*f16[1x128]-u4[1x128] (or a u8 zero) and the "
"ParoQuant forms. A recipe rule stores the weight in one of them "
"(docs/TOOLS.md, the import rule for a shipped int4 grid)\n", wn, en);
@@ -1291,13 +1404,15 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
RAD_ARCH_TRY(rp.set(row_parts, RAD_FP8_BLOCK, RAD_FP8_BLOCK, base, "scale blocks"));
const char* sn = nm.f("%s.scale", base);
const auto* fp8_scale = known ? rad_enc_plane(&enc, "scale") : nullptr;
f32_scale = fp8_scale && fp8_scale->dtype == RAD_F32;
/* One stored weight, two operands: the codes and scale plane of `<base>.weight`, block fp8 in
* the checkpoint or made so by rad-convert's recipe. */
w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K },
access, shard, grp, rp.w, rp.n);
ws_row_div = RAD_FP8_BLOCK;
ws = decl_view(b, sn, wn, "scale", RAD_BF16, { fp8_blocks(N), fp8_blocks(K) },
access, shard, grp, rp.s, rp.n);
ws = decl_view(b, sn, wn, "scale", f32_scale ? RAD_F32 : RAD_BF16,
{ fp8_blocks(N), fp8_blocks(K) }, access, shard, grp, rp.s, rp.n);
if (!w || !ws) return RAD_E_INVAL;
/* An uneven slice; the scale plane takes the same slice in blocks. */
if (span_hi > 0) {
@@ -1318,7 +1433,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
op = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", f32_scale?"fp8a8f32":"fp8a8")),
RAD_WEIGHTS(w, ws)),
{ a.q, a.s }, { y });
return RAD_OK;
@@ -1415,19 +1530,53 @@ struct DenseFP8 {
/* The caller made the name map (a row range of a checkpoint tensor); declare() does not. */
bool mapped = false;
/* `mapped`: the caller made the name map already, to ask the encoding before choosing this
* struct over another grid's -- a COPY map declared twice is refused (rad_builder.cpp). */
int declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K,
int access, int shard, RadWeightGroup grp,
std::initializer_list<const char*> src,
std::initializer_list<int64_t> row_parts = {});
/* `gemm_nt_q` over this weight, `fp8a8` or `mxfp4a8` as it was declared, ranged M 1..hi. */
std::initializer_list<int64_t> row_parts = {}, bool mapped = false);
/* Rows [lo, hi) of the stored block-fp8 weight `src_wn` (codes and scale plane; mapped by
* whoever declared it), read as an [hi - lo, K] weight named `<base>`: a row slice that need
* not be a rank's even share, and may be the same rows on every rank. Whole 128-row blocks,
* so each slice's codes and scales are the stored ones. fp8 only: an MXFP4 linear's GEMM
* splits K by its own rule. A slice issued with `gemm(..., split_n)` set to the stored width
* computes the stored linear's outputs to the bit. */
int declare_slice(RadBuilder* b, Names& nm, const char* base, const char* src_wn, int64_t lo,
int64_t hi, int64_t K, int access, RadWeightGroup grp) {
if (lo < 0 || hi <= lo || lo % RAD_FP8_BLOCK || hi % RAD_FP8_BLOCK || K % RAD_FP8_BLOCK)
return RAD_E_INVAL;
mx = false;
ref = 0;
const char* wn = nm.f("%s.weight", base);
const char* sn = nm.f("%s.scale", base);
const bool own = !std::strcmp(wn, src_wn); /* the stored weight's own name */
w = decl_view(b, wn, own ? nullptr : src_wn, "codes", RAD_F8E4M3, { hi - lo, K }, access,
RAD_SHARD_ROW, grp);
s = decl_view(b, sn, src_wn, "scale", RAD_BF16, { fp8_blocks(hi - lo), fp8_blocks(K) },
access, RAD_SHARD_ROW, grp);
if (!w || !s) return RAD_E_INVAL;
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);
}
/* `gemm_nt_q` over this weight, `fp8a8` or `mxfp4a8` as it was declared, ranged M 1..hi.
* `split_n`, when set, is the stored width a row slice takes its K split from (docs/OPS.md). */
rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K,
std::initializer_list<rad_buf> reads, std::initializer_list<rad_buf> writes) const {
std::initializer_list<rad_buf> reads, std::initializer_list<rad_buf> writes,
int64_t split_n = 0) const {
if (mx)
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")),
RAD_WEIGHTS(w, s, ref)),
reads, writes);
if (split_n > 0)
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8"),
RAD_INT("split_n", split_n)),
RAD_WEIGHTS(w, s)),
reads, writes);
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
@@ -1441,7 +1590,7 @@ struct DenseFP8 {
inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K,
int access, int shard, RadWeightGroup grp,
std::initializer_list<const char*> src,
std::initializer_list<int64_t> row_parts) {
std::initializer_list<int64_t> row_parts, bool mapped) {
if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL;
/* ---- OCP-MXFP4, from the weight's encoding. The exponent grid is one row tall, so parts need
File diff suppressed because it is too large. Load diff
+145
View File
@@ -0,0 +1,145 @@
/* GLM-5.3's tensor parallelism in one place: what a rank's shard of the model is, from which step
* size a replicated or head-split piece of work splits over the ranks instead, how a step's rows
* fall into one run a rank, and the column split of a replicated F32 projection.
*
* The residual stream is replicated (spec.md §9). Three kinds of split share the ranks' work:
*
* heads the MLA and KDA heads, with them the rows of their projections, the KDA state and
* the convolution history; the experts' and the dense feed-forward's width
* (`heads`, `kda_width`, `expert_width`, `dense_width`); joined by an all_reduce
* rows a prefill-sized step's rows, one run a rank, each rank computing its run with the
* unsplit kernels (`run_rows`, `run_of`); joined by an all_gather of whole runs
* columns a replicated F32 projection's output columns (SplitF32Proj); joined by a
* row-interleaved all_gather, bit for bit the replicated projection
*
* The one rule for a run: ceil(T / world) rows, rounded up to whole 16-byte words of the gathered
* row, because an all_gather moves whole words. The indexer gathers one i32 length a row beside
* its page tables, so its runs are multiples of four rows. The last rank's run may be short, or
* lie wholly past a small step (`run_of`). */
#ifndef RAD_GLM_TP_H
#define RAD_GLM_TP_H
#include "rad_arch.h"
#include <algorithm>
#include <numeric>
namespace rad {
namespace arch {
struct GlmTp {
/* The model's widths a rank's shard divides: 64 heads of 128 (KDA) and 256 (MLA), experts of
* 2048 and a dense feed-forward of 12288. */
static constexpr int64_t kHeads = 64, kKdaDim = 128, kMlaDim = 256, kExpertFF = 2048,
kDenseFF = 12288;
static bool world_ok(int world) { return world == 1 || world == 2 || world == 4 || world == 8; }
static int64_t heads(int world) { return kHeads / world; }
static int64_t kda_width(int world) { return heads(world) * kKdaDim; }
static int64_t mla_width(int world) { return heads(world) * kMlaDim; }
static int64_t expert_width(int world) { return kExpertFF / world; }
static int64_t dense_width(int world) { return kDenseFF / world; }
/* Rows from which a step splits by rows or columns over the ranks. Below it, as in decode, the
* collective's latency outweighs the saved arithmetic and every rank runs the replicated or
* head-split form. */
static constexpr int64_t kSplitRows = 256;
/* Rows x live blocks from which the indexer splits a smaller step as well: a decode step at
* long context, where scoring every query row against every block of its sequence outweighs
* the two gathers. On one R9700 48 rows over 8000 blocks (32k of context) score and select in
* about 250 us and a run of 8 in 50, against roughly 50 us for the two eight-rank gathers;
* over 4000 blocks the saving is about the gathers' cost, and six rows never pay. From 16
* rows, so that at least four ranks share the work and every run fits in the step. */
static constexpr int64_t kSplitWork = 1 << 18, kSplitWorkRows = 16;
static bool splits(int64_t rows, int world) { return world > 1 && rows >= kSplitRows; }
/* A rank's run of a step of `rows`, gathered as rows of `row_bytes`: ceil(rows / world) rounded
* up to whole 16-byte words of the gathered row. Every rank but possibly the last takes a whole
* run; the planes a split writes hold world runs, which can reach past the step. */
static int64_t run_rows(int64_t rows, int world, int64_t row_bytes) {
const int64_t word = 16 / std::gcd<int64_t>(16, row_bytes);
return word * ((rows + word * world - 1) / (word * world));
}
struct Run {
int64_t run = 0, first = 0, rows = 0;
};
/* Rank `rank`'s rows [first, first + rows) of a step of `rows`. A rank whose run lies wholly
* past a small step takes the step's first run instead, so every plane it computes from and
* gathers is written; what it computes there is dead rows past the step, and the gather lays
* them past T, where nothing reads them. */
static Run run_of(int64_t rows, int world, int rank, int64_t row_bytes) {
Run r;
r.run = run_rows(rows, world, row_bytes);
r.first = rank * r.run;
r.rows = std::min(r.run, rows - r.first);
if (r.rows <= 0) {
r.first = 0;
r.rows = r.run;
}
return r;
}
/* The all_reduce of a replicated 4096-wide bf16 row over the ranks: the embedding's (exact)
* and each head-split block's (the deployment's wire). */
static rad_op reduce(RadBuilder* b, const Geom& g, rad_buf x, bool exact = false) {
if (g.world == 1) return 0;
return rw(b,
RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", 4096, g.max_tok * 4096),
RAD_STR("dtype", "bf16"),
RAD_INT("exact", exact ? 1 : g.wire_exact),
RAD_INT("min_bytes", g.wire_min_bytes)),
RAD_NOWEIGHTS),
{ x }, { x });
}
};
/* The split's ops are declared whatever the step size, and each gather's message as a range of
* rows: the engine's arena levels declare again at a smaller max_tok and must get the same graph
* with the same fixed parameters.
*
* A replicated [n, k] F32 projection computed column-split: rank r runs the same gemm_nt_f32 on
* rows [r*n/world, (r+1)*n/world) of the weight and a row-interleaved all_gather lays the slices
* out as the full [M, n]. The kernel computes every output column independently of n and the
* gather moves bytes, so each value is bit-identical to the replicated projection's. */
struct SplitF32Proj {
rad_buf part = 0;
rad_op op_part = 0, op_gather = 0;
int64_t cols = 0, k = 0, min_rows = 0, first_col = 0;
int declare(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t rows, int64_t n,
int64_t width, rad_weight weight, rad_buf input, rad_buf output) {
min_rows = GlmTp::kSplitRows;
if (g.world < 2 || n % g.world || (n / g.world * 4) % 16) {
min_rows = 0;
return RAD_OK;
}
cols = n / g.world;
k = width;
first_col = g.rank * cols;
part = decl_b(b, nm.f("%s.part", name), RAD_F32, { rows, cols });
op_part = rw(b,
RAD_OP(b, "gemm_nt_f32",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", cols), RAD_INT("K", k),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(weight)),
{ input }, { part });
op_gather = rw(
b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", cols, rows * cols),
RAD_STR("dtype", "f32"), RAD_INT("row", cols)),
RAD_NOWEIGHTS),
{ part }, { output });
return part && op_part && op_gather ? RAD_OK : RAD_E_INVAL;
}
bool takes(int64_t rows) const { return min_rows && rows >= min_rows; }
void step(RadCtx* ctx, int64_t rows, RadOperand input, rad_weight weight,
RadOperand output) const {
RadOperand slice = RAD_W(weight);
slice.offset = first_col * k;
slice.rows = cols;
RAD_ISSUE_N(ctx, op_part, rows, input, slice, brows(part, rows));
RAD_ISSUE_N(ctx, op_gather, rows * cols, brows(part, rows), output);
}
};
}
} // namespace rad::arch
#endif
+430
View File
@@ -0,0 +1,430 @@
/* rad_vae2d.h -- an image VAE (encoder or decoder) as a recorded list of ops over NHWC images.
*
* Image size varies per request, so a VAE's ops are declared once for the largest image and issued
* with each pass's extents (`Vae::issue`). Qwen-Image 2.1's residual Wan-2.2 VAE, Qwen-Image's
* and Krea 2's Wan-2.1 one and FLUX's GroupNorm one are each a few lines of `conv`, `norm`,
* `resblock` and `attention` calls in their plugin.
*/
#pragma once
#include <arch/rad_arch.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <utility>
#include <vector>
namespace rad {
namespace arch {
/* ================================================================== the VAE as a recorded graph
*
* Image size varies per request, so the VAE's ops are declared once for the largest image and
* issued with the actual extents: every image operand is a raw [height, width * channels] view of
* its buffer (docs/OPS.md, "Image generation"), with extents from the pass's picture size and the
* stage's scale. `Vae` records each op with what it needs to rebuild its operands, so declare()
* and step() walk the same list.
*
* Every output is its own buffer, sized for its stage; the planner shares storage between those
* whose lives do not overlap, and no buffer is reused by hand. This is sound because ops are issued
* in declaration order. */
struct VImg {
rad_buf buf = 0;
int64_t ch = 0;
int lvl = 0; /* the side is the pass's base side times 2^lvl (decoder) or / 2^lvl (encoder) */
};
struct VOp {
enum Kind { CONV, NORM, ADD, D2S, S2D, ATTN, GNORM, LIN } kind = CONV;
rad_op op = 0;
VImg x{}, y{}, z{}; /* inputs x (and z for ADD), output y */
rad_weight w = 0, b = 0;
int k = 1, up = 1, stride = 1;
int64_t qkv_ch = 0; /* ATTN: x is the [*, 3C] qkv rows, y the [*, C] output */
};
/* What a checkpoint stores a VAE's convolutions as. */
enum VaeConvForm {
VAE_CONV_2D, /* [cout, cin, k, k] */
VAE_CONV_CAUSAL, /* a causal 3-D convolution [cout, cin, kt, k, k], run on one frame: its
* last temporal tap (RAD_MAP_TAP) */
};
struct Vae {
std::vector<VOp> ops;
Names* nm = nullptr;
RadBuilder* b = nullptr;
const char* scope = ""; /* "dec" or "enc" */
bool down = false; /* an encoder: a level halves the side */
int64_t base_px = 0; /* pixels at level 0, the largest any pass hands it */
int n_buf = 0;
int first_group = 0;
/* The banded tail. From op `band_from` on, every output pixel reads a bounded window of rows
* (3x3 convolutions, nearest upsampling, per-pixel norms and adds, depth-to-space shortcuts),
* so a rank can run the tail on its band of level-0 rows plus `halo` rows per side and get its
* band's pixels bit for bit: rows spoiled by a conv's zero padding at the band edge never reach
* the band. The ops before it include the mid-block's attention, which reads every pixel, and
* run whole; `whole` holds their outputs, read by the tail at the band's row offset. -1: no
* tail. */
int band_from = -1;
int64_t halo = 0;
std::vector<rad_buf> whole;
VaeConvForm form = VAE_CONV_2D;
/* group_norm's statistics scratch, one for every GroupNorm op (they run one after another). */
rad_buf gn_stats = 0;
int64_t px_at(int lvl) const {
int64_t p = base_px;
for (int i = 0; i < lvl; ++i) p = down ? (p + 3) / 4 : p * 4;
return p;
}
VImg img(int64_t ch, int lvl) {
VImg v;
v.ch = ch;
v.lvl = lvl;
v.buf = decl_b(b, nm->f("%s.t%d", scope, n_buf++), RAD_BF16, { px_at(lvl), ch });
return v;
}
rad_weight wt(const char* name, const char* src, std::initializer_list<int64_t> shape,
bool tap = false) {
if ((tap ? map_tap(b, name, src, 2, -1) : map_copy(b, name, src)) < 0) return 0;
return decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE,
grp_layer(first_group));
}
/* y = conv(x): k x k, stride, `up` 2 reads x upsampled, `pad` same or down. */
VImg conv(const VImg& x, int64_t cout, int k, int stride, int up, const char* pad,
const char* ckpt) {
VOp o;
o.kind = VOp::CONV;
o.x = x;
o.up = up;
o.stride = stride;
int lvl = x.lvl;
if (up == 2) lvl = down ? lvl - 1 : lvl + 1;
if (stride == 2) lvl = down ? lvl + 1 : lvl - 1;
o.y = img(cout, lvl);
o.k = k;
o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { cout, x.ch, k, k },
form == VAE_CONV_CAUSAL);
o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { cout });
o.op = RAD_OP(b, "conv2d_nhwc",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(lvl)), RAD_INT("cin", x.ch),
RAD_INT("cout", cout), RAD_INT("k", k),
RAD_INT("stride", stride), RAD_STR("pad", pad),
RAD_INT("up", up), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(o.w, o.b));
/* An input with no buffer is the picture the pass staged, read where it lies. */
if (x.buf) rw(b, o.op, { x.buf }, { o.y.buf });
else rw(b, o.op, {}, { o.y.buf });
ops.push_back(o);
return o.y;
}
/* The channel norm, `silu` or not. `gamma` is [C, 1, 1(, 1)] in the checkpoint. */
VImg norm(const VImg& x, bool silu, const char* ckpt, int gamma_rank) {
VOp o;
o.kind = VOp::NORM;
o.x = x;
o.y = img(x.ch, x.lvl);
const char* dn = nm->f("%s.gamma", ckpt);
if (map_copy(b, dn, nm->ckpt("%s.gamma", ckpt)) < 0) return VImg{};
o.w = gamma_rank == 4
? decl_w(b, dn, RAD_BF16, { x.ch, 1, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group))
: decl_w(b, dn, RAD_BF16, { x.ch, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group));
o.op = rw(b, RAD_OP(b, "l2norm_chan",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
RAD_STR("act", silu ? "silu" : "none"),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(o.w)),
{ x.buf }, { o.y.buf });
ops.push_back(o);
return o.y;
}
VImg add(const VImg& x, const VImg& z) {
VOp o;
o.kind = VOp::ADD;
o.x = x;
o.z = z;
o.y = img(x.ch, x.lvl);
o.op = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x.buf, z.buf }, { o.y.buf });
ops.push_back(o);
return o.y;
}
/* y += the resampling shortcut of x (in place on y). */
void shortcut(const VImg& x, const VImg& y, int ft) {
VOp o;
o.kind = down ? VOp::S2D : VOp::D2S;
o.x = x;
o.y = y;
o.up = ft;
o.op = rw(b, RAD_OP(b, down ? "s2d_avg_add" : "d2s_add",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(y.lvl)), RAD_INT("cin", x.ch),
RAD_INT("cout", y.ch), RAD_INT("ft", ft),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x.buf, y.buf }, { y.buf });
ops.push_back(o);
}
/* A residual block, in -> out channels. */
VImg resblock(const VImg& x, int64_t out, const char* ckpt) {
VImg h = x;
if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->f("%s.conv_shortcut", ckpt));
VImg t = norm(x, true, nm->f("%s.norm1", ckpt), 4);
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv1", ckpt));
t = norm(t, true, nm->f("%s.norm2", ckpt), 4);
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv2", ckpt));
return add(t, h);
}
/* The mid-block's single-head attention over every pixel. */
VImg attention(const VImg& x, const char* ckpt) {
const int64_t C = x.ch;
VImg t = norm(x, false, nm->f("%s.norm", ckpt), 3);
VImg qkv = conv(t, 3 * C, 1, 1, 1, "same", nm->f("%s.to_qkv", ckpt));
VOp o;
o.kind = VOp::ATTN;
o.x = qkv;
o.y = img(C, x.lvl);
o.qkv_ch = 3 * C;
o.op = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("head_dim", C),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)C))),
RAD_NOWEIGHTS),
{ qkv.buf }, { o.y.buf });
ops.push_back(o);
VImg p = conv(o.y, C, 1, 1, 1, "same", nm->f("%s.proj", ckpt));
return add(p, x);
}
/* PyTorch's GroupNorm over the whole picture, `silu` or not (FLUX's VAE). Not row-local, so a
* VAE that has one runs whole (no banded tail). */
VImg gnorm(const VImg& x, bool silu, const char* ckpt, int64_t groups, double eps) {
VOp o;
o.kind = VOp::GNORM;
o.x = x;
o.y = img(x.ch, x.lvl);
o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { x.ch });
o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { x.ch });
if (!gn_stats)
gn_stats = decl_b(b, nm->f("%s.gn_stats", scope), RAD_F32, { 64 * (2 + 3 * 1024) });
o.k = (int)groups;
o.op = RAD_OP(b, "group_norm",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
RAD_INT("groups", groups), RAD_F64("eps", eps),
RAD_STR("act", silu ? "silu" : "none"), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(o.w, o.b));
rw(b, o.op, { x.buf, gn_stats }, { o.y.buf, gn_stats });
ops.push_back(o);
return o.y;
}
/* A per-pixel linear with a bias (a 1x1 convolution kept as a Linear): `cout` from x's
* channels. */
VImg lin(const VImg& x, int64_t cout, const char* ckpt) {
VOp o;
o.kind = VOp::LIN;
o.x = x;
o.y = img(cout, x.lvl);
o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { cout, x.ch });
o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { cout });
o.op = rw(b, RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("N", cout),
RAD_INT("K", x.ch), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(o.w, o.b)),
{ x.buf }, { o.y.buf });
ops.push_back(o);
return o.y;
}
/* A GroupNorm residual block (FLUX's VAE, diffusers' ResnetBlock2D): norm1, silu, conv1,
* norm2, silu, conv2, plus the input or its 1x1 `conv_shortcut`. */
VImg resblock_gn(const VImg& x, int64_t out, const char* ckpt, int64_t groups, double eps) {
VImg h = x;
if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->f("%s.conv_shortcut", ckpt));
VImg t = gnorm(x, true, nm->f("%s.norm1", ckpt), groups, eps);
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv1", ckpt));
t = gnorm(t, true, nm->f("%s.norm2", ckpt), groups, eps);
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv2", ckpt));
return add(t, h);
}
/* diffusers' single-head VAE attention: GroupNorm, to_q / to_k / to_v linears with biases,
* attention over every pixel, to_out.0, plus the input. */
VImg attention_gn(const VImg& x, const char* ckpt, int64_t groups, double eps) {
const int64_t C = x.ch;
VImg t = gnorm(x, false, nm->f("%s.group_norm", ckpt), groups, eps);
VImg q = lin(t, C, nm->f("%s.to_q", ckpt));
VImg k = lin(t, C, nm->f("%s.to_k", ckpt));
VImg v = lin(t, C, nm->f("%s.to_v", ckpt));
VOp o;
o.kind = VOp::ATTN;
o.x = q;
o.y = img(C, x.lvl);
o.z = k;
o.w = 0;
o.qkv_ch = 0;
o.k = 0;
o.op = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("head_dim", C),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)C))),
RAD_NOWEIGHTS),
{ q.buf, k.buf, v.buf }, { o.y.buf });
attn_v.push_back({ ops.size(), v });
ops.push_back(o);
VImg p = lin(o.y, C, nm->f("%s.to_out.0", ckpt));
return add(p, x);
}
/* The value image of each separate-projection attention, by op index. */
std::vector<std::pair<size_t, VImg>> attn_v;
const VImg* value_of(size_t i) const {
for (const auto& e : attn_v) if (e.first == i) return &e.second;
return nullptr;
}
/* The operands of op `o` for a pass whose level-0 picture is H0 x W0 pixels (or latent tokens,
* for the decoder), in the op's schema order, and its ranged value. */
static int64_t side(int64_t s0, int lvl, bool dn) {
int64_t s = s0;
for (int i = 0; i < lvl; ++i) s = dn ? s / 2 : s * 2;
return s;
}
/* Declares `cu`, a buffer of the plugin's, as read by every attention: issue() hands it to
* them. */
int attn_reads(rad_buf cu) const {
for (const VOp& o : ops)
if (o.kind == VOp::ATTN) RAD_ARCH_TRY(rad_op_reads(b, o.op, &cu, 1));
return RAD_OK;
}
/* `cu` is {0, pixels} at the attention's level -- the pass's latent tokens -- and `input` the
* level-0 picture when the first op reads one the pass staged. Ops [from, to) are issued; with
* `row0`, H0 is a band's rows and a `whole` buffer is read from its level-0 row `row0`. */
void issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu, const void* input,
size_t from = 0, size_t to = (size_t)-1, int64_t row0 = 0) const;
bool is_whole(rad_buf v) const {
for (rad_buf w : whole) if (w == v) return true;
return false;
}
/* The tail's halo in level-0 rows: walked back from the last op, a buffer's margin is the most
* any reader of it needs, in its own rows -- a k x k conv adds k/2, reading through a 2x
* upsample halves it rounding up, and the depth-to-space shortcut halves it. -1 when the tail
* holds an op that is not row-local, or reads a whole buffer above level 0. */
int64_t band_halo() const {
if (band_from < 0 || ops.empty()) return -1;
std::vector<std::pair<rad_buf, int64_t>> need{ { ops.back().y.buf, 0 } };
auto get = [&](rad_buf v) -> int64_t {
for (const auto& e : need) if (e.first == v) return e.second;
return 0;
};
auto want = [&](rad_buf v, int64_t m) {
for (auto& e : need) if (e.first == v) { e.second = std::max(e.second, m); return; }
need.push_back({ v, m });
};
for (size_t i = ops.size(); i-- > (size_t)band_from;) {
const VOp& o = ops[i];
const int64_t my = get(o.y.buf);
switch (o.kind) {
case VOp::CONV: {
if (o.stride != 1) return -1;
const int64_t m = my + o.k / 2;
want(o.x.buf, o.up == 2 ? (m + 1) / 2 : m);
break;
}
case VOp::NORM: want(o.x.buf, my); break;
case VOp::LIN: want(o.x.buf, my); break;
case VOp::ADD: want(o.x.buf, my); want(o.z.buf, my); break;
case VOp::D2S: want(o.x.buf, (my + 1) / 2); break;
default: return -1;
}
}
int64_t h = 0;
for (size_t i = (size_t)band_from; i < ops.size(); ++i) {
const VOp& o = ops[i];
for (const VImg* v : { &o.x, &o.z })
if (v->buf && is_whole(v->buf)) {
if (v->lvl != 0) return -1;
h = std::max(h, get(v->buf));
}
}
return h;
}
};
inline void Vae::issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu,
const void* input, size_t from, size_t to, int64_t row0) const {
auto ptr = [&](const VImg& v) -> const void* {
if (!v.buf) return input;
const char* p = (const char*)rad_buf_ptr(c, v.buf);
return row0 && is_whole(v.buf) ? p + row0 * W0 * v.ch * (int64_t)sizeof(uint16_t) : p;
};
auto view = [&](const VImg& v, int64_t* H, int64_t* W) {
*H = side(H0, v.lvl, down);
*W = side(W0, v.lvl, down);
return RAD_P_T2(ptr(v), RAD_BF16, *H, *W * v.ch);
};
auto rows = [&](const VImg& v, int64_t cols) {
const int64_t H = side(H0, v.lvl, down), W = side(W0, v.lvl, down);
return RAD_P_T2(ptr(v), RAD_BF16, H * W * v.ch / cols, cols);
};
for (size_t i = from; i < to && i < ops.size(); ++i) {
const VOp& o = ops[i];
int64_t Hx, Wx, Hy, Wy;
switch (o.kind) {
case VOp::CONV: {
const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy);
RAD_ISSUE_N(c, o.op, Hy * Wy, x, RAD_W(o.w), RAD_W(o.b), y);
break;
}
case VOp::NORM: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), rows(o.y, o.y.ch));
break;
}
case VOp::ADD: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), rows(o.z, o.z.ch), rows(o.y, o.y.ch));
break;
}
case VOp::D2S:
case VOp::S2D: {
const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy);
RAD_ISSUE_N(c, o.op, Hy * Wy, x, y);
break;
}
case VOp::ATTN: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
const int64_t C = o.y.ch, n = H * W;
if (const VImg* v = value_of(i)) {
/* Separate q, k and v images. */
RAD_ISSUE_N(c, o.op, n, rows(o.x, C), rows(o.z, C), rows(*v, C), cu,
brows(o.y.buf, n));
} else {
/* q, k and v are column slices of the qkv rows, at its 3C pitch. */
RAD_ISSUE_N(c, o.op, n, bcol(o.x.buf, 0, C, n), bcol(o.x.buf, C, C, n),
bcol(o.x.buf, 2 * C, C, n), cu, brows(o.y.buf, n));
}
break;
}
case VOp::GNORM: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), RAD_W(o.b), RAD_NONE,
RAD_P_T2(rad_buf_ptr(c, gn_stats), RAD_F32, 1, 64 * (2 + 3 * 1024)),
rows(o.y, o.y.ch));
break;
}
case VOp::LIN: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), RAD_W(o.b), RAD_NONE,
rows(o.y, o.y.ch));
break;
}
}
}
}
} /* namespace arch */
} /* namespace rad */
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/flux3 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(flux3 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(flux3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/flux3.cpp)
+1273
View File
File diff suppressed because it is too large. Load diff
+11
View File
@@ -0,0 +1,11 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/flux3distilled -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see
# cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(flux3distilled LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(flux3distilled architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/flux3distilled.cpp)
+13
View File
@@ -0,0 +1,13 @@
/* flux3distilled -- arch/flux3 under the architecture name of FLUX.3 [klein]'s step-distilled
* release.
*
* The released pipeline is a `Flux3DistilledModularPipeline` and its base a
* `Flux3ModularPipeline`, so rad-convert names them `flux3distilled` and `flux3`. Both hold the same
* networks; the transformer's `flow_map` flag is what tells them apart inside the plugin. A
* separate .so because a plugin answers to one architecture name (spec §2.4). Everything else is
* arch/flux3/flux3.cpp.
*/
#define FLUX3_NS flux3distilled
#define FLUX3_ID "flux3distilled"
#include "../flux3/flux3.cpp"
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/gemma3 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(gemma3 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(gemma3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/gemma3.cpp)
File diff suppressed because it is too large. Load diff
+20 -183
View File
@@ -90,8 +90,7 @@
#include <arch/rad_arch.h>
#include <arch/rad_fp8.h>
#include <arch/rad_gemma4_chat.h>
#include "gemma4_dflash.h"
#include <arch/rad_gemma4_dflash.h>
#include <cmath>
#include <cstdint>
@@ -223,16 +222,15 @@ struct Model {
rad_weight w_tok = 0, w_onorm = 0;
rad_op op_embed = 0, op_embed_ar = 0, op_onorm = 0, op_gather = 0, op_logits = 0, op_cap = 0;
enum { MAX_TAPS = 8 };
enum { MAX_TAPS = Dflash1::MAX_TAPS };
int n_taps = 0;
int tap_layer[MAX_TAPS] = {};
rad_buf b_dfsrc = 0;
Dflash1 df{};
Dflash1::Wire dfw{};
rad_kvgroup kv_draft = 0;
bool have_df = false;
const char* tok_src = nullptr; /* the checkpoint's table, which the fp8 draft head copies */
const char* tok_src = nullptr; /* the checkpoint's table, which the 8-bit draft head copies */
std::vector<Layer> layers;
};
@@ -301,159 +299,19 @@ static rad_op decl_full_rope(RadBuilder* b, const Kind& k, int64_t rows, int64_t
/* ============================================================== the drafter */
/* z-lab's DFlash drafter (arch/common/rad_gemma4_dflash.h), past the trunk's layers, reading the
* taps the trunk copies into `dflash_src` and the trunk's tied table. */
static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx,
Model& m, int base_layer) {
Names& nm = m.nm;
Geom dg{};
RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "gemma4 DFlash"));
if (rad_meta_geti(meta, "draft.hidden_size", dg.n_embd) != dg.n_embd) {
fprintf(stderr, "radiance: gemma4: the drafter is %lld wide and the target %lld; it reads "
"the target's embedding and head, so it is not this target's drafter\n",
(long long)rad_meta_geti(meta, "draft.hidden_size", 0), (long long)dg.n_embd);
return RAD_E_UNSUPPORTED;
}
Dflash1::Config dc{};
dc.n_taps = m.n_taps;
dc.escale = m.escale;
/* v1 states its block at the top level; a SpecForge config nests it under dflash_config. */
long long trained = rad_meta_geti(meta, "draft.block_size", 0);
if (trained <= 0) trained = rad_meta_geti(meta, "draft.dflash_config.block_size", 0);
if (trained < 2) {
fprintf(stderr, "radiance: gemma4: the DFlash checkpoint states no block_size\n");
return RAD_E_FORMAT;
}
if ((long long)ctx->max_spec + 1 != trained) {
fprintf(stderr, "radiance: gemma4: the DFlash 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 "
"--num-speculative-tokens %lld (or `auto`).\n",
trained, trained - 1, ctx->max_spec, trained - 1);
return RAD_E_UNSUPPORTED;
}
dc.block = trained;
if (dg.n_layer > Dflash1::MAX_LAYERS) return RAD_E_UNSUPPORTED;
{
std::vector<int> full;
const char* lt = rad_meta_gets(meta, "draft.layer_types", nullptr);
if (lt) {
RAD_ARCH_TRY(parse_layer_kinds("gemma4", lt, {"full_attention"}, "sliding_attention",
&full));
if ((int64_t)full.size() != dg.n_layer) {
fprintf(stderr, "radiance: gemma4: the drafter's layer_types names %zu layers and "
"it has %lld\n", full.size(), (long long)dg.n_layer);
return RAD_E_INVAL;
}
} else {
full.assign((size_t)dg.n_layer, 1);
}
bool any_swa = false;
for (int64_t l = 0; l < dg.n_layer; ++l) {
dc.full[l] = full[(size_t)l];
any_swa = any_swa || !full[(size_t)l];
}
if (any_swa) {
dc.window = rad_meta_geti(meta, "draft.dflash_config.swa_window_size",
rad_meta_geti(meta, "draft.sliding_window", 0));
if (!rad_meta_geti(meta, "draft.use_sliding_window", 1) || dc.window <= 0) {
fprintf(stderr, "radiance: gemma4: the drafter names sliding layers and no "
"window\n");
return RAD_E_INVAL;
}
}
}
/* One unbounded cache for all the drafter's layers, because its full layer reads every
* position. The sliding layers bound themselves with their attention op's `window`, so the
* declared drafter window is 0 and the core stages the whole context. A separate window group
* for the sliding layers would save memory. */
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, 0, base_layer, &m.kv_draft));
const int64_t qd = dg.n_head * dg.head_dim;
const int64_t kvd = dg.n_head_kv * dg.head_dim;
int64_t qr = dg.max_seqs * dc.block;
if (qr > dg.max_tok) qr = dg.max_tok;
const int64_t sr = dg.max_seqs * dc.steps();
const int64_t tw = dc.n_taps * dg.n_embd;
Dflash1::Wire& dw = m.dfw;
dw.src = m.b_dfsrc;
dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3, {dg.max_tok, tw});
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, fp8_blocks(tw)});
dw.c = decl_b(b, nm.f("df_c"), dg.act_dtype, {dg.max_tok, dg.n_embd});
dw.cq = decl_b(b, nm.f("df_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd});
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)});
dw.ck = decl_b(b, nm.f("df_ck"), dg.act_dtype, {dg.max_tok, kvd});
dw.cv = decl_b(b, nm.f("df_cv"), dg.act_dtype, {dg.max_tok, kvd});
dw.x = decl_b(b, nm.f("df_x"), dg.act_dtype, {qr, dg.n_embd});
dw.h = decl_b(b, nm.f("df_h"), dg.act_dtype, {qr, dg.n_embd});
dw.hq = decl_b(b, nm.f("df_hq"), RAD_F8E4M3, {qr, dg.n_embd});
dw.hs = decl_b(b, nm.f("df_hs"), RAD_F32, {qr, fp8_blocks(dg.n_embd)});
dw.q = decl_b(b, nm.f("df_q"), dg.act_dtype, {qr, qd});
dw.k = decl_b(b, nm.f("df_k"), dg.act_dtype, {qr, kvd});
dw.v = decl_b(b, nm.f("df_v"), dg.act_dtype, {qr, kvd});
dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd});
dw.atq = decl_b(b, nm.f("df_atq"), RAD_F8E4M3, {qr, qd});
dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, fp8_blocks(qd)});
dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff});
dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff});
dw.ffq = decl_b(b, nm.f("df_ffq"), RAD_F8E4M3, {qr, dg.n_ff});
dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)});
dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd});
dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, dg.n_vocab});
if (Dflash1::head_sharded(dg)) {
const int64_t R = Dflash1::kTopR;
dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, R});
dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, R});
dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, R, 2});
dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * R, 2});
} else {
dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, 1});
}
if (!Dflash1::head_sharded(dg) && dg.world > 1) {
fprintf(stderr, "radiance: gemma4: the vocabulary (%lld) does not split evenly into whole "
"16-row blocks over %d ranks, which the drafter's sharded head needs\n",
(long long)dg.n_vocab_all, dg.world);
return RAD_E_UNSUPPORTED;
}
/* The draft, one row per draft position: [n_seq * steps, 1], i.e. [n_seq, steps] with pitch
* `steps`, read by the engine through the drafter declaration below. */
dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {sr, 1});
RAD_ARCH_TRY(m.df.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft", dw,
m.tok_src));
Dflash1::Trunk t{};
t.n_taps = m.n_taps;
t.escale = m.escale;
t.src = m.b_dfsrc;
t.w_tok = m.w_tok;
t.tok_src = m.tok_src;
t.base_layer = base_layer;
RAD_ARCH_TRY(Dflash1::declare_drafter(b, meta, ctx, m.nm, m.g, t, &m.df, &m.kv_draft));
m.have_df = true;
RadDrafterDecl drf{};
drf.name = "dflash";
drf.kind = RAD_DRAFT_BLOCK;
drf.depth = ctx->max_spec;
drf.block = dc.block; /* the anchor predicts nothing: block = depth + 1 */
drf.proposal = dw.tokens;
drf.proposal_pitch = dc.steps();
drf.window = 0; /* the full layer reads everything; see the group */
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id",
rad_meta_geti(meta, "draft.mask_token_id", -1));
if (drf.mask_token < 0) {
fprintf(stderr, "radiance: gemma4: the DFlash checkpoint declares no mask_token_id\n");
return RAD_E_FORMAT;
}
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
int nfull = 0;
for (int64_t l = 0; l < dg.n_layer; ++l) nfull += dc.full[l];
rad_note(b, "the DFlash drafter is declared: %lld layers at absolute %d..%d (%d full, %lld "
"sliding over %lld causal), %lld heads / %lld kv x %lld, ffn %lld, reading the "
"trunk at %d tap(s). ONE forward over %lld rows proposes %lld tokens; the head is "
"%s, argmax %s",
(long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1, nfull,
(long long)(dg.n_layer - nfull), (long long)dc.window, (long long)dg.n_head,
(long long)dg.n_head_kv, (long long)dg.head_dim, (long long)dg.n_ff, m.n_taps,
(long long)dc.block, (long long)dc.steps(),
m.df.fp8_head
? "the container's block-fp8 copy of the target's table (dflash.draft_head)"
: "the target's tied bf16 table",
Dflash1::head_sharded(dg) ? "per vocab shard, merged" : "over the whole vocabulary");
return RAD_OK;
}
@@ -662,7 +520,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* ---- the embedding scale and the rotary scaling the converter may have written. The scale
* is rounded to bf16 because the reference holds it in a bf16 buffer: sqrt(2816) = 53.066
* multiplies as 53.0. */
m.escale = rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)E)));
m.escale = embed_scale(E);
RAD_ARCH_TRY(yarn_from(g, meta, "", m.ks.hd));
if (g.yarn.factor != 0.0f || g.rope_scale != 1.0f) {
fprintf(stderr, "radiance: gemma4: --rope-scaling is not implemented for this family's "
@@ -794,24 +652,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* ---- the drafter's taps, declared when the container carries a DFlash drafter and this
* serve speculates. DFlash2 is refused by name: its convolutions and selector are another
* block. */
if (ctx->max_spec > 0) {
const char* da = rad_meta_gets(meta, "draft.architectures", "");
if (da && std::strstr(da, "DFlash2")) {
fprintf(stderr, "radiance: gemma4: the container carries a DFlash2 drafter; this plugin "
"serves the DFlash (v1) block z-lab publishes for Gemma 4\n");
return RAD_E_UNSUPPORTED;
}
if (da && std::strstr(da, "DFlash")) {
const char* ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr);
if (!ids) ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr);
m.n_taps = parse_layer_ids(ids, m.n_layer, m.tap_layer, Model::MAX_TAPS);
if (m.n_taps <= 0) {
fprintf(stderr, "radiance: gemma4: the drafter names no trunk layer this model "
"has; it is paired with a different target\n");
return RAD_E_UNSUPPORTED;
}
m.b_dfsrc = decl_b(b, nm.f("dflash_src"), RAD_BF16, {T, (int64_t)m.n_taps * E});
}
{
const int n = Dflash1::taps(meta, ctx, m.n_layer, m.tap_layer, Model::MAX_TAPS);
if (n < 0) return n;
m.n_taps = n;
if (n > 0) m.b_dfsrc = decl_b(b, nm.f("dflash_src"), RAD_BF16, {T, (int64_t)n * E});
}
m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
@@ -1869,15 +1714,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
out->draft_depth = 0;
const char* da = rad_meta_gets(meta, "draft.architectures", "");
if (da && std::strstr(da, "DFlash") && !std::strstr(da, "DFlash2")) {
long long bs = rad_meta_geti(meta, "draft.block_size", 0);
if (bs <= 0) bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 0);
if (bs > 1) {
out->draft_depth = (int)(bs - 1);
out->draft_depth_fixed = 1;
}
}
(void)dflash_probe(meta, out);
return RAD_OK;
}
-682
View File
@@ -1,682 +0,0 @@
/* gemma4_dflash.h -- the DFlash (v1) block-diffusion drafter, as z-lab trains it for Gemma 4.
*
* ============================== WHAT IT IS ==============================
*
* rad_block_dflash2.h without DFlash2's additions (the per-layer dynamic convolutions around
* attention and the feed-forward, and the candidate selector). The original DFlash is a small
* Qwen3-shaped transformer that denoises one anchor token plus `block - 1` mask tokens in one
* forward and takes every position's argmax from the target's lm_head.
*
* context pass, one row a committed token:
* c = hidden_norm(fc(concat of the trunk's residual stream at target_layer_ids)))
* for each layer: k = k_norm(k_proj(c)) then rope; v = v_proj(c); kv_store(k, v)
*
* query pass, `block` rows a sequence:
* x = embed(anchor, mask, ...) * sqrt(hidden) <- Gemma's embedding scale, see below
* for each layer:
* h = input_layernorm(x)
* q, k, v = q_proj(h), k_proj(h), v_proj(h); q_norm, k_norm; rope; kv_store
* x += o_proj(attention(q, cache)) sliding layers causal over a 2048 window,
* the full layer non-causal over everything
* x += down(silu(gate(h')) * up(h')), h' = post_attention_layernorm(x)
* x = norm(x)
* over the mask rows: logits = lm_head(x) [the target's]; draft = argmax
*
* ============================== THE THREE GEMMA-SPECIFIC FACTS ==============================
*
* From vLLM PR #41703. Getting any of them wrong costs only acceptance, since every draft is
* verified against the trunk.
*
* The embedding is scaled. Gemma multiplies its token embedding by sqrt(hidden_size), stored as
* bf16 (53.0 at 2816), and the drafter was trained through the target's embedding module, which
* applies it. `embed_lookup`'s `mult` carries it.
*
* The sliding layers are causal and the full layer is not. The checkpoint's `layer_types` names
* four sliding layers and one full one, and the PR's test pins `causal True` on the sliding
* layers and `False` on the full one, so this block declares two attention ops and issues the one
* each layer's type names.
*
* The logits are soft-capped, which is deliberately ignored: the draft is an argmax, and
* cap * tanh(x / cap) is strictly increasing.
*
* ============================== THE HEAD ==============================
*
* The target's own head, read in bf16 by an ordinary `gemm_nt` over the gathered mask rows. Gemma
* ties it to the embedding, so it is the weight the trunk's `embed_lookup` and `logits_gemm` read
* and costs no extra bytes. It is vocab-sharded with the trunk: the top-1 runs over this rank's
* slice and the ranks' candidates merge exactly (`row_topk` at R = 2 -> `all_gather` ->
* `pair_argmax`; R = 2 because the gather moves 16-byte rows, see kTopR).
*
* The bf16 head (262144 x 2816 x 2 bytes) is the widest read on the draft path, about 566 us of a
* 26B-A4B decode step at tp 4 on 4x R9700. So where the container holds a block-fp8 copy of the
* table under its own name, `dflash.draft_head.weight` (one checkpoint tensor, two logical
* weights, as in rad_block_dflash2.h), made by the recipe line
*
* dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
*
* the head is `gemm_nt_q` over that copy at fp8a8, half the bytes, with the argmax over its
* coarser logits. Drafts are still verified, so the copy can change proposals but never accepted
* text. Without the copy, or in another encoding, the bf16 table is read. The copy costs half the
* table's bytes again (176 MiB per rank at tp 4). There is no rerank against the bf16 table:
* DFlash2's rerank needs the target's head in fp8 or int8, which a tied Gemma head is not.
*
* ============================== THE LINEARS ARE FP8 ==============================
*
* As in DFlash2, since the drafter is read whole on every decode step: the container must be
* converted with a recipe that makes the six linears block fp8 (or MXFP4). declare() refuses a bf16
* one by name rather than letting the loader fail on a view.
*/
#ifndef GEMMA4_DFLASH_H
#define GEMMA4_DFLASH_H
#include <arch/rad_arch.h>
#include <arch/rad_fp8.h>
#include <cstdio>
#include <cstring>
namespace gemma4 {
using namespace rad::arch;
/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no
* transform (a recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`). */
inline bool block_fp8_128(const RadEncoding& e) {
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
return rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] &&
e.plane[0].dtype == RAD_F8E4M3 && sc && sc->dtype == RAD_BF16 &&
sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK;
}
struct Dflash1 {
enum { MAX_LAYERS = 8 };
struct Config {
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
int64_t block = 0; /* query rows per sequence: the anchor plus block - 1 masks */
int64_t window = 0; /* the sliding layers' window; 0 for none */
int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */
double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */
int64_t steps() const { return block - 1; }
};
struct Wire {
/* the context pass */
rad_buf src = 0, srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] bf16 | e4m3 | f32 */
rad_buf c = 0, cq = 0, cs = 0; /* [max_tok, n_embd] */
rad_buf ck = 0, cv = 0; /* [max_tok, kv_dim] -- see rad_block_dflash2.h */
/* the query pass */
rad_buf x = 0, h = 0, hq = 0, hs = 0; /* [qrows, n_embd] */
rad_buf q = 0, k = 0, v = 0; /* [qrows, q_dim | kv_dim | kv_dim] */
rad_buf attn = 0, atq = 0, ats = 0; /* [qrows, q_dim] */
rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */
rad_buf ffn = 0, ffq = 0, ffs = 0; /* [qrows, n_ff] */
/* the head, one row per draft position */
rad_buf sel_h = 0; /* [srows, n_embd] */
rad_buf selq = 0, sels = 0; /* [srows, n_embd] e4m3 | f32, the fp8 head's */
rad_buf dlog = 0; /* [srows, n_vocab on this rank] bf16 */
rad_buf cand = 0, unary = 0; /* [srows, kTopR] i32 | f32 -- this rank's best */
rad_buf dpair = 0, dgath = 0; /* [srows, kTopR, 2] | [srows, world * kTopR, 2] f32 */
rad_buf tokens = 0; /* [srows, 1] i32: the draft, pitch `steps` */
};
Geom g{}; /* the drafter's geometry */
Config cfg{};
Wire w{};
int first_layer = 0;
int64_t qrows = 0, crows = 0, srows = 0, gated_rows = 0;
rad_kvgroup kv = 0;
bool sharded = false;
DenseFP8 w_fc{};
rad_weight w_hnorm = 0, w_norm = 0;
rad_weight w_tok = 0; /* the target's table: embedding and head */
DenseFP8 w_dh{}; /* its block-fp8 copy, the head where it is stored */
bool fp8_head = false;
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
DenseFP8 w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{};
rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {};
DenseFP8 w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{};
rad_op op_qsrc = 0, op_cfc = 0, op_cnorm = 0, op_qc = 0, op_crope = 0, op_cstore = 0;
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
rad_op op_embed = 0, op_embed_ar = 0, op_qh = 0, op_qat = 0, op_qff = 0;
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {};
/* The residual add, norm and quantiser in one launch where `rmsnorm_quant_fp8` is served
* (libr4d): op_anq[i] for the attention input (layer 0's without the add) and op_fnq[i] for
* the feed-forward input. Zero where not served; the `add` / `rmsnorm` / `quant_act_fp8` chain
* is issued instead. */
rad_op op_anq[MAX_LAYERS] = {}, op_fnq[MAX_LAYERS] = {};
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
rad_op op_op[MAX_LAYERS] = {}, op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {};
rad_op op_gu[MAX_LAYERS] = {}, op_gug[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn_swa = 0, op_attn_full = 0;
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
rad_op op_gather = 0, op_qsel = 0, op_head = 0, op_topk = 0, op_dgather = 0, op_pick = 0;
/* Candidates each rank contributes under a sharded head. The draft needs one, but the gather
* moves whole 16-byte words per row and an (int32 id, f32 value) pair is 8 bytes, so R = 1 is
* refused at launch (as rad_block_mtp_hc.h states). Two pairs make one word; `pair_argmax`
* reduces the world * 2 of them to the global top-1. */
static constexpr int64_t kTopR = 2;
static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); }
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
rad_kvgroup group, rad_weight tok_embd, const char* ck, const Wire& wire,
const char* tok_src);
void context(RadCtx* c, const RadBatch* batch) const;
void step(RadCtx* c, const RadBatch* batch) const;
private:
int64_t q_dim() const { return g.n_head * g.head_dim; }
int64_t kv_dim() const { return g.n_head_kv * g.head_dim; }
/* The six linears must be quantised by the recipe. DenseFP8 declares E4M3 (or MXFP4) views
* whatever the container holds, and the loader's error for a bf16 weight read through an fp8
* view would name the view, not the missing recipe. */
static int need_quantised(RadBuilder* b, const char* wn) {
RadEncoding e{};
if (!weight_enc(b, wn, &e) || e.n_planes <= 0) return RAD_OK; /* nothing to ask yet */
const uint32_t dt = e.plane[0].dtype;
if (dt == RAD_F8E4M3 || dt == RAD_FP4E2M1) return RAD_OK;
fprintf(stderr, "radiance: gemma4: the DFlash drafter's '%s' is stored %s. Its six linears "
"are served block fp8 (or MXFP4): convert with a recipe that names them, "
"e.g. `dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 "
"scale=bf16` and the same for fc, attn_k/v/output, ffn_gate_up and "
"ffn_down.\n", wn, rad_dtype_name(dt));
return RAD_E_DTYPE;
}
};
/* ------------------------------------------------------------------------------ declare */
inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
int base_layer, rad_kvgroup group, rad_weight tok_embd,
const char* ck, const Wire& wire, const char* tok_src) {
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
if (!ck || !w_tok || !tok_src) return RAD_E_INVAL;
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
fprintf(stderr, "radiance: gemma4: the drafter has %lld layers; this block carries at most "
"%d\n", (long long)g.n_layer, MAX_LAYERS);
return RAD_E_UNSUPPORTED;
}
if (cfg.block < 2 || cfg.n_taps <= 0) return RAD_E_INVAL;
const int64_t qd = q_dim(), kvd = kv_dim();
crows = g.max_tok;
qrows = g.max_seqs * cfg.block;
if (qrows > g.max_tok) qrows = g.max_tok;
srows = g.max_seqs * cfg.steps();
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
sharded = head_sharded(g);
/* ---------------------------------------------------------------- model-scope weights */
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, cfg.n_taps * g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
{ nm.ckpt("%s.fc.weight", ck) }));
RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.fc.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
/* ---------------------------------------------------------------- per-layer weights */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
const RadWeightGroup gl = grp_layer(first_layer + i);
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_norm.weight", i),
nm.ckpt("%s.layers.%d.input_layernorm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_norm.weight", i),
nm.ckpt("%s.layers.%d.post_attention_layernorm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i),
nm.ckpt("%s.layers.%d.self_attn.q_norm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i),
nm.ckpt("%s.layers.%d.self_attn.k_norm.weight", ck, i)));
w_anorm[i] = decl_w(b, nm.f("dflash.blk.%d.attn_norm.weight", i), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
w_fnorm[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
/* The declared names match rad_block_dflash2.h's, so one recipe quantises both
* drafters. */
RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dflash.blk.%d.attn_q", i), qd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
{ nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dflash.blk.%d.attn_k", i), kvd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
{ nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
{ nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_o[i].declare(b, nm, nm.f("dflash.blk.%d.attn_output", i), g.n_embd, qd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl,
{ nm.ckpt("%s.layers.%d.self_attn.o_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_gu[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_gate_up", i), 2 * g.n_ff,
g.n_embd, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
{ nm.ckpt("%s.layers.%d.mlp.gate_proj.weight", ck, i),
nm.ckpt("%s.layers.%d.mlp.up_proj.weight", ck, i) },
{ g.n_ff, g.n_ff }));
RAD_ARCH_TRY(w_dn[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_down", i), g.n_embd, g.n_ff,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl,
{ nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) }));
for (const char* s : { "attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate_up",
"ffn_down" })
RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.blk.%d.%s.weight", i, s)));
}
/* ---------------------------------------------------------------- attention: two kinds
* Declared before either kv_store, which reads `block_size` back from the resolved kernel.
* Both read the one KV group, so whichever resolves first answers for it. */
auto attn = [&](int causal, int64_t window) {
return rw(b, RAD_OP(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", causal),
RAD_INT("window", window), RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.q}, {w.attn});
};
bool any_full = false, any_swa = false;
for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true;
if (any_swa) op_attn_swa = attn(1, cfg.window);
if (any_full) op_attn_full = attn(0, 0);
/* ---------------------------------------------------------------- the context pass */
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.src}, {w.srcq, w.srcs});
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_hnorm)),
{w.c}, {w.c});
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.c}, {w.cq, w.cs});
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck});
op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv});
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_kn[i])),
{w.ck}, {w.ck});
}
op_crope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.ck}, {w.ck});
op_cstore = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.ck, w.cv}, {});
/* ---------------------------------------------------------------- the query pass */
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
RAD_INT("vocab_offset", g.vocab_off), RAD_F64("mult", cfg.escale)),
RAD_WEIGHTS(w_tok)),
{}, {w.x});
if (g.world > 1)
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, qrows * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
RAD_NOWEIGHTS),
{w.x}, {w.x});
op_qh = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.h}, {w.hq, w.hs});
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.attn}, {w.atq, w.ats});
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.ffn}, {w.ffq, w.ffs});
/* x's norm under `gain`, quantised into hq|hs, in one launch; with `add`, the
* fused_add_rms_norm form (x += h first). It computes exactly the chain's result: the norm of
* the bf16-rounded sum and the codes of the bf16-rounded norm (libr4d/r4d_rows.cpp). */
auto norm_quant = [&](rad_weight gain, bool add) -> rad_op {
const rad_op h = RAD_OP(b, "rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", g.dtype), RAD_F64("wadd", 0.0)),
RAD_WEIGHTS(gain));
return add ? rw(b, h, {w.h, w.x}, {w.x, w.hq, w.hs}) : rw(b, h, {w.x}, {w.hq, w.hs});
};
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_anorm[i])),
{w.x}, {w.h});
op_anq[i] = norm_quant(w_anorm[i], l > 0);
op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.hq, w.hs}, {w.q});
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.k});
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.v});
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_qn[i])),
{w.q}, {w.q});
op_kn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv),
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_kn[i])),
{w.k}, {w.k});
op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.atq, w.ats}, {w.h});
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_fnorm[i])),
{w.x}, {w.h});
op_fnq[i] = norm_quant(w_fnorm[i], true);
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.hq, w.hs}, {w.gate_up});
/* The gate_up|silu|quant fold where it resolves, else the pair (rad_block_dflash2.h's
* rule, band included). */
{
const int64_t hi = qrows < 64 ? qrows : 64;
if (hi > 0 && !w_gu[i].mx) {
op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff),
RAD_INT("K", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")),
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
{w.hq, w.hs}, {w.ffq, w.ffs});
if (op_gug[i]) gated_rows = hi;
}
}
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
}
op_qrope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.q}, {w.q});
op_krope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.k}, {w.k});
op_store = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.k, w.v}, {});
op_act = rw(b, RAD_OP(b, "silu_mul",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.gate_up}, {w.ffn});
if (g.world > 1)
op_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, qrows * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
RAD_INT("min_bytes", g.wire_min_bytes)),
RAD_NOWEIGHTS),
{w.h}, {w.h});
op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h}, {w.x});
op_final = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h});
/* ---------------------------------------------------------------- the head
* The mask rows (offsets 1..block-1 of each block, named by out_ids) are gathered contiguous,
* projected onto this rank's slice of the target's vocabulary, and the argmax taken. Sharded,
* each rank reports its best kTopR as global ids with logits; these are all-gathered and
* reduced to the global top-1 by `pair_argmax` (ties to the lower id), which is exact since the
* global winner is its own shard's first. */
op_gather = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.h}, {w.sel_h});
/* The fp8 copy, where the container holds one (see the file header). The name map comes first
* since it is how the encoding is looked up; rad-convert writes only declared weights. The
* copy is row-sharded like the table, so this rank's rows are the same vocabulary slice and
* `vocab_off` holds. */
const char* dhn = nm.f("dflash.draft_head.weight");
RAD_ARCH_TRY(map_copy(b, dhn, tok_src));
RadEncoding he{};
fp8_head = weight_enc(b, dhn, &he) && block_fp8_128(he);
if (fp8_head) {
if (g.n_vocab % RAD_FP8_BLOCK || g.n_embd % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: gemma4: the fp8 draft head is %lldx%lld a rank, which "
"is not whole %d-row scale blocks\n",
(long long)g.n_vocab, (long long)g.n_embd, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
const int shard = g.world > 1 ? RAD_SHARD_ROW : RAD_SHARD_NONE;
w_dh.w = decl_view(b, dhn, nullptr, "codes", RAD_F8E4M3, { g.n_vocab, g.n_embd },
RAD_ACCESS_PER_TOKEN, shard, grp_model());
w_dh.s = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_BF16,
{ fp8_blocks(g.n_vocab), fp8_blocks(g.n_embd) }, RAD_ACCESS_PER_TOKEN,
shard, grp_model());
if (!w_dh.w || !w_dh.s) return RAD_E_INVAL;
w.selq = decl_b(b, nm.f("df_selq"), RAD_F8E4M3, {srows, g.n_embd});
w.sels = decl_b(b, nm.f("df_sels"), RAD_F32, {srows, fp8_blocks(g.n_embd)});
op_qsel = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.sel_h}, {w.selq, w.sels});
op_head = w_dh.gemm(b, srows, g.n_vocab, g.n_embd, {w.selq, w.sels}, {w.dlog});
} else {
op_head = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_tok)),
{w.sel_h}, {w.dlog});
}
if (sharded) {
op_topk = rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
RAD_INT("R", kTopR), RAD_INT("vocab_off", g.vocab_off),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.cand, w.unary, w.dpair});
/* Row-interleaved, so one draft position's pairs from every rank land side by side. */
op_dgather = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", srows * kTopR * 2), RAD_STR("dtype", "f32"),
RAD_INT("row", kTopR * 2)),
RAD_NOWEIGHTS),
{w.dpair}, {w.dgath});
op_pick = rw(b, RAD_OP(b, "pair_argmax",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.world * kTopR),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{w.dgath}, {w.tokens});
if (!op_pick) {
fprintf(stderr, "radiance: gemma4: the sharded draft head needs `pair_argmax` on the "
"device, and no loaded kernel library serves it there\n");
return RAD_E_UNSUPPORTED;
}
} else {
op_topk = rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
RAD_INT("R", 1), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.tokens, w.unary});
}
return RAD_OK;
}
/* ------------------------------------------------------------------------------ the context pass */
inline void Dflash1::context(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (T <= 0) return;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
brows(w.c, T), RAD_NONE, w_fc.bref());
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref());
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]),
brows(w.ck, T));
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_cstore, T, brows(w.ck, T), brows(w.cv, T), praw(slot, RAD_I32, T),
kv_cache(kv, first_layer + i));
}
}
/* ------------------------------------------------------------------------------ the query pass */
inline void Dflash1::step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (T <= 0) return;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int32_t* used = kvb ? kvb->seqused : nullptr;
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T));
if (op_embed_ar)
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE);
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
const rad_op op_attn = cfg.full[i] ? op_attn_full : op_attn_swa;
/* The attention input, with the last layer's residual add where one launch takes both. */
if (op_anq[i]) {
RAD_ISSUE_N(c, op_anq[i], T, l > 0 ? brows(w.h, T) : brows(w.x, T),
l > 0 ? brows(w.x, T) : RAD_NONE, RAD_W(w_anorm[i]), brows(w.hq, T),
brows(w.hs, T), RAD_NONE);
} else {
RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T));
}
RAD_ISSUE_N(c, op_qp[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref());
RAD_ISSUE_N(c, op_kp[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_vp[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
kv_cache(kv, first_layer + i));
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
brows(w.q, T), kv_cache(kv, first_layer + i),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn, T));
RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref());
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
if (op_fnq[i]) {
RAD_ISSUE_N(c, op_fnq[i], T, brows(w.h, T), brows(w.x, T), RAD_W(w_fnorm[i]),
brows(w.hq, T), brows(w.hs, T), RAD_NONE);
} else {
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T));
RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T));
}
if (op_gug[i] && T <= gated_rows) {
RAD_ISSUE_N(c, op_gug[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.ffq, T), brows(w.ffs, T),
RAD_NONE);
} else {
RAD_ISSUE_N(c, op_gu[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
w_gu[i].bref());
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T));
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn, T), brows(w.ffq, T), brows(w.ffs, T));
}
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T),
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
/* the residual add, unless the next layer's input norm takes it */
if (l + 1 == g.n_layer || !op_anq[i + 1])
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T));
}
RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
const int64_t S = batch->n_out;
if (S <= 0) return;
RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S));
if (fp8_head) {
RAD_ISSUE_N(c, op_qsel, S, brows(w.sel_h, S), brows(w.selq, S), brows(w.sels, S));
RAD_ISSUE_N(c, op_head, S, brows(w.selq, S), brows(w.sels, S), RAD_W(w_dh.w),
RAD_W(w_dh.s), brows(w.dlog, S), RAD_NONE, w_dh.bref());
} else {
RAD_ISSUE_N(c, op_head, S, brows(w.sel_h, S), RAD_W(w_tok), brows(w.dlog, S));
}
if (sharded) {
RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
brows(w.dpair, S));
RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S));
RAD_ISSUE_N(c, op_pick, S, brows(w.dgath, S), brows(w.tokens, S), RAD_NONE);
} else {
RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.tokens, S), brows(w.unary, S),
RAD_NONE);
}
}
} /* namespace gemma4 */
#endif /* GEMMA4_DFLASH_H */
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(glm5next LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(glm5next architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/glm5next.cpp)
+557
View File
@@ -0,0 +1,557 @@
/* glm5next -- GLM-5.3-Flash (`model_type: glm5_next`) from AMD's Quark MXFP4 export: four mHC
* residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers behind a DSA indexer,
* 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32
* scales, each weight served as the container stores it; its MTP layer is a serial drafter, and
* its vision tower is declared when the container carries it and the deployment asks for an
* encoder. docs/ARCHITECTURES.md describes the model and its traps.
*
* The blocks live in arch/common (installed as <arch/...>), one a file:
*
* rad_block_glm_mhc.h ManifoldConn the four-stream residual read and write
* rad_block_glm_kda.h GlmKda the 34 linear layers, KdaState their recurrence
* rad_block_glm_mla.h GlmMla the 11 sparse MLA layers, MlaLatent their core
* rad_block_glm_indexer.h GlmIndexer the DSA indexer, DsaCache its key cache and selection
* rad_block_glm_router.h GlmRouter the correction-bias router (through MoeFP8)
* rad_block_glm_mtp.h GlmMtp the draft head around the plugin's layer 45
* rad_block_glm_vision.h GlmVision the tower, MediaRows its rows over the embeddings
* rad_glm_tp.h GlmTp the shards, the row runs and the split thresholds
*
* This file declares the buffers the blocks share, places the blocks and issues the step's
* order. Declaration order is liveness (the buffer plan takes lifetimes from it) and the issue
* order is the recorded pass, so both are kept as they read here. This plugin uses only the
* public ABI and the installed common headers. */
#include <arch/rad_block_glm_mhc.h>
#include <arch/rad_block_glm_kda.h>
#include <arch/rad_block_glm_mla.h>
#include <arch/rad_block_glm_indexer.h>
#include <arch/rad_block_glm_mtp.h>
#include <arch/rad_block_glm_vision.h>
#include <arch/rad_block_mlp_fp8.h>
#include <arch/rad_block_moe_fp8.h>
#include <memory>
namespace glm5next {
using namespace rad::arch;
struct Layer {
bool full = false, draft = false;
ManifoldConn attn_hc{}, ffn_hc{};
NormQuantFP8 norm{};
GlmKda kda{};
GlmMla mla{};
GlmIndexer index{};
MlpFP8 dense{};
MoeFP8 moe{};
};
struct Model {
Names nm{};
Geom g{};
std::vector<Layer> layers;
rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0;
/* The streams and the step's stream-wide buffers. */
rad_buf h0 = 0, h1 = 0, x = 0, y = 0, post = 0, comb = 0, final_hidden = 0, logit_input = 0,
logits = 0;
ActFP8 act{};
/* The blocks' wires: one set of activations, shared by every layer of a kind. */
GlmKda::Wire kw{};
GlmMla::Wire aw{};
GlmIndexer::Wire iw{};
MlpFP8::Wire dw{};
MoeFP8::Wire mw{};
rad_weight token = 0, head = 0, final_gain = 0;
rad_op embed = 0, embed_ar = 0, expand = 0, contract = 0, norm = 0, gather = 0, head_op = 0;
/* The draft head and its layer, declared only when the deployment speculates. */
bool have_mtp = false;
GlmMtp mtp{};
Layer draft{};
/* Media: the tower, and its rows over the trunk's embedding (the draft head scatters its own). */
bool media = false;
GlmVision vit{};
MediaRows mrows{};
};
static std::unique_ptr<Model> models[MAX_RANKS];
static thread_local std::unique_ptr<Model> probe_model;
static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) {
char nested[160];
std::snprintf(nested, sizeof nested, "text_config.%s", key);
return rad_meta_geti(m, key, rad_meta_geti(m, nested, fallback));
}
static rad_op copy(RadBuilder* b, const Geom& g, rad_buf x, rad_buf y) {
return rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{ x }, { y });
}
static rad_op norm(RadBuilder* b, const Geom& g, rad_weight w, rad_buf x, rad_buf y) {
return rw(b,
RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w)),
{ x }, { y });
}
/* ------------------------------------------------------------------ the shared activations */
static int stream_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok;
m.h0 = decl_b(b, nm.f("manifold"), RAD_BF16, { T, 16384 });
m.h1 = decl_b(b, nm.f("manifold_mid"), RAD_BF16, { T, 16384 });
m.x = decl_b(b, nm.f("collapsed"), RAD_BF16, { T, 4096 });
m.y = decl_b(b, nm.f("attn_delta"), RAD_BF16, { T, 4096 });
m.post = decl_b(b, nm.f("post"), RAD_F32, { T, 4 });
m.comb = decl_b(b, nm.f("mix"), RAD_F32, { T, 16 });
m.act.x = decl_b(b, nm.f("normalized"), RAD_BF16, { T, 4096 });
RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normalized", 4096));
m.final_hidden = decl_b(b, nm.f("final_hidden"), RAD_BF16, { T, 4096 }, RAD_BUF_PERSIST);
m.logit_input = decl_b(b, nm.f("logit_input"), RAD_BF16, { g.max_logit_rows, 4096 });
m.logits = decl_b(b, nm.f("logits"), RAD_F32, { g.max_logit_rows, g.n_vocab });
return rad_declare_logits(b, m.logits);
}
static int kda_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok, W = GlmTp::kda_width(g.world);
auto bf = [&](const char* n, int64_t width) {
return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width });
};
auto& kw = m.kw;
kw.input = m.act.x;
kw.out = m.y;
kw.forget_low = bf("forget_low", 128);
kw.gate_low = bf("gate_low", 128);
kw.core.qkv = bf("qkv", 3 * W);
kw.core.conv = bf("convolved", 3 * W);
kw.core.a = bf("forget", W);
kw.core.beta = bf("beta", GlmTp::heads(g.world));
kw.core.gate = bf("gate", W);
kw.core.out = bf("recurrent_out", W);
return RAD_OK;
}
/* The head form's buffers, then the selection planes the indexer writes and the MLA reads. Under
* TP the selection planes hold every rank's run of rows, which can reach past the step
* (DsaCache::part_rows). */
static int mla_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok, H = GlmTp::heads(g.world), Q = GlmTp::mla_width(g.world);
auto bf = [&](const char* n, int64_t width) {
return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width });
};
auto& aw = m.aw;
aw.input = m.act;
aw.q_raw = bf("q_raw", 1536);
aw.kv_raw = bf("kv_raw", 512);
aw.q_low.x = bf("q_low", 1536);
RAD_ARCH_TRY(aw.q_low.declare_qs(b, nm, g, "q_low", 1536));
aw.latent = bf("latent", 512);
aw.out = m.y;
aw.core.q = bf("query", Q);
aw.core.q_latent = decl_b(b, nm.f("q_latent"), RAD_BF16, { T, H, 512 });
aw.core.attn_latent = decl_b(b, nm.f("attn_latent"), RAD_BF16, { T, H, 512 });
aw.attn.x = bf("expanded", Q);
RAD_ARCH_TRY(aw.attn.declare_qs(b, nm, g, "expanded", Q));
aw.core.out = aw.attn.x;
const int64_t part = g.world > 1 ? DsaCache::part_rows(T, g.world) : 0;
const int64_t TQ = g.world > 1 ? std::max(T, g.world * part) : T;
aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { TQ, 513 });
aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { TQ });
return RAD_OK;
}
static int indexer_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok;
const int64_t part = g.world > 1 ? DsaCache::part_rows(T, g.world) : 0;
const int64_t TQ = g.world > 1 ? std::max(T, g.world * part) : T;
const int64_t work = (T + 3) / 4 + g.max_seqs, blocks = (g.max_ctx + 3) / 4 + 1;
auto bf = [&](const char* n, int64_t width) {
return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width });
};
auto& iw = m.iw;
iw.input = m.act.x;
iw.q_low = m.aw.q_low.x;
iw.q_wide = bf("index_query", 4096);
iw.kg_raw = bf("index_key_gate", 256);
auto& c = iw.cache;
c.query = decl_b(b, nm.f("index_heads"), RAD_BF16, { T * 32, 128 });
c.codes = decl_b(b, nm.f("index_codes"), RAD_F8E4M3, { TQ * 32, 128 });
c.scales = decl_b(b, nm.f("index_scales"), RAD_F32, { TQ * 32, 1 });
c.gate = decl_b(b, nm.f("index_head_weights"), RAD_F32, { TQ, 32 });
c.kg = bf("index_normalized_key_gate", 256);
c.stage = decl_b(b, nm.f("pool_stage"), RAD_BF16, { work * 4, 256 });
c.page = decl_b(b, nm.f("pool_page"), RAD_I32, { work });
c.bpos = decl_b(b, nm.f("pool_pos"), RAD_I32, { work });
c.nc = decl_b(b, nm.f("pool_count"), RAD_I32, { g.max_seqs });
c.pooled = decl_b(b, nm.f("pool_codes"), RAD_F8E4M3, { work, 128 });
c.pool_scale = decl_b(b, nm.f("pool_scales"), RAD_F32, { work, 1 });
/* A split step scores one run of rows a rank and an unsplit one is under GlmTp::kSplitRows:
* 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;
c.score = decl_b(b, nm.f("index_scores"), RAD_F32, { scored, blocks });
c.selected = m.aw.core.selected;
c.length = m.aw.core.length;
c.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T });
if (g.world > 1) {
c.cu_part = decl_b(b, nm.f("index_part_bounds"), RAD_I32, { g.max_seqs + 1 });
c.sel_part = decl_b(b, nm.f("selected_part"), RAD_I32, { part, 513 });
c.len_part = decl_b(b, nm.f("length_part"), RAD_I32, { part });
}
return RAD_OK;
}
static int ffn_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok, F = GlmTp::expert_width(g.world);
auto bf = [&](const char* n, int64_t width) {
return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width });
};
auto& dw = m.dw;
dw.x = m.x;
dw.h = m.act;
dw.gate_up = bf("dense_gate_up", 2 * g.n_ff);
dw.ffn.x = bf("dense_ff", g.n_ff);
RAD_ARCH_TRY(dw.ffn.declare_qs(b, nm, g, "dense_ff", g.n_ff));
auto& mw = m.mw;
mw.x = m.x;
mw.h = m.act;
mw.logits = decl_b(b, nm.f("router_logits"), RAD_F32, { T, 288 });
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.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { 289 });
mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 });
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.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { T * 8, 2 * F });
mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { T * 8, F });
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * 8));
mw.edn = decl_b(b, nm.f("expert_down"), RAD_BF16, { T * 8, 4096 });
mw.sgu = bf("shared_gate_up", 2 * F);
mw.sff.x = bf("shared_ff", F);
RAD_ARCH_TRY(mw.sff.declare_qs(b, nm, g, "shared_ff", F));
mw.sout = bf("shared_out", 4096);
mw.sgate = bf("shared_one", 1);
return RAD_OK;
}
static int kv_groups(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
RadKVGroupDecl d{};
d.kind = RAD_KV_FULL;
d.dtype = RAD_BF16;
d.n_head_kv = 1;
d.head_dim = 256;
m.latent = rad_decl_kv_group(b, nm.f("kv_latent"), &d);
d = {};
d.kind = RAD_KV_LINEAR;
d.dtype = RAD_BF16;
d.n_head_kv = 1;
d.state_dim[0] = 4 + g.max_spec;
d.state_dim[1] = 256;
m.tail = rad_decl_kv_group(b, nm.f("kv_index_tail"), &d);
d = {};
d.kind = RAD_KV_LINEAR;
d.dtype = RAD_F32;
d.n_head_kv = GlmTp::heads(g.world);
d.state_dim[0] = d.state_dim[1] = 128;
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 * GlmTp::kda_width(g.world);
d.conv_width = 4;
m.conv = rad_decl_kv_group(b, nm.f("kv_kda_conv"), &d);
// The index group is declared by the first indexer, right before its cache consumer.
return m.latent && m.tail && m.state && m.conv ? RAD_OK : RAD_E_INVAL;
}
/* ------------------------------------------------------------------ one layer */
static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool draft) {
const auto& g = m.g;
lay.draft = draft;
lay.full = draft || l % 4 == 3;
const char* pre = nm.ckpt("model.language_model.layers.%d", l);
const char* ap = nm.ckpt("%s.self_attn", pre);
rad_buf input = draft ? m.mtp.x : m.x;
ManifoldConn::Config hc;
hc.eps = g.eps;
if (!draft) {
ManifoldConn::Wire a{ m.h0, m.x, m.y, m.h1, m.post, m.comb };
ManifoldConn::Src as{ nm.ckpt("%s.hc_attn_fn", pre), nm.ckpt("%s.hc_attn_scale", pre),
nm.ckpt("%s.hc_attn_base", pre) };
RAD_ARCH_TRY(lay.attn_hc.declare(b, nm, g, l, nm.f("blk.%d.hc_attn", l), hc, a, as, true));
}
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)));
const auto gain =
decl_w(b, nn, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
RAD_ARCH_TRY(lay.norm.declare(b, g, gain, input, m.act, 4096));
if (lay.full) {
RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, m.aw, ap, m.latent, true, true));
DsaCache::Config c;
c.blocks = (g.max_ctx + 3) / 4 + 1;
c.work = (g.max_tok + 3) / 4 + g.max_seqs;
c.ring = 4 + g.max_spec;
RAD_ARCH_TRY(lay.index.declare(b, nm, g, l, m.iw, nm.ckpt("%s.indexer", ap), c, m.latent,
m.tail, &m.index));
RAD_ARCH_TRY(lay.mla.declare_finish(b, nm, ap));
} else {
KdaState::Src s{ nm.ckpt("%s.q_conv1d.weight", ap), nm.ckpt("%s.k_conv1d.weight", ap),
nm.ckpt("%s.v_conv1d.weight", ap), nm.ckpt("%s.A_log", ap),
nm.ckpt("%s.dt_bias", ap), nm.ckpt("%s.o_norm.weight", ap) };
RAD_ARCH_TRY(lay.kda.declare(b, nm, g, l, m.kw, ap, s, m.state, m.conv));
}
// The ffn connection is declared after the attention's post: declaration order is liveness.
if (!draft) {
RAD_ARCH_TRY(lay.attn_hc.declare_post(b));
ManifoldConn::Wire f{ m.h1, m.x, m.act.x, m.h0, m.post, m.comb };
ManifoldConn::Src fs{ nm.ckpt("%s.hc_ffn_fn", pre), nm.ckpt("%s.hc_ffn_scale", pre),
nm.ckpt("%s.hc_ffn_base", pre) };
RAD_ARCH_TRY(lay.ffn_hc.declare(b, nm, g, l, nm.f("blk.%d.hc_ffn", l), hc, f, fs, true));
} else {
RAD_ARCH_TRY(m.mtp.declare_join(b, m.y));
}
if (l < 3) {
auto w = m.dw;
w.x = input;
MlpFP8::Src s{ nm.ckpt("%s.post_attention_layernorm.weight", pre),
nm.ckpt("%s.mlp.gate_proj.weight", pre),
nm.ckpt("%s.mlp.up_proj.weight", pre),
nm.ckpt("%s.mlp.down_proj.weight", pre) };
lay.dense.swiglu_quant = true;
RAD_ARCH_TRY(lay.dense.declare(b, nm, g, l, w, s, false, draft, kArNone, false, 10));
} else {
auto w = m.mw;
w.x = input;
MoeFP8::Src s;
s.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
s.router = nm.ckpt("%s.mlp.gate.weight", pre);
s.router_bias = nm.ckpt("%s.mlp.gate.e_score_correction_bias", pre);
s.experts = nm.ckpt("%s.mlp.experts", pre);
s.shared = nm.ckpt("%s.mlp.shared_experts", pre);
s.cfg.n_expert = s.cfg.n_expert_all = 288;
s.cfg.top_k = 8;
s.cfg.n_ff_exp = s.cfg.n_ff_shared = GlmTp::expert_width(g.world);
s.cfg.rows = g.max_tok;
s.cfg.sigmoid_router = 1;
s.cfg.route_scale = 2.5;
s.cfg.swiglu_limit = 10;
s.cfg.shared_ungated = 1;
s.cfg.router_fuse = 1;
s.cfg.swiglu_quant = 1;
for (int q = 0; q < 2; ++q) {
s.cfg.ff_lo[q] = g.rank * GlmTp::expert_width(g.world);
s.cfg.ff_hi[q] = (g.rank + 1) * GlmTp::expert_width(g.world);
}
RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, s, &s.cfg));
RAD_ARCH_TRY(lay.moe.declare(b, nm, g, l, w, s, false, draft));
}
if (!draft) RAD_ARCH_TRY(lay.ffn_hc.declare_post(b));
return RAD_OK;
}
/* ------------------------------------------------------------------ declare */
static int geometry(Geom& g, const RadModelMeta* meta, const RadBuildCtx* ctx, int world) {
g.n_layer = 45;
g.n_embd = 4096;
g.head_dim = GlmTp::kMlaDim;
g.n_head_all = g.n_head_kv_all = GlmTp::kHeads;
g.n_head = g.n_head_kv = GlmTp::heads(world);
g.n_ff_all = GlmTp::kDenseFF;
g.n_ff = GlmTp::dense_width(world);
g.n_vocab_all = 154880;
g.n_vocab = shard_extent(154880, world, ctx->rank);
g.vocab_off = shard_begin(154880, world, ctx->rank);
g.rank = ctx->rank;
g.world = world;
g.attn_world = world;
g.attn_rank = ctx->rank;
g.max_tok = ctx->max_tok;
g.max_ctx = ctx->max_ctx;
g.max_seqs = ctx->max_seqs;
g.max_spec = ctx->max_spec;
g.max_logit_rows = std::min<int64_t>(g.max_tok, g.max_seqs * (g.max_spec + 1));
if (ctx->max_out_rows > g.max_logit_rows) g.max_logit_rows = ctx->max_out_rows;
g.eps = meta->rms_eps;
g.wire_exact = !ctx->tp_wire_lossy;
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;
}
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;
if (!GlmTp::world_ok(world) || meta->n_embd != 4096 || meta->n_layers != 45 ||
meta->n_vocab != 154880 || cfg(meta, "num_nextn_predict_layers", 0) != 1 ||
cfg(meta, "hc_mult", 0) != 4 || cfg(meta, "n_routed_experts", 0) != 288 ||
cfg(meta, "index_topk", 0) != 2048 || ctx->max_spec > 31 ||
(ctx->kv_dtype && ctx->kv_dtype != RAD_BF16))
return RAD_E_UNSUPPORTED;
auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank];
slot = std::make_unique<Model>();
auto& m = *slot;
auto& g = m.g;
m.nm = Names(ctx->scope);
auto& nm = m.nm;
RAD_ARCH_TRY(geometry(g, meta, ctx, world));
RAD_ARCH_TRY(stream_buffers(b, m));
RAD_ARCH_TRY(kda_buffers(b, m));
RAD_ARCH_TRY(mla_buffers(b, m));
RAD_ARCH_TRY(indexer_buffers(b, m));
RAD_ARCH_TRY(ffn_buffers(b, m));
RAD_ARCH_TRY(kv_groups(b, m));
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"),
nm.ckpt("model.language_model.embed_tokens.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("output.weight"), nm.ckpt("lm_head.weight")));
RAD_ARCH_TRY(
map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.language_model.norm.weight")));
m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, { g.n_vocab, 4096 }, RAD_ACCESS_VOCAB,
RAD_SHARD_ROW, grp_model());
m.head = decl_w(b, nm.f("output.weight"), RAD_BF16, { g.n_vocab, 4096 }, RAD_ACCESS_VOCAB,
RAD_SHARD_ROW, grp_model());
m.final_gain = decl_w(b, nm.f("output_norm.weight"), RAD_F32, { 4096 }, 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", 4096),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(m.token)),
{}, { m.x });
// The encoder's rows overwrite the lookup before its reduction (MediaRows).
m.media = GlmVision::present(meta) && ctx->max_enc_patches > 0;
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, 4096, m.x));
m.embed_ar = GlmTp::reduce(b, g, m.x, true);
m.expand = copy(b, g, m.x, m.h0);
m.layers.resize(45);
for (int l = 0; l < 45; ++l) RAD_ARCH_TRY(layer(b, m, m.layers[l], nm, l, false));
// Every rank computes the whole normed latent and pools into the whole index cache
// (rad_block_glm_mla.h, rad_block_glm_indexer.h), so the host tier keeps each once a slot.
RAD_ARCH_TRY(rad_kv_group_replicated(b, m.latent));
if (m.index) RAD_ARCH_TRY(rad_kv_group_replicated(b, m.index));
m.contract = rw(b,
RAD_OP(b, "mhc_contract",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_INT("hc", 4), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.h0 }, { m.x });
m.norm = norm(b, g, m.final_gain, m.x, m.final_hidden);
m.gather = rw(b,
RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096),
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", 4096), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(m.head)),
{ m.logit_input }, { m.logits });
if (g.max_spec > 0) {
GlmMtp::Wire tw{ m.final_hidden, m.logits, m.token, m.head };
RAD_ARCH_TRY(m.mtp.declare_inputs(b, g, tw, m.media));
RAD_ARCH_TRY(layer(b, m, m.draft, m.mtp.nm, 45, true));
RAD_ARCH_TRY(m.mtp.declare_head(b));
m.have_mtp = true;
}
// The tower, last: an encoder pass issues nothing else, so its activations share the arena
// with every buffer above. Its weight groups follow the 45 layers and the MTP layer's.
if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, 4096, 46));
rad_note(b,
"GLM-5.3: TP%d, 45 mHC layers, 34 KDA + 11 sparse MLA, mixed MXFP4/FP8, native MTP "
"%s, vision %s",
world, m.have_mtp ? "enabled" : "disabled", m.media ? "enabled" : "disabled");
return RAD_OK;
}
/* ------------------------------------------------------------------ step */
static void attention(RadCtx* c, Layer& l, const RadBatch* batch) {
l.norm.step(c, batch->n_tok);
if (l.full) {
l.mla.prepare(c, batch);
l.index.step(c, batch);
l.mla.finish(c, batch);
} else
l.kda.step(c, batch);
}
static void draft_pass(RadCtx* c, Model& m, const RadBatch* batch) {
if (!m.have_mtp || batch->draft_pass == 1) {
rad_step_fail(c, "GLM 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.mla.prepare(c, batch);
l.index.step(c, batch);
// A history pass with no proposal row fills the draft caches and ends there.
if (batch->draft_pass < 0 && batch->n_draft_out <= 0) return;
l.mla.finish(c, batch);
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) {
auto& m = *models[rad_rank(c)];
const int64_t T = batch->n_tok;
// An encoder pass runs only the vision tower (RadBatch::enc).
if (batch->enc) {
m.vit.step(c, batch);
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));
m.mrows.step(c, batch, m.x, T);
if (m.embed_ar) RAD_ISSUE_N(c, m.embed_ar, T * 4096, brows(m.x, T), RAD_NONE);
for (int i = 0; i < 4; ++i)
RAD_ISSUE_N(c, m.expand, T, brows(m.x, T), bcol(m.h0, i * 4096, 4096, T));
for (int i = 0; i < 45; ++i) {
auto& l = m.layers[i];
l.attn_hc.read(c, T);
attention(c, l, batch);
l.attn_hc.write(c, T);
l.ffn_hc.read(c, T);
if (i < 3)
l.dense.step(c, batch);
else
l.moe.step(c, batch);
l.ffn_hc.write(c, T);
}
RAD_ISSUE_N(c, m.contract, T, brows(m.h0, T), brows(m.x, T));
RAD_ISSUE_N(c, m.norm, T, brows(m.x, T), RAD_W(m.final_gain), brows(m.final_hidden, T));
if (batch->n_out > 0) {
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));
}
}
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;
// The tower's merged block, so a pass size the core picks itself is whole output rows.
if (GlmVision::present(meta)) {
const int64_t k = rad_meta_geti(meta, "vision_config.spatial_merge_size", 0);
if (k > 0) out->enc_merge = k * k;
}
out->shape_probe_ok = 1;
return RAD_OK;
}
} // namespace glm5next
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(glm5next)
RAD_ARCH_PLUGIN(glm5next, "glm5next", "", "0.1.0",
"GLM-5.3-Flash mixed MXFP4/FP8, mHC/KDA/MLA and native serial MTP")
#endif
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/krea2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(krea2 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(krea2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/krea2.cpp)
+1466
View File
File diff suppressed because it is too large. Load diff
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/ltx2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(ltx2 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(ltx2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/ltx2.cpp)
+4196
View File
File diff suppressed because it is too large. Load diff
+36
View File
@@ -928,6 +928,41 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
return m.op_embed ? RAD_OK : RAD_E_INVAL;
}
/* ================================================================== adapter key names */
/* LoRA files for H3 name the DiT by ComfyUI's modules (comfy/ldm/minimax): one fused
* `attn.qkv_proj` (q, k, v), `attn.out_proj`, and `mlp.fc1` with the SwiGLU's gate half first,
* where the checkpoint keeps the value half first in `ff.net.0.proj`. */
static int declare_lora_names(RadBuilder* b, const Model& m) {
std::vector<LoraName> n;
const int64_t Q = m.gd.n_head_all * m.gd.head_dim, KV = m.gd.n_head_kv_all * m.gd.head_dim;
const int64_t F = m.gd.n_ff_all;
static const char* const kBlocks[][2] = {
{ "blocks.#.", "transformer_blocks.#." },
{ "token_refiner.blocks.#.", "token_refiner.refiner_blocks.#." },
};
for (const auto& bl : kBlocks) {
const std::string f = bl[0], t = bl[1];
n.push_back({ f + "attn.qkv_proj", t + "attn.to_q", 0, Q, 0 });
n.push_back({ f + "attn.qkv_proj", t + "attn.to_k", Q, Q + KV, 0 });
n.push_back({ f + "attn.qkv_proj", t + "attn.to_v", Q + KV, Q + 2 * KV, 0 });
n.push_back({ f + "attn.out_proj", t + "attn.to_out.0" });
n.push_back({ f + "attn.to_gate_compress", t + "attn.to_gate_compress" });
n.push_back({ f + "mlp.fc1", t + "ff.net.0.proj", 0, F, F });
n.push_back({ f + "mlp.fc1", t + "ff.net.0.proj", F, 2 * F, 0 });
n.push_back({ f + "mlp.fc2", t + "ff.net.2" });
}
n.push_back({ "blocks.#.adaln_proj.linear", "transformer_blocks.#.adaln_proj.linear" });
n.push_back({ "video_patch_proj", "proj_in" });
n.push_back({ "audio_patch_proj", "audio_proj_in" });
n.push_back({ "condition_proj", "context_embedder" });
n.push_back({ "time_embedder.proj_in", "time_embedder.linear_1" });
n.push_back({ "time_embedder.proj_out", "time_embedder.linear_2" });
n.push_back({ "final_layer.video_out", "proj_out" });
n.push_back({ "final_layer.audio_out", "audio_proj_out" });
n.push_back({ "final_layer.adaln_proj.linear", "norm_out.linear" });
return lora_names(b, "transformer.", kLoraDiffusionSpellings, n);
}
/* ================================================================== the token refiner */
/* `context_embedder` (5120 -> 5376, bf16, replicated), two plain blocks with full attention over
* the prompt and no rotary, and the final RMSNorm into the lane's prompt rows. The feed-forward is
@@ -3201,6 +3236,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* ---- in issue order: the conditioning pass, the step, the soundtrack, the frames */
m.b_text = decl_b(b, nm.f("lane.text"), RAD_BF16, { (int64_t)kMaxLanes * kMaxText, m.D },
RAD_BUF_PERSIST);
RAD_ARCH_TRY(declare_lora_names(b, m));
RAD_ARCH_TRY(declare_te(b, meta, m));
RAD_ARCH_TRY(declare_refiner(b, meta, m));
RAD_ARCH_TRY(declare_tables(b, meta, m));
+150 -9
View File
@@ -45,9 +45,30 @@
* and includes this file. Every difference is behind `#if QWEN35_MOE`: the expert-count check, the
* routing geometry read from metadata, the block's buffers, the per-layer source names, the MTP
* head's feed-forward, and the plugin identity. */
/* ============================== AND A THIRD: qwen35_w8a8 ==============================
*
* `qwen35_w8a8` is the dense build with an int8 trunk: every large linear `i8*bf16[1x128]/fwht128`,
* rotated by a 128-wide Hadamard and served at i8a8h, each quantising its own input from the bf16
* plane (LinearFP8's int8 branch). The producers already write that plane, as they do for a rotated
* MXFP4 linear, so the graph is this one. It is a plugin of its own because the quantisation
* descriptor is half of the selection key: `w8a8_fwht128`, which names the rotation, so a plain
* int8 trunk is refused.
*
* Its differences are behind `#if QWEN35_W8A8`: check_format's method, the probe that learns the
* trunk is int8 before the activations are declared (and refuses one that is not), and the plugin
* identity. The int8 activation pairs follow from the probe. */
#ifndef QWEN35_MOE
#define QWEN35_MOE 0
#endif
#ifndef QWEN35_W8A8
#define QWEN35_W8A8 0
#endif
#if QWEN35_MOE && QWEN35_W8A8
#error "qwen35_w8a8 is the dense build; a routed int8 trunk is not a format this file serves"
#endif
/* The plugin's name for a message, expanded once more so it is QWEN35_NS's value. */
#define QWEN35_STR_X(x) #x
#define QWEN35_STR(x) QWEN35_STR_X(x)
#ifndef QWEN35_NS
#define QWEN35_NS qwen35_fp8
#endif
@@ -101,6 +122,10 @@ struct Model {
rad_kvgroup kv_full = 0, kv_state = 0, kv_conv = 0;
/* The trunk's linears are int8 (LinearFP8::i8), learned before the activations are declared
* because it decides whether they carry an int8 code pair. Only qwen35_w8a8 sets it. */
bool trunk_i8 = false;
/* the residual stream and the two vocabulary edges */
rad_buf b_x = 0, b_hout = 0, b_logits = 0;
ActFP8 a_h{};
@@ -126,6 +151,8 @@ struct Model {
ActFP8 a_eff{};
rad_buf b_sgu = 0, b_sout = 0, b_sgate = 0;
ActFP8 a_sff{};
/* Rotated codes of the expert input, for rotated four-bit experts (MoeFP8::Config::expert_rot). */
ActFP8 a_hr{};
#endif
/* The DFlash2 drafter, declared only when the container carries one and the deployment
@@ -178,6 +205,18 @@ static Model g_model[MAX_RANKS];
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 QWEN35_W8A8
/* The format the convert stated (the recipe's --set keys); the trunk probe in declare() holds
* the weights to it. */
if (!method || std::strcmp(method, "w8a8") != 0 || !fmt || std::strcmp(fmt, "fwht128") != 0) {
fprintf(stderr, "radiance: qwen35_w8a8 serves a container converted for an int8 trunk "
"(quant_method 'w8a8', fmt 'fwht128': data/recipes/"
"q38-27b-w8a8-df2.recipe's --set keys); this one says '%s' / '%s'.\n",
method ? method : "(none)", fmt ? fmt : "(none)");
return RAD_E_UNSUPPORTED;
}
return RAD_OK;
#else
const char* block = rad_meta_gets(meta, "quantization_config.weight_block_size", nullptr);
if (method && std::strcmp(method, "fp8") != 0) {
@@ -204,6 +243,7 @@ static int check_format(const RadModelMeta* meta) {
}
}
return RAD_OK;
#endif
}
/* The DFlash2 drafter: its geometry, KV group, buffers and block.
@@ -406,8 +446,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
}
#else
if (meta->n_expert > 0) {
fprintf(stderr, "radiance: qwen35_fp8 refuses a checkpoint with %lld experts; that is "
"qwen35moe\n", (long long)meta->n_expert);
fprintf(stderr, "radiance: " QWEN35_STR(QWEN35_NS) " refuses a checkpoint with %lld "
"experts; that is qwen35moe\n", (long long)meta->n_expert);
return RAD_E_UNSUPPORTED;
}
#endif
@@ -516,9 +556,32 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
fd.n_head_kv = g.n_head_kv;
fd.head_dim = g.head_dim;
/* --kv-cache-dtype fp8_v4 / k6_v4 (RadBuildCtx::kv_quant): V as int4 in groups of 32 with f16
* scales, K E4M3 as above or int6 the same way (libr4d's fp8_v4 / k6_v4 rows). A token's row
* is 25 or 22 * head_dim / 16 bytes instead of 2 * head_dim, so the group is declared at half
* that and the core sizes pages from it; only those kernels read the layout. The drafter's
* group stays E4M3 (declare_dflash2). The engine asks only for a layout probe() offered. */
const int kvq = fd.dtype == RAD_F8E4M3 ? ctx->kv_quant : RAD_KVQ_NONE;
const char* kvq_name = kvq == RAD_KVQ_V4 ? "fp8_v4" : kvq == RAD_KVQ_K6V4 ? "k6_v4" : nullptr;
if (kvq != RAD_KVQ_NONE && !kvq_name) {
fprintf(stderr, "radiance: KV cache layout %d is not one this plugin knows\n", kvq);
return RAD_E_UNSUPPORTED;
}
if (kvq_name && !(g.head_dim == 256 && g.n_head == 6 * g.n_head_kv)) {
fprintf(stderr, "radiance: --kv-cache-dtype %s has libr4d rows at head_dim 256, gqa 6 "
"only; this model is head_dim %lld, gqa %lld\n", kvq_name,
(long long)g.head_dim, (long long)(g.n_head_kv ? g.n_head / g.n_head_kv : 0));
return RAD_E_UNSUPPORTED;
}
const int64_t row16 = kvq == RAD_KVQ_V4 ? 25 : kvq == RAD_KVQ_K6V4 ? 22 : 32;
fd.head_dim = g.head_dim * row16 / 32;
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
/* The op parameter must use the spelling the rows band on, which is rad_dtype_name's. */
g.kv_dtype = rad_dtype_name(fd.dtype);
g.kv_dtype = kvq_name ? kvq_name : rad_dtype_name(fd.dtype);
if (kvq_name)
rad_note(b, "kv cache %s: %s K, int4 V, in groups of 32 with f16 scales, %lld bytes a token "
"and head instead of %lld", kvq_name, kvq == RAD_KVQ_V4 ? "E4M3" : "int6",
(long long)(g.head_dim * row16 / 16), (long long)(2 * g.head_dim));
/* The SSM state cache is f32.
*
@@ -544,13 +607,41 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
cd.conv_width = gc.conv_width;
m.kv_conv = rad_decl_kv_group(b, nm.f("kv_gdn_conv"), &cd);
#if QWEN35_W8A8
/* ---- the trunk's stored format, read from the first delta-net layer's input projection as
* qwen4exp_fp8 reads its own: the activations below carry an int8 code pair only for an int8
* trunk, and this build serves only the rotated one its descriptor names. The probe maps the
* weight through the layer's own LinearFP8, which then does not map it again; the resize
* before the layer loop keeps the layers sized here. */
m.layers.resize((size_t)m.n_main);
for (int64_t l = 0; l < m.n_main; ++l) {
if (is_full_attention(l, interval)) continue;
const char* pre = "model.language_model.layers";
RAD_ARCH_TRY(m.layers[(size_t)l].gdn.in.probe(
b, nm, g, nm.f("blk.%lld.ssm_inz", (long long)l),
{ nm.ckpt("%s.%lld.linear_attn.in_proj_qkv.weight", pre, (long long)l),
nm.ckpt("%s.%lld.linear_attn.in_proj_z.weight", pre, (long long)l) }));
RadEncoding enc{};
m.trunk_i8 = weight_enc(b, nm.f("blk.%lld.ssm_inz.weight", (long long)l), &enc) &&
linear_is_w8h(enc);
break;
}
if (!m.trunk_i8) {
fprintf(stderr, "radiance: qwen35_w8a8 serves a rotated int8 trunk (i8 codes with a bf16 "
"scale a [1 x 128], /fwht128), and this container's first delta-net input "
"projection is not one; convert with "
"data/recipes/q38-27b-w8a8-df2.recipe\n");
return RAD_E_DTYPE;
}
#endif
/* ---- activation buffers. Every activation that feeds a GEMM has an fp8 copy: an E4M3 plane
* of the same shape and an f32 scale plane with one column per 128. They are transients that
* liveness analysis can share, but not free: the largest, `ffn`'s, is 8192 x 17408 bytes
* (143 MiB) beside its 285 MiB bf16 buffer. */
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
m.a_h.x = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd));
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.trunk_i8));
m.b_qg = decl_b(b, nm.f("attn_qg"), g.act_dtype, {g.max_tok, g.n_head, 2 * g.head_dim});
m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {g.max_tok, kv_dim});
@@ -566,7 +657,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* it must not share storage with transients. */
m.b_rope_cs = decl_b(b, nm.f("rope_cs"), RAD_F32, {rope_table_rows(g), m.n_rot},
RAD_BUF_PERSIST);
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim));
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim, 0, m.trunk_i8));
/* `gdn_in` is conv_dim + v_dim, not in_dim: a and b have their own buffer because the
* checkpoint keeps them bf16, while the fp8 output gate is the tail of this one
@@ -586,7 +677,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* Rank 3, as libr4d's scan and recurrent kernels require; the quantiser reads dim 0 as the
* row. */
m.a_go.x = decl_b(b, nm.f("gdn_o"), g.act_dtype, {g.max_tok, gc.n_head_v, gc.head_v});
RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim));
RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim, 0, m.trunk_i8));
#if QWEN35_MOE
/* ---- the routing geometry, read here so a refusal names the container's key. `n_ff` is
@@ -624,6 +715,21 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
(long long)mc.top_k, (long long)mc.n_expert);
return RAD_E_INVAL;
}
/* GPTQ calibration run (MoeFP8::Config::calib), on when the output directory is set. */
mc.calib = calib_dir() != nullptr ? 1 : 0;
/* The experts' stored format, read from layer 0's first expert as qwen4exp does, so a
* container with four-bit experts is served in that format. */
{
MoeFP8::Src ps{};
RAD_ARCH_TRY(moe_expert_sources(b, nm, "format",
"model.language_model.layers.0.mlp.experts", &ps));
RAD_ARCH_TRY(MoeFP8::probe(b, nm, 0, ps, &mc));
}
if (mc.expert_bf16) {
fprintf(stderr, "radiance: qwen35moe: plain bf16 experts are not served by this "
"plugin; convert with a quantising recipe\n");
return RAD_E_UNSUPPORTED;
}
}
{
/* The step's height for everything with one row per token, and a pass's height only for
@@ -654,11 +760,26 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
m.b_sout = decl_b(b, nm.f("shexp_out"), g.act_dtype, {R, g.n_embd});
m.b_sgate = decl_b(b, nm.f("shexp_gate"), g.act_dtype, {R, 1});
}
if (mc.expert_rot) RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd));
}
#else
m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff});
m.a_ffn.x = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff});
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff));
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.trunk_i8));
#endif
#if QWEN35_W8A8
/* ---- the rotated trunk's quantisers in their producers. Every reader of `h`'s codes is a
* rotated int8 projection (q, k, v; the delta net's qkv|z; gate_up), and of `ffn`'s the down
* projection, so where libr4d serves the `_had_quant_i8g` forms the norms and the gated
* product write had_quant_act_i8g's codes themselves (ActFP8::q8_rot) and those projections
* declare no quantiser: one launch for q, k and v instead of three, and none before down. The
* codes are the same bytes. Where the forms are not declared (the CPU kernels), each
* projection quantises its own input from the bf16 plane, as before. */
if (rad_op_declared(b, "rmsnorm_had_quant_i8g") &&
(g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g")))
m.a_h.q8_fed = m.a_h.q8_rot = true;
if (rad_op_declared(b, "gated_had_quant_i8g")) m.a_ffn.q8_fed = m.a_ffn.q8_rot = true;
#endif
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
@@ -762,6 +883,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
mw.sorted = m.b_sorted; mw.eoff = m.b_eoff; mw.ecnt = m.b_ecnt;
mw.egu = m.b_egu; mw.eff = m.a_eff; mw.edn = m.b_edn; mw.moe = m.b_emoe;
mw.sgu = m.b_sgu; mw.sff = m.a_sff; mw.sout = m.b_sout; mw.sgate = m.b_sgate;
mw.hr = m.a_hr;
#else
mw.x = m.b_x; mw.h = m.a_h; mw.gate_up = m.b_gate_up; mw.ffn = m.a_ffn;
#endif
@@ -813,7 +935,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
ms.cfg = m.moecfg;
ms.norm = nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l);
ms.router = nm.ckpt("%s.%lld.mlp.gate.weight", pre, (long long)l);
ms.experts = nm.ckpt("%s.%lld.mlp.experts", pre, (long long)l);
RAD_ARCH_TRY(moe_expert_sources(b, nm, "layer",
nm.ckpt("%s.%lld.mlp.experts", pre, (long long)l), &ms));
if (m.moecfg.n_ff_shared > 0) {
ms.shared = nm.ckpt("%s.%lld.mlp.shared_expert", pre, (long long)l);
ms.shared_gate = nm.ckpt("%s.%lld.mlp.shared_expert_gate.weight", pre, (long long)l);
@@ -916,7 +1039,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* MtpBlockFP8 is a template over the feed-forward. */
ts.mlp.cfg = m.moecfg;
ts.mlp.router = nm.ckpt("mtp.layers.0.mlp.gate.weight");
ts.mlp.experts = nm.ckpt("mtp.layers.0.mlp.experts");
RAD_ARCH_TRY(moe_expert_sources(b, nm, "mtp", nm.ckpt("mtp.layers.0.mlp.experts"),
&ts.mlp));
if (m.moecfg.n_ff_shared > 0) {
ts.mlp.shared = nm.ckpt("mtp.layers.0.mlp.shared_expert");
ts.mlp.shared_gate = nm.ckpt("mtp.layers.0.mlp.shared_expert_gate.weight");
@@ -1109,6 +1233,15 @@ static void step(RadCtx* c, const RadBatch* batch) {
* 0 when the container carries no drafter. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
/* --kv-cache-dtype fp8_v4 / k6_v4: libr4d's rows for them are the h256/gqa6 attention
* family's (Qwen3.8-27B), so other geometries are refused at startup rather than in declare. */
{
const long long hd = meta->head_dim ? meta->head_dim
: (meta->n_head ? meta->n_embd / meta->n_head : 0);
const long long nkv = meta->n_head_kv ? meta->n_head_kv : meta->n_head;
if (hd == 256 && nkv > 0 && meta->n_head == 6 * nkv)
out->kv_quant_ok = (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4);
}
const char* da = rad_meta_gets(meta, "draft.architectures", "");
if (da && std::strstr(da, "DFlash2")) {
const long long bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 8);
@@ -1137,6 +1270,14 @@ QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "fp8_e4m3", "0.1.0",
"dense graph with a routed feed-forward (256 experts, 8 a token, and a shared "
"expert), gated attention over paged KV every fourth layer and gated delta net "
"between")
#elif QWEN35_W8A8
QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "w8a8_fwht128", "0.1.0",
"Qwen3.5 / 3.6 / 3.8 dense (0.8B..27B), 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; gated attention over paged KV every fourth layer and "
"gated delta net between")
/* An imported checkpoint is never a rotated int8 trunk: qwen35_fp8 serves those. */
RAD_ARCH_SERVES_IMPORTS(0)
#else
QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "fp8_e4m3", "0.1.0",
"Qwen3.5 / 3.6 / 3.8 dense (0.8B..27B), block-scaled fp8 weights and fp8 "
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/qwen35_w8a8 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(qwen35_w8a8 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(qwen35_w8a8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen35_w8a8.cpp)
+19
View File
@@ -0,0 +1,19 @@
/* qwen35_w8a8 -- Qwen3.5 / 3.6 / 3.8 dense with an int8 trunk: i8 weights with a bf16 scale a 128
* of K, rotated by a 128-wide Hadamard, against int8 activations quantised under the same rotation.
*
* This is arch/qwen35_fp8/qwen35_fp8.cpp built again, as qwen35moe_fp8 is: the same gated
* attention, gated delta net, MLP, layer schedule, rope, vocabulary edges, drafters and vision
* tower. A linear's weight encoding makes it int8 (arch/common/rad_fp8.h: LinearFP8):
* `i8*bf16[1x128]/fwht128` is gemm_nt_q at i8a8h behind had_quant_act_i8g, each linear quantising
* its own input from the bf16 plane its producer already writes. The places this build differs are
* behind `#if QWEN35_W8A8` in that file.
*
* A plugin of its own rather than qwen35_fp8 serving any encoding it is handed, because the
* quantisation descriptor is half of the selection key (spec §2.4): a container converted with
* data/recipes/q38-27b-w8a8-df2.recipe says `w8a8_fwht128`.
*/
#define QWEN35_W8A8 1
#define QWEN35_NS qwen35_w8a8
#define QWEN35_ARCH_ID "qwen35"
#include "../qwen35_fp8/qwen35_fp8.cpp"
+56 -1
View File
@@ -109,6 +109,11 @@ struct Layer {
QsaIndexer qsa; /* full-attention layers only; inert when the checkpoint has none */
GdnFP8 gdn;
MoeFP8 mlp;
/* The control vector's projection, applied to the wide stream right after this layer's
* feed-forward write -- where llama.cpp's `build_cvec(res_hc, il)` sits in the `qwen4exp`
* graph. Inert (no op) when the deployment has no vector or this layer is outside its range
* (arch/common/rad_block_hc.h). */
HcProject proj;
};
struct Model {
@@ -649,8 +654,36 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
fd.n_head_kv = g.n_head_kv;
fd.head_dim = g.head_dim;
/* --kv-cache-dtype fp8_v4 / k6_v4 (RadBuildCtx::kv_quant): V as int4 in groups of 32 with
* f16 scales, K E4M3 as above or int6 the same way (libr4d's gqa12 and four-rank gqa6
* rows for these layers). A token's row is 25 or 22 * head_dim / 16 bytes instead of
* 2 * head_dim, so the group is declared at half that and the core sizes pages from it;
* only those kernels read the layout. The MTP head's layer shares this group. The engine
* asks only for a layout probe() offered. */
const int kvq = fd.dtype == RAD_F8E4M3 ? ctx->kv_quant : RAD_KVQ_NONE;
const char* kvq_name = kvq == RAD_KVQ_V4 ? "fp8_v4" : kvq == RAD_KVQ_K6V4 ? "k6_v4"
: nullptr;
if (kvq != RAD_KVQ_NONE && !kvq_name) {
fprintf(stderr, "radiance: KV cache layout %d is not one this plugin knows\n", kvq);
return RAD_E_UNSUPPORTED;
}
/* A rank's ratio: twelve at one and two ranks, six at four (each KV head replicated
* across a rank pair). */
if (kvq_name && !(g.head_dim == 256 && (g.gqa() == 12 || g.gqa() == 6))) {
fprintf(stderr, "radiance: --kv-cache-dtype %s has libr4d rows at head_dim 256 and a "
"rank's gqa 12 or 6 only; this rank is head_dim %lld, gqa %lld\n",
kvq_name, (long long)g.head_dim, (long long)g.gqa());
return RAD_E_UNSUPPORTED;
}
const int64_t row16 = kvq == RAD_KVQ_V4 ? 25 : kvq == RAD_KVQ_K6V4 ? 22 : 32;
fd.head_dim = g.head_dim * row16 / 32;
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
g.kv_dtype = rad_dtype_name(fd.dtype);
g.kv_dtype = kvq_name ? kvq_name : rad_dtype_name(fd.dtype);
if (kvq_name)
rad_note(b, "kv cache %s: %s K, int4 V, in groups of 32 with f16 scales, %lld bytes a "
"token and head instead of %lld", kvq_name,
kvq == RAD_KVQ_V4 ? "E4M3" : "int6", (long long)(g.head_dim * row16 / 16),
(long long)(2 * g.head_dim));
RadKVGroupDecl sd{};
sd.kind = RAD_KV_LINEAR;
@@ -913,6 +946,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* The stream's initial value: hc identical copies of the embedding. */
RAD_ARCH_TRY(m.enter.declare(b, g, m.hccfg.hc, m.a_x.x, m.b_h));
/* The control vector's per-token switch, when this deployment found one (HcProject). All zeros
* is the stock model, so a request that does not ask for the vector is unaffected. */
const rad_buf proj_on = HcProject::declare_mask(b, nm.f("projection_on"), g, ctx->cvec);
/* ---- the layers.
*
* Declaration order is the buffer planner's liveness: a transient lives over [first
@@ -1142,6 +1179,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
lay.mlp.gather_out_rows = lay.hc_ffn.gather_rows;
lay.mlp.gather_out_rows6 = lay.hc_ffn.gather_rows6;
}
/* The control vector's projection for this layer, if the vector steers it. */
RAD_ARCH_TRY(lay.proj.declare(b, nm.f("blk.%lld.proj", (long long) l), g, l, ctx->cvec,
proj_on, m.b_h, m.hccfg.hc));
}
/* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */
@@ -1513,6 +1554,8 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
for (int64_t p = 0; p < K; ++p) {
if (p == K - 1) wait1();
l.hc_ffn.write(c, T, r0(p), rn(p));
/* The projection of this piece, before the next layer reads it. */
l.proj.step(c, r0(p), rn(p));
if (nx && !ple_next) nx->hc_mix.read(c, T, r0(p), rn(p));
}
if (ple_next) {
@@ -1556,6 +1599,8 @@ static void step_serial(RadCtx* c, const RadBatch* batch, Model& m, const int32_
l.hc_ffn.read_pieces(c, T);
l.mlp.step(c, batch);
l.hc_ffn.write(c, T, 0, T);
/* The request's control vector, on the stream the write just finished. */
l.proj.step(c, 0, T);
dbg_resid(c, (int)li, "ffn", g.n_embd, m.b_h, m.a_x.x);
}
}
@@ -1622,6 +1667,16 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (meta_int2(meta, "qwen4exp.mtp_num_hidden_layers", "mtp_num_hidden_layers", 0) > 0)
out->draft_depth = 3;
out->shape_probe_ok = 1; /* declare() writes scratch under shape_probe */
/* --kv-cache-dtype fp8_v4 / k6_v4: libr4d has their rows for the QSA layers' geometry
* (head_dim 256, twelve queries per KV head; gqa6 with 4-token pages at four ranks), so other
* geometries are refused at startup rather than in declare. */
{
const long long hd = meta->head_dim ? meta->head_dim
: (meta->n_head ? meta->n_embd / meta->n_head : 0);
const long long nkv = meta->n_head_kv ? meta->n_head_kv : meta->n_head;
if (hd == 256 && nkv > 0 && meta->n_head == 12 * nkv)
out->kv_quant_ok = (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4);
}
return RAD_OK;
}
+12 -285
View File
@@ -47,6 +47,7 @@
#include <arch/rad_arch.h>
#include <arch/rad_fp8.h>
#include <arch/rad_block_vit.h>
#include <arch/rad_vae2d.h>
#include <algorithm>
#include <cmath>
@@ -75,291 +76,6 @@ static inline int64_t ref_tokens_max() { return (int64_t)kRefArea / 256 * 11 / 1
static const char* kSysPrompt = "Comprehend and analyze the provided prompt.";
/* ================================================================== the VAE as a recorded graph
*
* Image size varies per request, so the VAE's ops are declared once for the largest image and
* issued with the actual extents: every image operand is a raw [height, width * channels] view of
* its buffer (docs/OPS.md, "Image generation"), with extents from the pass's picture size and the
* stage's scale. `Vae` records each op with what it needs to rebuild its operands, so declare()
* and step() walk the same list.
*
* Every output is its own buffer, sized for its stage; the planner shares storage between those
* whose lives do not overlap, and no buffer is reused by hand. This is sound because ops are issued
* in declaration order. */
struct VImg {
rad_buf buf = 0;
int64_t ch = 0;
int lvl = 0; /* the side is the pass's base side times 2^lvl (decoder) or / 2^lvl (encoder) */
};
struct VOp {
enum Kind { CONV, NORM, ADD, D2S, S2D, ATTN } kind = CONV;
rad_op op = 0;
VImg x{}, y{}, z{}; /* inputs x (and z for ADD), output y */
rad_weight w = 0, b = 0;
int k = 1, up = 1, stride = 1;
int64_t qkv_ch = 0; /* ATTN: x is the [*, 3C] qkv rows, y the [*, C] output */
};
struct Vae {
std::vector<VOp> ops;
Names* nm = nullptr;
RadBuilder* b = nullptr;
const char* scope = ""; /* "dec" or "enc" */
bool down = false; /* an encoder: a level halves the side */
int64_t base_px = 0; /* pixels at level 0, the largest any pass hands it */
int n_buf = 0;
int first_group = 0;
/* The banded tail. From op `band_from` on, every output pixel reads a bounded window of rows
* (3x3 convolutions, nearest upsampling, per-pixel norms and adds, depth-to-space shortcuts),
* so a rank can run the tail on its band of level-0 rows plus `halo` rows per side and get its
* band's pixels bit for bit: rows spoiled by a conv's zero padding at the band edge never reach
* the band. The ops before it include the mid-block's attention, which reads every pixel, and
* run whole; `whole` holds their outputs, read by the tail at the band's row offset. -1: no
* tail. */
int band_from = -1;
int64_t halo = 0;
std::vector<rad_buf> whole;
int64_t px_at(int lvl) const {
int64_t p = base_px;
for (int i = 0; i < lvl; ++i) p = down ? (p + 3) / 4 : p * 4;
return p;
}
VImg img(int64_t ch, int lvl) {
VImg v;
v.ch = ch;
v.lvl = lvl;
v.buf = decl_b(b, nm->f("%s.t%d", scope, n_buf++), RAD_BF16, { px_at(lvl), ch });
return v;
}
rad_weight wt(const char* name, const char* src, std::initializer_list<int64_t> shape) {
if (map_copy(b, name, src) < 0) return 0;
return decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE,
grp_layer(first_group));
}
/* y = conv(x): k x k, stride, `up` 2 reads x upsampled, `pad` same or down. */
VImg conv(const VImg& x, int64_t cout, int k, int stride, int up, const char* pad,
const char* ckpt) {
VOp o;
o.kind = VOp::CONV;
o.x = x;
o.up = up;
o.stride = stride;
int lvl = x.lvl;
if (up == 2) lvl = down ? lvl - 1 : lvl + 1;
if (stride == 2) lvl = down ? lvl + 1 : lvl - 1;
o.y = img(cout, lvl);
o.k = k;
o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { cout, x.ch, k, k });
o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { cout });
o.op = RAD_OP(b, "conv2d_nhwc",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(lvl)), RAD_INT("cin", x.ch),
RAD_INT("cout", cout), RAD_INT("k", k),
RAD_INT("stride", stride), RAD_STR("pad", pad),
RAD_INT("up", up), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(o.w, o.b));
/* An input with no buffer is the picture the pass staged, read where it lies. */
if (x.buf) rw(b, o.op, { x.buf }, { o.y.buf });
else rw(b, o.op, {}, { o.y.buf });
ops.push_back(o);
return o.y;
}
/* The channel norm, `silu` or not. `gamma` is [C, 1, 1(, 1)] in the checkpoint. */
VImg norm(const VImg& x, bool silu, const char* ckpt, int gamma_rank) {
VOp o;
o.kind = VOp::NORM;
o.x = x;
o.y = img(x.ch, x.lvl);
const char* dn = nm->f("%s.gamma", ckpt);
if (map_copy(b, dn, nm->ckpt("%s.gamma", ckpt)) < 0) return VImg{};
o.w = gamma_rank == 4
? decl_w(b, dn, RAD_BF16, { x.ch, 1, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group))
: decl_w(b, dn, RAD_BF16, { x.ch, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group));
o.op = rw(b, RAD_OP(b, "l2norm_chan",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
RAD_STR("act", silu ? "silu" : "none"),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(o.w)),
{ x.buf }, { o.y.buf });
ops.push_back(o);
return o.y;
}
VImg add(const VImg& x, const VImg& z) {
VOp o;
o.kind = VOp::ADD;
o.x = x;
o.z = z;
o.y = img(x.ch, x.lvl);
o.op = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x.buf, z.buf }, { o.y.buf });
ops.push_back(o);
return o.y;
}
/* y += the resampling shortcut of x (in place on y). */
void shortcut(const VImg& x, const VImg& y, int ft) {
VOp o;
o.kind = down ? VOp::S2D : VOp::D2S;
o.x = x;
o.y = y;
o.up = ft;
o.op = rw(b, RAD_OP(b, down ? "s2d_avg_add" : "d2s_add",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(y.lvl)), RAD_INT("cin", x.ch),
RAD_INT("cout", y.ch), RAD_INT("ft", ft),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x.buf, y.buf }, { y.buf });
ops.push_back(o);
}
/* A residual block, in -> out channels. */
VImg resblock(const VImg& x, int64_t out, const char* ckpt) {
VImg h = x;
if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->f("%s.conv_shortcut", ckpt));
VImg t = norm(x, true, nm->f("%s.norm1", ckpt), 4);
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv1", ckpt));
t = norm(t, true, nm->f("%s.norm2", ckpt), 4);
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv2", ckpt));
return add(t, h);
}
/* The mid-block's single-head attention over every pixel. */
VImg attention(const VImg& x, const char* ckpt) {
const int64_t C = x.ch;
VImg t = norm(x, false, nm->f("%s.norm", ckpt), 3);
VImg qkv = conv(t, 3 * C, 1, 1, 1, "same", nm->f("%s.to_qkv", ckpt));
VOp o;
o.kind = VOp::ATTN;
o.x = qkv;
o.y = img(C, x.lvl);
o.qkv_ch = 3 * C;
o.op = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("head_dim", C),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)C))),
RAD_NOWEIGHTS),
{ qkv.buf }, { o.y.buf });
ops.push_back(o);
VImg p = conv(o.y, C, 1, 1, 1, "same", nm->f("%s.proj", ckpt));
return add(p, x);
}
/* The operands of op `o` for a pass whose level-0 picture is H0 x W0 pixels (or latent tokens,
* for the decoder), in the op's schema order, and its ranged value. */
static int64_t side(int64_t s0, int lvl, bool dn) {
int64_t s = s0;
for (int i = 0; i < lvl; ++i) s = dn ? s / 2 : s * 2;
return s;
}
/* `cu` is {0, pixels} at the attention's level -- the pass's latent tokens -- and `input` the
* level-0 picture when the first op reads one the pass staged. Ops [from, to) are issued; with
* `row0`, H0 is a band's rows and a `whole` buffer is read from its level-0 row `row0`. */
void issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu, const void* input,
size_t from = 0, size_t to = (size_t)-1, int64_t row0 = 0) const;
bool is_whole(rad_buf v) const {
for (rad_buf w : whole) if (w == v) return true;
return false;
}
/* The tail's halo in level-0 rows: walked back from the last op, a buffer's margin is the most
* any reader of it needs, in its own rows -- a k x k conv adds k/2, reading through a 2x
* upsample halves it rounding up, and the depth-to-space shortcut halves it. -1 when the tail
* holds an op that is not row-local, or reads a whole buffer above level 0. */
int64_t band_halo() const {
if (band_from < 0 || ops.empty()) return -1;
std::vector<std::pair<rad_buf, int64_t>> need{ { ops.back().y.buf, 0 } };
auto get = [&](rad_buf v) -> int64_t {
for (const auto& e : need) if (e.first == v) return e.second;
return 0;
};
auto want = [&](rad_buf v, int64_t m) {
for (auto& e : need) if (e.first == v) { e.second = std::max(e.second, m); return; }
need.push_back({ v, m });
};
for (size_t i = ops.size(); i-- > (size_t)band_from;) {
const VOp& o = ops[i];
const int64_t my = get(o.y.buf);
switch (o.kind) {
case VOp::CONV: {
if (o.stride != 1) return -1;
const int64_t m = my + o.k / 2;
want(o.x.buf, o.up == 2 ? (m + 1) / 2 : m);
break;
}
case VOp::NORM: want(o.x.buf, my); break;
case VOp::ADD: want(o.x.buf, my); want(o.z.buf, my); break;
case VOp::D2S: want(o.x.buf, (my + 1) / 2); break;
default: return -1;
}
}
int64_t h = 0;
for (size_t i = (size_t)band_from; i < ops.size(); ++i) {
const VOp& o = ops[i];
for (const VImg* v : { &o.x, &o.z })
if (v->buf && is_whole(v->buf)) {
if (v->lvl != 0) return -1;
h = std::max(h, get(v->buf));
}
}
return h;
}
};
inline void Vae::issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu,
const void* input, size_t from, size_t to, int64_t row0) const {
auto ptr = [&](const VImg& v) -> const void* {
if (!v.buf) return input;
const char* p = (const char*)rad_buf_ptr(c, v.buf);
return row0 && is_whole(v.buf) ? p + row0 * W0 * v.ch * (int64_t)sizeof(uint16_t) : p;
};
auto view = [&](const VImg& v, int64_t* H, int64_t* W) {
*H = side(H0, v.lvl, down);
*W = side(W0, v.lvl, down);
return RAD_P_T2(ptr(v), RAD_BF16, *H, *W * v.ch);
};
auto rows = [&](const VImg& v, int64_t cols) {
const int64_t H = side(H0, v.lvl, down), W = side(W0, v.lvl, down);
return RAD_P_T2(ptr(v), RAD_BF16, H * W * v.ch / cols, cols);
};
for (size_t i = from; i < to && i < ops.size(); ++i) {
const VOp& o = ops[i];
int64_t Hx, Wx, Hy, Wy;
switch (o.kind) {
case VOp::CONV: {
const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy);
RAD_ISSUE_N(c, o.op, Hy * Wy, x, RAD_W(o.w), RAD_W(o.b), y);
break;
}
case VOp::NORM: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), rows(o.y, o.y.ch));
break;
}
case VOp::ADD: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), rows(o.z, o.z.ch), rows(o.y, o.y.ch));
break;
}
case VOp::D2S:
case VOp::S2D: {
const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy);
RAD_ISSUE_N(c, o.op, Hy * Wy, x, y);
break;
}
case VOp::ATTN: {
/* q, k and v are column slices of the qkv rows, at its 3C pitch. */
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
const int64_t C = o.y.ch, n = H * W;
RAD_ISSUE_N(c, o.op, n, bcol(o.x.buf, 0, C, n), bcol(o.x.buf, C, C, n),
bcol(o.x.buf, 2 * C, C, n), cu, brows(o.y.buf, n));
break;
}
}
}
}
/* ================================================================== the model */
struct TeLayer {
@@ -1195,6 +911,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* (Vae says why the order matters.) */
m.media = VisionTower::present(meta) && ctx->max_enc_patches > 0;
if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, m.gt.n_embd, kGrpVision, true));
/* ---- adapter key names. The DiT's LoRA files use the checkpoint's own names, or
* ComfyUI's, which join the SwiGLU's gate and up projections as `img_mlp.gate_up` [gate; up]
* (comfy/ldm/qwen_image21). */
{
const int64_t F = gd.n_ff_all;
RAD_ARCH_TRY(lora_names(b, "transformer.", kLoraDiffusionSpellings,
{ { "transformer_blocks.#.img_mlp.gate_up",
"transformer_blocks.#.img_mlp.gate_layer", 0, F, 0 },
{ "transformer_blocks.#.img_mlp.gate_up",
"transformer_blocks.#.img_mlp.proj", F, 2 * F, 0 } }));
}
RAD_ARCH_TRY(declare_te(b, meta, m));
RAD_ARCH_TRY(declare_encoder(b, meta, m));
RAD_ARCH_TRY(declare_dit(b, meta, m));
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/sdxl -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(sdxl LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(sdxl architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/sdxl.cpp)
+1236
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -125,6 +125,9 @@ public:
int declare_pooled(rad_buf b);
int declare_drafter(const RadDrafterDecl* d);
int drafter_shared_kv(int pos_offset);
int lora_root(const char* native, const char* spellings);
int lora_alias(const char* native, const char* from, const char* to, int64_t from_lo,
int64_t from_hi, int64_t to_lo);
int declare_encoder(const RadEncoderDecl* d);
int declare_generator(const RadGeneratorDecl* d);
int declare_audio_generator(const RadAudioGenDecl* d);
@@ -141,6 +144,7 @@ public:
int weight_shard_span_parts(rad_weight w, const int64_t* lo, const int64_t* hi,
const int64_t* total, int n);
int kv_group_zero(rad_kvgroup g);
int kv_group_replicated(rad_kvgroup g);
/* Finalise: weight first/last use, KV group geometry, buffer liveness and packing. Returns
* RAD_OK, or the first structural error class. Resolution misses are not errors here: an
+303 -28
View File
@@ -14,6 +14,7 @@
#include <algorithm>
#include <climits>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <mutex>
@@ -927,10 +928,38 @@ int Builder::kv_group_zero(rad_kvgroup h) {
prog_.kv_groups[h].name.c_str());
return RAD_E_INVAL;
}
if (prog_.kv_groups[h].replicated) {
err(RAD_E_INVAL, "kv group '%s': kv_group_zero on a group declared replicated; a "
"replicated group is held whole on every rank", prog_.kv_groups[h].name.c_str());
return RAD_E_INVAL;
}
prog_.kv_groups[h].zero = true;
return RAD_OK;
}
int Builder::kv_group_replicated(rad_kvgroup h) {
if (finished_) {
err(RAD_E_STATE, "kv_group_replicated after declare finished");
return RAD_E_STATE;
}
if (h == 0 || h >= prog_.kv_groups.size()) return RAD_E_INVAL;
/* Paged groups only: the tiers move blocks. A linear or conv group's state travels in the
* checkpoint store, which has no such window. */
const int kind = prog_.kv_groups[h].decl.kind;
if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW) {
err(RAD_E_INVAL, "kv group '%s': kv_group_replicated on a group that is not paged",
prog_.kv_groups[h].name.c_str());
return RAD_E_INVAL;
}
if (prog_.kv_groups[h].zero) {
err(RAD_E_INVAL, "kv group '%s': kv_group_replicated on a group declared zero; a zero "
"rank holds none of it", prog_.kv_groups[h].name.c_str());
return RAD_E_INVAL;
}
prog_.kv_groups[h].replicated = true;
return RAD_OK;
}
/* ================================================================== name map */
int Builder::decl_name_map(const RadNameMap* m) {
if (finished_) { err(RAD_E_STATE, "decl_name_map after declare finished"); return RAD_E_STATE; }
@@ -940,7 +969,8 @@ int Builder::decl_name_map(const RadNameMap* m) {
return RAD_E_INVAL;
}
if (m->mode != RAD_MAP_COPY && m->mode != RAD_MAP_CONCAT && m->mode != RAD_MAP_WNORM &&
m->mode != RAD_MAP_ROWS && m->mode != RAD_MAP_TRANSPOSE && m->mode != RAD_MAP_EMA) {
m->mode != RAD_MAP_ROWS && m->mode != RAD_MAP_TRANSPOSE && m->mode != RAD_MAP_EMA &&
m->mode != RAD_MAP_TAP && m->mode != RAD_MAP_COLS) {
err(RAD_E_INVAL, "name map for '%s': unknown mode %d", m->declared, m->mode);
return RAD_E_INVAL;
}
@@ -951,9 +981,11 @@ int Builder::decl_name_map(const RadNameMap* m) {
: "the magnitude and the direction", m->n_src);
return RAD_E_INVAL;
}
if (m->mode == RAD_MAP_TRANSPOSE && m->n_src != 1) {
err(RAD_E_INVAL, "name map for '%s': a transpose map names one source, not %d",
m->declared, m->n_src);
if ((m->mode == RAD_MAP_TRANSPOSE || m->mode == RAD_MAP_TAP || m->mode == RAD_MAP_COLS) &&
m->n_src != 1) {
err(RAD_E_INVAL, "name map for '%s': a %s map names one source, not %d", m->declared,
m->mode == RAD_MAP_TAP ? "tap" : m->mode == RAD_MAP_COLS ? "column" : "transpose",
m->n_src);
return RAD_E_INVAL;
}
@@ -982,14 +1014,20 @@ int Builder::decl_name_map(const RadNameMap* m) {
m->declared, i, m->src_index[i], (long long)m->src_rows[i]);
return RAD_E_INVAL;
}
if (m->mode == RAD_MAP_COLS && (m->src_index[0] < 0 || m->src_rows[0] <= 0)) {
err(RAD_E_INVAL, "name map for '%s': the column range starts at %d and holds %lld columns",
m->declared, m->src_index[0], (long long)m->src_rows[0]);
return RAD_E_INVAL;
}
/* A CONCAT map may be declared in pieces; any other repeat is an error.
/* A CONCAT, ROWS or EMA map may be declared in pieces; any other repeat is an error.
*
* `src[8]` is the ABI's cap, and a sharded checkpoint exceeds it: Qwen3.8-Flash-Next stores
* its n-gram embedding as 128 tensors `...ngram_embedding.shard_K.weight`. Growing the array
* would cost ~80 MB of Program (one map per declared weight, ~50K weights). So successive
* CONCAT maps for one name extend it in call order, and rad-convert joins their sources end
* to end (map_concat_shards() in arch/common/rad_arch.h).
* to end (map_concat_shards() in arch/common/rad_arch.h). ROWS maps extend the same way (a
* row permutation is one piece a row).
*
* Other repeats are refused: a lookup built with std::map::emplace would silently keep the
* first, so a copy-paste mistake would convert weights from the wrong tensors. */
@@ -997,11 +1035,12 @@ int Builder::decl_name_map(const RadNameMap* m) {
if (seen != name_map_first_.end()) {
const RadNameMap& first = prog_.name_map[seen->second];
const bool joins = (c.mode == RAD_MAP_CONCAT && first.mode == RAD_MAP_CONCAT) ||
(c.mode == RAD_MAP_EMA && first.mode == RAD_MAP_EMA);
(c.mode == RAD_MAP_EMA && first.mode == RAD_MAP_EMA) ||
(c.mode == RAD_MAP_ROWS && first.mode == RAD_MAP_ROWS);
if (!joins) {
err(RAD_E_INVAL, "name map for '%s': declared twice, and only a CONCAT or EMA map may "
"be extended -- a repeated COPY map means two sources for one weight, "
"and which one wins is not something a declaration can express",
err(RAD_E_INVAL, "name map for '%s': declared twice, and only a CONCAT, ROWS or EMA "
"map may be extended -- a repeated COPY map means two sources for one "
"weight, and which one wins is not something a declaration can express",
c.declared);
return RAD_E_INVAL;
}
@@ -1192,16 +1231,27 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
: prog_.is_audio_generator() ? "an audio generator" : "a video generator");
return RAD_E_STATE;
}
if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID) {
if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID && d->layout != RAD_GEN_LAYOUT_JOINT_STEP) {
err(RAD_E_INVAL, "declare_generator '%s': layout %d is not one this engine builds", nm,
(int)d->layout);
return RAD_E_INVAL;
}
const bool joint = d->layout == RAD_GEN_LAYOUT_JOINT_STEP;
auto has = [](const char* t, const char* what) { return t && std::strstr(t, what); };
if (!has(d->tmpl_text, "{prompt}") || !has(d->tmpl_edit, "{prompt}") ||
!has(d->tmpl_edit, "{images}") || !has(d->tmpl_image, "{image}")) {
err(RAD_E_INVAL, "declare_generator '%s': tmpl_text needs {prompt}, tmpl_edit {images} and "
"{prompt}, and tmpl_image {image}, where the picture's tokens go", nm);
if (joint ? !has(d->tmpl_text, "{prompt}") || !has(d->tmpl_edit, "{prompt}")
: !has(d->tmpl_text, "{prompt}") || !has(d->tmpl_edit, "{prompt}") ||
!has(d->tmpl_edit, "{images}") || !has(d->tmpl_image, "{image}")) {
err(RAD_E_INVAL, "declare_generator '%s': tmpl_text and tmpl_edit need {prompt}, and "
"with the pictures in the prompt tmpl_edit needs {images} and tmpl_image "
"{image}, where the picture's tokens go", nm);
return RAD_E_INVAL;
}
if (joint && (d->cond_rows <= 0 || !(d->rope_hw_scale > 0) || d->pad_multiple < 0 ||
(d->pad_multiple > 0 && d->pad_token < 0))) {
err(RAD_E_INVAL, "declare_generator '%s': the joint layout needs cond_rows, a positive "
"rope_hw_scale and, with padding, a pad token (cond_rows %lld, scale %g, "
"pad %d to a multiple of %d)", nm, (long long)d->cond_rows,
d->rope_hw_scale, (int)d->pad_token, (int)d->pad_multiple);
return RAD_E_INVAL;
}
if (d->latent_channels <= 0 || d->latent_scale <= 0 || d->size_multiple <= 0 ||
@@ -1219,8 +1269,34 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
(long long)d->default_height, (long long)d->max_lanes);
return RAD_E_INVAL;
}
if (d->n_sigmas < 0 || (d->n_sigmas > 0 && !d->sigmas) ||
(d->n_sigmas == 0 && d->default_steps <= 0) || !(d->default_cfg >= 1.0) ||
if (d->train_steps < 0) {
err(RAD_E_INVAL, "declare_generator '%s': train_steps %d is negative", nm,
(int)d->train_steps);
return RAD_E_INVAL;
}
if (d->train_steps > 0) {
/* A discrete-time denoiser: its own schedule, a sampler it serves by default. */
const uint32_t all = (1u << RAD_GEN_SAMPLER_COUNT) - 1;
if (d->train_steps < 2 || !(d->beta_start > 0) || !(d->beta_end > d->beta_start) ||
!(d->beta_end < 1) ||
(d->beta_schedule != RAD_GEN_BETAS_SCALED_LINEAR &&
d->beta_schedule != RAD_GEN_BETAS_LINEAR) ||
d->n_sigmas != 0 || d->default_steps <= 0 || (d->samplers & ~all) || !d->samplers ||
d->default_sampler < 0 || d->default_sampler >= RAD_GEN_SAMPLER_COUNT ||
!(d->samplers & (1u << d->default_sampler)) || d->default_scheduler < 0 ||
d->default_scheduler >= RAD_GEN_SCHED_COUNT ||
!(d->default_cfg >= (d->cfg_original ? 0.0 : 1.0))) {
err(RAD_E_INVAL, "declare_generator '%s': the discrete-time sampler is incomplete (%d "
"timesteps, betas %g..%g kind %d, %lld default steps, samplers 0x%x "
"default %d, scheduler %d, %d fixed sigmas, guidance %g)", nm,
(int)d->train_steps, d->beta_start, d->beta_end, (int)d->beta_schedule,
(long long)d->default_steps, (unsigned)d->samplers, (int)d->default_sampler,
(int)d->default_scheduler, (int)d->n_sigmas, d->default_cfg);
return RAD_E_INVAL;
}
} else if (d->n_sigmas < 0 || (d->n_sigmas > 0 && !d->sigmas) ||
(d->n_sigmas == 0 && d->default_steps <= 0) ||
!(d->default_cfg >= (d->cfg_original ? 0.0 : 1.0)) ||
(d->dyn_shift && (d->max_seq <= d->base_seq || d->base_seq <= 0)) ||
(!d->dyn_shift && !(d->shift > 0)) || d->shift_terminal < 0 || d->shift_terminal >= 1) {
err(RAD_E_INVAL, "declare_generator '%s': the sampler is incomplete (%d fixed sigmas, %lld "
@@ -1230,6 +1306,23 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
d->shift_terminal, d->default_cfg);
return RAD_E_INVAL;
}
if (d->sigma_grid < 0 || d->min_tokens < 0 || (d->aux_tokens && d->aux_max_tokens <= 0)) {
err(RAD_E_INVAL, "declare_generator '%s': sigma_grid %d, min_tokens %d and a second "
"tokenizer of at most %lld tokens are not a schedule and a prompt it can "
"read", nm, (int)d->sigma_grid, (int)d->min_tokens,
(long long)d->aux_max_tokens);
return RAD_E_INVAL;
}
if (d->chunk_tokens < 0 ||
(d->chunk_tokens > 0 &&
(!joint || d->pad_multiple != 0 || d->pad_token < 0 || d->chunk_bos < 0 ||
d->chunk_eos < 0 || d->cond_rows % (d->chunk_tokens + 2) != 0))) {
err(RAD_E_INVAL, "declare_generator '%s': a prompt in windows of %d tokens needs the joint "
"layout without pad_multiple, bos, eos and pad tokens, and cond_rows a "
"whole number of windows (cond_rows %lld)", nm, (int)d->chunk_tokens,
(long long)d->cond_rows);
return RAD_E_INVAL;
}
for (int i = 0; i < d->n_sigmas; ++i)
if (!(d->sigmas[i] > 0.0 && d->sigmas[i] <= 1.0) ||
(i > 0 && !(d->sigmas[i] < d->sigmas[i - 1]))) {
@@ -1255,17 +1348,19 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
g.name = nm;
g.tmpl_text = d->tmpl_text;
g.tmpl_edit = d->tmpl_edit;
g.tmpl_image = d->tmpl_image;
g.tmpl_image = d->tmpl_image ? d->tmpl_image : "";
g.tmpl_image_sep = d->tmpl_image_sep ? d->tmpl_image_sep : "";
g.drop_prefix = d->drop_prefix ? d->drop_prefix : "";
g.tmpl_transparent = d->tmpl_transparent ? d->tmpl_transparent : "";
g.has_default_negative = d->default_negative != nullptr;
g.default_negative = d->default_negative ? d->default_negative : "";
g.sigmas.assign(d->sigmas, d->sigmas + d->n_sigmas);
prog_.generator = *d;
/* The Program is moved after declare, which would invalidate pointers into gen_str, so the
* decl's string fields are cleared; read them only through gen_str. */
RadGeneratorDecl& c = prog_.generator;
c.name = c.tmpl_text = c.tmpl_edit = c.tmpl_image = c.tmpl_image_sep = nullptr;
c.drop_prefix = c.tmpl_transparent = nullptr;
c.drop_prefix = c.tmpl_transparent = c.default_negative = nullptr;
c.sigmas = nullptr;
return RAD_OK;
}
@@ -1461,22 +1556,78 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) {
(long long)d->audio_latent_channels);
return RAD_E_INVAL;
}
if (d->default_steps <= 0 || d->max_steps < d->default_steps || !(d->shift_video > 0.0) ||
!(d->shift_audio > 0.0) || d->max_lanes <= 0) {
/* Form 1 (LTX-2's FlowMatchEulerDiscrete) steps both modalities the same sigmas and reads
* no per-modality shift. */
const bool shifts = d->sched_kind == 1 || (d->shift_video > 0.0 && d->shift_audio > 0.0);
if (d->default_steps <= 0 || d->max_steps < d->default_steps || !shifts || d->max_lanes <= 0) {
err(RAD_E_INVAL, "declare_video_generator '%s': the sampler is incomplete (%lld steps by "
"default, %lld at most, shifts %g and %g, %lld lanes)", nm,
(long long)d->default_steps, (long long)d->max_steps, d->shift_video, d->shift_audio,
(long long)d->max_lanes);
return RAD_E_INVAL;
}
if (d->n_rungs < 0 || (d->n_rungs > 0 && !d->rungs) ||
(d->n_rungs > 0 && (d->default_steps != d->n_rungs + 1 || d->max_steps != d->n_rungs + 1))) {
err(RAD_E_INVAL, "declare_video_generator '%s': a trained schedule of %d rungs runs %d grid "
"points, which default_steps and max_steps must both be (%lld, %lld)", nm,
(int)d->n_rungs, (int)d->n_rungs + 1, (long long)d->default_steps,
/* Form 0 counts grid points, form 1 evaluations. */
const int64_t rung_steps = d->sched_kind == 1 ? d->n_rungs : d->n_rungs + 1;
if (d->sched_kind < 0 || d->sched_kind > 1 || d->n_rungs < 0 || (d->n_rungs > 0 && !d->rungs) ||
(d->n_rungs > 0 && (d->default_steps != rung_steps || d->max_steps != rung_steps))) {
err(RAD_E_INVAL, "declare_video_generator '%s': a trained schedule of %d rungs runs %lld "
"steps, which default_steps and max_steps must both be (%lld, %lld)", nm,
(int)d->n_rungs, (long long)rung_steps, (long long)d->default_steps,
(long long)d->max_steps);
return RAD_E_INVAL;
}
if (d->sched_kind == 1 && d->dyn_shift &&
(!(d->max_seq > d->base_seq) || !std::isfinite(d->base_shift) ||
!std::isfinite(d->max_shift))) {
err(RAD_E_INVAL, "declare_video_generator '%s': the dynamic shift runs from %lld tokens "
"(%g) to %lld (%g); the second length must be the larger", nm,
(long long)d->base_seq, d->base_shift, (long long)d->max_seq, d->max_shift);
return RAD_E_INVAL;
}
if (!(d->shift_terminal >= 0.0 && d->shift_terminal < 1.0)) {
err(RAD_E_INVAL, "declare_video_generator '%s': shift_terminal %g is outside [0, 1)", nm,
d->shift_terminal);
return RAD_E_INVAL;
}
if (d->n_refine_rungs < 0 || (d->n_refine_rungs > 0 && (!d->refine_rungs ||
d->sched_kind != 1 || d->n_rungs == 0 || !(d->upscale_max > 1.0)))) {
err(RAD_E_INVAL, "declare_video_generator '%s': refinement rungs need a trained schedule of "
"form 1 and a latent upscaler", nm);
return RAD_E_INVAL;
}
for (int i = 0; i < d->n_refine_rungs; ++i)
if (!(d->refine_rungs[i] > 0.0 && d->refine_rungs[i] <= 1.0) ||
(i > 0 && !(d->refine_rungs[i] < d->refine_rungs[i - 1]))) {
err(RAD_E_INVAL, "declare_video_generator '%s': refinement rung %d (%g) is outside "
"(0, 1] or not below the one before it", nm, i, d->refine_rungs[i]);
return RAD_E_INVAL;
}
if (d->step_text_rows < 0 || d->step_text_rows > d->max_text * 64 || d->image_crf < 0 ||
d->image_crf > 51 || (d->image_cond != 0 && d->image_cond != 1) ||
(d->guidance != 0 && d->guidance != 1)) {
err(RAD_E_INVAL, "declare_video_generator '%s': step_text_rows %lld, image_cond %d, "
"image_crf %d (0..51) or guidance %d is out of range", nm,
(long long)d->step_text_rows, (int)d->image_cond, (int)d->image_crf, (int)d->guidance);
return RAD_E_INVAL;
}
if (d->text_left_pad < 0 || (d->text_left_pad > 0 && d->text_left_pad < d->max_text) ||
d->audio_streams < 0 ||
(d->upscale_exact && (!(d->upscale_max > 1.0) ||
d->upscale_max != std::floor(d->upscale_max)))) {
err(RAD_E_INVAL, "declare_video_generator '%s': text_left_pad %lld must hold the longest "
"prompt (%lld), audio_streams %d may not be negative, and an exact "
"upscaler's factor (%g) is a whole number above 1", nm,
(long long)d->text_left_pad, (long long)d->max_text, (int)d->audio_streams,
d->upscale_max);
return RAD_E_INVAL;
}
if (d->guidance)
for (int i = 0; i < 8; ++i)
if (!std::isfinite(d->guidance_default[i]) || d->guidance_default[i] < 0.0) {
err(RAD_E_INVAL, "declare_video_generator '%s': default guidance term %d (%g) must "
"be finite and not negative", nm, i, d->guidance_default[i]);
return RAD_E_INVAL;
}
for (int i = 0; i < d->n_rungs; ++i)
if (!(d->rungs[i] > 0.0 && d->rungs[i] <= 1.0) ||
(i > 0 && !(d->rungs[i] < d->rungs[i - 1]))) {
@@ -1486,9 +1637,13 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) {
}
/* An upscaler needs a schedule it can split: one evaluation at the small size at least, and
* `upscale_refine` of them after it by default. */
const int64_t def_evals = d->n_rungs > 0 ? d->n_rungs : d->default_steps - 1;
const int64_t def_evals = d->n_rungs > 0 ? d->n_rungs
: d->sched_kind == 1 ? d->default_steps : d->default_steps - 1;
const bool own_refine = d->n_refine_rungs > 0;
if (d->upscale_max != 0.0 &&
(!(d->upscale_max > 1.0) || d->upscale_refine < 1 || d->upscale_refine >= def_evals)) {
(!(d->upscale_max > 1.0) ||
(!own_refine && (d->upscale_refine < 1 || d->upscale_refine >= def_evals)) ||
(own_refine && d->upscale_refine != d->n_refine_rungs))) {
err(RAD_E_INVAL, "declare_video_generator '%s': a latent upscaler of factor %g at most, "
"refining %d evaluations of %lld by default; the factor must be above 1 "
"and the refinement 1 to %lld", nm, d->upscale_max, (int)d->upscale_refine,
@@ -1521,15 +1676,52 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) {
if (!buf_ok(d->frames_out, RAD_U8, chunk_px, "frames_out") ||
!buf_ok(d->audio_out, RAD_F32, max_samples * d->audio_channels, "audio_out"))
return RAD_E_INVAL;
if (d->duration_out != RAD_NULL_HANDLE) {
if (!buf_ok(d->duration_out, RAD_F32, 1, "duration_out")) return RAD_E_INVAL;
if (!(d->duration_min > 0.0 && d->duration_max > d->duration_min) ||
!std::isfinite(d->duration_max) ||
(d->duration_dtype != RAD_F32 && d->duration_dtype != RAD_BF16)) {
err(RAD_E_INVAL, "declare_video_generator '%s': a length head clamps to "
"[%g, %g] seconds in dtype %u; the bounds must be positive, finite "
"and in order, the dtype f32 or bf16", nm, d->duration_min,
d->duration_max, (unsigned)d->duration_dtype);
return RAD_E_INVAL;
}
}
prog_.vgen_str.name = nm;
prog_.vgen_str.tmpl = d->tmpl;
prog_.vgen_str.rungs.assign(d->rungs, d->rungs + d->n_rungs);
prog_.vgen_str.refine_rungs.assign(d->refine_rungs, d->refine_rungs + d->n_refine_rungs);
prog_.vgen_str.default_negative = d->default_negative ? d->default_negative : "";
prog_.vgen_str.decoders.clear();
prog_.vgen_str.decoder_max_area.clear();
for (const char* s = d->decoders; s && *s;) {
while (*s == ' ') ++s;
const char* e = s;
while (*e && *e != ' ') ++e;
if (e > s) prog_.vgen_str.decoders.emplace_back(s, e);
s = e;
}
for (size_t i = 0; i < prog_.vgen_str.decoders.size(); ++i) {
const int64_t a = d->decoder_max_area ? d->decoder_max_area[i] : 0;
if (a < 0 || a > d->max_area) {
err(RAD_E_INVAL, "declare_video_generator '%s': decoder '%s' makes frames of %lld pixels "
"at most, outside 0..max_area", nm,
prog_.vgen_str.decoders[i].c_str(), (long long)a);
return RAD_E_INVAL;
}
prog_.vgen_str.decoder_max_area.push_back(a > 0 ? a : d->max_area);
}
prog_.video_gen = *d;
/* As for the other generators: the Program is moved after declare; strings and the rungs live
* in vgen_str. */
prog_.video_gen.name = nullptr;
prog_.video_gen.tmpl = nullptr;
prog_.video_gen.rungs = nullptr;
prog_.video_gen.refine_rungs = nullptr;
prog_.video_gen.default_negative = nullptr;
prog_.video_gen.decoders = nullptr;
prog_.video_gen.decoder_max_area = nullptr;
return RAD_OK;
}
@@ -1651,6 +1843,69 @@ int Builder::drafter_shared_kv(int pos_offset) {
return RAD_OK;
}
int Builder::lora_root(const char* native, const char* spellings) {
if (finished_) {
err(RAD_E_STATE, "lora_root after declare finished");
return RAD_E_STATE;
}
if (!native || !*native) {
err(RAD_E_INVAL, "lora_root: an empty checkpoint prefix would put every tensor in one "
"network; name the prefix the network's tensors share");
return RAD_E_INVAL;
}
for (const LoraRoot& r : prog_.lora_roots)
if (r.native == native) {
err(RAD_E_INVAL, "lora_root '%s' declared twice", native);
return RAD_E_INVAL;
}
LoraRoot r;
r.native = native;
std::string cur;
for (const char* p = spellings ? spellings : "";; ++p) {
if (*p && *p != ' ') { cur += *p; continue; }
if (!cur.empty()) r.spellings.push_back(cur == "-" ? std::string() : cur);
cur.clear();
if (!*p) break;
}
prog_.lora_roots.push_back(std::move(r));
return RAD_OK;
}
int Builder::lora_alias(const char* native, const char* from, const char* to, int64_t from_lo,
int64_t from_hi, int64_t to_lo) {
if (finished_) {
err(RAD_E_STATE, "lora_alias after declare finished");
return RAD_E_STATE;
}
bool root = false;
for (const LoraRoot& r : prog_.lora_roots) root = root || (native && r.native == native);
if (!root) {
err(RAD_E_INVAL, "lora_alias '%s': its root '%s' is not declared (rad_lora_root first)",
from ? from : "", native ? native : "");
return RAD_E_INVAL;
}
if (!from || !*from || !to || !*to) {
err(RAD_E_INVAL, "lora_alias under '%s': an empty module path", native);
return RAD_E_INVAL;
}
auto hashes = [](const char* s) { int n = 0; for (; *s; ++s) n += *s == '#'; return n; };
if (hashes(from) != hashes(to)) {
err(RAD_E_INVAL, "lora_alias '%s' -> '%s': %d index placeholders against %d", from, to,
hashes(from), hashes(to));
return RAD_E_INVAL;
}
if (from_lo < 0 || to_lo < 0 || (from_hi != 0 && from_hi <= from_lo)) {
err(RAD_E_INVAL, "lora_alias '%s' -> '%s': rows [%lld, %lld) to %lld", from, to,
(long long)from_lo, (long long)from_hi, (long long)to_lo);
return RAD_E_INVAL;
}
LoraAlias a;
a.root = native; a.from = from; a.to = to;
a.from_lo = from_lo; a.from_hi = from_hi; a.to_lo = to_lo;
prog_.lora_aliases.push_back(std::move(a));
return RAD_OK;
}
void Builder::note_v(const char* f, va_list ap) {
char msg[1024];
vsnprintf(msg, sizeof msg, f ? f : "", ap);
@@ -1739,6 +1994,8 @@ void Builder::finish_layouts() {
const int st = ki->layout ? ki->layout(r.geom.params(), r.geom.n_params(),
operand, &w.enc, w.sel, t, w.n_sel, &L)
: RAD_E_UNSUPPORTED;
/* Reads the bytes uninterpreted (a prefetch): no claim (rad_abi.h). */
if (st == RAD_LAYOUT_ANY) continue;
char enc[256];
rad_enc_format(&w.enc, enc, sizeof enc);
if (st == RAD_E_DTYPE) {
@@ -2090,6 +2347,11 @@ int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) {
return B(b)->kv_group_zero(g);
}
int rad_kv_group_replicated(RadBuilder* b, rad_kvgroup g) {
if (!b) return RAD_E_INVAL;
return B(b)->kv_group_replicated(g);
}
int rad_decl_name_map(RadBuilder* b, const RadNameMap* m) {
if (!b) return RAD_E_INVAL;
return B(b)->decl_name_map(m);
@@ -2115,6 +2377,19 @@ int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) {
return B(b)->drafter_shared_kv(pos_offset);
}
int rad_lora_root(RadBuilder* b, const char* native, const char* spellings) {
if (!b) return RAD_E_INVAL;
return B(b)->lora_root(native, spellings);
}
int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const char* to,
int64_t from_lo, int64_t from_hi, int64_t to_lo) {
if (!b) return RAD_E_INVAL;
return B(b)->lora_alias(native, from, to, from_lo, from_hi, to_lo);
}
int rad_chain_on(void) { return rad_dev_chain_enabled(); }
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) {
if (!b) return RAD_E_INVAL;
return B(b)->declare_encoder(d);
+4 -2
View File
@@ -173,11 +173,13 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
}
}
/* An imported quantisation is served by the family's quantised plugin (startup.h). */
/* An imported quantisation is served by the family's quantised plugin (startup.h). A plugin
* that declines imports (rad_arch_serves_imports) is left out of the family here: neither
* counted as a second quantised plugin nor picked as the only one. */
if (imported && !arch_id.empty() && out->arch_plugin.empty()) {
std::vector<const Plugin*> fam, quantised;
for (const Plugin& p : r.plugins())
if (p.kind == RAD_PLUGIN_ARCH && p.arch_id == arch_id) {
if (p.kind == RAD_PLUGIN_ARCH && p.arch_id == arch_id && p.arch_serves_imports) {
fam.push_back(&p);
if (!p.arch_quant.empty()) quantised.push_back(&p);
}
+2 -1
View File
@@ -67,7 +67,8 @@ std::string rad_home_file(const std::string& home, const std::string& rel);
* `imported`: the checkpoint's quantisation is imported weight by weight (Checkpoint::imports), so
* its descriptor names the producing tool and no plugin claims it. The family's quantised plugin
* serves it: the one plugin claiming a descriptor, or the only plugin if none does. Two quantised
* plugins are refused by name. `out->arch_quant` is the chosen descriptor, which a container
* plugins are refused by name. A plugin whose rad_arch_serves_imports returns 0 is left out of
* both counts. `out->arch_quant` is the chosen descriptor, which a container
* converted from it records. */
int rad_tools_load_plugins(const std::string& radiance_home,
const std::vector<std::string>& hierarchy,
+52 -21
View File
@@ -23,6 +23,7 @@
#include <fstream>
#include <set>
#include <sstream>
#include <sys/stat.h>
namespace rad {
@@ -71,8 +72,12 @@ static const Flag g_flags[] = {
"keys, no reconvert (docs/YARN.md); none: off" },
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" },
{ "--kv-cache-dtype", "T", "bf16 | fp8 -- fp8 halves what a token of context costs" },
{ "--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"
"also K in 6 (0.69); both Qwen3.8-27B and -Flash-Next" },
{ "--host-pool-mib", "N", "pinned host tier" },
{ "--host-headroom-mib", "N", "host RAM to leave free for the system when radiance\n"
" pins its host memory at startup (default 4096)" },
{ "--embedding-placement", "WHERE", "ram (default) | vram: where the token embedding lives. ram\n"
" pins it in host memory beside --host-pool-mib, read over the\n"
" link in place; by default a model whose output head reads the\n"
@@ -99,18 +104,30 @@ static const Flag g_flags[] = {
" or host memory (default 3600). 0 keeps it until the memory\n"
" is wanted" },
{ "--lora", "ADAPTER", "NAME=PATH: serve a PEFT LoRA adapter beside the base model,\n"
" as model NAME (repeatable). The base stays as it is; each\n"
" request picks its adapter by `model`"},
{ "--lora", "ADAPTER", "NAME=PATH: serve a LoRA adapter beside the base model\n"
" (repeatable). A text model takes a PEFT directory and\n"
" serves it as model NAME; an image or video generator takes\n"
" a .safetensors file (kohya, ComfyUI, PEFT, LyCORIS) that\n"
" a request names in `loras`. The base stays as it is"},
{ "--lora-dir", "DIR", "image and video generators: a request may name any\n"
" NAME.safetensors under DIR in `loras`, opened when first\n"
" asked for"},
{ "--max-loras", "N", "adapter slots resident at once (default: the number of\n"
" --lora). Each slot holds one adapter's A/B on the card"},
{ "--max-lora-rank", "R", "the rank each slot is sized for (default 16); a smaller\n"
" adapter is zero-padded, a larger one refused"},
" --lora, 2 with --lora-dir alone). A text model's slot holds\n"
" one adapter, a generator's one request's combination"},
{ "--max-lora-rank", "R", "the rank each slot is sized for (default 16 for a text\n"
" model, 64 for a generator); a text model's larger adapter is\n"
" refused, a generator's larger combination truncated"},
{ "--lora-target-modules", "LIST", "comma-separated HF module leaf names adapters may\n"
" target (q_proj,k_proj,...). Default: what the --lora\n"
" adapters target. Needed with --max-loras and no --lora"},
{ "--placement", "MODE", "all_vram | layer_offload | expert_tiered | auto" },
{ "--control-vector", "MODE", "off | on | disabled: load the control-vector file found\n"
" for this model and start requests off (off) or on (on).\n"
" disabled -- the default, also with no flag at all -- loads\n"
" nothing: no projection op is declared, and a request that\n"
" asks for the vector is refused" },
{ "--deterministic", nullptr, "pin placement to the plan the loader made, so the resident\n"
" set cannot change under the heat engine. The sampler is\n"
" already order-independent and needs no pinning; note that\n"
@@ -223,8 +240,9 @@ static const Flag g_flags[] = {
{ "--video-max-frames", "N", "the most frames sampled from a video" },
{ "--video-max-frame-tokens", "N", "the most prompt tokens one video frame may become; 0 is no cap (a token\n"
" budget processor -- Gemma 4's -- takes 70, 140, 280, 560 or 1120)" },
{ "--image-tokens", "N", "a token-budget processor's image budget (Gemma 4: 70, 140, 280, 560, 1120;\n"
" default the container's); a request's `image_tokens` overrides it" },
{ "--image-tokens", "N", "a token-budget processor's image budget (Gemma 4: 70, 140, 280, 560, 1120,\n"
" which a request's `image_tokens` overrides; GLM-5.3: the most tokens an\n"
" image becomes, at most --mm-max-patches / 4; default the container's)" },
{ "--max-source-pixels", "N", "the largest image or video frame the decoder accepts, before any resize\n"
" (default 67108864). The media flags above default to what the container\n"
" states, and do nothing for a model that takes no media" },
@@ -461,10 +479,12 @@ int config_parse(int argc, char** argv, Config* c) {
/* --gpu-headroom is accepted as an alias of --gpu-headroom-mib. */
else if (S("--gpu-headroom-mib") || S("--gpu-headroom"))
{ if (!num(0, INT64_MAX, &c->gpu_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")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (std::strcmp(v, "bf16") && std::strcmp(v, "fp8")) {
RAD_ERR("--kv-cache-dtype takes bf16 or fp8, not '%s'", v);
if (std::strcmp(v, "bf16") && std::strcmp(v, "fp8") && std::strcmp(v, "fp8_v4") &&
std::strcmp(v, "k6_v4")) {
RAD_ERR("--kv-cache-dtype takes bf16, fp8, fp8_v4 or k6_v4, not '%s'", v);
return RAD_E_INVAL;
}
c->kv_cache_dtype = v;
@@ -514,6 +534,7 @@ int config_parse(int argc, char** argv, Config* c) {
}
c->lora.adapters.emplace_back(std::string(v, eq), std::string(eq + 1));
}
else if (S("--lora-dir")) { if (!(v = need(i))) return RAD_E_INVAL; c->lora.dir = v; }
else if (S("--max-loras")) { if (!num(0, 64, &c->lora.max_loras)) return RAD_E_INVAL; }
else if (S("--max-lora-rank")) { if (!num(1, 512, &c->lora.max_rank)) return RAD_E_INVAL; }
else if (S("--lora-target-modules")) {
@@ -563,6 +584,14 @@ int config_parse(int argc, char** argv, Config* c) {
}
c->placement = v;
}
else if (S("--control-vector")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (std::strcmp(v, "off") && std::strcmp(v, "on") && std::strcmp(v, "disabled")) {
RAD_ERR("--control-vector takes off, on or disabled -- got '%s'", v);
return RAD_E_INVAL;
}
c->control_vector = v;
}
else if (S("--deterministic")) c->deterministic = true;
else if (S("--checkpoint-interval")) { if (!num(0, INT64_MAX, &c->checkpoint_interval)) return RAD_E_INVAL; }
else if (S("--prefill-span")) { if (!num(1, INT32_MAX, &c->prefill_span)) return RAD_E_INVAL; }
@@ -875,21 +904,18 @@ int config_parse(int argc, char** argv, Config* c) {
RAD_ERR("--lora names the adapter '%s' twice", name.c_str());
return RAD_E_INVAL;
}
if (L.max_loras > 0 && L.max_loras < (int)L.adapters.size()) {
RAD_ERR("--max-loras %d holds fewer adapters than the %zu that --lora names",
L.max_loras, L.adapters.size());
return RAD_E_INVAL;
}
const bool rank_given = c->given.count("--max-lora-rank") != 0;
if (!L.enabled() && (rank_given || !L.targets.empty())) {
RAD_ERR("%s sizes runtime LoRA slots, and there are none: give --lora or --max-loras",
rank_given ? "--max-lora-rank" : "--lora-target-modules");
return RAD_E_INVAL;
}
if (L.adapters.empty() && L.max_loras > 0 && L.targets.empty()) {
RAD_ERR("--max-loras with no --lora names no module an adapter may target; give "
"--lora-target-modules (q_proj,k_proj,v_proj,o_proj,...)");
return RAD_E_INVAL;
if (!L.dir.empty()) {
struct stat sb{};
if (stat(L.dir.c_str(), &sb) != 0 || !S_ISDIR(sb.st_mode)) {
RAD_ERR("--lora-dir '%s' is not a directory", L.dir.c_str());
return RAD_E_INVAL;
}
}
if (!c->kld_lora.empty() && !c->kld()) {
RAD_ERR("--kld-lora scores through an adapter in KL mode; give --kld-record or "
@@ -1000,6 +1026,7 @@ const ShowRow kShow[] = {
{ "--gpu-headroom-mib", [](const Config& c) { return num(c.gpu_headroom_mib); } },
{ "--kv-cache-dtype", [](const Config& c) { return c.kv_cache_dtype; } },
{ "--host-pool-mib", [](const Config& c) { return num(c.host_pool_mib); } },
{ "--host-headroom-mib", [](const Config& c) { return num(c.host_headroom_mib); } },
{ "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } },
{ "--ngram-placement", [](const Config& c) { return std::string(table_placement_name(c.ngram_placement)); } },
{ "--vision-tower-placement", [](const Config& c) { return std::string(table_placement_name(c.tower_placement)); } },
@@ -1012,14 +1039,18 @@ const ShowRow kShow[] = {
std::string o;
for (const auto& [n, p] : c.lora.adapters) o += (o.empty() ? "" : ", ") + n + "=" + p;
return o.empty() ? std::string("none") : o; } },
{ "--lora-dir", [](const Config& c) {
return c.lora.dir.empty() ? std::string("none") : c.lora.dir; } },
{ "--max-loras", [](const Config& c) {
return c.lora.enabled() ? num(c.lora.slots()) : std::string("0 (off)"); } },
{ "--max-lora-rank", [](const Config& c) { return num(c.lora.max_rank); } },
{ "--max-lora-rank", [](const Config& c) {
return c.lora.max_rank > 0 ? num(c.lora.max_rank) : std::string("auto (16 text, 64 generator)"); } },
{ "--lora-target-modules", [](const Config& c) {
std::string o;
for (const std::string& t : c.lora.targets) o += (o.empty() ? "" : ",") + t;
return o.empty() ? std::string(c.lora.enabled() ? "the adapters' own" : "-") : o; } },
{ "--placement", [](const Config& c) { return c.placement; } },
{ "--control-vector", [](const Config& c) { return c.control_vector; } },
{ "--deterministic", [](const Config& c) { return onoff(c.deterministic); } },
{ "--checkpoint-interval", [](const Config& c) { return num(c.checkpoint_interval); } },
{ "--prefill-span", [](const Config& c) { return num(c.prefill_span); } },
+318
View File
@@ -0,0 +1,318 @@
/* cvec.cpp -- loading and validating a GGUF control vector (core/cvec.h).
*
* The format is llama.cpp's `controlvector` package: one `direction.<l>` tensor of unit f32 per
* layer, plus three metadata keys. The reader is core/text/gguf.cpp, which already mmaps a GGUF
* and computes tensor byte sizes, so nothing here parses bytes by hand.
*
* The published package (hf.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection) is what the checks
* below are written against, and its own JSON states the operation's parameters:
*
* {"mode": "project", "dir": "per-layer", "scale": 1.0, "layer_range": [4, 44], ...}
*
* so a file is only accepted for a model whose hidden size equals the directions' width and whose
* architecture the file names. Everything else is refused at startup, by name, rather than
* steered along a direction from another residual basis.
*/
#include "cvec.h"
#include "text/gguf.h"
#include <algorithm>
#include <cmath>
#include <fstream>
#include <nlohmann/json.hpp>
namespace rad {
namespace {
/* FNV-1a over the table, so two different vectors never share a cache partition. */
uint64_t hash_table(const ControlVector& cv) {
uint64_t h = 1469598103934665603ull;
const auto mix = [&h](const void* p, size_t n) {
const uint8_t* b = (const uint8_t*) p;
for (size_t i = 0; i < n; ++i) { h ^= b[i]; h *= 1099511628211ull; }
};
mix(cv.dir.data(), cv.dir.size() * sizeof(float));
mix(cv.scales.data(), cv.scales.size() * sizeof(float));
return h ? h : 1ull;
}
} /* namespace */
std::string control_vector_sidecar_path(const std::string& model_path) {
const size_t slash = model_path.find_last_of("/\\");
const size_t dot = model_path.find_last_of('.');
const bool has_ext = dot != std::string::npos && (slash == std::string::npos || dot > slash);
return (has_ext ? model_path.substr(0, dot) : model_path) + ".control-vector.gguf";
}
namespace {
bool file_present(const std::string& p) {
std::ifstream f(p, std::ios::binary);
if (!f) return false;
f.seekg(0, std::ios::end);
return f.tellg() > 0;
}
} /* namespace */
int control_vector_discover(const std::string& model_path, const std::string& arch,
const std::string& radiance_home, std::string* found,
std::string* tried) {
if (!found) return RAD_E_INVAL;
found->clear();
if (tried) tried->clear();
std::vector<std::string> cand;
const size_t slash = model_path.find_last_of("/\\");
const std::string dir = slash == std::string::npos ? std::string(".") : model_path.substr(0, slash);
if (!model_path.empty()) {
cand.push_back(control_vector_sidecar_path(model_path));
/* One file for a directory of containers: each quant of the family shares the directions,
* since the file names the architecture and its width, not the quantisation. */
cand.push_back(dir + "/control-vector.gguf");
}
if (!arch.empty() && !radiance_home.empty()) {
size_t at = 0;
while (at <= radiance_home.size()) {
const size_t colon = radiance_home.find(':', at);
const std::string home = radiance_home.substr(
at, colon == std::string::npos ? std::string::npos : colon - at);
if (!home.empty())
cand.push_back(home + "/vectors/" + arch + "-control-vector.gguf");
if (colon == std::string::npos) break;
at = colon + 1;
}
}
for (const std::string& p : cand) {
if (tried) {
if (!tried->empty()) *tried += ", ";
*tried += p;
}
if (file_present(p)) { *found = p; return RAD_OK; }
}
return RAD_OK;
}
/* The package's own JSON, if it is beside the vector: `{"mode": "project", "scale": 1.0,
* "layer_range": [4, 44]}` is what the published Flash-Next vector ships. It is the only place
* the operation's parameters are stated, so they are read from there rather than configured; a
* malformed or absent file only means the defaults below. */
namespace {
struct PackageJson {
int first = 0, last = -1; /* -1: not stated */
float scale = 1.0f;
};
PackageJson read_package_json(const std::string& gguf_path) {
PackageJson out;
std::string stem = gguf_path;
const size_t dot = stem.find_last_of('.');
const size_t slash = stem.find_last_of("/\\");
if (dot != std::string::npos && (slash == std::string::npos || dot > slash))
stem = stem.substr(0, dot);
const std::string path = stem + ".json";
std::ifstream f(path);
if (!f) return out;
try {
const nlohmann::json j = nlohmann::json::parse(f);
if (const auto m = j.find("mode"); m != j.end() && m->is_string() &&
m->get<std::string>() != "project") {
RAD_WARN("control vector: %s says mode '%s'; only 'project' is implemented, so the "
"defaults apply", path.c_str(), m->get<std::string>().c_str());
return out;
}
if (const auto r = j.find("layer_range"); r != j.end() && r->is_array() && r->size() == 2 &&
(*r)[0].is_number_integer() &&
(*r)[1].is_number_integer()) {
out.first = (*r)[0].get<int>();
out.last = (*r)[1].get<int>();
}
if (const auto s = j.find("scale"); s != j.end() && s->is_number())
out.scale = (float) s->get<double>();
} catch (const std::exception& e) {
RAD_WARN("control vector: %s is not readable JSON (%s); the defaults apply", path.c_str(),
e.what());
}
return out;
}
} /* namespace */
int control_vector_load(const std::string& path, const std::string& arch, int64_t n_embd,
int64_t n_model_layers, ControlVector* out, std::string* err) {
const auto fail = [err](const std::string& why) {
if (err) *err = why;
return RAD_E_INVAL;
};
if (!out) return RAD_E_INVAL;
*out = ControlVector{};
GgufFile f;
const int rc = f.open(path.c_str());
if (rc != RAD_OK)
return fail("control vector " + path + ": cannot read it as a GGUF container");
std::string a;
if (!f.get_str("general.architecture", &a) || a != "controlvector")
return fail("control vector " + path + ": general.architecture is '" + a +
"', not 'controlvector' -- this is not a control vector");
/* The hint is optional in llama.cpp's generator, but when a file states one it must be this
* model's architecture: a direction is a basis vector inferred from that architecture's
* residual stream, and nothing else. */
std::string hint;
if (f.get_str("controlvector.model_hint", &hint) && !hint.empty() && !arch.empty() &&
hint != arch)
return fail("control vector " + path + ": the vector is for architecture '" + hint +
"', this container is '" + arch + "' -- a direction from another model's "
"residual basis would move hidden states along a meaningless axis");
/* The file's directions: direction.<l>, one dimensional, F32, n_embd wide. Anything else is
* refused rather than skipped, because a quietly missing layer is a differently steered model. */
int64_t n_dir = 0, dir_first = -1, dir_last = -1;
for (const GgufTensor& t : f.tensors()) {
if (t.name.rfind("direction.", 0) != 0)
return fail("control vector " + path + ": tensor '" + t.name +
"' is not a direction.<layer> entry");
int64_t layer = 0;
try {
layer = std::stoll(t.name.substr(10));
} catch (...) {
return fail("control vector " + path + ": tensor name '" + t.name +
"' does not end in a layer number");
}
/* 1 .. n_layers-1: the table is indexed by layer (row 0 is unused, the format carrying no
* direction for it), so direction.<n_layers> would write one row past it. */
if (layer < 1 || layer >= n_model_layers)
return fail("control vector " + path + ": direction." + std::to_string(layer) +
" is outside this model's " + std::to_string(n_model_layers) + " layers");
if (t.n_dims != 1 || t.ne[0] != n_embd)
return fail("control vector " + path + ": " + t.name + " is shape [" +
std::to_string(t.ne[0]) + "] with rank " + std::to_string(t.n_dims) +
"; this model's residual streams are " + std::to_string(n_embd) +
" wide and a direction is one row of that");
if (gguf_to_rad_dtype(t.ggml_type) != RAD_F32)
return fail("control vector " + path + ": " + t.name +
" is not F32 -- only an f32 direction is read");
if (dir_first < 0 || layer < dir_first) dir_first = layer;
if (layer > dir_last) dir_last = layer;
++n_dir;
}
if (n_dir == 0) return fail("control vector " + path + ": the file holds no directions");
/* The package's parameters: its JSON, else the published selection where the file covers it,
* else every direction the file carries. A deployment therefore has nothing to configure, and
* a file published with a different selection states it itself. */
const PackageJson pj = read_package_json(path);
int first = pj.first, last = pj.last;
float scale = pj.scale;
if (last < 0) {
if (n_model_layers >= 45 && dir_last >= 44) { first = 4; last = 44; }
else { first = (int) dir_first; last = (int) dir_last; }
}
if (first < 1 || last < first)
return fail("control vector " + path + ": the layer range " + std::to_string(first) + ":" +
std::to_string(last) + " is empty");
if (last >= n_model_layers)
return fail("control vector " + path + ": the layer range " + std::to_string(first) + ":" +
std::to_string(last) + " runs past this model's " +
std::to_string(n_model_layers) + " layers");
if (!(scale > 0.0f) || !std::isfinite(scale))
return fail("control vector " + path + ": its scale is not a positive number");
out->n_embd = n_embd;
/* Indexed by layer: rows 0..n_layers-1. Row 0 stays zero, the format carrying no direction
* for layer 0, and every row a model can name exists. */
out->n_layers = n_model_layers;
out->n_dirs = n_dir;
out->first = first;
out->last = last;
out->user_scale = scale;
out->path = path;
out->dir.assign((size_t) (out->n_layers * n_embd), 0.0f);
out->scales.assign((size_t) out->n_layers, 0.0f);
double worst = 0.0;
for (int64_t l = 1; l <= n_model_layers; ++l) {
const GgufTensor* t = f.tensor("direction." + std::to_string(l));
if (!t) continue;
const float* d = (const float*) f.tensor_data(*t);
if (!d) return fail("control vector " + path + ": " + t->name + " lies outside the file");
double nn = 0.0;
for (int64_t i = 0; i < n_embd; ++i) nn += (double) d[i] * (double) d[i];
const double norm = std::sqrt(nn);
if (!(norm > 0.0) || !std::isfinite(norm))
return fail("control vector " + path + ": " + t->name + " has no direction");
float* dst = &out->dir[(size_t) (l * n_embd)];
const float inv = (float) (1.0 / norm);
for (int64_t i = 0; i < n_embd; ++i) dst[i] = d[i] * inv;
/* Zero outside the range: a layer is steered exactly when its scale is nonzero
* (abi/rad_builder.h, RadControlVector), and a file carries directions for layers the
* package's JSON leaves out. The row is kept so a range change needs no new upload. */
out->scales[(size_t) l] = (l >= first && l <= last) ? (float) norm * scale : 0.0f;
/* A layer inside the range with no direction would silently be unsteered. */
if (l >= first && l <= last) worst = std::max(worst, std::fabs(norm - 1.0));
}
for (int64_t l = first; l <= last; ++l)
if (out->scales[(size_t) l] == 0.0f)
return fail("control vector " + path + ": the range " + std::to_string(first) + ":" +
std::to_string(last) + " includes layer " + std::to_string(l) +
", which has no direction in the file");
if (worst > 1e-2)
RAD_WARN("control vector: %s: the directions are not unit-normalised (worst |norm - 1| "
"= %.4f); each is divided by its own norm, so the operation is unchanged",
path.c_str(), worst);
return RAD_OK;
}
RadControlVector control_vector_view(const ControlVector& cv, const float* dir_device) {
RadControlVector v{};
v.dir = dir_device;
v.scales = cv.scales.data();
v.n_embd = cv.n_embd;
v.n_layers = cv.n_layers;
return v;
}
const float* control_vector_upload(const ControlVector& cv, int rank) {
if (!cv.loaded()) return nullptr;
const int64_t bytes = (int64_t) cv.dir.size() * 4;
void* d = rad_dev_alloc(bytes, RAD_MEM_DEVICE);
if (!d) {
RAD_ERR("control vector: rank %d: could not allocate %.2f MiB on the card for the "
"directions", rank, (double) bytes / (1024.0 * 1024.0));
return nullptr;
}
RadStream s = nullptr;
if (rad_stream_create(&s, 0) < 0) {
rad_dev_free(d, RAD_MEM_DEVICE);
return nullptr;
}
const int rc = rad_memcpy_async(d, cv.dir.data(), bytes, s);
rad_stream_sync(s);
rad_stream_destroy(s);
if (rc < 0) {
RAD_ERR("control vector: rank %d: uploading the directions failed: %s", rank,
rad_dev_last_error());
rad_dev_free(d, RAD_MEM_DEVICE);
return nullptr;
}
return (const float*) d;
}
uint64_t control_vector_salt(const ControlVector& cv) {
if (!cv.loaded()) return 0;
return hash_table(cv) | 1ull;
}
} /* namespace rad */
+101
View File
@@ -0,0 +1,101 @@
/* cvec.h -- control vectors: one GGUF direction per layer, projected out of the residual stream.
*
* ============================== what it is ==============================
*
* The package at huggingface.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection carries one unit
* direction per layer (`direction.1` .. `direction.47`, 2560 f32 each) and the configuration its
* authors selected: the llama.cpp `--cvec-mode project` operation
*
* h <- h - s_l (h . v_l) v_l v_l = d_l / |d_l|, s_l = |d_l|
*
* over layers 4..44, applied to every stream of the gated residual. Strata ports the same
* package (`data/experimental-speed-projection`) with the same operation, range and per-request
* switch; this is that port for radiance, which has its own graph and cannot use llama.cpp's
* patch (arch/qwen4exp_fp8 issues `hc_project` from the op vocabulary instead).
*
* The vector is a refusal-direction projection: with it on the model declines far fewer requests.
* Removing refusals removes a safety behaviour, so the default is OFF and every request names its
* own choice, and the file is only read when the engine finds one for this container.
*
* ============================== compatibility, checked, not assumed ==============================
*
* Nothing here trusts the file's provenance. A vector is refused unless
*
* - `general.architecture` is `controlvector`,
* - `controlvector.model_hint`, when present, names this model's architecture plugin
* (`qwen4exp`), since a direction from another architecture's residual basis is noise,
* - every tensor is `direction.<l>`, F32, one dimension, and exactly the model's `n_embd`,
* - the layer range lies inside the model and every layer in it has a direction.
*
* The published Flash-Next vector passes all four against a Flash-Next container: 47 tensors of
* 2560 f32, hint `qwen4exp`, range 4..44 of 48 layers. A 27B, Gemma or Qwen3.6 container refuses
* it at startup with the reason, rather than serving a model whose hidden states are moved along
* an unrelated direction.
*/
#pragma once
#include "rad_internal.h"
#include <string>
#include <vector>
namespace rad {
/* What a loaded vector keeps on the host, before it is uploaded per rank. `dir` is
* [n_layers * n_embd] f32, unit rows, row 0 unused (the format has no direction for layer 0);
* `scales[l]` is |d_l| * user scale, or 0 where the layer is outside the loaded range. */
struct ControlVector {
std::vector<float> dir;
std::vector<float> scales;
int64_t n_embd = 0;
int64_t n_layers = 0;
int64_t n_dirs = 0; /* directions the file carried (47 for the published one) */
int first = -1, last = -1; /* inclusive layer range */
float user_scale = 1.0f;
std::string path;
bool loaded() const { return n_layers > 0 && n_embd > 0; }
/* Whether layer `l` is steered, i.e. a kernel has something to project. Mirror of the loader's
* range check, used by the architecture plugin at declare. */
bool covers(int64_t l) const {
return loaded() && l >= first && l <= last && l < (int64_t) scales.size() &&
scales[(size_t) l] != 0.0f;
}
};
/* Read and validate `path` against a model of `n_embd` and `n_model_layers`.
*
* The operation's parameters come with the package, never from a command line: `path`'s own
* `<stem>.json` (the JSON the vector is published with) supplies `layer_range` and `scale` when it
* says `"mode": "project"`. Without one, the range is the published Qwen3.8-Flash-Next selection
* (4..44) where the file has directions there, else every layer the file carries, at scale 1. */
int control_vector_load(const std::string& path, const std::string& arch, int64_t n_embd,
int64_t n_model_layers, ControlVector* out, std::string* err);
/* Where a vector for `model_path` is looked for:
* the container's sidecar, then one generic name in the container's directory, then each
* $RADIANCE_HOME's `vectors/` directory. Mirrors gen_sidecar_path's naming so an operator who
* already knows the generation-config convention knows this one. */
std::string control_vector_sidecar_path(const std::string& model_path);
/* Resolve `auto`: sets *found to the first candidate that exists and is non-empty, or to "" when
* none does. *tried receives the candidates, for the log line that says why the feature is
* unavailable on this deployment. Discovery is a filesystem test only; whether the file is
* compatible is control_vector_load's answer. */
int control_vector_discover(const std::string& model_path, const std::string& arch,
const std::string& radiance_home, std::string* found,
std::string* tried);
/* Build the ABI view for one rank. `dir_device` is that rank's [n_layers, n_embd] f32 copy. */
RadControlVector control_vector_view(const ControlVector& cv, const float* dir_device);
/* Upload the host table to a fresh device buffer on rank `rank`, or null on failure. The caller
* owns the buffer and frees it with rad_dev_free. */
const float* control_vector_upload(const ControlVector& cv, int rank);
/* The layer salt a cache uses so that blocks and linear-state snapshots computed with the mode on
* are never handed to a request with it off (or to another vector's). 0 for "off", which is also
* the value the engine uses with no vector loaded, so a deployment without the feature hashes
* exactly as it did before it existed. */
uint64_t control_vector_salt(const ControlVector& cv);
} /* namespace rad */
+128 -30
View File
@@ -16,8 +16,9 @@
*
* Fences: kernels on one queue see each other's writes through the L2 with an agent-scope fence.
* System scope is needed only for memory the L2 does not see:
* - the kernel argument ring is in VRAM and written by the host through the BAR, which the L2
* does not snoop. A slot is rewritten one lap after it was last read, so a system-scope
* - the kernel argument ring is written by the host: into VRAM through the BAR when the BAR
* spans the card's memory, into pinned host memory otherwise. The L2 caches neither without
* an invalidation. A slot is rewritten one lap after it was last read, so a system-scope
* acquire is placed at least once per half lap; without it every kernel after the first lap
* reads its predecessor's arguments. Slots are 1 KiB so no argument fetch shares a cache line
* with the next slot;
@@ -160,6 +161,9 @@ struct KernelRec {
int32_t hid[16]; /* offset of each Hidden kind, or -1 */
uint8_t hid_size[16];
std::string name;
/* A chained form (RadKernelChainFn): its name carries "r4dchain". Only such a kernel gets a
* chain record and may lose its barrier bit; a row's other kernels keep the bit. */
bool chained = false;
};
struct ModuleImage {
@@ -210,6 +214,7 @@ struct Dev {
hsa_amd_memory_pool_t vram{};
bool has_vram = false;
uint32_t kfd_id = 0; /* the driver's gpu_id: its sysfs and ioctls name it so */
bool host_kargs = false; /* no large BAR: the argument ring lives in host memory */
};
struct Global {
@@ -282,8 +287,8 @@ int topo_node(uint32_t gpu_id) {
/* Whether the CPU can write the card's VRAM: 1 yes, 0 no, -1 unknown. The driver maps VRAM for
* the CPU only when the PCI BAR spans all of it. With a smaller BAR (Resizable BAR off or
* unsupported) the topology reports a private frame buffer heap and the runtime maps every VRAM
* allocation PROT_NONE, including the kernel argument rings. The heap type is what the runtime
* itself decides from. */
* allocation PROT_NONE, so argument rings go to host memory instead (init_devices). The heap type
* is what the runtime itself decides from. */
int vram_host_writable(uint32_t gpu_id) {
constexpr unsigned long long kHeapFbPrivate = 2; /* HSA_HEAPTYPE_FRAME_BUFFER_PRIVATE */
const int n = gpu_id ? topo_node(gpu_id) : -1;
@@ -405,14 +410,26 @@ bool init_devices() {
g.why = fmt("HIP device %d (%s) has no matching HSA agent with a VRAM pool", i, bus);
return false;
}
/* The host writes every dispatch's arguments into VRAM (a_stream_create), so a card the
* CPU cannot write is refused here instead of at the first launch's SIGSEGV. */
/* The host writes every dispatch's arguments (a_stream_create), in VRAM when the BAR
* spans it. A smaller BAR makes the runtime map VRAM for the CPU PROT_NONE, which would
* fault at the first launch; the ring goes to pinned host memory instead, as HIP's own
* launches do, at the cost of the card reading each dispatch's arguments over the link. */
if (vram_host_writable(g.dev[(size_t)i].kfd_id) == 0) {
g.why = fmt("card %d (%s) does not let the CPU write its VRAM: its PCI BAR is smaller "
"than its memory. The AQL backend needs Resizable BAR -- turn on Above 4G "
"Decoding and Resizable BAR in the firmware setup; `lspci -vv` then shows "
"the card's first region as large as its VRAM", i, bus);
return false;
g.dev[(size_t)i].host_kargs = true;
RAD_WARN("device: card %d (%s) has a PCI BAR smaller than its VRAM (Resizable BAR "
"off, or the slot's window too small), so kernel arguments stay in pinned host "
"memory and every dispatch reads them across the link, which costs launch "
"rate. Above 4G Decoding and Resizable BAR in the firmware setup remove the "
"difference where the slot allows it",
i, bus);
}
/* The fallback on a card that needs none, to measure what reading each dispatch's
* arguments across the link costs against the same card's VRAM rings. */
const char* force_host_kargs = std::getenv("RADIANCE_DEBUG_AQL_HOST_KARGS");
if (force_host_kargs && *force_host_kargs && *force_host_kargs != '0') {
g.dev[(size_t)i].host_kargs = true;
RAD_WARN("device: card %d (%s): RADIANCE_DEBUG_AQL_HOST_KARGS puts the kernel argument "
"rings in host memory", i, bus);
}
}
/* Without the handler a fault falls back to the runtime's own handling, which the
@@ -495,6 +512,7 @@ KernelRec* resolve(Func* fn, int ord) {
}
auto k = std::make_unique<KernelRec>();
k->name = fn->name;
k->chained = k->name.find("r4dchain") != std::string::npos;
hsa_executable_symbol_get_info(s, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_OBJECT, &k->object);
hsa_executable_symbol_get_info(s, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_KERNARG_SEGMENT_SIZE,
&k->kernarg_size);
@@ -570,7 +588,7 @@ struct Stream {
hsa_agent_t agent{};
hsa_queue_t* q = nullptr;
uint64_t mask = 0;
char* karg = nullptr; /* VRAM, CPU-mapped through the BAR */
char* karg = nullptr; /* VRAM the CPU writes through the BAR, or host memory */
std::atomic<bool> busy{false};
uint64_t wr = 0; /* next packet index */
uint64_t rd = 0; /* last read index seen */
@@ -582,6 +600,16 @@ struct Stream {
std::atomic<int> fault{0};
char* bounce = nullptr; /* pinned, for pageable copies */
std::mutex bounce_mu;
/* Chained launches (RadKernelChainFn): the completion counter every block of a chained kernel
* adds 1 to (in the slot after the argument ring), the blocks of chained kernels issued so
* far, and whether the last packet on the queue was a chained kernel. */
uint64_t* chain_ctr = nullptr;
uint64_t chain_issued = 0;
bool prev_chained = false;
/* Whether a packet that adds nothing to the counter (a plain kernel) may still be running: one
* launched since the last packet whose barrier bit held it behind everything before. A chained
* kernel's wait covers only chained blocks, so while this is set the next one keeps its bit. */
bool plain_inflight = false;
void lock() {
while (busy.exchange(true, std::memory_order_acquire))
@@ -906,7 +934,7 @@ inline int reserve(Stream* s, uint64_t* out) {
inline void publish(Stream* s, uint64_t idx, uint16_t header, uint16_t setup) {
s->wr = idx + 1;
hsa_queue_store_write_index_relaxed(s->q, idx + 1);
_mm_sfence(); /* the argument slot is write-combined VRAM */
_mm_sfence(); /* the argument slot, written before the header */
__atomic_store_n(reinterpret_cast<uint32_t*>(
static_cast<hsa_kernel_dispatch_packet_t*>(s->q->base_address) +
(idx & s->mask)),
@@ -941,13 +969,16 @@ struct TapeRec {
* on the queue still run. Set only where the dispatch touches nothing those packets write
* (tape_set_overlap). */
uint8_t overlap = 0;
/* A chained kernel (RadKernelChainFn): played from the queue's own argument slot with a chain
* record, and without the barrier bit behind another chained kernel. */
uint8_t chain = 0;
};
struct Tape {
uint64_t magic = kTapeMagic;
std::vector<TapeRec> rec;
std::vector<unsigned char> karg_host; /* the argument blocks, kept to compare tapes by */
char* karg = nullptr; /* VRAM, CPU-mapped, from the end of the capture on */
char* karg = nullptr; /* placed at the end of the capture */
std::string bad; /* why this tape cannot be played, if it cannot */
/* Last packet the latest play wrote on each queue; the argument block is freed only after
* all of them are consumed. */
@@ -961,11 +992,12 @@ inline bool capturing() { return t_tape && t_tape_pause == 0; }
/* A dispatch just written at `p` on `s`, with its argument block `ka`. */
void tape_note_dispatch(Stream* s, const hsa_kernel_dispatch_packet_t* p, uint16_t setup,
const unsigned char* ka, uint32_t n, uint8_t fence) {
const unsigned char* ka, uint32_t n, uint8_t fence, bool chain) {
Tape* t = t_tape;
TapeRec r;
r.kind = kTapeDispatch;
r.fence = fence;
r.chain = chain ? 1 : 0;
r.s = s;
r.pkt = *p;
r.pkt.header = 0;
@@ -1000,12 +1032,32 @@ inline int acquire_scope(Stream* s, uint64_t idx, bool forced) {
return HSA_FENCE_SCOPE_AGENT;
}
/* The chain record of a chained launch (RadKernelChainFn) at `slot`: wait for every chained
* block issued before it on `s`. `on` false writes a record no kernel accepts. */
inline void chain_record(Stream* s, char* slot, bool on) {
uint64_t rec[4];
rec[0] = on ? RAD_CHAIN_MAGIC : 0;
rec[1] = s->chain_issued;
rec[2] = (uint64_t)(uintptr_t)s->chain_ctr;
rec[3] = rec[0] ^ rec[1] ^ rec[2] ^ RAD_CHAIN_CHECK;
std::memcpy(slot + RAD_CHAIN_KARG_OFF, rec, sizeof rec);
}
inline uint64_t blocks_of(const hsa_kernel_dispatch_packet_t* p) {
auto n = [](uint32_t g, uint16_t b) { return b ? (uint64_t)((g + b - 1u) / b) : 1u; };
return n(p->grid_size_x, p->workgroup_size_x) * n(p->grid_size_y, p->workgroup_size_y) *
n(p->grid_size_z, p->workgroup_size_z);
}
static_assert(RAD_CHAIN_KARG_OFF >= kKargMax && RAD_CHAIN_KARG_OFF + RAD_CHAIN_REC_BYTES <= kKargSlot,
"the chain record sits in an argument slot's tail, past every kernel's arguments");
int barrier(Stream* s, hsa_signal_t dep, hsa_signal_t done, int acq, int rel,
uint64_t* out_idx = nullptr) {
s->lock();
uint64_t idx = 0;
const int rc = reserve(s, &idx);
if (rc < 0) { s->unlock(); return rc; }
s->prev_chained = false;
s->plain_inflight = false;
if (out_idx) *out_idx = idx;
auto* p = reinterpret_cast<hsa_barrier_and_packet_t*>(
static_cast<hsa_kernel_dispatch_packet_t*>(s->q->base_address) + (idx & s->mask));
@@ -1065,7 +1117,11 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t
p->reserved2 = 0;
p->completion_signal.handle = 0;
constexpr uint16_t setup = 3u << HSA_KERNEL_DISPATCH_PACKET_SETUP_DIMENSIONS;
if (capturing()) tape_note_dispatch(s, p, setup, ka, n, fence);
/* A chained kernel (RadKernelChainFn, named r4dchain*): its record in the slot's tail. */
const bool chain = k->chained && rad_dev_chain_enabled() && s->chain_ctr &&
n <= RAD_CHAIN_KARG_OFF;
if (k->chained) chain_record(s, slot, chain);
if (capturing()) tape_note_dispatch(s, p, setup, ka, n, fence, chain);
/* Attach the ride after the tape copied the packet: a recorded packet carries no signal, and
* a play attaches whichever ride is pending then (PlayRun::put). */
if (s->ride.handle) {
@@ -1074,7 +1130,13 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t
}
const int acq = acquire_scope(s, idx, (fence & kFenceAcquireSystem) != 0);
const int rel = (fence & kFenceReleaseSystem) ? HSA_FENCE_SCOPE_SYSTEM : HSA_FENCE_SCOPE_AGENT;
publish(s, idx, header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel), setup);
/* Behind another chained kernel a chained one waits in its prologue; a completion signal keeps
* the bit, since its completion must cover everything before it. */
const bool keep = !(chain && s->prev_chained && !s->plain_inflight && !p->completion_signal.handle);
publish(s, idx, header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel, keep), setup);
if (chain) s->chain_issued += blocks_of(p);
s->prev_chained = chain;
s->plain_inflight = keep ? !chain : s->plain_inflight || !chain;
s->unlock();
return RAD_OK;
}
@@ -1083,7 +1145,7 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t
* doorbell once per kPlayRing packets: the doorbell is an uncached write across the link and a
* pass is over a thousand dispatches. Each body is copied as recorded; the header is decided now
* as in dispatch(), since its acquire scope depends on host writes since recording. Argument
* blocks were written to VRAM when the tape was made, so no fence precedes the header. Ring
* blocks were placed when the tape was made, so no fence precedes the header. Ring
* before a reserve that would wait: the packet processor only takes announced packets. */
constexpr int kPlayRing = 64;
@@ -1096,6 +1158,7 @@ constexpr int kPlayLeft = 8;
thread_local PlayLeft t_left[kPlayLeft];
struct PlayRun {
const Tape* tape = nullptr; /* the tape played, for a chained record's argument bytes */
Stream* s = nullptr;
uint64_t next = 0; /* the write index after the last packet written */
int unrung = 0;
@@ -1153,16 +1216,38 @@ struct PlayRun {
s->ride.handle = 0;
}
if (done.handle) p->completion_signal = done;
/* A chained record plays from this queue's own argument slot, where its chain record goes:
* the tape's copy is shared by every play, and the next step's play may be written while
* this one runs. */
bool chain = false;
if (r.chain && tape) {
char* slot = s->karg + (size_t)(idx & s->mask) * kKargSlot;
chain = s->chain_ctr && r.karg_len <= RAD_CHAIN_KARG_OFF;
if (chain) {
std::memcpy(slot, tape->karg_host.data() + r.karg_off, r.karg_len);
p->kernarg_address = slot;
chain_record(s, slot, true);
}
}
const int acq = acquire_scope(s, idx, (r.fence & kFenceAcquireSystem) != 0);
int rel = (r.fence & kFenceReleaseSystem) ? HSA_FENCE_SCOPE_SYSTEM : HSA_FENCE_SCOPE_AGENT;
if (rel < rel_min) rel = rel_min;
/* A dispatch carrying a record keeps the bit: its completion must cover everything before
* it on the queue, which an unordered dispatch's does not. */
const bool ordered = foreign || !r.overlap || done.handle;
* it on the queue, which an unordered dispatch's does not. A chained kernel behind another chained one
* on this queue waits in its prologue instead. */
bool ordered = foreign || !r.overlap || done.handle;
/* Not while a plain packet may still run: a played plain kernel the overlap analysis let
* start early (it touched nothing in flight) adds nothing to the counter, so a chained
* kernel that reads its output and sits behind a chained one (a cache read beside a
* collective, say) would wait for the chained blocks only. */
if (chain && s->prev_chained && !s->plain_inflight && !foreign && !done.handle) ordered = false;
const uint16_t h = header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel, ordered);
__atomic_store_n(reinterpret_cast<uint32_t*>(p), (uint32_t)h | ((uint32_t)r.pkt.setup << 16),
__ATOMIC_RELEASE);
foreign = false;
if (chain) s->chain_issued += blocks_of(p);
s->prev_chained = chain;
s->plain_inflight = ordered ? !chain : s->plain_inflight || !chain;
s->wr = idx + 1;
next = idx + 1;
*out_idx = idx;
@@ -1407,15 +1492,20 @@ int a_stream_create(RadStream* out, int high_priority) {
hsa_amd_profiling_set_profiler_enabled(s->q, 1);
if (high_priority) hsa_amd_queue_set_priority(s->q, HSA_AMD_QUEUE_PRIORITY_HIGH);
void* ka = nullptr;
if (hsa_amd_memory_pool_allocate(d.vram, (size_t)(s->mask + 1) * kKargSlot, 0, &ka) !=
hsa_amd_memory_pool_t kpool = d.host_kargs ? G().host_fine : d.vram;
hsa_agent_t kpeer = d.host_kargs ? d.agent : G().cpu;
if (hsa_amd_memory_pool_allocate(kpool, (size_t)(s->mask + 2) * kKargSlot, 0, &ka) !=
HSA_STATUS_SUCCESS ||
hsa_amd_agents_allow_access(1, &G().cpu, nullptr, ka) != HSA_STATUS_SUCCESS) {
hsa_amd_agents_allow_access(1, &kpeer, nullptr, ka) != HSA_STATUS_SUCCESS) {
hsa_queue_destroy(s->q);
device_set_error("rad_stream_create: the kernel argument ring could not be placed in VRAM "
"the host can write -- the AQL backend needs a large BAR");
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");
return RAD_E_DEVICE;
}
s->karg = static_cast<char*>(ka);
s->chain_ctr = reinterpret_cast<uint64_t*>(s->karg + (size_t)(s->mask + 1) * kKargSlot);
*reinterpret_cast<volatile uint64_t*>(s->chain_ctr) = 0;
_mm_sfence();
void* bb = nullptr;
if (hsa_amd_memory_pool_allocate(G().host_fine, kBounceBytes, 0, &bb) != HSA_STATUS_SUCCESS ||
hsa_amd_agents_allow_access(1, &d.agent, nullptr, bb) != HSA_STATUS_SUCCESS) {
@@ -1425,7 +1515,7 @@ int a_stream_create(RadStream* out, int high_priority) {
return RAD_E_NOMEM;
}
s->bounce = static_cast<char*>(bb);
note_alloc(ka, (int64_t)(s->mask + 1) * kKargSlot, -1);
note_alloc(ka, (int64_t)(s->mask + 2) * kKargSlot, -1);
note_alloc(bb, kBounceBytes, -1);
s->id = g_next_queue_id.fetch_add(1, std::memory_order_relaxed);
if (s->id >= kMaxQueues) {
@@ -1758,8 +1848,9 @@ void a_tape_pause(int on) {
else if (t_tape_pause > 0) --t_tape_pause;
}
/* Moves the argument blocks to VRAM on the tape's card, where the packet processor reads them as
* it reads the ring; the packets are then final except for the header. */
/* Moves the argument blocks to the tape's card, into the memory the stream ring uses there: VRAM
* the host writes through the BAR, or pinned host memory without one. The packets are then final
* except for the header. */
RadTape a_tape_end(int keep) {
Tape* t = t_tape;
t_tape = nullptr;
@@ -1783,13 +1874,19 @@ RadTape a_tape_end(int keep) {
}
}
if (!t->karg_host.empty()) {
const Dev& d = G().dev[(size_t)ord];
void* ka = nullptr;
if (hsa_amd_memory_pool_allocate(G().dev[(size_t)ord].vram, t->karg_host.size(), 0, &ka) !=
/* Padded by a slot: a chained kernel played from here reads its record's place
* (RAD_CHAIN_KARG_OFF) past its own arguments. */
hsa_amd_memory_pool_t pool = d.host_kargs ? G().host_fine : d.vram;
hsa_agent_t peer = d.host_kargs ? d.agent : G().cpu;
if (hsa_amd_memory_pool_allocate(pool, t->karg_host.size() + kKargSlot, 0, &ka) !=
HSA_STATUS_SUCCESS ||
hsa_amd_agents_allow_access(1, &G().cpu, nullptr, ka) != HSA_STATUS_SUCCESS) {
hsa_amd_agents_allow_access(1, &peer, nullptr, ka) != HSA_STATUS_SUCCESS) {
if (ka) hsa_amd_memory_pool_free(ka);
device_set_error("the pass cannot be recorded: %zu bytes of kernel arguments could "
"not be placed in VRAM", t->karg_host.size());
"not be placed in %s", t->karg_host.size(),
d.host_kargs ? "pinned host memory" : "VRAM");
tape_free(t);
return nullptr;
}
@@ -1834,6 +1931,7 @@ int a_tape_play(RadTape rt, int from, int to) {
++t_tape_pause;
int rc = RAD_OK;
PlayRun run;
run.tape = t;
for (int i = from; i < to && rc >= 0; ++i) {
const TapeRec& r = t->rec[(size_t)i];
if (r.kind == kTapeDispatch) {
+9
View File
@@ -36,6 +36,15 @@ extern "C" int rad_event_create_as(RadEvent* out, unsigned flags);
/* The host has just written memory that a kernel issued after this call reads, with no host wait
* in between (e.g. a host-site op's output read over the link by the next device op). */
extern "C" void rad_dev_host_wrote(void);
/* Chained launches: chainable rows run their chained forms (RadKernelChainFn), and the backend
* lets a chained kernel (named r4dchain*) wait in its prologue instead of behind the barrier bit.
* Only on the AQL backend, whose queues keep the completion counter. On by default where the
* model's plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays: the
* Gemma 4 31B and 26B) and that drafter decodes speculatively (rad_dev_chain_infer, from the
* engine before any row resolves). RADIANCE_CHAIN=0 turns them off and =1 on wherever the backend
* chains; `auto` is the default. */
extern "C" int rad_dev_chain_enabled(void);
extern "C" void rad_dev_chain_infer(int pays);
/* One range of a ranged copy: `bytes` from source offset `src` to destination offset `dst`, all
* three multiples of four. */
+23
View File
@@ -556,6 +556,29 @@ int rad_event_sync(RadEvent e) {
return dev()->event_sync(e);
}
void rad_dev_host_wrote(void) { dev()->host_wrote(); }
/* Chaining's default, from the engine (rad_dev_chain_infer), and the answer once taken. Only
* where the backend chains: the AQL backend writes the record a chained form reads, while a HIP
* launch carries only the kernel's own arguments. */
static std::atomic<int> g_chain_pays{0};
static std::atomic<int> g_chain{-1};
void rad_dev_chain_infer(int pays) {
g_chain_pays.store(pays ? 1 : 0, std::memory_order_relaxed);
g_chain.store(-1, std::memory_order_relaxed);
}
int rad_dev_chain_enabled(void) {
int on = g_chain.load(std::memory_order_relaxed);
if (on < 0) {
const char* e = std::getenv("RADIANCE_CHAIN");
const bool want = e && *e && std::strcmp(e, "auto") != 0
? *e != '0'
: g_chain_pays.load(std::memory_order_relaxed) != 0;
on = want && std::strcmp(rad::device_backend_name(), "aql") == 0 ? 1 : 0;
g_chain.store(on, std::memory_order_relaxed);
}
return on;
}
int rad_event_elapsed_ms(RadEvent a, RadEvent b, float* out) {
return dev()->event_elapsed_ms(a, b, out);
}
+3 -1
View File
@@ -203,7 +203,9 @@ void check_small_bar(const Facts& f, std::vector<Finding>* out) {
fmt("%s: the host and the other cards see %s of its %s of VRAM", card_name(*c).c_str(),
humanb(c->vram_visible).c_str(), humanb(c->vram_total).c_str()),
"without Resizable BAR a peer can address only a window of the card's memory, which "
"limits peer-to-peer collectives and copies into VRAM from the host",
"limits peer-to-peer collectives and copies into VRAM from the host; the engine also "
"keeps that card's kernel arguments in pinned host memory, and every dispatch reads "
"them across the link",
"enable Resizable BAR (\"Re-Size BAR Support\" and \"Above 4G Decoding\") in the "
"firmware setup");
}
+196 -21
View File
@@ -8,6 +8,7 @@
#include "gen/video_driver.h"
#include "kld.h"
#include "mm/processor.h"
#include "mm/media.h"
#include "build/startup.h"
#include "build/rad_build.h"
@@ -57,6 +58,18 @@ Engine::Readback::~Readback() {
}
Engine::~Engine() {
/* The control vector's per-rank direction copies. Uploaded at declare, outside any arena, so
* nothing else frees them; each rank's copy is freed with that rank's device bound, since the
* allocator is per device. */
for (const auto& r : ranks_) {
if (!r || (size_t) r->index >= cvec_views_.size()) continue;
const float* d = cvec_views_[(size_t) r->index].dir;
if (!d) continue;
if (rad_dev_set(r->device) < 0) continue;
rad_dev_free((void*) d, RAD_MEM_DEVICE);
cvec_views_[(size_t) r->index].dir = nullptr;
}
cvec_views_.clear();
/* --profile-ops prints its final table here, the last point where the program still holds
* the op table the rows name. */
if (cfg_.profile_ops) for (auto& r : ranks_) r->ctx.dump_profile();
@@ -340,6 +353,8 @@ int Engine::issue_ahead(const RadBatch** out) {
if (!pipelining_) return RAD_OK;
for (int i = 0; i < serial_rows_ && serial_done_ > 0; ++i)
sched_.expect_draft(serial_row_[(size_t)i].seq, serial_done_);
for (int i = 0; i < block_rows_; ++i)
sched_.expect_draft(block_row_[(size_t)i].seq, drafter_.depth);
const RadBatch* nb = sched_.step_next();
if (!nb) return RAD_OK;
/* Its rows' tokens, positions and slots, advanced on the card behind this step's acceptance
@@ -390,9 +405,13 @@ int Engine::step_loop() {
int idle = 0;
std::vector<uint64_t> cancel;
/* Not in KL mode: its scored rows are copied out of the logits buffer after collection, and a
* pass issued ahead would overwrite them. */
pipelining_ = !cfg_.kld() && !embedding_ && drafter_.kind != RAD_DRAFT_BLOCK &&
(serial_drafting() || cfg_.n_spec <= 0);
* pass issued ahead would overwrite them. A block drafter pipelines only on the card
* (engine_draft.cpp); the host's driver stages from the committed sequence. */
block_card_ = drafter_.kind == RAD_DRAFT_BLOCK && drafter_.depth > 0 && !cfg_.kld() &&
!embedding_ && [] { const char* v = std::getenv("RADIANCE_DRAFT_BLOCK_HOST");
return !(v && *v && *v != '0'); }();
pipelining_ = !cfg_.kld() && !embedding_ && (drafter_.kind != RAD_DRAFT_BLOCK || block_card_) &&
(serial_drafting() || block_card_ || cfg_.n_spec <= 0);
const bool t_on = (int)log_level() >= (int)Log::Debug;
/* The next step's forward pass when already issued behind the previous step, before its
* readback (Scheduler::step_next). */
@@ -683,10 +702,10 @@ int Engine::step_loop() {
}
if (t_on) phase_mark(PH_SAVE);
/* Queue the serial drafter's passes behind the step before waiting: the card computes
* acceptance itself and every pass reads it there (sched/advance.h), so one wait covers
* the whole step. */
st = issue_serial_drafter(b->step, so);
/* Queue the drafter's passes behind the step before waiting: the card computes acceptance
* itself and every pass reads it there (sched/advance.h), so one wait covers the whole
* step. */
st = block_card_ ? issue_block_drafter(b->step, so) : issue_serial_drafter(b->step, so);
if (st < 0) return fail_loop(st);
st = mark_step_end(b, so);
if (st < 0) return fail_loop(st);
@@ -750,12 +769,13 @@ int Engine::step_loop() {
if (t_on) phase_mark(PH_COMMIT);
if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); }
/* The drafter for the next step. A block drafter runs here, since its passes are staged
* from the committed sequence. A serial one already ran on the card; what remains is to
* check its acceptance against the host's and publish its proposals. Both drivers return
* immediately for a kind that is not theirs. */
st = drafter_.kind == RAD_DRAFT_BLOCK ? run_block_drafter(b->step)
: finish_serial_drafter(so);
/* The drafter for the next step. The host's block driver runs here, since it stages from
* the committed sequence. A serial one, or a block one on the card, already ran; what
* remains is to check its acceptance against the host's and publish its proposals. Each
* driver returns immediately for a kind that is not its own. */
st = drafter_.kind != RAD_DRAFT_BLOCK ? finish_serial_drafter(so)
: block_card_ ? finish_block_drafter(so)
: run_block_drafter(b->step);
if (st < 0) return fail_loop(st);
/* The step ends here, after its draft rounds, so step timing includes them
* (Scheduler::step_finished). */
@@ -1226,6 +1246,18 @@ void Engine::tier_tick() {
}
if (ranks_.size() > 1) (void)rad_dev_set(lead.device);
if (all) {
/* RADIANCE_DEBUG_TIER_VERIFY: now that every rank's window has landed, each
* follower's hash of the replicated groups it gathered is held against the window
* the leader wrote (rad_kv_group_replicated's claim). The sums are taken either way,
* so a failed batch leaves none behind. */
if (lead.tierx.verifying_replicated()) {
for (size_t i = 1; i < ranks_.size(); ++i)
for (const TierJob& j : P.copy) {
uint64_t sum = 0;
if (ranks_[i]->tierx.take_replicated_sum(j.key, &sum) && good)
(void)lead.tierx.verify_replicated(j, (int)i, sum);
}
}
/* A copy is good only if every rank's shard landed; otherwise the host copy is
* partly stale, so the whole batch fails and every slot goes back. */
const std::vector<char> ok(P.copy.size(), good ? 1 : 0);
@@ -1443,6 +1475,11 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
kv_iface_ = std::make_unique<KVBinding<KVManager>>(&ranks_[0]->kv);
pc_iface_ = std::make_unique<PCBinding<PrefixCache>>(&ranks_[0]->prefix);
/* The control vector's identity partitions the block cache (PCBinding::salt_id): a request
* that runs with the projection on never adopts a block or a linear-state snapshot produced
* without it, or the other way round. Zero with no vector loaded, and then every chain hashes
* exactly as it did before the feature existed. */
static_cast<PCBinding<PrefixCache>*>(pc_iface_.get())->salt_id = cvec_salt_;
/* The restore path, installed only when the tiers are on. The scheduler calls it before the
* admission lookup without knowing about tiers, so it is a callable rather than an include in
* core/sched.
@@ -1454,12 +1491,14 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
auto* b = static_cast<PCBinding<PrefixCache>*>(pc_iface_.get());
/* Called inside Scheduler::step() under its lock, which makes touching the cache and rank
* 0's manager safe; nothing here may call back into the scheduler. */
b->restore_fn = [this](const Request& req) {
b->restore_fn = [this, b](const Request& req) {
const uint64_t t0 = rad_mono_ns();
PrefixCache& pc = ranks_[0]->prefix;
std::vector<MMContentKey> mk;
media_keys(req, &mk);
const std::vector<BlockHash> want = pc.restorable_from(req.prompt, mk);
/* Room is made before anything is planned (PCBinding::restore_plan): a chain the free
* list cannot hold would otherwise come back only as far as it reaches. One block
* table serves every rank, so what rank 0's cache gives up is room on every rank. */
const std::vector<BlockHash> want =
b->restore_plan(req, cvec_salt_for(req.sp.use_control_vector));
if (want.empty()) return;
/* The whole chain in one restore. With 4-token blocks a long conversation is tens of
* thousands of entries; batched, it is one launch per (group, layer) per staging batch
@@ -1613,6 +1652,28 @@ bool Engine::state_slots_of(uint64_t seq, std::vector<int32_t>* out) const {
}
/* ------------------------------------------------------------------ the HTTP frontend */
/* The control vector, for /stats and /server_info. `available` is
* what a client should test before sending the field: without a loaded vector a request that asks
* for it is refused, so a UI can hide the control rather than offer a switch that fails. */
std::string Engine::cvec_json() const {
nlohmann::ordered_json o;
o["available"] = cvec_.loaded();
o["default"] = cvec_default_.load();
if (cvec_.loaded()) {
/* The family the file was validated against, not a label the UI supplies: this is the same
* `meta_.arch_id` the loader compared against the file's own model_hint. */
o["arch"] = meta_.arch_id ? meta_.arch_id : "";
o["first"] = cvec_.first;
o["last"] = cvec_.last;
o["n_embd"] = cvec_.n_embd;
o["n_layers"] = cvec_.n_layers;
o["scale"] = cvec_.user_scale;
o["file"] = cvec_.path;
o["mode"] = "project";
}
return o.dump();
}
/* The engine's part of /server_info: model, cards, KV, drafting and wire, for a running process.
* The server holds only interfaces, so the engine renders this object and the server splices it in
* verbatim. */
@@ -1639,6 +1700,7 @@ std::string Engine::engine_info() const {
e["vision_tower_placement"] = { { "asked", table_placement_name(cfg_.tower_placement) },
{ "resolved", table_placement_name(cfg_.tower_resolved) } };
e["prefix_cache"] = cfg_.prefix_cache;
e["control_vector"] = nlohmann::ordered_json::parse(cvec_json());
e["checkpoint_slots"] = cfg_.checkpoint_slots;
e["deterministic"] = cfg_.deterministic;
@@ -1993,6 +2055,15 @@ int Engine::run_server() {
d.tok = &tok_bridge;
d.grammar = &grammar_bridge;
d.live = snap;
/* The control vector, when one was found. The admin endpoint flips the
* default through this; nothing rebuilds a graph, so a toggle takes effect on the next request
* and leaves the running ones alone. */
if (cvec_.loaded()) {
d.control_vector.available = [this] { return cvec_loaded(); };
d.control_vector.get_default = [this] { return cvec_default_on(); };
d.control_vector.set_default = [this](bool on) { set_cvec_default(on); };
d.control_vector.json = [this] { return cvec_json(); };
}
/* An embedding model serves /v1/embeddings and no chat. Its named prompts are the checkpoint's
* sentence-transformers configuration (`sentence_transformers.prompts.*`); a `messages` input
@@ -2114,7 +2185,23 @@ int Engine::run_server() {
o.graph_json = [this] { return dump_graph_json(ranks_[0]->program); };
/* Per request, from a reading at most a second old (Engine::diagnostics_json). */
o.diagnostics_json = [this] { return diagnostics_json(); };
if (cfg_.lora.enabled()) {
if (cfg_.lora.enabled() && ranks_[0]->program.is_pass_driven()) {
/* A generator's request names its adapters in `loras`; `model` stays the model. */
o.gen_lora_acquire = [this](const std::vector<std::pair<std::string, double>>& u,
int32_t* slot, std::shared_ptr<void>* hold, std::string* note,
std::string* e) {
std::vector<LoraUse> uses;
for (const auto& [n, w] : u) uses.push_back({ n, w });
return gen_lora_acquire(uses, slot, hold, note, e);
};
o.gen_lora_names = [this] { return gen_lora_names(); };
o.lora_load = [this](const std::string& n, const std::string& d, std::string* e) {
return lora_load(n, d, e);
};
o.lora_unload = [this](const std::string& n, std::string* e, int* in_flight) {
return lora_unload(n, e, in_flight);
};
} else if (cfg_.lora.enabled()) {
/* `model` picks the adapter, and the served model's own name picks the base. */
for (const auto& [name, dir] : cfg_.lora.adapters)
if (name == o.model_id) {
@@ -2158,7 +2245,7 @@ int Engine::run_server() {
* are refused by name: LFM2-VL takes pictures only, and a token-budget processor (Gemma
* 4's) sizes by soft tokens (--image-tokens, --video-max-frame-tokens), not pixel
* bands. */
if (vc.family == mm::Family::Lfm2 &&
if ((vc.family == mm::Family::Lfm2 || vc.family == mm::Family::Glm5Next) &&
(cfg_.video_min_pixels || cfg_.video_max_pixels || cfg_.video_min_frames ||
cfg_.video_max_frames || cfg_.video_fps || cfg_.video_max_frame_tokens)) {
RAD_ERR("media: this model's processor takes pictures, not video, so the --video-* "
@@ -2176,6 +2263,16 @@ int Engine::run_server() {
}
if (cfg_.image_tokens) vc.image_soft_tokens = *cfg_.image_tokens;
if (cfg_.video_max_frame_tokens) vc.video_soft_tokens = *cfg_.video_max_frame_tokens;
} else if (vc.family == mm::Family::Glm5Next) {
/* GLM-5.3 budgets an image in tokens (max_image_tokens), so --image-tokens is its
* ceiling and the pixel bands do not apply. */
if (cfg_.image_min_pixels || cfg_.image_max_pixels) {
RAD_ERR("media: this model's processor sizes images by a token budget, so "
"--image-min-pixels and --image-max-pixels do nothing; use "
"--image-tokens");
return RAD_E_INVAL;
}
if (cfg_.image_tokens) vc.max_image_tokens = *cfg_.image_tokens;
} else {
if (cfg_.image_tokens) {
RAD_ERR("media: --image-tokens is a token budget, and this model's processor "
@@ -2211,6 +2308,16 @@ int Engine::run_server() {
(long long)encd.patch_dim, (long long)encd.merge);
return RAD_E_INVAL;
}
/* An explicit budget past one pass is refused; the container's is lowered to fit
* (Processor::init), as a pixel band is. */
if (vc.family == mm::Family::Glm5Next && cfg_.image_tokens &&
(int64_t)*cfg_.image_tokens * vc.merge * vc.merge > encd.max_patches) {
RAD_ERR("media: --image-tokens %d is more patches than one encoder pass holds "
"(--mm-max-patches %lld, %lld tokens)", *cfg_.image_tokens,
(long long)encd.max_patches,
(long long)(encd.max_patches / ((int64_t)vc.merge * vc.merge)));
return RAD_E_INVAL;
}
if (vc.family == mm::Family::Gemma4 &&
(int64_t)std::max(vc.image_soft_tokens, vc.video_soft_tokens) * vc.merge * vc.merge >
encd.max_patches) {
@@ -2247,6 +2354,17 @@ int Engine::run_server() {
mm_proc->config().max_pixels_tolerance, mm_proc->config().min_tiles,
mm_proc->config().max_tiles, mm_proc->config().tile,
(long long)encd.max_patches);
else if (mm_proc->config().family == mm::Family::Glm5Next) {
RAD_INFO("media: images through '%s'; an image becomes %d..%d tokens, padded to its "
"canvas rather than stretched; %lld patches a pass",
ranks_[0]->program.encoder_name.c_str(), mm_proc->config().min_image_tokens,
mm_proc->config().max_image_tokens, (long long)encd.max_patches);
if (mm_proc->config().max_image_tokens < vc.max_image_tokens)
RAD_INFO("media: the budget of %d tokens an image is lowered to %d, what one "
"encoder pass holds; --mm-max-patches %lld serves it whole",
vc.max_image_tokens, mm_proc->config().max_image_tokens,
(long long)vc.max_image_tokens * vc.merge * vc.merge);
}
else if (mm_proc->config().family == mm::Family::Gemma4)
RAD_INFO("media: %s%s through '%s'; an image becomes at most %d soft tokens (a "
"request's image_tokens may ask for 70..1120), a video %d a frame at %.3g "
@@ -2348,7 +2466,14 @@ int Engine::run_server() {
gen::Driver* drv = nullptr;
const mm::Processor* proc = nullptr;
server::ImageGenInfo inf;
Tokenizer aux;
bool has_aux = false;
const server::ImageGenInfo& info() const override { return inf; }
int encode_aux(const std::string& text, std::vector<int32_t>* out) const override {
if (!has_aux) return RAD_E_UNSUPPORTED;
out->clear();
return aux.encode(text, *out, /*add_special=*/true, /*parse_special=*/true);
}
int submit(std::unique_ptr<gen::Request> r, std::string* why) override {
return drv->submit(std::move(r), why);
}
@@ -2377,8 +2502,11 @@ int Engine::run_server() {
in.size_multiple = gd.size_multiple;
in.pixel_channels = gd.pixel_channels;
in.max_tokens = gd.max_tokens;
/* Edits need the conditioning network to read pictures. */
in.max_refs = mm_proc ? gd.max_refs : 0;
/* Edits need the conditioning network to read pictures, unless only the generator's
* own encoder reads them. */
in.refs_encoder_only = gd.layout == RAD_GEN_LAYOUT_JOINT_STEP;
in.max_refs = mm_proc || in.refs_encoder_only ? gd.max_refs : 0;
in.ref_shrink_only = gd.ref_shrink_only != 0;
in.ref_area = gd.ref_area;
in.default_width = gd.default_width;
in.default_height = gd.default_height;
@@ -2388,6 +2516,30 @@ int Engine::run_server() {
in.fixed_schedule = !pg.gen_str.sigmas.empty();
in.fixed_steps = (int64_t)pg.gen_str.sigmas.size();
in.default_cfg = gd.default_cfg;
in.cfg_original = gd.cfg_original != 0;
in.has_default_negative = pg.gen_str.has_default_negative;
in.default_negative = pg.gen_str.default_negative;
in.min_tokens = gd.min_tokens;
in.pad_token = gd.pad_token;
in.aux_tokens = gd.aux_tokens != 0;
in.aux_max_tokens = gd.aux_max_tokens;
if (in.aux_tokens) {
if (!aux_vocab_) {
RAD_ERR("images: '%s' reads its prompt through a second tokenizer and %s carries "
"none; convert it with rad-convert --tokenizer2", in.name.c_str(),
cfg_.model.c_str());
return RAD_E_FORMAT;
}
RAD_TRY(image_bridge.aux.init(aux_vocab_));
image_bridge.has_aux = true;
}
in.samplers = gd.train_steps > 0 ? gd.samplers : 0;
in.default_sampler = gd.default_sampler;
in.default_scheduler = gd.default_scheduler;
in.chunk_tokens = gd.chunk_tokens;
in.chunk_bos = gd.chunk_bos;
in.chunk_eos = gd.chunk_eos;
in.chunk_pad = gd.pad_token;
image_bridge.drv = img_gen_;
image_bridge.proc = mm_proc.get();
d.images = &image_bridge;
@@ -2402,6 +2554,9 @@ int Engine::run_server() {
(long long)in.default_height, (long long)in.max_tokens, (long long)in.max_refs,
in.fixed_schedule ? (std::to_string(in.fixed_steps) + " fixed steps").c_str()
: (std::to_string(in.default_steps) + " steps by default").c_str());
if (in.samplers)
RAD_INFO("images: sampler %s, scheduler %s by default", gen::sampler_name(in.default_sampler),
gen::scheduler_name(in.default_scheduler));
}
/* An audio generator's endpoint: the driver's queue, the declared prompt and limits, and the
@@ -2501,6 +2656,19 @@ int Engine::run_server() {
in.shift_audio = vd.shift_audio;
in.upscale_max = vd.upscale_max;
in.upscale_refine = vd.upscale_refine;
in.step_evals = vd.sched_kind == 1;
in.guidance = vd.guidance != 0;
for (int i = 0; i < 8; ++i) in.guidance_default[i] = vd.guidance_default[i];
in.default_negative = pg.vgen_str.default_negative;
in.image_cond = vd.image_cond != 0;
in.image_crf = vd.image_crf;
in.length_head = vd.duration_out != RAD_NULL_HANDLE;
in.decoders = pg.vgen_str.decoders;
in.decoder_max_area = pg.vgen_str.decoder_max_area;
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 "
"needs libx264; this build's libavcodec has none, so input_reference is "
"refused", in.name.c_str(), (int)in.image_crf);
in.max_lanes = vd.max_lanes;
in.max_ref_images = vd.max_ref_images;
in.max_ref_videos = vd.max_ref_videos;
@@ -2569,6 +2737,12 @@ int Engine::run_server() {
RAD_INFO("chat: the template takes reasoning_effort %s, and none or minimal turn "
"thinking off%s%s", list.c_str(), mapped.empty() ? "" : "; mapped: ",
mapped.c_str());
/* What a request naming no effort gets, which a client cannot see: Qwen3.8's template
* renders xhigh into a system prompt (#113). */
const std::string& dflt = srv.template_default_effort();
if (cfg_.reasoning_effort.empty() && !dflt.empty())
RAD_INFO("chat: a request naming no reasoning_effort renders as '%s', the "
"template's own default (--reasoning-effort sets another)", dflt.c_str());
} else if (!mapped.empty()) {
RAD_INFO("chat: reasoning_effort mapped: %s", mapped.c_str());
}
@@ -2643,6 +2817,7 @@ int Engine::run_server() {
/* Startup ends here; a quiet server from now on is an idle one. */
startup_watch_.reset();
srv.note_ready(startup_begin_ns_);
const int rc = srv.run();
/* The watcher tests `watching` first, so clearing it ends the thread without a second stop;
* run() has already torn the transport down. Joining costs up to one sleep interval. */
+82 -3
View File
@@ -19,6 +19,7 @@
*/
#pragma once
#include "rad_core.h"
#include "cvec.h"
#include <map>
#include <set>
#include "build/startup.h"
@@ -31,6 +32,7 @@
#include "text/tokenizer.h"
#include "format/radfile.h"
#include "format/table_copy.h"
#include "lora/adapter.h"
#include "lora/slots.h"
#include <atomic>
@@ -87,6 +89,24 @@ public:
std::string diagnostics_json() const;
bool startup_report_printed() const { return report_printed_; }
/* ---- the control vector's public surface (core/cvec.h).
*
* `cvec_loaded` is whether a vector was found and validated for this container; a request
* asking for the feature on a deployment without one is refused by name rather than silently
* served unprojected. `cvec_default_on` is the runtime default for requests that name no
* choice, and the setter is what POST /admin/control-vector calls: it flips a flag, builds
* nothing, reloads nothing, and leaves every running request alone. */
bool cvec_loaded() const { return cvec_.loaded(); }
bool cvec_default_on() const { return cvec_default_.load(); }
void set_cvec_default(bool on) { cvec_default_.store(on); }
/* {available, default, mode, first, last, n_embd, n_layers, scale, file} for /stats, the
* admin route and the dashboard. */
std::string cvec_json() const;
/* The value the block cache is keyed by for a step with this mode: the vector's identity when
* on, 0 when off. Zero with no vector loaded, so a deployment without the feature hashes
* exactly as before. */
uint64_t cvec_salt_for(bool on) const { return on ? cvec_salt_ : 0; }
private:
/* One thread per tensor-parallel rank, each owning one device. Ranks share the address
* space, so there is no IPC or serialisation and the step batch is shared by pointer rather
@@ -98,6 +118,9 @@ private:
/* serve()'s startup stall watch, released when the server listens (run_server) or the KL
* mode starts (run_kld). */
std::unique_ptr<StallWatch> startup_watch_;
/* rad_mono_ns at the top of start(), so serve() can report how long bringup took. The same
* span the startup watch covers (main.cpp creates it here and ends it at the listen). */
uint64_t startup_begin_ns_ = 0;
std::vector<std::thread> rank_threads_;
Config cfg_;
@@ -152,6 +175,30 @@ public:
int lora_acquire(const std::string& name, int32_t* slot, uint64_t* uid,
std::shared_ptr<void>* hold);
std::vector<std::string> lora_names() const;
/* A generator's adapters: a request names one or more adapter files at their strengths, and
* gets the slot holding exactly that combination, composed into a free (or the least recently
* used idle) slot when none holds it yet. `note` says what the composition left out or
* approximated, for the reply. RAD_E_NOTFOUND names an adapter neither --lora nor --lora-dir
* provides; RAD_E_FULL means every slot is held by running requests. */
struct LoraUse { std::string name; double weight = 1.0; };
int gen_lora_acquire(const std::vector<LoraUse>& uses, int32_t* slot,
std::shared_ptr<void>* hold, std::string* note, std::string* err);
/* The adapter files a generator request may name: --lora's and those under --lora-dir. */
std::vector<std::string> gen_lora_names() const;
bool gen_lora_enabled() const { return lora_gen_; }
private:
/* A generator's adapter files by name (--lora, POST /v1/load_lora_adapter, --lora-dir), opened
* once and kept mapped; compositions read them when a combination is put in a slot. */
int gen_lora_open(const std::string& name, std::shared_ptr<const lora::AdapterFile>* out,
std::string* err);
int gen_lora_start();
/* Every rank's packed bytes into `slot` of its pools, each rank on a stream of its own. */
int lora_copy(int slot, const std::vector<std::vector<lora::PackedSite>>& packed,
std::string* err);
bool lora_gen_ = false;
std::unique_ptr<lora::KeyMap> lora_keys_;
mutable std::mutex lora_lib_mu_;
std::map<std::string, std::pair<std::string, std::shared_ptr<const lora::AdapterFile>>> lora_lib_;
private:
std::atomic<uint64_t> lora_epoch_{0}; /* step-loop iterations, for slot reuse */
lora::SlotTable lora_table_; /* reads lora_epoch_, so declared after it */
@@ -159,6 +206,10 @@ private:
* time. Requests and unloads go to the table alone and never wait for a load's copy. */
std::mutex lora_mu_;
std::set<std::string> lora_targets_;
/* --host-headroom-mib in bytes: the host RAM startup leaves free for the system when it
* pins host memory (engine_bringup.cpp). 4 GiB suits a busy server; a small host wants to
* leave less to make room for its tiers, which is why it is a flag and not a constant. */
int64_t host_headroom_bytes() const { return cfg_.host_headroom_mib * ((int64_t)1 << 20); }
/* Resolves --embedding-placement, --vision-tower-placement and --ngram-placement into Config
* before the card is split (engine_bringup.cpp describes how auto chooses). `wfs` is every
* rank's footprint, read for its towers. `host_late` is the pinned host memory startup
@@ -209,6 +260,9 @@ private:
* which references `vocab_` and must not outlive it. */
std::shared_ptr<const Vocab> vocab_;
std::unique_ptr<VocabView> vocab_view_;
/* The container's second vocabulary (rad-convert --tokenizer2), which an image generator that
* declares `aux_tokens` reads its prompt through; null without one. */
std::shared_ptr<const Vocab> aux_vocab_;
/* The chunk geometry, resolved once and shared: the prefix cache needs the checkpoint interval
* at configure time and the scheduler the whole geometry at init. Resolving it separately
@@ -328,8 +382,8 @@ private:
int issue_ahead(const RadBatch** out);
/* The arena level and the followers' pools, before any release that runs a forward pass. */
int prepare_release(const RadBatch* b);
/* Whether a step may be issued ahead: requires that the drafter, if any, runs on the card (a
* block drafter and the prompt-lookup drafter both read the committed sequence). */
/* Whether a step may be issued ahead: requires that the drafter, if any, runs on the card (the
* prompt-lookup drafter and the host's block driver both read the committed sequence). */
bool pipelining_ = false;
int finish_serial_drafter(const StepOut& so);
/* Handed from issue_serial_drafter to finish_serial_drafter: the drafting rows, the rounds
@@ -353,8 +407,19 @@ private:
void phase_mark(int p);
/* Block driver (spec §10): a context pass mirroring the step just run, then one pass that
* fills every drafted position at once. DFlash2 has this shape. */
* fills every drafted position at once. DFlash2 has this shape. run_block_drafter stages both
* after the commit; on the card (`block_card_`, the default), issue_block_drafter queues them
* behind the step before its readback and finish_block_drafter publishes the proposals after
* the commit, so the step can be issued ahead. RADIANCE_DRAFT_BLOCK_HOST=1 keeps the host's. */
int run_block_drafter(int step);
int block_pass(const RadBatch* db, const char* what, int step);
bool block_card_ = false;
int issue_block_drafter(int step, StepOut& so);
int finish_block_drafter(const StepOut& so);
/* Handed from issue_block_drafter to finish_block_drafter and issue_ahead: the drafting rows,
* in the query pass's order, and how many there are (0 when no query pass ran). */
std::vector<Scheduler::BlockRow> block_row_;
int block_rows_ = 0;
/* Encoder driver (spec §11, core/engine_mm.cpp): encodes every media item the scheduler waits
* on, in passes of whole segments, and reads it back into the item. Runs between steps, never
* inside one. */
@@ -428,6 +493,20 @@ private:
std::string p2p_blocked_;
bool has_ngram_ = false; /* the model carries an n-gram table */
std::string prefix_off_why_; /* why the engine itself turned prefix caching off, or "" */
/* ---- control vectors (core/cvec.h). `cvec_` is the host table, loaded
* once at bringup and empty when the feature is off; `cvec_views_` is, per rank, that table
* uploaded to the rank's card and the ABI view build_ctx hands to a declaring plugin (the
* view's `dir` is the allocation, so one vector holds both). `cvec_salt_` partitions the
* prefix cache between the mode on and off, so a conversation's KV and linear state are never
* reused by a step that would compute different hidden states from the same tokens. */
ControlVector cvec_;
std::vector<RadControlVector> cvec_views_;
uint64_t cvec_salt_ = 0;
/* Runtime default for requests that name no choice (flippable through
* POST /admin/control-vector). Atomic: the server's admin thread writes it while
* request threads read it; nothing about the graph changes with it. */
std::atomic<bool> cvec_default_{false};
std::vector<std::string> env_set_; /* the RADIANCE_* names set when the engine was made */
bool report_printed_ = false;
/* Runtime device identity (PCI address, name, integrated flag, runtime version), read once in
+193 -57
View File
@@ -5,6 +5,7 @@
* Separate from engine.cpp (the hot step loop), with which it shares only the Engine's fields.
*/
#include "engine_priv.h"
#include "rad_internal.h"
#include "engine_hostmem.h"
#include "gen/driver.h"
#include "gen/audio_driver.h"
@@ -275,10 +276,11 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const
}
/* ------------------------------------------------------------------ locked host memory */
/* Host memory left free beside a table locked whole: the process's unpooled allocations, the
* load's staging windows, and the page cache holding the container's hot pages. Without it the
* kernel reclaims the files the engine reads, then the OOM killer runs. */
static const int64_t kLockMargin = (int64_t)4 << 30;
/* The margin (--host-headroom-mib, Engine::host_headroom_bytes): host memory left free beside a
* table locked whole -- the process's unpooled allocations, the load's staging windows, and the
* page cache holding the container's hot pages. Without it the kernel reclaims the files the
* engine reads, then the OOM killer runs. It is dead RAM by design; a host that can reclaim
* cheaply trades it for pool, cache or slots. */
/* Every level of every memory cgroup the process is in, leaf first: `visit(dir, room)` until it
* returns false (cgroup_levels). /proc/self/cgroup reads "0::/path" on v2 and "N:memory:/path"
@@ -309,12 +311,13 @@ static void memory_cgroups(const std::function<bool(const std::string&, int64_t)
}
/* Whether `need` more bytes fit in host memory after `still` more this process will allocate
* first, or why not. Checks MemAvailable; every memory cgroup from the process's own up to the
* visible root (Docker's --memory, enforced by the OOM killer); and, for an mlock()ed copy
* (`mlocks`), RLIMIT_MEMLOCK unless the process has CAP_IPC_LOCK. Pinned memory a card reads is a
* driver userptr mapping, which RLIMIT_MEMLOCK does not count. An unreadable limit is ignored,
* never guessed. */
static bool lockable_room(int64_t need, int64_t still, bool mlocks, std::string* why) {
* first and `margin` (--host-headroom-mib) stays free, or why not. Checks MemAvailable; every
* memory cgroup from the process's own up to the visible root (Docker's --memory, enforced by
* the OOM killer); and, for an mlock()ed copy (`mlocks`), RLIMIT_MEMLOCK unless the process has
* CAP_IPC_LOCK. Pinned memory a card reads is a driver userptr mapping, which RLIMIT_MEMLOCK
* does not count. An unreadable limit is ignored, never guessed. */
static bool lockable_room(int64_t need, int64_t still, int64_t margin, bool mlocks,
std::string* why) {
long long locked_kb = 0;
unsigned long long caps = 0;
{
@@ -334,43 +337,44 @@ static bool lockable_room(int64_t need, int64_t still, bool mlocks, std::string*
return false;
}
if (const int64_t avail = meminfo_bytes("MemAvailable");
avail >= 0 && avail - still - kLockMargin < need) {
avail >= 0 && avail - still - margin < need) {
*why = fmt("%s of memory is available, %s more is still to be allocated (the pinned host "
"pools, the prefix cache's host tier, the checkpoint slots and the host "
"activation arenas), and this wants %s with %s to spare",
"activation arenas), and this wants %s with %s to spare "
"(--host-headroom-mib)",
humanb(avail).c_str(), humanb(still).c_str(), humanb(need).c_str(),
humanb(kLockMargin).c_str());
humanb(margin).c_str());
return false;
}
bool fits = true;
memory_cgroups([&](const std::string& dir, int64_t room) {
if (room - still - kLockMargin >= need) return true;
if (room - still - margin >= need) return true;
*why = fmt("the memory cgroup at %s leaves %s, %s more is still to be allocated, "
"and this wants %s with %s to spare", dir.c_str(),
"and this wants %s with %s to spare (--host-headroom-mib)", dir.c_str(),
humanb(room).c_str(), humanb(still).c_str(), humanb(need).c_str(),
humanb(kLockMargin).c_str());
humanb(margin).c_str());
fits = false;
return false;
});
return fits;
}
/* The most lockable_room(need, still, false) admits, and in `limit` the bound that decides it.
* INT64_MAX when no limit can be read. */
static int64_t lockable_bytes(int64_t still, std::string* limit) {
/* The most lockable_room(need, still, margin, false) admits, and in `limit` the bound that
* decides it. INT64_MAX when no limit can be read. */
static int64_t lockable_bytes(int64_t still, int64_t margin, std::string* limit) {
int64_t most = INT64_MAX;
*limit = "no readable memory limit";
if (const int64_t avail = meminfo_bytes("MemAvailable"); avail >= 0) {
most = avail - still - kLockMargin;
most = avail - still - margin;
*limit = fmt("%s of memory available, less %s still to be allocated and %s to spare",
humanb(avail).c_str(), humanb(still).c_str(), humanb(kLockMargin).c_str());
humanb(avail).c_str(), humanb(still).c_str(), humanb(margin).c_str());
}
memory_cgroups([&](const std::string& dir, int64_t room) {
if (room - still - kLockMargin < most) {
most = room - still - kLockMargin;
if (room - still - margin < most) {
most = room - still - margin;
*limit = fmt("the memory cgroup at %s, which leaves %s, less %s still to be allocated "
"and %s to spare", dir.c_str(), humanb(room).c_str(),
humanb(still).c_str(), humanb(kLockMargin).c_str());
humanb(still).c_str(), humanb(margin).c_str());
}
return true;
});
@@ -470,7 +474,9 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
const int64_t pools_still = (int64_t)cfg_.tp * cfg_.host_pool_mib * MiB +
cfg_.prefix_cache_mib * MiB + host_late;
std::string emb_room_why;
auto emb_room = [&]() { return lockable_room(emb_pin, pools_still, false, &emb_room_why); };
auto emb_room = [&]() {
return lockable_room(emb_pin, pools_still, host_headroom_bytes(), false, &emb_room_why);
};
if (emb_max == 0) {
if (emb == TablePlacement::Ram && emb_asked) {
RAD_ERR("--embedding-placement ram: this model has no token embedding table that only "
@@ -525,7 +531,7 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
std::string why;
const int64_t pin = (int64_t)cfg_.tp * align_up(tower_max, (int64_t)MiB);
if (!lockable_room(pin, pools_still + (int64_t)cfg_.tp * cfg_.embedding_host_mib * MiB,
false, &why)) {
host_headroom_bytes(), false, &why)) {
RAD_ERR("--vision-tower-placement ram: the encoder towers (%s a rank, pinned on every "
"rank) cannot be held in host memory: %s. Use vram.", humanb(tower_max).c_str(),
why.c_str());
@@ -609,7 +615,8 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
} else {
std::string card_why, ram_why;
const bool card = ng == TablePlacement::Auto && ngram_device && card_holds(&card_why);
const bool room = !card && lockable_room(need, still, !ngram_device, &ram_why);
const bool room =
!card && lockable_room(need, still, host_headroom_bytes(), !ngram_device, &ram_why);
if (ng == TablePlacement::Ram) {
if (!room) {
RAD_ERR("--ngram-placement ram: the n-gram table (%s) cannot be held in memory as "
@@ -875,7 +882,9 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
bc.tp_wire_lossy = cfg_.tp_wire_exact ? 0 : 1;
/* The engine always states the KV dtype. RAD_DT_INVALID (zero) remains valid in the ABI for
* other callers and means the plugin's default. */
bc.kv_dtype = cfg_.kv_cache_dtype == "fp8" ? RAD_F8E4M3 : RAD_BF16;
bc.kv_dtype = cfg_.kv_cache_dtype == "bf16" ? RAD_BF16 : RAD_F8E4M3;
bc.kv_quant = cfg_.kv_cache_dtype == "fp8_v4" ? RAD_KVQ_V4
: cfg_.kv_cache_dtype == "k6_v4" ? RAD_KVQ_K6V4 : RAD_KVQ_NONE;
bc.tp_wire_min_bytes = cfg_.tp_wire_min_kb * 1024;
bc.scope = "";
bc.max_enc_patches = cfg_.mm_max_patches > 0 ? cfg_.mm_max_patches : 0;
@@ -886,6 +895,12 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
/* Under --prefill-span every step but a lone prefill is planned at the shared budget
* (Scheduler::step), so a wider step is one sequence; 0 without a span. */
bc.max_mixed_tok = cfg_.prefill_span > 1 ? std::min(max_tok, prefill_shared_tok(cfg_)) : 0;
/* The control vector, when one is loaded: this rank's view, or null. A plugin reads it at
* declare only (the direction table never changes); the per-request switch rides the derived
* mask, not this struct. */
if (cvec_.loaded() && rank >= 0 && rank < (int) cvec_views_.size() &&
cvec_views_[(size_t) rank].dir)
bc.cvec = &cvec_views_[(size_t) rank];
return bc;
}
@@ -991,6 +1006,19 @@ int Engine::declare() {
cfg_.prefix_cache = false;
}
}
/* fp8_v4 and k6_v4 are layouts only the plugin and libr4d's rows for them know. A plugin that
* does not say it serves one (RadArchProbe::kv_quant_ok) would store plain E4M3 under a name
* that promised a smaller cache, so the flag is refused rather than ignored. */
if (cfg_.kv_cache_dtype == "fp8_v4" || cfg_.kv_cache_dtype == "k6_v4") {
const int q = cfg_.kv_cache_dtype == "fp8_v4" ? RAD_KVQ_V4 : RAD_KVQ_K6V4;
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
if (!(pb.kv_quant_ok & (1 << q))) {
RAD_ERR("--kv-cache-dtype %s: the '%s' plugin does not serve it for this model "
"(fp8 does)", cfg_.kv_cache_dtype.c_str(), plugins_.arch_plugin.c_str());
return RAD_E_UNSUPPORTED;
}
}
/* Resolved here, not at argument parsing: the plugin states its drafter's depth, and it is
* selected only once the container is open. Every consumer of `n_spec` (buffer sizing, kernel
* bands, the scheduler's window) runs after this. rad_arch_probe is the core's only source of
@@ -1008,6 +1036,25 @@ int Engine::declare() {
cfg_.n_spec > 0 ? "the depth the drafter in this container states as its operating point"
: "this container carries no draft head");
}
/* Chained launches pay on some speculative steps and cost plain decode (4x R9700: the 31B
* with DFlash2 +13%, the 26B-A4B with DFlash +1%, Qwen3.8-27B with DFlash2 even; the 31B with
* no drafter -6.5%), so they are on by default only where the model's plugin measured a gain
* with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes
* speculatively. */
{
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
rad_dev_chain_infer(cfg_.n_spec > 0 && pb.chain_pays);
const char* e = std::getenv("RADIANCE_CHAIN");
const bool on = rad_dev_chain_enabled() != 0;
const char* why = e && *e && std::strcmp(e, "auto") != 0
? (on || *e == '0' ? "RADIANCE_CHAIN says so" : "the backend does not chain")
: on ? "the model's plugin measured a gain with its speculative drafter"
: "no drafter whose plugin measured a gain with them decodes "
"speculatively, or the backend does not chain";
RAD_INFO("chained launches: %s -- %s", on ? "on" : "off", why);
decide("RADIANCE_CHAIN", on ? "1" : "0", why);
}
/* The audio encoder's pass: the plugin's longest clip, when the model file carries an audio
* encoder (`radiance.encoder` names one) and the deployment is not text-only. */
if (cfg_.mm_audio_frames < 0) {
@@ -1051,6 +1098,64 @@ int Engine::declare() {
* a serial loop times out. Registry::select() and init_instance() share a mutex for this. Each
* thread binds its device first, because the current device is thread-local and the init
* allocates on it. */
/* Control vectors are resolved here, before any rank declares: the plugin reads the direction
* table from RadBuildCtx, so a table that failed validation must stop the server before a graph
* is built around it.
*
* The feature is loaded only when the deployment asks: `--control-vector off|on`. Without it
* nothing is looked for, the graph declares no projection op, and a request that asks for one
* is refused by name -- so a deployment that does not use the feature pays nothing. With the
* flag, the engine looks beside the container (or in the directory, or in
* $RADIANCE_HOME/vectors) and uses the file if it is compatible; its operation parameters come
* from the package's own JSON. A file that does not fit is reported and skipped -- a sidecar
* must never stop a server nobody pointed at it. The flag's value is the startup switch: `off`
* leaves requests off until one asks (or the dashboard flips the default), `on` starts them on. */
const std::string arch = meta_.arch_id ? meta_.arch_id : "";
if (cfg_.control_vector == "disabled") {
RAD_INFO("control vectors: not loaded (no --control-vector); a request that asks for one is "
"refused");
} else if (!arch.empty()) {
std::string proj_path, tried;
(void) control_vector_discover(cfg_.model, arch, cfg_.radiance_home, &proj_path, &tried);
if (proj_path.empty()) {
RAD_INFO("control vectors: none found (%s)", tried.c_str());
} else if (arch != "qwen4exp") {
RAD_WARN("control vectors: %s is for this family only (qwen4exp, whose gated residual "
"carries the projection op); this container is '%s' -- ignoring it",
proj_path.c_str(), arch.c_str());
} else {
std::string why;
const int rc = control_vector_load(proj_path, arch, meta_.n_embd, meta_.n_layers,
&cvec_, &why);
if (rc != RAD_OK) {
RAD_WARN("%s -- serving without it", why.c_str());
cvec_ = ControlVector{};
}
}
}
if (cvec_.loaded()) {
cvec_views_.assign(ranks_.size(), RadControlVector{});
cvec_salt_ = control_vector_salt(cvec_);
/* `--control-vector on` starts the request default on, which is also how `--kld-record`/
* `--kld-ref` score the projection itself: those modes serve no request to carry the
* switch. The switch still decides per request. */
const bool default_on = cfg_.control_vector == "on";
cvec_default_.store(default_on);
RAD_INFO("control vectors: %s: %lld directions of %lld, layers %d..%d, scale %.3f -- "
"default %s%s",
cvec_.path.c_str(), (long long) cvec_.n_dirs,
(long long) cvec_.n_embd, cvec_.first, cvec_.last, (double) cvec_.user_scale,
default_on ? "ON" : "off",
default_on ? " (--control-vector on; a request can still say false)"
: " until a request asks for it (the dashboard's switch, or a request's "
"`control_vector` field)");
decide("control vectors", cvec_.path,
"found beside the container, in its directory, or in $RADIANCE_HOME/vectors; "
"requests opt in");
} else {
cvec_default_.store(false);
}
std::vector<int> st(ranks_.size(), RAD_OK);
std::vector<std::thread> th;
th.reserve(ranks_.size());
@@ -1064,6 +1169,17 @@ int Engine::declare() {
st[(size_t)ri] = RAD_E_DEVICE;
return;
}
/* This rank's copy of the control vector's directions, on the device the thread has
* just bound. Uploaded outside the program's arena: it is not a weight (it is not in
* the container) and not an activation (it lives for the deployment). */
if (cvec_.loaded()) {
const float* d = control_vector_upload(cvec_, ri);
if (!d) {
st[(size_t)ri] = RAD_E_DEVICE;
return;
}
cvec_views_[(size_t)ri] = control_vector_view(cvec_, d);
}
const RadBuildCtx bc = build_ctx(ri, cfg_.max_tok);
LoraDeclare ld;
ld.cfg = &cfg_.lora;
@@ -1361,18 +1477,6 @@ int Engine::plan() {
ngram_bytes = std::max(ngram_bytes, wf.ngram);
ngram_device = ngram_device || wf.ngram_device;
ngram_host = ngram_host || wf.ngram_host;
/* One --max-model-len sequence's cache: the least a KV pool can hold and still serve
* every acceptable request (configure_kv warns below it). --ngram-placement auto puts
* the table on the card only if the pool stays above it. */
{
Config one = cfg_;
one.max_seqs = 1;
KVManager single;
if (single.plan_groups(r->program.kv_groups, one) == RAD_OK) {
kv_floor = std::max(kv_floor, single.ceiling(ctx));
f.kv_one = single.ceiling(ctx);
}
}
/* The staging region is sized only where the arena lends its top: without smaller
* levels nothing returns it to the slab at decode, and a deterministic plan moves
* nothing. */
@@ -1385,6 +1489,13 @@ int Engine::plan() {
ck_slot += probe.checkpoint_bytes();
f.kv_ceiling = probe.ceiling(ctx);
f.kv_fixed = probe.fixed_bytes();
/* One --max-model-len sequence's pool, as the inverse of the real plan: its
* recurrent and conv slots stay allocated with one request active, which a
* separate one-sequence plan would leave out. */
const int64_t MiB = 1ll << 20;
const int64_t need = probe.pool_mib_for_tokens(ctx, (f.kv_ceiling + MiB - 1) / MiB);
if (need >= 0) f.kv_one = need * MiB;
kv_floor = std::max(kv_floor, f.kv_one);
}
/* The step batch's device staging, reserved by the scheduler after this split: block
* tables for max_seqs sequences at max_ctx, media staging for max_tok encoder rows.
@@ -1440,6 +1551,11 @@ int Engine::plan() {
const int64_t ck_cap = INT64_MAX / 8;
const int64_t ck_store = !cfg_.prefix_cache || ck_slot <= 0 ? 0
: ck_n > ck_cap / ck_slot ? ck_cap : ck_slot * ck_n;
/* The direction table was allocated in declare(); it is not part of the program, and
* claiming its bytes back keeps a deployment that offers a vector planning against the
* same card as one that does not (VramFacts::held_out). */
const int64_t cvec_bytes = cvec_.loaded() ? (int64_t) cvec_.dir.size() * 4 : 0;
for (VramFacts& f : facts) f.held_out = cvec_bytes;
RAD_TRY(resolve_table_placement(facts, emb_bytes, wfs, kv_floor, ngram_bytes,
ngram_device, ngram_host, ck_store + host_arenas));
/* The n-gram table was counted off the card; on it, every rank holds the whole table. */
@@ -2773,7 +2889,7 @@ int Engine::size_checkpoint_store(int64_t slot, const char* what) {
int64_t still = cfg_.prefix_cache_mib * ((int64_t)1 << 20);
for (const auto& r : ranks_) still += arena_host_bytes(r->program);
std::string limit;
int64_t room = lockable_bytes(still, &limit);
int64_t room = lockable_bytes(still, host_headroom_bytes(), &limit);
if (!device_is_host()) {
bool lifted = false;
if (const int64_t cap = amdgpu_pin_cap(&lifted); cap > 0) {
@@ -2916,7 +3032,8 @@ int Engine::configure_kv() {
};
if (!sized) return refuse("no host has");
std::string why;
if (!lockable_room(slot * n, 0, false, &why)) return refuse("does not fit: " + why);
if (!lockable_room(slot * n, 0, host_headroom_bytes(), false, &why))
return refuse("does not fit: " + why);
if (ck_store_.open(slot, slot * n) != RAD_OK)
return refuse(std::string("the host did not pin: ") + rad_dev_last_error());
if (!sized_auto)
@@ -2943,21 +3060,17 @@ int Engine::configure_kv() {
{
const bool tier_asked = cfg_.prefix_cache_mib > 0;
const std::vector<int32_t>& cg = ranks_[0]->prefix.cached_groups();
/* One slot holds every rank's shard of an entry; each rank writes only its window. Shards
* can differ or be empty (uneven heads, rad_kv_group_zero), so a slot is the sum and each
* window starts where the previous ends. TierExec::sizes uses the largest rank's entry,
* since the staging ring is per rank. */
std::vector<int64_t> rank_entry(ranks_.size(), 0), entry_off(ranks_.size(), 0);
int64_t entry_bytes = 0, slot_bytes = 0;
for (size_t i = 0; i < ranks_.size(); ++i) {
for (int32_t g : cg) {
const KVGroupPlan* p = ranks_[i]->kv.plan(g);
if (p && p->paged()) rank_entry[i] += p->bytes_per_block;
}
entry_off[i] = slot_bytes;
slot_bytes += rank_entry[i];
entry_bytes = std::max(entry_bytes, rank_entry[i]);
}
/* One slot holds the whole engine's entry: the groups every rank holds alike
* (rad_kv_group_replicated) once, at the front, then every rank's own shard in its own
* window. Shards can differ or be empty (uneven heads, rad_kv_group_zero). The layout is
* TierExec's, so the arithmetic here and the copies agree; TierExec::sizes takes the
* largest rank's entry, since the staging ring is per rank. */
std::vector<const KVManager*> rank_kv;
for (auto& r : ranks_) rank_kv.push_back(&r->kv);
TierExec::SlotLayout layout;
RAD_TRY(TierExec::slot_layout(rank_kv, cg, &layout));
const std::vector<int64_t>& entry_off = layout.own_off;
const int64_t entry_bytes = layout.entry_bytes, slot_bytes = layout.slot_bytes;
/* Snapshots live in the checkpoint store (--checkpoint-slots); --prefix-cache-mib is for
* blocks only. */
@@ -2985,6 +3098,20 @@ int Engine::configure_kv() {
* fit is right after the turn. */
const int64_t held = T.arena().capacity() * tc.block_tokens;
const int64_t ctx = cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train;
if (layout.rep_bytes > 0 && ranks_.size() > 1) {
/* What the slot would be with every rank's copy of the replicated groups. */
const int64_t each = slot_bytes + layout.rep_bytes * (int64_t)(ranks_.size() - 1);
std::string names;
for (const std::string& n : layout.replicated)
names += (names.empty() ? "" : ", ") + n;
RAD_INFO("kv tiers: %s (%s of each entry) is the same on every rank and held "
"once a slot: %s a slot rather than %s, so --prefix-cache-mib %lld "
"holds %lld tokens rather than %lld",
names.c_str(), humanb(layout.rep_bytes).c_str(),
humanb(slot_bytes).c_str(), humanb(each).c_str(),
(long long)cfg_.prefix_cache_mib, (long long)held,
(long long)(tc.host_cap_bytes / each * tc.block_tokens));
}
if (held < ctx)
RAD_WARN("kv tiers: --prefix-cache-mib %lld holds %lld tokens of context (%s "
"per %lld-token block), less than one --max-model-len %lld "
@@ -3112,6 +3239,7 @@ int Engine::configure_kv() {
/* ================================================================== start */
int Engine::start() {
startup_begin_ns_ = rad_mono_ns();
std::vector<int> devs;
std::string inventory;
std::string devnote;
@@ -3654,6 +3782,14 @@ int Engine::load_vocab() {
auto v = std::make_shared<Vocab>();
RAD_TRY(v->load(std::move(vb)));
vocab_ = v;
if (file_ && file_->aux_vocab()) {
VocabBuild ab;
RAD_TRY(vocab_deserialize(file_->base(), (uint64_t)file_->size(), file_->aux_vocab().h, ab));
auto av = std::make_shared<Vocab>();
RAD_TRY(av->load(std::move(ab)));
aux_vocab_ = av;
RAD_INFO("vocab: a second vocabulary of %d tokens", aux_vocab_->n_tokens());
}
auto view = std::make_unique<TokenView>();
RAD_TRY(view->init(vocab_));
+109 -25
View File
@@ -275,7 +275,37 @@ int Engine::finish_serial_drafter(const StepOut& so) {
* one.
*
* Proposals go out through set_draft() like every other.
*
* Two drivers run these passes. run_block_drafter, after the step commits, stages both from the
* committed sequence and reads the proposals back: two host waits a step with the card idle
* between them, and no step issued ahead. The card's driver (issue_block_drafter, the default)
* queues both behind the step before its readback, from the card's acceptance, as the serial
* driver does; RADIANCE_DRAFT_BLOCK_HOST=1 selects the host's.
*/
/* One drafter pass through the barrier. Neither pass samples (no logits in the context pass; the
* query pass has its own selector), so the sampler chain is zero rows. */
int Engine::block_pass(const RadBatch* db, const char* what, int step) {
for (auto& rk : ranks_) {
int s = rk->sampler.build_greedy(0);
if (s < 0) {
RAD_ERR("drafter '%s': build_greedy: %s", drafter_.name, rad_strerror(s));
return s;
}
}
issue_what_.store(kIssueAll, std::memory_order_release);
step_batch_.store(db, std::memory_order_release);
barrier_->arrive_and_wait();
barrier_->arrive_and_wait();
const int s = step_status_.load(std::memory_order_acquire);
if (s < 0)
RAD_ERR("drafter '%s': %s pass of step %d failed: %s -- the engine cannot continue",
drafter_.name, what, step, rad_strerror(s));
/* Probe after each pass; by the step loop's dump these buffers hold stale values. */
if (s >= 0) dump_buffers(ranks_[0]->ctx, step, what);
return s;
}
int Engine::run_block_drafter(int step) {
if (drafter_.kind != RAD_DRAFT_BLOCK || drafter_.depth <= 0) return RAD_OK;
@@ -294,39 +324,16 @@ int Engine::run_block_drafter(int step) {
return RAD_E_STATE;
}
/* Neither pass samples (no logits in the context pass; the query pass has its own selector),
* so the sampler chain is zero rows. */
auto run_pass = [&](const RadBatch* db, const char* what) -> int {
for (auto& rk : ranks_) {
int s = rk->sampler.build_greedy(0);
if (s < 0) {
RAD_ERR("drafter '%s': build_greedy: %s", drafter_.name, rad_strerror(s));
return s;
}
}
issue_what_.store(kIssueAll, std::memory_order_release);
step_batch_.store(db, std::memory_order_release);
barrier_->arrive_and_wait();
barrier_->arrive_and_wait();
const int s = step_status_.load(std::memory_order_acquire);
if (s < 0)
RAD_ERR("drafter '%s': %s pass of step %d failed: %s -- the engine cannot continue",
drafter_.name, what, step, rad_strerror(s));
/* Probe after each pass; by the step loop's dump these buffers hold stale values. */
if (s >= 0) dump_buffers(r0.ctx, step, what);
return s;
};
/* The context pass runs even when nothing drafts: a mid-prompt sequence has hidden states the
* drafter will need, and skipping would leave a permanent hole in its cache. */
if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(run_pass(cb, "context"));
if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(block_pass(cb, "context", step));
/* Cleared so a query batch that could not be built does not republish the previous step's
* proposals. */
draft_out_.clear();
if (n > 0) {
if (const RadBatch* qb = sched_.block_query(step)) {
RAD_TRY(run_pass(qb, "query"));
RAD_TRY(block_pass(qb, "query", step));
const int64_t n_raw = (int64_t)n * steps;
int32_t* const raw = readback_.reserve(n_raw);
if (!raw) return RAD_E_NOMEM;
@@ -346,4 +353,81 @@ int Engine::run_block_drafter(int step) {
return RAD_OK;
}
/* The card's driver: both passes behind the step, without waiting. After the trunk's ranks join,
* the acceptance runs on every rank (ADV_ACCEPT), leaving each sequence's anchor and committed
* end in its StepSlot. The context pass mirrors the trunk step, whose positions the host knows.
* The query pass's rows are device rows that the card positions at the committed end (ADV_BLOCK),
* and its proposals go into the slots behind the anchor (ADV_BTAKE): exactly the token row the
* next verify reads (ADV_TRUNK), so the step issued ahead verifies them with no host round trip.
* collect_step's wait covers both passes and the slots' readback. */
int Engine::issue_block_drafter(int step, StepOut& so) {
block_rows_ = 0;
if (!block_card_) return RAD_OK;
RAD_TRY(advance_all(ADV_ACCEPT, 0, false));
/* The sampled ids before either pass, as the serial driver reads them. */
RAD_TRY(collect_issue(so));
const int steps = drafter_.depth;
const int block = drafter_.block > 0 ? (int)drafter_.block : drafter_.depth + 1;
block_row_.resize((size_t)cfg_.max_seqs);
const int n = sched_.block_begin(block, steps, (int)drafter_.window, drafter_.mask_token,
block_row_.data(), (int)block_row_.size(), /*on_card=*/true);
/* Even when nothing drafts; see run_block_drafter. */
if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(block_pass(cb, "context", step));
if (n <= 0) return RAD_OK;
const RadBatch* qb = sched_.block_query(step);
if (!qb) return RAD_OK;
RAD_TRY(advance_all(ADV_BLOCK, 0, false));
RAD_TRY(block_pass(qb, "query", step));
RAD_TRY(advance_all(ADV_BTAKE, steps, true, n));
Rank& r0 = *ranks_[0];
RAD_TRY(rad_memcpy_async(slots_host_, r0.step_slots,
(int64_t)cfg_.max_seqs * (int64_t)sizeof(StepSlot), r0.ctx.stream()));
block_rows_ = n;
return RAD_OK;
}
/* After commit: check the host's acceptance against the card's, which positioned the query pass
* (a disagreement is a defect and the step is refused, as in finish_serial_drafter), move the
* drafter's filled range, and publish each row's proposal from the slots. */
int Engine::finish_block_drafter(const StepOut& so) {
if (!block_card_) return RAD_OK;
if (block_rows_ > 0) {
const StepPlan& plan = sched_.plan();
for (size_t i = 0; i < plan.e.size(); ++i) {
const StepEntry& e = plan.e[i];
if (so.first_row[i] < 0) continue;
const StepSlot& S = slots_host_[e.card]; /* in range: the builder refuses others */
if (S.acc != so.accepted[i] || S.tok[0] != so.token[i]) {
RAD_ERR("drafter '%s': the card accepted %d draft(s) ending in token %d for "
"sequence %llu and the host %d ending in %d; the query pass ran from the "
"card's", drafter_.name, S.acc, S.tok[0], (unsigned long long)e.seq,
so.accepted[i], so.token[i]);
sched_.block_end();
return RAD_E_STATE;
}
}
}
sched_.block_end();
if (block_rows_ <= 0) return RAD_OK;
Rank& r0 = *ranks_[0];
const int steps = drafter_.depth;
draft_out_.assign((size_t)block_rows_ * (size_t)steps, 0);
for (int i = 0; i < block_rows_; ++i) {
const StepSlot& S = slots_host_[block_row_[(size_t)i].card];
for (int j = 0; j < steps; ++j)
draft_out_[(size_t)i * (size_t)steps + (size_t)j] = S.tok[1 + j];
}
for (int i = 0; i < block_rows_; ++i) {
/* As in finish_serial_drafter: the step issued ahead only carries a request whose answer
* is fixed (Scheduler::step_next_locked), so this agrees with the count it verifies. */
if (!r0.sampler.allows_speculation(block_row_[(size_t)i].seq)) continue;
sched_.set_draft(block_row_[(size_t)i].seq, &draft_out_[(size_t)i * (size_t)steps], steps);
}
return RAD_OK;
}
} /* namespace rad */
+3
View File
@@ -43,6 +43,8 @@ int Engine::gen_loop() {
return fail_loop(st);
};
while (!stopping_.load(std::memory_order_acquire)) {
/* A round of the loop, idle or not: what lets a freed adapter slot cool (lora/slots.h). */
lora_epoch_.fetch_add(1, std::memory_order_acq_rel);
const RadBatch* b = gen_->next(step);
if (!b) {
step_batch_.store(nullptr, std::memory_order_release);
@@ -52,6 +54,7 @@ int Engine::gen_loop() {
}
idle = 0;
if (const int ps = prepare_release(b); ps < 0) return stop(ps);
for (auto& rk : ranks_) rk->ctx.set_gen_lora_slot(gen_->lora_slot());
issue_what_.store(kIssueModel, std::memory_order_release);
step_batch_.store(b, std::memory_order_release);
barrier_->arrive_and_wait(); /* release the ranks */
+321 -13
View File
@@ -4,16 +4,25 @@
* A load packs the adapter for each rank (lora::load_adapter, host only), refuses a module no rank
* placed, copies each rank's bytes into the slot on a stream of its own, waits, and only then
* publishes the name. A request can name the adapter only after the publish, so no step reads a
* slot while it is written. */
* slot while it is written.
*
* A generator keeps its adapter files in a library instead (--lora, --lora-dir, the load
* endpoint), and a slot holds one combination of them at given strengths, named by the
* combination: the first request that asks for it composes it (lora/adapter.h) into a free slot,
* or the least recently used one no request holds, and later ones find it there. */
#include "engine_priv.h"
#include "lora/lora.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstring>
#include <dirent.h>
#include <fstream>
#include <sstream>
#include <sys/stat.h>
#include <thread>
namespace rad {
@@ -50,13 +59,41 @@ int read_targets(const std::string& dir, std::set<std::string>* out, std::string
return RAD_OK;
}
/* A generator's adapter name: a file stem under --lora-dir, possibly in a subdirectory, never
* leaving it. */
bool valid_name(const std::string& n) {
if (n.empty() || n.size() > 200 || n[0] == '/' || n[0] == '.') return false;
if (n.find("..") != std::string::npos || n.find("//") != std::string::npos) return false;
for (char c : n)
if (!(std::isalnum((unsigned char)c) || c == '_' || c == '-' || c == '.' || c == '/' ||
c == ' ' || c == '(' || c == ')' || c == '+' || c == ','))
return false;
return true;
}
bool is_file(const std::string& p) {
struct stat sb{};
return stat(p.c_str(), &sb) == 0 && S_ISREG(sb.st_mode);
}
/* The combination's slot name: the adapters sorted by name, each at its strength. */
std::string combo_key(const std::vector<Engine::LoraUse>& uses) {
std::string k;
for (const Engine::LoraUse& u : uses) k += fmt("%s%s*%.6g", k.empty() ? "" : "+", u.name.c_str(), u.weight);
return k;
}
} /* namespace */
int Engine::lora_targets() {
if (!cfg_.lora.enabled()) return RAD_OK;
lora_targets_ = std::set<std::string>(cfg_.lora.targets.begin(), cfg_.lora.targets.end());
if (lora_targets_.empty()) {
/* A PEFT directory names its targets; an adapter file (a generator's) and a directory of
* them do not, and a generator's default is every plain GEMM under its declared roots. A
* text model refuses "*" at declare. */
for (const auto& [name, dir] : cfg_.lora.adapters) {
if (is_file(dir)) { lora_targets_.insert("*"); continue; }
std::string err;
const int s = read_targets(dir, &lora_targets_, &err);
if (s < 0) {
@@ -64,6 +101,7 @@ int Engine::lora_targets() {
return s;
}
}
if (cfg_.lora.adapters.empty()) lora_targets_.insert("*");
}
lora_table_.reset(cfg_.lora.slots(), &lora_epoch_);
return RAD_OK;
@@ -71,6 +109,12 @@ int Engine::lora_targets() {
int Engine::lora_start() {
if (!cfg_.lora.enabled()) return RAD_OK;
lora_gen_ = ranks_[0]->program.is_pass_driven();
if (!lora_gen_ && cfg_.lora.slots() < (int)cfg_.lora.adapters.size()) {
RAD_ERR("lora: --max-loras %d holds fewer adapters than the %zu that --lora names",
cfg_.lora.slots(), cfg_.lora.adapters.size());
return RAD_E_INVAL;
}
size_t n_sites = 0;
for (const auto& r : ranks_) n_sites += r->program.lora_sites.size();
if (n_sites == 0) {
@@ -82,7 +126,7 @@ int Engine::lora_start() {
}
/* Every target is a module some rank carries adapters on. A leaf the model lacks, or holds
* only outside the trunk (embedding, lm_head, a tower, the drafter), would target nothing. */
{
if (!lora_targets_.count("*")) {
std::set<std::string> carried;
for (const auto& r : ranks_)
for (const lora::Site& site : r->lora_sites)
@@ -117,9 +161,10 @@ int Engine::lora_start() {
for (const std::string& x : lora_targets_) t += (t.empty() ? "" : ",") + x;
RAD_INFO("lora: %zu GEMMs over %zu weights carry adapters on rank 0 (%s); %d slots of rank "
"%d, %s a slot, %s on the card", P.lora_sites.size(), P.lora_pools.size(), t.c_str(),
cfg_.lora.slots(), cfg_.lora.max_rank, humanb(slot_bytes).c_str(),
cfg_.lora.slots(), cfg_.lora.rank(lora_gen_), humanb(slot_bytes).c_str(),
humanb(slot_bytes * cfg_.lora.slots()).c_str());
}
if (lora_gen_) return gen_lora_start();
for (const auto& [name, dir] : cfg_.lora.adapters) {
std::string err;
const int s = lora_load(name, dir, &err);
@@ -135,6 +180,37 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri
std::lock_guard<std::mutex> lk(lora_mu_);
if (!cfg_.lora.enabled()) { *err = "the engine was started without adapters"; return RAD_E_STATE; }
if (name.empty()) { *err = "an adapter needs a name"; return RAD_E_INVAL; }
if (lora_gen_) {
/* A generator's adapter goes into the library; a slot takes it when a request asks. */
if (!valid_name(name)) { *err = "'" + name + "' is not an adapter name"; return RAD_E_INVAL; }
{
std::lock_guard<std::mutex> lk2(lora_lib_mu_);
if (lora_lib_.count(name)) { *err = "an adapter named '" + name + "' is already loaded"; return RAD_E_INVAL; }
}
auto f = std::make_shared<lora::AdapterFile>();
RAD_TRY(f->open(dir, err));
int placed = 0, rank = 0;
std::string first;
for (const lora::FileModule& m : f->modules()) {
std::string why;
if (!lora_keys_->resolve(m.key, &why).empty()) { ++placed; continue; }
if (first.empty()) first = m.key + ": " + why;
}
for (const lora::FileModule& m : f->modules())
if (m.kind == lora::FileModule::LORA && m.t[0]) rank = std::max(rank, (int)m.t[0]->shape[0]);
if (placed == 0) {
*err = fmt("none of its %zu modules is a module of this model (%s)", f->modules().size(),
first.c_str());
return RAD_E_NOTFOUND;
}
RAD_INFO("lora: '%s' -- %s, %d of %zu modules on this model%s%s%s", name.c_str(),
f->kind_name(), placed, f->modules().size(),
rank ? fmt(", rank %d", rank).c_str() : "", first.empty() ? "" : "; not placed: ",
first.c_str());
std::lock_guard<std::mutex> lk2(lora_lib_mu_);
lora_lib_[name] = { dir, f };
return RAD_OK;
}
/* A slot that is still cooling (lora/slots.h) is waited for here rather than answered with a
* retry: the step loop goes round idle or busy, so the wait is milliseconds, and a hot swap
* (unload, then load at once) would otherwise fail under traffic. Only other loads wait on
@@ -155,7 +231,7 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri
std::vector<lora::AdapterInfo> infos(ranks_.size());
std::vector<std::vector<lora::PackedSite>> packed(ranks_.size());
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
const int s = lora::load_adapter(dir, ranks_[ri]->lora_sites, cfg_.lora.max_rank, &infos[ri],
const int s = lora::load_adapter(dir, ranks_[ri]->lora_sites, cfg_.lora.rank(false), &infos[ri],
&packed[ri], err);
if (s < 0) {
if (ranks_.size() > 1) *err = fmt("rank %zu: ", ri) + *err;
@@ -167,7 +243,19 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri
if (s < 0) return s;
}
/* ---- copy, per rank, on a stream of its own (the compute stream may be recording a pass) */
RAD_TRY(lora_copy(slot, packed, err));
lora_table_.publish(slot, name, dir);
const lora::AdapterInfo& a = infos[0];
RAD_INFO("lora: '%s' in slot %d -- %zu modules, rank %lld, alpha %g%s, base %s", name.c_str(),
slot, a.modules.size(), (long long)a.max_module_rank, a.alpha, a.rslora ? " (rsLoRA)" : "",
a.base_model.empty() ? "(unnamed)" : a.base_model.c_str());
return RAD_OK;
}
int Engine::lora_copy(int slot, const std::vector<std::vector<lora::PackedSite>>& packed,
std::string* err) {
/* Each rank on a stream of its own: the compute stream may be recording a pass. */
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
Rank& r = *ranks_[ri];
const Program& P = r.program;
@@ -218,12 +306,6 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri
return rc;
}
}
lora_table_.publish(slot, name, dir);
const lora::AdapterInfo& a = infos[0];
RAD_INFO("lora: '%s' in slot %d -- %zu modules, rank %lld, alpha %g%s, base %s", name.c_str(),
slot, a.modules.size(), (long long)a.max_module_rank, a.alpha, a.rslora ? " (rsLoRA)" : "",
a.base_model.empty() ? "(unnamed)" : a.base_model.c_str());
return RAD_OK;
}
@@ -233,11 +315,237 @@ int Engine::lora_acquire(const std::string& name, int32_t* slot, uint64_t* uid,
}
int Engine::lora_unload(const std::string& name, std::string* err, int* in_flight) {
return lora_table_.unload(name, in_flight, err);
if (!lora_gen_) return lora_table_.unload(name, in_flight, err);
/* A generator's adapter leaves the library, and every combination holding it its slot (at
* once when idle, after its requests otherwise). */
{
std::lock_guard<std::mutex> lk(lora_lib_mu_);
if (!lora_lib_.erase(name)) {
*err = "no adapter named '" + name + "' is loaded";
return RAD_E_NOTFOUND;
}
}
*in_flight = 0;
for (const std::string& k : lora_table_.names()) {
bool uses = false;
size_t at = 0;
while (at <= k.size()) {
const size_t plus = std::min(k.find('+', at), k.size());
const std::string part = k.substr(at, plus - at);
if (part.substr(0, part.rfind('*')) == name) uses = true;
at = plus + 1;
}
if (!uses) continue;
int n = 0;
std::string e;
lora_table_.unload(k, &n, &e);
*in_flight += n;
}
return RAD_OK;
}
std::vector<std::string> Engine::lora_names() const {
return lora_table_.names();
return lora_gen_ ? gen_lora_names() : lora_table_.names();
}
/* ================================================================== generator adapters */
int Engine::gen_lora_start() {
/* Every slot's run of the slot-row table holds its own index (Program::lora_rows). */
for (auto& rp : ranks_) {
Rank& r = *rp;
const Program& P = r.program;
if (!P.lora_rows || P.lora_rows_n <= 0) continue;
const int S = cfg_.lora.slots();
std::vector<int32_t> v((size_t)(S * P.lora_rows_n));
for (int s = 0; s < S; ++s)
std::fill(v.begin() + (int64_t)s * P.lora_rows_n, v.begin() + (int64_t)(s + 1) * P.lora_rows_n, s);
void* d = P.buffers[P.lora_rows].ptr;
if (!d || rad_dev_set(r.device) < 0) {
RAD_ERR("lora: rank %d: the slot-row table has no address", r.index);
return RAD_E_STATE;
}
RadStream st{};
if (rad_stream_create(&st, 0) < 0) return RAD_E_DEVICE;
const int rc = rad_memcpy_async(d, v.data(), (int64_t)v.size() * 4, st);
const int sy = rad_stream_sync(st);
rad_stream_destroy(st);
if (rc < 0 || sy < 0) return RAD_E_DEVICE;
}
lora_keys_ = std::make_unique<lora::KeyMap>(ranks_[0]->program, ranks_[0]->lora_sites);
for (const auto& [name, path] : cfg_.lora.adapters) {
std::string err;
const int s = lora_load(name, path, &err);
if (s < 0) {
RAD_ERR("lora: adapter '%s' (%s): %s", name.c_str(), path.c_str(), err.c_str());
return s;
}
}
if (!cfg_.lora.dir.empty())
RAD_INFO("lora: requests may name the %zu adapter files under %s", gen_lora_names().size(),
cfg_.lora.dir.c_str());
return RAD_OK;
}
int Engine::gen_lora_open(const std::string& name, std::shared_ptr<const lora::AdapterFile>* out,
std::string* err) {
{
std::lock_guard<std::mutex> lk(lora_lib_mu_);
auto it = lora_lib_.find(name);
if (it != lora_lib_.end()) { *out = it->second.second; return RAD_OK; }
}
const std::string path = cfg_.lora.dir + "/" + name + ".safetensors";
if (cfg_.lora.dir.empty() || !valid_name(name) || !is_file(path)) {
*err = "no adapter named '" + name + "'" +
(cfg_.lora.dir.empty() ? std::string(" is loaded")
: " is loaded or under --lora-dir (GET /v1/loras lists them)");
return RAD_E_NOTFOUND;
}
/* lora_load takes lora_mu_, which the caller holds: open here, as lora_load would. */
auto f = std::make_shared<lora::AdapterFile>();
RAD_TRY(f->open(path, err));
RAD_INFO("lora: '%s' opened from --lora-dir -- %s, %zu modules", name.c_str(), f->kind_name(),
f->modules().size());
std::lock_guard<std::mutex> lk(lora_lib_mu_);
lora_lib_[name] = { path, f };
*out = f;
return RAD_OK;
}
std::vector<std::string> Engine::gen_lora_names() const {
std::set<std::string> n;
{
std::lock_guard<std::mutex> lk(lora_lib_mu_);
for (const auto& [k, v] : lora_lib_) n.insert(k);
}
if (!cfg_.lora.dir.empty()) {
/* Two levels: the directory and its subdirectories, as a UI's lora folder is laid out. */
std::vector<std::string> dirs{ "" };
for (size_t i = 0; i < dirs.size(); ++i) {
const std::string rel = dirs[i];
DIR* d = opendir((cfg_.lora.dir + "/" + rel).c_str());
if (!d) continue;
while (dirent* e = readdir(d)) {
const std::string fn = e->d_name;
if (fn.empty() || fn[0] == '.') continue;
const std::string p = rel + fn;
struct stat sb{};
if (stat((cfg_.lora.dir + "/" + p).c_str(), &sb) != 0) continue;
if (S_ISDIR(sb.st_mode)) { if (rel.empty()) dirs.push_back(p + "/"); continue; }
const size_t k = fn.size();
if (k > 12 && fn.compare(k - 12, 12, ".safetensors") == 0) {
const std::string stem = p.substr(0, p.size() - 12);
if (valid_name(stem)) n.insert(stem);
}
}
closedir(d);
}
}
return std::vector<std::string>(n.begin(), n.end());
}
int Engine::gen_lora_acquire(const std::vector<LoraUse>& uses_in, int32_t* slot,
std::shared_ptr<void>* hold, std::string* note, std::string* err) {
*slot = -1;
hold->reset();
if (note) note->clear();
if (!lora_gen_) { *err = "this model takes no adapters (start it with --lora or --lora-dir)"; return RAD_E_STATE; }
/* One entry per adapter, strengths of a repeated name summed; strength 0 is no adapter. */
std::map<std::string, double> by;
for (const LoraUse& u : uses_in) {
if (!std::isfinite(u.weight) || std::fabs(u.weight) > 16.0) {
*err = fmt("adapter '%s': strength %g is outside [-16, 16]", u.name.c_str(), u.weight);
return RAD_E_INVAL;
}
by[u.name] += u.weight;
}
std::vector<LoraUse> uses;
for (const auto& [n, w] : by) if (w != 0.0) uses.push_back({ n, w });
if (uses.empty()) return RAD_OK;
if (uses.size() > 16) { *err = fmt("%zu adapters in one request; at most 16", uses.size()); return RAD_E_INVAL; }
const std::string key = combo_key(uses);
uint64_t uid = 0;
if (lora_table_.acquire(key, slot, &uid, hold) == RAD_OK) return RAD_OK;
std::lock_guard<std::mutex> lk(lora_mu_);
if (lora_table_.acquire(key, slot, &uid, hold) == RAD_OK) return RAD_OK;
const auto t0 = std::chrono::steady_clock::now();
std::vector<lora::Strength> ss;
for (const LoraUse& u : uses) {
lora::Strength s;
s.name = u.name;
s.weight = u.weight;
RAD_TRY(gen_lora_open(u.name, &s.file, err));
ss.push_back(std::move(s));
}
/* A slot: free, or freed from the least recently used combination no request holds. */
const auto give_up = std::chrono::steady_clock::now() + std::chrono::seconds(2);
int sl = -1;
for (;;) {
bool cooling = false;
const int s = lora_table_.reserve(key, &sl, &cooling, err);
if (s >= 0) break;
if (s == RAD_E_FULL && !cooling) {
std::string ev;
if (lora_table_.evict_idle(&ev) == RAD_OK) continue;
*err = fmt("all %d adapter slots are held by running requests with other adapters "
"(--max-loras); retry when one finishes", cfg_.lora.slots());
return RAD_E_FULL;
}
if (s != RAD_E_FULL || stopping_.load(std::memory_order_acquire) ||
std::chrono::steady_clock::now() >= give_up)
return s;
std::this_thread::sleep_for(std::chrono::milliseconds(2));
}
const int rank = cfg_.lora.rank(true);
std::map<std::string, lora::Composite> comp;
lora::ComposeReport rep;
RAD_TRY(lora::compose(*lora_keys_, ss, rank, &comp, &rep, err));
if (rep.modules == 0) {
*err = "none of the adapters' modules is a module of this model" +
(rep.unplaced.empty() ? std::string() : " (" + rep.unplaced[0] + ")");
return RAD_E_NOTFOUND;
}
const std::map<std::string, lora::AdModule> mods = lora::as_modules(comp, *lora_keys_);
std::vector<std::vector<lora::PackedSite>> packed(ranks_.size());
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
lora::AdapterInfo info;
const int s = lora::pack_modules(ranks_[ri]->lora_sites, rank, mods, &info, &packed[ri], err,
/*compact=*/true);
if (s < 0) {
if (ranks_.size() > 1) *err = fmt("rank %zu: ", ri) + *err;
return s;
}
/* Pools past the last one a site names hold nothing (lora_declare's dropped GEMMs). */
packed[ri].resize(ranks_[ri]->program.lora_pools.size());
}
RAD_TRY(lora_copy(sl, packed, err));
/* The ranks each pool takes in this slot, before a pass can name the slot (the publish). */
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
Program& P = ranks_[ri]->program;
const size_t S = (size_t)cfg_.lora.slots();
for (size_t p = 0; p < P.lora_pools.size() && p < packed[ri].size(); ++p)
if (p * S + (size_t)sl < P.lora_rused.size())
P.lora_rused[p * S + (size_t)sl] = packed[ri][p].empty ? 0 : (int32_t)packed[ri][p].r_used;
}
lora_table_.publish(sl, key, "");
const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
std::string n;
if (!rep.unplaced.empty())
n += fmt("%zu adapter module%s not on this model (%s)", rep.unplaced.size(),
rep.unplaced.size() == 1 ? "" : "s", rep.unplaced[0].c_str());
if (rep.exact < rep.modules)
n += fmt("%s%lld module%s past rank %d were truncated to it, keeping at worst %.1f%% of the "
"delta (%s)", n.empty() ? "" : "; ", (long long)(rep.modules - rep.exact),
rep.modules - rep.exact == 1 ? "" : "s", rank, 100.0 * rep.worst_kept,
rep.worst_module.c_str());
RAD_INFO("lora: slot %d <- %s: %lld modules (%lld exact) in %.0f ms%s%s", sl, key.c_str(),
(long long)rep.modules, (long long)rep.exact, ms, n.empty() ? "" : "; ", n.c_str());
if (note) *note = n;
if (lora_table_.acquire(key, slot, &uid, hold) != RAD_OK) {
*err = "the combination's slot was taken back before the request could hold it; retry";
return RAD_E_STATE;
}
return RAD_OK;
}
} /* namespace rad */
+4
View File
@@ -162,6 +162,10 @@ static bool dump_at(Ctx& ctx, int step, const char* phase, const std::string& na
return true;
}
/* A buffer is read where it lives after the pass, and the arena shares a transient's bytes with
* every buffer whose lifetime does not overlap it. So a dump after a drafter's context pass shows
* a tap buffer (dflash_src) already overwritten by a later one in that pass (df_c), and only the
* step loop's dump, after the trunk, shows the taps as written. A PERSIST buffer is never shared. */
void dump_buffers(Ctx& ctx, int step, const char* phase) {
if ((int)log_level() < (int)Log::Trace) return;
static const char* const names = std::getenv("RADIANCE_DUMP_BUF");
+326 -25
View File
@@ -56,10 +56,36 @@ void MetaOwn::finish() {
* path, and typed fields are read from `text_config.X`, falling back to `X`, so a plugin finds
* `vision_config.depth` under that name either way.
*/
/* An array's scalars appended to `s` space-separated, nested arrays flattened row-major (a
* vocoder's per-resnet dilations, [[1, 3, 5], [1, 3, 5]], read as "1 3 5 1 3 5"); false for an
* array holding an object or a null. */
static bool join_scalars(const nlohmann::json& v, std::string* s) {
for (const auto& e : v) {
if (e.is_array()) {
if (!join_scalars(e, s)) return false;
continue;
}
if (!s->empty()) *s += ' ';
if (e.is_number_integer()) *s += fmt("%lld", (long long)e.get<int64_t>());
else if (e.is_number()) *s += fmt("%.17g", e.get<double>());
else if (e.is_string()) *s += e.get<std::string>();
else if (e.is_boolean()) *s += e.get<bool>() ? "1" : "0";
else return false;
}
return true;
}
static void flatten_json(const nlohmann::json& j, const std::string& prefix, MetaOwn* out) {
for (auto it = j.begin(); it != j.end(); ++it) {
const std::string key = prefix.empty() ? it.key() : prefix + "." + it.key();
const nlohmann::json& v = it.value();
/* Retain otherwise invisible Quark weight overrides so import validation can reject
* null/empty schemes instead of accidentally inheriting global MXFP4 packing. */
if (key.rfind("quantization_config.layer_quant_config.", 0) == 0 &&
it.key() == "weight" && (v.is_null() || (v.is_object() && v.empty()))) {
out->kv(key, v.is_null() ? "null" : "{}");
continue;
}
if (v.is_object()) flatten_json(v, key, out);
else if (v.is_boolean()) out->kv(key, v.get<bool>() ? "1" : "0");
else if (v.is_number_integer()) out->kv(key, fmt("%lld", (long long)v.get<int64_t>()));
@@ -67,19 +93,10 @@ 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_array()) {
/* An array of scalars becomes a space-separated string (mrope_section "11 11 10",
* layer_types "linear_attention full_attention ..."). Arrays of objects are
* skipped. */
* layer_types "linear_attention full_attention ..."), nested arrays row-major.
* Arrays of objects are skipped. */
std::string s;
bool ok = true;
for (const auto& e : v) {
if (!s.empty()) s += ' ';
if (e.is_number_integer()) s += fmt("%lld", (long long)e.get<int64_t>());
else if (e.is_number()) s += fmt("%.17g", e.get<double>());
else if (e.is_string()) s += e.get<std::string>();
else if (e.is_boolean()) s += e.get<bool>() ? "1" : "0";
else { ok = false; break; }
}
if (ok) out->kv(key, s);
if (join_scalars(v, &s)) out->kv(key, s);
}
}
}
@@ -230,9 +247,10 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
m.n_ff = gi("intermediate_size", gi("moe_intermediate_size", 0));
m.n_vocab = gi("vocab_size", 0);
m.n_ctx_train = gi("max_position_embeddings", 0);
m.n_expert = gi("num_experts", gi("num_local_experts", 0));
m.n_expert = gi("num_experts", gi("num_local_experts", gi("n_routed_experts", 0)));
m.n_expert_used = gi("num_experts_per_tok", 0);
m.n_expert_shared = gi("shared_expert_intermediate_size", 0) ? 1 : 0;
m.n_expert_shared = gi("n_shared_experts", gi("num_shared_experts",
gi("shared_expert_intermediate_size", 0) ? 1 : 0));
m.rms_eps = (float)gf("rms_norm_eps", gf("norm_eps", 1e-6)); /* LFM2: norm_eps */
m.rope_theta = (float)gf("rope_parameters.rope_theta", gf("rope_theta", 10000.0));
/* Rotary scaling stays in the free-form keys with its type (arch/common/rad_arch.h,
@@ -582,7 +600,9 @@ int Checkpoint::open_diffusers() {
RAD_TRY(meta_merge_json_file(dir_ + "/" + sc + "/scheduler_config.json", sc, true,
&meta_));
}
for (const char* sub : { "processor", "tokenizer" }) {
/* The tokenizer's own folder, or the text encoder's when the release keeps it there (FLUX.3
* [klein]'s modular pipeline points its tokenizer at text_encoder/). */
for (const char* sub : { "processor", "tokenizer", "text_encoder" }) {
const std::string d = dir_ + "/" + sub;
if (!path_exists(d + "/tokenizer.json")) continue;
tok_dir_ = d;
@@ -608,6 +628,191 @@ int Checkpoint::open_diffusers() {
return RAD_OK;
}
/* 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
*
* model.diffusion_model.* the UNet, under the names it is trained and adapted
* (LoRA) under, kept as they are;
* conditioner.embedders.0.transformer.* CLIP ViT-L's text model, already in transformers'
* CLIPTextModel names, kept;
* conditioner.embedders.1.model.* OpenCLIP ViT-bigG's text tower in open_clip's names,
* read as transformers' CLIPTextModelWithProjection
* under conditioner.embedders.1.transformer.: each
* block's fused in_proj split into q/k/v_proj (row
* views, nothing copied), c_fc / c_proj as fc1 / fc2,
* ln_1 / ln_2 / ln_final as layer_norm1 / layer_norm2 /
* final_layer_norm, and the (in, out) text_projection
* transposed into a linear's (out, in)
* `text_projection.weight`;
* first_stage_model.* the VAE, its decoder read in diffusers' AutoencoderKL
* names under vae. (its 1 x 1 attention convolutions
* keep their rank-4 shape).
*
* A `v_pred` tensor marks a v-prediction model and `ztsnr` one trained to a zero terminal SNR
* (ComfyUI's convention): they become the `sdxl.prediction` and `sdxl.zero_snr` keys. The
* architecture is `sdxl`. The checkpoint holds no tokenizer; rad-convert takes CLIP's with
* --tokenizer. */
int Checkpoint::open_sgm() {
kind_ = SafeT;
RAD_TRY(add_shard(path_));
bool vpred = false, zsnr = false;
std::vector<SrcTensor> add;
std::vector<std::string> drop;
auto rename = [&](const SrcTensor& t, const std::string& name) {
SrcTensor v = t;
v.name = name;
add.push_back(std::move(v));
drop.push_back(t.name);
};
const std::string g_old = "conditioner.embedders.1.model.";
const std::string g_new = "conditioner.embedders.1.transformer.";
const std::string tm = g_new + "text_model.";
const std::string v_old = "first_stage_model.";
for (const SrcTensor& t : tensors_) {
const std::string& n = t.name;
if (n == "v_pred") { vpred = true; continue; }
if (n == "ztsnr") { zsnr = true; continue; }
if (n.rfind(g_old, 0) == 0) {
const std::string r = n.substr(g_old.size());
if (r == "token_embedding.weight") {
rename(t, tm + "embeddings.token_embedding.weight");
} else if (r == "positional_embedding") {
rename(t, tm + "embeddings.position_embedding.weight");
} else if (r.rfind("ln_final.", 0) == 0) {
rename(t, tm + "final_layer_norm." + r.substr(std::strlen("ln_final.")));
} else if (r == "text_projection") {
/* x @ P in open_clip; a linear's weight is P^T. */
if (t.shape.size() != 2 || !t.data ||
(t.rad_dtype != RAD_F16 && t.rad_dtype != RAD_BF16 && t.rad_dtype != RAD_F32)) {
RAD_ERR("%s: '%s' is not a 2-D float matrix", path_.c_str(), n.c_str());
return RAD_E_FORMAT;
}
const int64_t a = t.shape[0], b = t.shape[1];
const int64_t es = rad_dtype_bytes(t.rad_dtype, 1);
owned_.push_back(std::make_unique<uint8_t[]>((size_t)(a * b * es)));
uint8_t* dst = owned_.back().get();
const uint8_t* src = (const uint8_t*)t.data;
for (int64_t i = 0; i < a; ++i)
for (int64_t j = 0; j < b; ++j)
std::memcpy(dst + (size_t)((j * a + i) * es),
src + (size_t)((i * b + j) * es), (size_t)es);
SrcTensor v = t;
v.name = g_new + "text_projection.weight";
v.shape = { b, a };
v.data = dst;
add.push_back(std::move(v));
drop.push_back(n);
} else if (r.rfind("transformer.resblocks.", 0) == 0) {
/* transformer.resblocks.N.<rest> */
const size_t p0 = std::strlen("transformer.resblocks.");
const size_t dot = r.find('.', p0);
if (dot == std::string::npos) continue;
const std::string layer = tm + "encoder.layers." + r.substr(p0, dot - p0) + ".";
const std::string rest = r.substr(dot + 1);
if (rest == "attn.in_proj_weight" || rest == "attn.in_proj_bias") {
const bool w = rest == "attn.in_proj_weight";
if (t.shape.empty() || t.shape[0] % 3 || !t.data) {
RAD_ERR("%s: '%s' does not split into q, k and v", path_.c_str(),
n.c_str());
return RAD_E_FORMAT;
}
const int64_t d = t.shape[0] / 3, rb = t.bytes / t.shape[0];
const char* part[3] = { "q_proj", "k_proj", "v_proj" };
for (int k = 0; k < 3; ++k) {
SrcTensor v = t;
v.name = layer + "self_attn." + part[k] + (w ? ".weight" : ".bias");
v.shape[0] = d;
v.bytes = rb * d;
v.data = (const uint8_t*)t.data + (size_t)(k * d * rb);
add.push_back(std::move(v));
}
drop.push_back(n);
} else {
static const std::pair<const char*, const char*> kMap[] = {
{ "attn.out_proj.", "self_attn.out_proj." }, { "ln_1.", "layer_norm1." },
{ "ln_2.", "layer_norm2." }, { "mlp.c_fc.", "mlp.fc1." },
{ "mlp.c_proj.", "mlp.fc2." } };
for (const auto& [from, to] : kMap)
if (rest.rfind(from, 0) == 0) {
rename(t, layer + to + rest.substr(std::strlen(from)));
break;
}
}
}
continue;
}
if (n.rfind(v_old + "decoder.", 0) == 0 || n.rfind(v_old + "post_quant_conv.", 0) == 0) {
/* diffusers' convert_ldm_vae_checkpoint, the decoder's half. */
std::string r = n.substr(v_old.size());
auto sub = [&](const std::string& from, const std::string& to) {
const size_t at = r.find(from);
if (at != std::string::npos) r.replace(at, from.size(), to);
};
sub("decoder.mid.block_1.", "decoder.mid_block.resnets.0.");
sub("decoder.mid.block_2.", "decoder.mid_block.resnets.1.");
sub("decoder.mid.attn_1.norm.", "decoder.mid_block.attentions.0.group_norm.");
sub("decoder.mid.attn_1.q.", "decoder.mid_block.attentions.0.to_q.");
sub("decoder.mid.attn_1.k.", "decoder.mid_block.attentions.0.to_k.");
sub("decoder.mid.attn_1.v.", "decoder.mid_block.attentions.0.to_v.");
sub("decoder.mid.attn_1.proj_out.", "decoder.mid_block.attentions.0.to_out.0.");
sub("decoder.norm_out.", "decoder.conv_norm_out.");
if (r.rfind("decoder.up.", 0) == 0) {
/* up.i runs at the i-th resolution from the bottom of the encoder's pyramid;
* up_blocks count in the order the decoder runs them. */
const size_t p0 = std::strlen("decoder.up."), dot = r.find('.', p0);
if (dot == std::string::npos) continue;
const int i = std::atoi(r.substr(p0, dot - p0).c_str());
std::string rest = r.substr(dot + 1);
if (rest.rfind("block.", 0) == 0) rest = "resnets." + rest.substr(6);
else if (rest.rfind("upsample.", 0) == 0) rest = "upsamplers.0." + rest.substr(9);
r = "decoder.up_blocks." + std::to_string(3 - i) + "." + rest;
}
sub(".nin_shortcut.", ".conv_shortcut.");
rename(t, "vae." + r);
}
}
for (const std::string& n : drop) index_.erase(n);
for (SrcTensor& v : add) {
if (index_.count(v.name)) {
RAD_ERR("%s: '%s' is read from two tensors", path_.c_str(), v.name.c_str());
return RAD_E_FORMAT;
}
index_.emplace(v.name, tensors_.size());
tensors_.push_back(std::move(v));
}
meta_.arch = "sdxl";
const size_t slash = path_.find_last_of('/');
meta_.name = slash == std::string::npos ? path_ : path_.substr(slash + 1);
meta_.kv("sdxl.prediction", vpred ? "v" : "eps");
meta_.kv("sdxl.zero_snr", zsnr ? "1" : "0");
/* The typed dimensions are the conditioning network's, OpenCLIP bigG's text tower (as a
* diffusers pipeline's are its text encoder's), read off its tensors. */
{
RadModelMeta& m = meta_.m;
const SrcTensor* tok = find(tm + "embeddings.token_embedding.weight");
const SrcTensor* fc1 = find(tm + "encoder.layers.0.mlp.fc1.weight");
int64_t layers = 0;
while (find(tm + "encoder.layers." + std::to_string(layers) + ".layer_norm1.weight"))
++layers;
if (!tok || tok->shape.size() != 2 || !fc1 || fc1->shape.size() != 2 || !layers) {
RAD_ERR("%s: OpenCLIP bigG's text tower is incomplete", path_.c_str());
return RAD_E_FORMAT;
}
m.n_layers = layers;
m.n_embd = tok->shape[1];
m.head_dim = 64;
m.n_head = m.n_head_kv = m.n_embd / 64;
m.n_ff = fc1->shape[0];
m.n_vocab = tok->shape[0];
m.n_ctx_train = 77;
m.rms_eps = 1e-5f;
m.rope_theta = 10000.0f;
m.rope_scale = 1.0f;
}
meta_.finish();
return RAD_OK;
}
int Checkpoint::open_safetensors(const std::string& path) {
kind_ = SafeT;
/* One shard, an index, or the directory holding either, as one namespace. */
@@ -624,15 +829,29 @@ int Checkpoint::open_safetensors(const std::string& path) {
return open_diffusers();
if (is_file) {
shards.push_back(path);
/* A single-file Stable Diffusion XL checkpoint, as Stability and every SDXL finetune
* ship one: read by its own importer. */
SafeTensorsFile probe;
if (probe.open(path) == RAD_OK) {
bool unet = false, bigg = false;
for (const auto& t : probe.tensors()) {
unet = unet || t.name == "model.diffusion_model.label_emb.0.0.weight";
bigg = bigg ||
t.name.rfind("conditioner.embedders.1.model.transformer.resblocks.", 0) == 0;
}
if (unet && bigg) return open_sgm();
}
} else {
RAD_TRY(shard_list(dir_, is_index ? path : dir_ + "/model.safetensors.index.json",
is_index, &shards, &owner));
}
for (const auto& sh : shards) RAD_TRY(add_shard(sh, "", owner.empty() ? nullptr : &owner));
RAD_TRY(meta_from_config_json(dir_, &meta_));
RAD_TRY(meta_merge_generation_config(dir_, &meta_));
RAD_TRY(meta_merge_preprocessor_configs(dir_, &meta_));
const std::string& md = meta_dir_.empty() ? dir_ : meta_dir_;
RAD_TRY(meta_from_config_json(md, &meta_));
RAD_TRY(meta_merge_generation_config(md, &meta_));
RAD_TRY(meta_merge_preprocessor_configs(md, &meta_));
if (!meta_dir_.empty() && !path_exists(dir_ + "/tokenizer.json")) tok_dir_ = meta_dir_;
if (!is_file && !is_index) RAD_TRY(add_companions());
/* FP8's block, where the checkpoint states one. */
if (const char* bs = meta_.get("quantization_config.weight_block_size")) {
@@ -703,13 +922,45 @@ void Checkpoint::detect_import() {
else import_why_ = "GPTQ's checkpoint_format '" + cf + "' is not one this reads; 'gptq' is";
} else if (qm == "quark") {
const std::string w = "global_quant_config.weight.";
/* Quark can retain block-FP8 attention/MTP weights alongside MXFP4 experts.
* Validate every override rather than rejecting every nonempty override map.
* Keep a lookup here: large exports have tens of thousands of flattened fields. */
std::map<std::string, std::string> fields;
for (size_t i = 0; i < meta_.keys.size(); ++i) fields.emplace(meta_.keys[i], meta_.vals[i]);
const std::string lp = "quantization_config.layer_quant_config.";
const std::string suffix = ".weight.dtype";
std::map<std::string, bool> layers;
for (const auto& [k, v] : fields)
if (k.rfind(lp, 0) == 0 && k.size() > lp.size() + suffix.size() &&
k.compare(k.size() - suffix.size(), suffix.size(), suffix) == 0)
layers.emplace(k.substr(0, k.size() - suffix.size()) + ".", true);
bool overrides_ok = true;
for (const auto& [layer, unused] : layers) {
auto f = [&](const char* key) {
auto it = fields.find(layer + "weight." + key);
return it == fields.end() ? std::string() : it->second;
};
const bool mx = f("dtype") == "fp4" && f("qscheme") == "per_group" &&
f("group_size") == "32" && f("scale_format") == "e8m0";
const bool fp8 = f("dtype") == "fp8_e4m3" && f("qscheme") == "per_block" &&
f("block_size") == "128 128";
overrides_ok = overrides_ok && (mx || fp8);
}
/* A partial/null weight override must not disappear merely because it has no dtype. */
for (const auto& [k, v] : fields) if (k.rfind(lp, 0) == 0) {
bool covered = false;
for (size_t dot = k.rfind('.'); dot != std::string::npos;
dot = dot ? k.rfind('.', dot - 1) : std::string::npos)
if (layers.count(k.substr(0, dot + 1))) { covered = true; break; }
overrides_ok = overrides_ok && covered;
}
if (qc(w + "dtype") == "fp4" && qc(w + "qscheme") == "per_group" &&
qc(w + "group_size") == "32" && qc(w + "scale_format") == "e8m0" &&
!any_under("layer_quant_config.") && !any_under("layer_type_quant_config."))
overrides_ok && !any_under("layer_type_quant_config."))
import_ = Import::QuarkMx;
else
import_why_ = "Quark's weight scheme here is not MXFP4 (fp4, per_group 32, e8m0 scales) "
"throughout, which is the one this reads";
import_why_ = "Quark requires global MXFP4 (fp4, per_group 32, e8m0 scales), with "
"only MXFP4 or 128x128 E4M3 block-FP8 layer overrides";
} else if (qm == "compressed-tensors") {
/* compressed-tensors states each scheme as a config group with a format. Three are read:
* pack-quantized grouped int4, symmetric (e.g. Google's Gemma 4 QAT w4a16-ct)
@@ -1534,6 +1785,17 @@ int Checkpoint::add_lora(const std::string& path, double strength,
return RAD_OK;
}
int Checkpoint::add_file(const std::string& path) {
if (kind_ != SafeT) {
RAD_ERR("%s is merged into a safetensors checkpoint's namespace; %s is not one",
path.c_str(), path_.c_str());
return RAD_E_UNSUPPORTED;
}
RAD_TRY(add_shard(path));
meta_.finish();
return RAD_OK;
}
const SrcTensor* Checkpoint::find(const std::string& n) const {
auto it = index_.find(n);
return it == index_.end() ? nullptr : &tensors_[it->second];
@@ -1797,8 +2059,9 @@ static int resolve_wnorm(Checkpoint& ck, const RadNameMap& m, bool optional, Ckp
return RAD_OK;
}
/* RAD_MAP_TRANSPOSE (src[0] [.., a, b] read as [.., b, a]) and RAD_MAP_EMA (src[0] the embedding
* sums [bins, ...], src[1] the cluster usage [bins]; each row over max(usage, 1e-5)), computed in
/* RAD_MAP_TRANSPOSE (src[0] [.., a, b] read as [.., b, a]), RAD_MAP_EMA (src[0] the embedding
* sums [bins, ...], src[1] the cluster usage [bins]; each row over max(usage, 1e-5)), RAD_MAP_TAP
* (one index of one dimension of src[0]) and RAD_MAP_COLS (one column range of src[0]), computed in
* f32 into `derived`. */
static int resolve_derived(Checkpoint& ck, const std::vector<const RadNameMap*>& maps,
bool optional, CkptWeight* out, std::string* why) {
@@ -1863,7 +2126,44 @@ static int resolve_derived(Checkpoint& ck, const std::vector<const RadNameMap*>&
return refuse(RAD_E_FORMAT, "'" + a->name + "' cannot be read as f32");
out->rank = (uint32_t)rank;
for (size_t i = 0; i < rank; ++i) out->shape[i] = a->shape[i];
if (ema) {
if (m.mode == RAD_MAP_COLS) {
const int64_t cb = a->shape[rank - 1], c0 = m.src_index[0], nc = m.src_rows[0];
if (c0 < 0 || nc <= 0 || c0 + nc > cb)
return refuse(RAD_E_SHAPE, "columns [" + std::to_string(c0) + ", " +
std::to_string(c0 + nc) + ") of '" + a->name + "', which "
"has " + std::to_string(cb));
const int64_t outer = n / cb;
out->derived.resize((size_t)(outer * nc));
for (int64_t o = 0; o < outer; ++o)
std::memcpy(&out->derived[(size_t)(o * nc)], &src[(size_t)(o * cb + c0)],
(size_t)nc * sizeof(float));
out->shape[rank - 1] = nc;
out->why = "it is columns [" + std::to_string(c0) + ", " + std::to_string(c0 + nc) +
") of '" + a->name + "', at convert -- a recipe rule stores it";
} else if (m.mode == RAD_MAP_TAP) {
const int d = m.concat_dim;
if (d < 0 || (size_t)d >= rank || rank < 3)
return refuse(RAD_E_SHAPE, "'" + a->name + "' has rank " + std::to_string(rank) +
"; a tap of dimension " + std::to_string(d) +
" leaves no matrix");
const int64_t k = a->shape[(size_t)d];
const int64_t t = m.src_index[0] < 0 ? k + m.src_index[0] : m.src_index[0];
if (t < 0 || t >= k)
return refuse(RAD_E_SHAPE, "tap " + std::to_string(m.src_index[0]) + " of '" +
a->name + "' dimension " + std::to_string(d) + " of " +
std::to_string(k));
int64_t outer = 1, inner = 1;
for (int i = 0; i < d; ++i) outer *= a->shape[(size_t)i];
for (size_t i = (size_t)d + 1; i < rank; ++i) inner *= a->shape[i];
out->derived.resize((size_t)(outer * inner));
for (int64_t o = 0; o < outer; ++o)
std::memcpy(&out->derived[(size_t)(o * inner)], &src[(size_t)((o * k + t) * inner)],
(size_t)inner * sizeof(float));
out->rank = (uint32_t)(rank - 1);
for (size_t i = (size_t)d; i + 1 < rank; ++i) out->shape[i] = a->shape[i + 1];
out->why = "it is tap " + std::to_string(t) + " of '" + a->name + "' dimension " +
std::to_string(d) + ", at convert -- a recipe rule stores it";
} else if (ema) {
const int64_t bins = a->shape[0], per = n / bins;
int64_t un = 1;
for (int64_t x : u->shape) un *= x;
@@ -1918,7 +2218,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
if (maps.empty()) return refuse(RAD_E_NOTFOUND, "the name map has no entry for it");
if (maps.front()->mode == RAD_MAP_WNORM)
return resolve_wnorm(ck, *maps.front(), optional, out, why);
if (maps.front()->mode == RAD_MAP_TRANSPOSE || maps.front()->mode == RAD_MAP_EMA)
if (maps.front()->mode == RAD_MAP_TRANSPOSE || maps.front()->mode == RAD_MAP_EMA ||
maps.front()->mode == RAD_MAP_TAP || maps.front()->mode == RAD_MAP_COLS)
return resolve_derived(ck, maps, optional, out, why);
struct Src1 { const char* name; int index; int64_t rows; };
std::vector<Src1> srcs;
+11 -2
View File
@@ -120,6 +120,14 @@ public:
* borrows the target's embedding and head, so it goes into the target's container with its
* tensors and config.json keys under `draft.`. */
int add_draft(const std::string& dir, const std::string& prefix);
/* Merge one more safetensors file, its tensor names kept: a release that ships its networks
* as separate single files (ComfyUI's split_files: a diffusion model, a text encoder and a
* VAE). A name already present is refused. */
int add_file(const std::string& path);
/* Before open(): read config.json, generation_config.json and the tokenizer from `dir` rather
* than from beside the checkpoint, for a single-file checkpoint that ships none of them (the
* text encoder's repository describes such a release). */
void set_meta_dir(const std::string& dir) { meta_dir_ = dir; }
/* Merge PEFT adapters into the tensors they name, before anything reads the checkpoint:
* `path` is a .safetensors file or a directory of them, holding `<module>.lora_A.weight`
@@ -202,12 +210,13 @@ private:
const std::unordered_map<std::string, std::string>* owner = nullptr);
int open_safetensors(const std::string& path);
int open_diffusers();
int open_sgm();
int add_companions();
int open_gguf(const std::string& path);
void detect_import();
enum Kind { None, Gguf, SafeT } kind_ = None;
std::string path_, dir_, tok_dir_;
std::string path_, dir_, tok_dir_, meta_dir_;
GgufFile gguf_;
MetaOwn meta_;
std::vector<std::unique_ptr<SafeTensorsFile>> shards_;
@@ -274,7 +283,7 @@ struct CkptWeight {
* (the values change), so a recipe rule stores it. */
bool wnorm = false;
std::vector<float> wnorm_scale;
/* A weight computed from its sources at resolve (RAD_MAP_TRANSPOSE, RAD_MAP_EMA): its f32
/* A weight computed from its sources at resolve (RAD_MAP_TRANSPOSE, EMA, TAP, COLS): its f32
* values in the logical shape, which ckpt_rows_f32 serves. Not trivial, so a recipe rule
* stores it. */
std::vector<float> derived;
+90 -51
View File
@@ -40,6 +40,7 @@ void RadFile::close() {
hdr_ = nullptr; meta_ = nullptr; dir_ = nullptr; planes_ = nullptr; encs_ = nullptr;
prof_ = nullptr;
vocab_ = VocabSection{};
aux_vocab_ = VocabSection{};
groups_.clear();
by_name_.clear();
path_.clear();
@@ -197,6 +198,9 @@ int RadFile::validate() {
if (!need(span_n(hdr_->prof_off, hdr_->prof_count, sizeof(RadFileProfile)),
"the expert profile")) return RAD_E_FORMAT;
if (!need(span_ok(hdr_->vocab_off, hdr_->vocab_bytes), "the vocab section")) return RAD_E_FORMAT;
if (!need(span_ok(hdr_->reserved[RAD_HDR_AUX_VOCAB_OFF],
hdr_->reserved[RAD_HDR_AUX_VOCAB_BYTES]), "the second vocab section"))
return RAD_E_FORMAT;
if (!need(span_ok(hdr_->data_off, hdr_->data_bytes), "the data blob")) return RAD_E_FORMAT;
if (hdr_->data_bytes && (hdr_->data_off % RAD_ALIGN_POOL) != 0) {
@@ -312,22 +316,29 @@ int RadFile::validate() {
}
/* ---------------------------------------------------------------- vocab */
if (hdr_->vocab_bytes >= sizeof(RadVocabHeader)) {
/* The section is read in place through typed pointers, so the header and every array must
* be aligned to their element (the writer guarantees it). */
if (hdr_->vocab_off % alignof(RadVocabHeader) != 0) {
RAD_ERR("%s: the vocab section starts at %llu, which is not %zu-aligned", path_.c_str(),
(unsigned long long)hdr_->vocab_off, alignof(RadVocabHeader));
/* The vocab section, and the second one a generator may read its prompt through: the same
* layout, each checked against its own extent. */
auto read_vocab = [&](uint64_t voff, uint64_t vbytes, const char* what,
VocabSection* out) -> int {
if (vbytes == 0) return RAD_OK;
if (vbytes < sizeof(RadVocabHeader)) {
RAD_ERR("%s: the %s section is %llu bytes, shorter than its own header (%zu)",
path_.c_str(), what, (unsigned long long)vbytes, sizeof(RadVocabHeader));
return RAD_E_FORMAT;
}
const RadVocabHeader* v = (const RadVocabHeader*)(base_ + hdr_->vocab_off);
/* The section is read in place through typed pointers, so the header and every array must
* be aligned to their element (the writer guarantees it). */
if (voff % alignof(RadVocabHeader) != 0) {
RAD_ERR("%s: the %s section starts at %llu, which is not %zu-aligned", path_.c_str(),
what, (unsigned long long)voff, alignof(RadVocabHeader));
return RAD_E_FORMAT;
}
const RadVocabHeader* v = (const RadVocabHeader*)(base_ + voff);
/* Offset 0 means an optional array is absent (scores are unigram-only; types default to
* normal). Nothing real lives at file offset 0. */
auto arr_ok = [&](uint64_t off, uint64_t bytes, size_t align) {
return bytes == 0 || off == 0 ||
(off >= hdr_->vocab_off &&
off - hdr_->vocab_off <= hdr_->vocab_bytes &&
bytes <= hdr_->vocab_bytes - (off - hdr_->vocab_off) &&
(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;
@@ -336,47 +347,50 @@ int RadFile::validate() {
!arr_ok(v->tok_type_off, nt, 1) ||
!arr_ok(v->merge_off, nm * 2 * sizeof(uint32_t), alignof(uint32_t)) ||
!arr_ok(v->step_off, ns * sizeof(RadVocabStep), alignof(RadVocabStep))) {
RAD_ERR("%s: the vocab section's arrays do not fit inside it, or one is not aligned "
"to its element", path_.c_str());
RAD_ERR("%s: the %s section's arrays do not fit inside it, or one is not aligned to its "
"element",
path_.c_str(), what);
return RAD_E_FORMAT;
}
vocab_.h = v;
vocab_.tok_text = (nt && v->tok_text_off) ? (const rad_stroff*)(base_ + v->tok_text_off) : nullptr;
vocab_.tok_score = (nt && v->tok_score_off) ? (const float*)(base_ + v->tok_score_off) : nullptr;
vocab_.tok_type = (nt && v->tok_type_off) ? (const uint8_t*)(base_ + v->tok_type_off) : nullptr;
vocab_.merges = (nm && v->merge_off) ? (const uint32_t*)(base_ + v->merge_off) : nullptr;
vocab_.steps = (ns && v->step_off) ? (const RadVocabStep*)(base_ + v->step_off) : nullptr;
VocabSection& vs = *out;
vs.h = v;
vs.tok_text = (nt && v->tok_text_off) ? (const rad_stroff*)(base_ + v->tok_text_off) : nullptr;
vs.tok_score = (nt && v->tok_score_off) ? (const float*)(base_ + v->tok_score_off) : nullptr;
vs.tok_type = (nt && v->tok_type_off) ? (const uint8_t*)(base_ + v->tok_type_off) : nullptr;
vs.merges = (nm && v->merge_off) ? (const uint32_t*)(base_ + v->merge_off) : nullptr;
vs.steps = (ns && v->step_off) ? (const RadVocabStep*)(base_ + v->step_off) : nullptr;
if (vocab_.tok_text)
if (vs.tok_text)
for (uint64_t i = 0; i < nt; ++i)
if (!str_ok(vocab_.tok_text[i])) {
RAD_ERR("%s: vocab token %llu points outside the string blob", path_.c_str(),
(unsigned long long)i);
if (!str_ok(vs.tok_text[i])) {
RAD_ERR("%s: %s token %llu points outside the string blob", path_.c_str(),
what, (unsigned long long)i);
return RAD_E_FORMAT;
}
if (vocab_.steps)
if (vs.steps)
for (uint64_t i = 0; i < ns; ++i)
if (!str_ok(vocab_.steps[i].arg0) || !str_ok(vocab_.steps[i].arg1)) {
RAD_ERR("%s: vocab step %llu points outside the string blob", path_.c_str(),
if (!str_ok(vs.steps[i].arg0) || !str_ok(vs.steps[i].arg1)) {
RAD_ERR("%s: %s step %llu points outside the string blob", path_.c_str(), what,
(unsigned long long)i);
return RAD_E_FORMAT;
}
if (vocab_.merges)
if (vs.merges)
for (uint64_t i = 0; i < nm * 2; ++i)
if (vocab_.merges[i] >= nt) {
RAD_ERR("%s: merge %llu names token %u of %llu", path_.c_str(),
(unsigned long long)(i / 2), vocab_.merges[i], (unsigned long long)nt);
if (vs.merges[i] >= nt) {
RAD_ERR("%s: %s merge %llu names token %u of %llu", path_.c_str(), what,
(unsigned long long)(i / 2), vs.merges[i], (unsigned long long)nt);
return RAD_E_FORMAT;
}
if (!str_ok(v->chat_template)) {
RAD_ERR("%s: the chat template offset is outside the string blob", path_.c_str());
RAD_ERR("%s: the %s section's chat template offset is outside the string blob",
path_.c_str(), what);
return RAD_E_FORMAT;
}
} else if (hdr_->vocab_bytes != 0) {
RAD_ERR("%s: the vocab section is %llu bytes, shorter than its own header (%zu)",
path_.c_str(), (unsigned long long)hdr_->vocab_bytes, sizeof(RadVocabHeader));
return RAD_E_FORMAT;
}
return RAD_OK;
};
RAD_TRY(read_vocab(hdr_->vocab_off, hdr_->vocab_bytes, "vocab", &vocab_));
RAD_TRY(read_vocab(hdr_->reserved[RAD_HDR_AUX_VOCAB_OFF],
hdr_->reserved[RAD_HDR_AUX_VOCAB_BYTES], "second vocab", &aux_vocab_));
return RAD_OK;
}
@@ -956,6 +970,29 @@ int RadWriter::check_complete() const {
return RAD_OK;
}
/* A serialised vocab section's arrays rebased from section-relative to file offsets. */
static void rebase_vocab(std::vector<uint8_t>& blob, uint64_t at) {
auto* vh = (RadVocabHeader*)blob.data();
if (vh->tok_text_off) vh->tok_text_off += at;
if (vh->tok_score_off) vh->tok_score_off += at;
if (vh->tok_type_off) vh->tok_type_off += at;
if (vh->merge_off) vh->merge_off += at;
if (vh->step_off) vh->step_off += at;
}
int RadWriter::set_aux_vocab_section(const void* blob, int64_t bytes) {
std::vector<uint8_t> keep;
keep.swap(vocab_blob_);
const bool had = have_vocab_;
const int s = set_vocab_section(blob, bytes);
keep.swap(vocab_blob_);
have_vocab_ = had;
if (s < 0) return s;
aux_vocab_blob_.assign((const uint8_t*)blob, (const uint8_t*)blob + bytes);
have_aux_vocab_ = true;
return RAD_OK;
}
int RadWriter::set_vocab_section(const void* blob, int64_t bytes) {
if (!began_ || sealed_) return RAD_E_STATE;
if (!blob || bytes < (int64_t)sizeof(RadVocabHeader)) {
@@ -1049,6 +1086,10 @@ void RadWriter::layout(RadFileHeader* hp) {
h.enc_count = encs_.size();
h.vocab_off = (uint64_t)place8((int64_t)vocab_blob_.size());
h.vocab_bytes= have_vocab_ ? vocab_blob_.size() : 0;
if (have_aux_vocab_) {
h.reserved[RAD_HDR_AUX_VOCAB_OFF] = (uint64_t)place8((int64_t)aux_vocab_blob_.size());
h.reserved[RAD_HDR_AUX_VOCAB_BYTES] = aux_vocab_blob_.size();
}
h.prof_off = (uint64_t)place8((int64_t)(prof_.size() * sizeof(RadFileProfile)));
h.prof_count = prof_.size();
@@ -1095,14 +1136,8 @@ int RadWriter::finish() {
* aligned within the blob, so alignment is preserved. */
for (auto& e : dir_) e.offset += h.data_off;
for (auto& p : planes_) p.offset += h.data_off;
if (have_vocab_) {
auto* vh = (RadVocabHeader*)vocab_blob_.data();
if (vh->tok_text_off) vh->tok_text_off += h.vocab_off;
if (vh->tok_score_off) vh->tok_score_off += h.vocab_off;
if (vh->tok_type_off) vh->tok_type_off += h.vocab_off;
if (vh->merge_off) vh->merge_off += h.vocab_off;
if (vh->step_off) vh->step_off += h.vocab_off;
}
if (have_vocab_) rebase_vocab(vocab_blob_, h.vocab_off);
if (have_aux_vocab_) rebase_vocab(aux_vocab_blob_, h.reserved[RAD_HDR_AUX_VOCAB_OFF]);
int st = RAD_OK;
int64_t at = 0;
@@ -1120,6 +1155,9 @@ int RadWriter::finish() {
emit(planes_.data(), (int64_t)(planes_.size() * sizeof(RadFilePlane)), (int64_t)h.plane_off);
emit(encs_.data(), (int64_t)(encs_.size() * sizeof(RadEncoding)), (int64_t)h.enc_off);
if (have_vocab_) emit(vocab_blob_.data(), (int64_t)vocab_blob_.size(), (int64_t)h.vocab_off);
if (have_aux_vocab_)
emit(aux_vocab_blob_.data(), (int64_t)aux_vocab_blob_.size(),
(int64_t)h.reserved[RAD_HDR_AUX_VOCAB_OFF]);
emit(prof_.data(), (int64_t)(prof_.size() * sizeof(RadFileProfile)), (int64_t)h.prof_off);
if (st < 0) { RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno)); abort(); return st; }
@@ -1249,6 +1287,10 @@ int RadWriter::finish_append() {
h.enc_count = encs_.size();
h.vocab_off = (uint64_t)place8((int64_t)vocab_blob_.size());
h.vocab_bytes= have_vocab_ ? vocab_blob_.size() : 0;
if (have_aux_vocab_) {
h.reserved[RAD_HDR_AUX_VOCAB_OFF] = (uint64_t)place8((int64_t)aux_vocab_blob_.size());
h.reserved[RAD_HDR_AUX_VOCAB_BYTES] = aux_vocab_blob_.size();
}
h.prof_off = (uint64_t)place8((int64_t)(prof_.size() * sizeof(RadFileProfile)));
h.prof_count = prof_.size();
@@ -1264,14 +1306,8 @@ int RadWriter::finish_append() {
if (!dir_abs_[i])
for (uint32_t k = 0; k < dir_[i].n_planes; ++k)
planes_[dir_[i].plane_first + k].offset += (uint64_t)append_base_;
if (have_vocab_) {
auto* vh = (RadVocabHeader*)vocab_blob_.data();
if (vh->tok_text_off) vh->tok_text_off += h.vocab_off;
if (vh->tok_score_off) vh->tok_score_off += h.vocab_off;
if (vh->tok_type_off) vh->tok_type_off += h.vocab_off;
if (vh->merge_off) vh->merge_off += h.vocab_off;
if (vh->step_off) vh->step_off += h.vocab_off;
}
if (have_vocab_) rebase_vocab(vocab_blob_, h.vocab_off);
if (have_aux_vocab_) rebase_vocab(aux_vocab_blob_, h.reserved[RAD_HDR_AUX_VOCAB_OFF]);
int st = RAD_OK;
auto put = [&](const void* p, int64_t bytes, uint64_t at) {
@@ -1283,6 +1319,9 @@ int RadWriter::finish_append() {
put(planes_.data(), (int64_t)(planes_.size() * sizeof(RadFilePlane)), h.plane_off);
put(encs_.data(), (int64_t)(encs_.size() * sizeof(RadEncoding)), h.enc_off);
if (have_vocab_) put(vocab_blob_.data(), (int64_t)vocab_blob_.size(), h.vocab_off);
if (have_aux_vocab_)
put(aux_vocab_blob_.data(), (int64_t)aux_vocab_blob_.size(),
h.reserved[RAD_HDR_AUX_VOCAB_OFF]);
put(prof_.data(), (int64_t)(prof_.size() * sizeof(RadFileProfile)), h.prof_off);
if (st >= 0 && ::ftruncate(fd_out_, (off_t)off) != 0) st = RAD_E_IO;
/* Make everything durable before the new header names it. */
+7 -1
View File
@@ -141,6 +141,8 @@ public:
/* ------------------------------------------------------------ vocab and profile */
VocabSection vocab() const { return vocab_; }
/* The second vocab section, or an empty one (RAD_HDR_AUX_VOCAB_OFF in rad_format.h). */
VocabSection aux_vocab() const { return aux_vocab_; }
int64_t profile_count() const { return (int64_t)hdr_->prof_count; }
const RadFileProfile* profile() const { return prof_; }
@@ -161,7 +163,7 @@ private:
const RadFileProfile* prof_ = nullptr;
uint64_t str_bytes_ = 1;
VocabSection vocab_;
VocabSection vocab_, aux_vocab_;
std::vector<ExpertGroup> groups_;
std::unordered_map<std::string_view, int64_t> by_name_;
};
@@ -244,6 +246,8 @@ public:
/* The serialised vocab section. Its internal offsets must be section-relative (serialise with
* section_file_off 0); finish() rebases them, as it does the directory. */
int set_vocab_section(const void* blob, int64_t bytes);
/* The second vocab section (RAD_HDR_AUX_VOCAB_OFF), serialised the same way. */
int set_aux_vocab_section(const void* blob, int64_t bytes);
void add_profile(int32_t layer, int32_t expert, float share);
@@ -301,6 +305,8 @@ private:
/* The vocab section, assembled in memory and appended verbatim. */
std::vector<uint8_t> vocab_blob_;
bool have_vocab_ = false;
std::vector<uint8_t> aux_vocab_blob_;
bool have_aux_vocab_ = false;
int64_t blob_bytes_ = 0; /* the blob's reserved length */
+317 -56
View File
@@ -23,7 +23,8 @@ int64_t ref_tokens_max(const RadGeneratorDecl& d) {
}
struct Sizes {
int64_t T = 0, S = 0, EP = 0, PD = 0, R = 0, P = 0, PX = 0, NT = 0, NB = 0;
int64_t T = 0, S = 0, EP = 0, PD = 0, R = 0, P = 0, PX = 0, NT = 0, NB = 0, AX = 0;
bool joint = false;
};
Sizes sizes_of(const Program& prog, int64_t block_size) {
@@ -34,11 +35,15 @@ Sizes sizes_of(const Program& prog, int64_t block_size) {
z.EP = prog.encoder.modalities ? prog.ctx.max_enc_patches : 0;
z.PD = prog.encoder.modalities ? prog.encoder.patch_dim : 0;
z.R = d.max_refs;
z.P = z.T + z.R * ref_tokens_max(d);
z.joint = d.layout == RAD_GEN_LAYOUT_JOINT_STEP;
/* The longest conditioning: in the joint layout, the declared bound (its rows ride in the
* step, which the step size bounds anyway). */
z.P = z.joint ? std::min(d.cond_rows, z.T) : z.T + z.R * ref_tokens_max(d);
const int64_t s2 = d.latent_scale * d.latent_scale;
z.PX = z.R * (ref_tokens_max(d) * s2) + d.max_tokens * s2;
z.NT = d.max_tokens;
z.NB = block_size > 0 ? (z.P + block_size - 1) / block_size : 0;
z.AX = d.aux_tokens ? d.aux_max_tokens : 0;
return z;
}
@@ -47,6 +52,7 @@ Sizes sizes_of(const Program& prog, int64_t block_size) {
int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
const int64_t I = 4, H = 2;
const int64_t rope_rows = std::max(z.P, z.T);
const int64_t J = z.joint ? 1 : 0; /* the joint layout's regions, empty otherwise */
const int64_t want[][2] = {
{ 0, z.T * I }, /* R_TOK */
{ 0, z.T * I }, /* R_POS */
@@ -56,7 +62,7 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
{ 0, z.EP * z.PD * H }, /* R_ENCPIX */
{ 0, 4 * z.EP * I }, /* R_ENCCRD */
{ 0, (z.R + 2) * I }, /* R_ENCCU */
{ 0, z.P * I }, /* R_SRC */
{ 0, rope_rows * I }, /* R_SRC: a COND's rows, or a joint DENOISE's */
{ 0, 3 * rope_rows * I }, /* R_GROPE */
{ 0, (12 * z.R + 24) * I }, /* R_SEG: offsets; per segment a {0, length} pair and a start; per picture a {0, tokens} pair */
{ 0, z.P * I }, /* R_SLOT */
@@ -71,6 +77,21 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
{ 0, 2 * z.S * 4 }, /* R_SEED */
{ 0, z.S * z.NB * I }, /* R_BT */
{ 0, z.S * I }, /* R_USED */
{ 0, J * 4 * rope_rows * 4 }, /* R_ROPEF */
{ 0, J * (z.S + 1) * I }, /* R_ICU */
{ 0, J * z.T * I }, /* R_IROWS */
{ 0, J * (3 * z.S + 1) * I }, /* R_MCU */
{ 0, J * 2 * I }, /* R_VCU */
{ 0, J * z.T * I }, /* R_MROWS */
{ 0, J * z.T * I }, /* R_MSRC */
{ 0, J * 3 * (z.S + 1) * I }, /* R_MCCU */
{ 0, J * 4 * z.T * 4 }, /* R_MROPE */
{ 0, (z.AX ? z.AX + 2 : 0) * I }, /* R_AUX: a COND's {0, n} and second-tokenizer ids */
{ 0, z.S * 4 }, /* R_SIGP */
{ 0, z.S * 4 }, /* R_TSTEP */
{ 0, z.S * I }, /* R_SAMP */
{ 0, z.S * I }, /* R_STEPI */
{ 0, 2 * z.S * 4 }, /* R_SIZE */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
@@ -84,8 +105,10 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
} /* namespace */
int64_t Driver::device_bytes(const Program& prog) {
if (!prog.is_generator() || prog.kv_groups.size() < 2) return 0;
const Sizes z = sizes_of(prog, prog.kv_groups[1].block_size);
if (!prog.is_generator()) return 0;
const bool joint = prog.generator.layout == RAD_GEN_LAYOUT_JOINT_STEP;
if (!joint && prog.kv_groups.size() < 2) return 0;
const Sizes z = sizes_of(prog, joint ? 0 : prog.kv_groups[1].block_size);
int64_t b[R_N][2];
return carve(z, prog.generator.pixel_channels, b, R_N);
}
@@ -97,16 +120,34 @@ int Driver::init(const Program& prog, IKVManager* kv, const std::vector<RankIO>&
fixed_ = prog.gen_str.sigmas;
kv_ = kv;
ranks_ = ranks;
/* Exactly one paged full-attention KV group, holding the conditioning. Group handles start at
* 1 (group 0 is the null handle); the KV manager and a batch both index by handle. */
if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL ||
prog.kv_groups[1].block_size <= 0) {
table_ = DiscreteTable{};
if (discrete()) {
std::string why;
if (discrete_table(decl_, &table_, &why) < 0) {
RAD_ERR("image generator: %s", why.c_str());
return RAD_E_INVAL;
}
}
/* Exactly one paged full-attention KV group, holding the conditioning; none in the joint
* layout, where the conditioning rides in the steps. Group handles start at 1 (group 0 is the
* null handle); the KV manager and a batch both index by handle. */
if (joint()) {
if (prog.kv_groups.size() > 1) {
RAD_ERR("image generator: the joint layout keeps its conditioning in the plugin's "
"state, and the program declares %zu KV group(s)", prog.kv_groups.size() - 1);
return RAD_E_UNSUPPORTED;
}
kv_group_ = 0;
block_size_ = 0;
} else if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL ||
prog.kv_groups[1].block_size <= 0) {
RAD_ERR("image generator: the program declares %zu KV group(s); the driver stages exactly "
"one full-attention group, the conditioning's", prog.kv_groups.size() - 1);
return RAD_E_UNSUPPORTED;
} else {
kv_group_ = 1;
block_size_ = prog.kv_groups[1].block_size;
}
kv_group_ = 1;
block_size_ = prog.kv_groups[1].block_size;
const Sizes z = sizes_of(prog, block_size_);
max_tok_ = z.T;
max_seqs_ = z.S;
@@ -181,15 +222,19 @@ int Driver::submit(std::unique_ptr<Request> r, std::string* why) {
" latent tokens (" + std::to_string(d.max_tokens * d.latent_scale * d.latent_scale) +
" pixels)");
if (tokens * nb > max_tok_)
return no("an image of this size with guidance needs " + std::to_string(tokens * nb) +
" rows a step and a step carries " + std::to_string(max_tok_) +
" (--max-num-batched-tokens)");
return no("an image of this size" + std::string(nb > 1 ? " with guidance" : "") +
" needs " + std::to_string(tokens * nb) + " rows a step and a step carries " +
std::to_string(max_tok_) + " (--max-num-batched-tokens)");
if (r->n < 1 || r->n > d.max_lanes)
return no("n must be 1.." + std::to_string(d.max_lanes));
if ((int64_t)r->refs.size() > d.max_refs)
return no("at most " + std::to_string(d.max_refs) + " pictures a request");
for (const Branch* b : { &r->pos, &r->neg }) {
if (b == &r->neg && !r->has_neg) continue;
if (d.aux_tokens && (b->aux.empty() || (int64_t)b->aux.size() > d.aux_max_tokens))
return no("the prompt is " + std::to_string(b->aux.size()) + " tokens to the "
"model's second tokenizer, which reads 1.." +
std::to_string(d.aux_max_tokens));
if ((int64_t)b->tokens.size() > max_tok_)
return no("the prompt is " + std::to_string(b->tokens.size()) + " tokens with its "
"pictures; a conditioning pass carries " + std::to_string(max_tok_));
@@ -209,6 +254,10 @@ int Driver::submit(std::unique_ptr<Request> r, std::string* why) {
r->inp_src.h != r->height))
return no("the mask's picture is not at the size being made");
if (r->previews < 0 || r->previews > 3) return no("partial_images must be 0..3");
if (discrete() && (r->sampler < 0 || r->sampler >= RAD_GEN_SAMPLER_COUNT ||
!(decl_.samplers & (1u << r->sampler)) || r->scheduler < 0 ||
r->scheduler >= RAD_GEN_SCHED_COUNT))
return no("the sampler or scheduler is not one this model serves");
r->ticket->t_submit_ns = (int64_t)rad_mono_ns();
std::lock_guard<std::mutex> lk(mu_);
if (closed_) {
@@ -293,22 +342,36 @@ int Driver::admit_locked() {
for (const Pixels& p : r.refs)
j.ref_hw.push_back({ (int32_t)(p.h / decl_.latent_scale),
(int32_t)(p.w / decl_.latent_scale) });
int64_t step_rows = 0;
for (int b = 0; b < j.n_branch; ++b) {
std::string why;
const int s = build_layout(b ? r.neg : r.pos, decl_.slot_rows, j.ref_hw,
&j.cond[b].lay, &why);
const int s = joint()
? build_joint_layout(b ? r.neg : r.pos, decl_.pad_multiple,
decl_.rope_hw_scale, decl_.rope_text_l != 0, j.ref_hw,
&j.cond[b].lay, &why)
: build_layout(b ? r.neg : r.pos, decl_.slot_rows, j.ref_hw, &j.cond[b].lay,
&why);
if (s < 0) { fail_locked(j, s, why); break; }
if (j.cond[b].lay.rows > max_rows_) {
fail_locked(j, RAD_E_INVAL, "the conditioning is " +
std::to_string(j.cond[b].lay.rows) + " rows; the driver stages " +
std::to_string(j.cond[b].lay.rows) + " rows (the prompt" +
std::string(r.refs.empty() ? "" : " and its pictures") +
"); this model conditions on at most " +
std::to_string(max_rows_));
break;
}
step_rows += entry_rows(j, b);
}
if (j.failed) continue;
if (step_rows > max_tok_) {
fail_locked(j, RAD_E_INVAL, "an image with its conditioning needs " +
std::to_string(step_rows) + " rows a step and a step carries " +
std::to_string(max_tok_) + " (--max-num-batched-tokens)");
continue;
}
}
bool ok = true;
for (int b = 0; b < j.n_branch && ok; ++b) {
for (int b = 0; b < j.n_branch && ok && !joint(); ++b) {
Cond& c = j.cond[b];
if (c.have_kv) continue;
if (!kv_->can_ever_fit(c.lay.rows)) {
@@ -333,12 +396,24 @@ int Driver::admit_locked() {
release_kv_locked(j);
break;
}
j.sigmas = schedule(decl_, fixed_, r.steps, j.tokens);
if (discrete()) {
j.sigmas = schedule_discrete(decl_, table_, r.scheduler, r.steps);
j.tsteps.clear();
for (float sg : j.sigmas) j.tsteps.push_back(sg > 0 ? (float)table_.timestep(sg) : 0.0f);
} else {
j.sigmas = schedule(decl_, fixed_, r.steps, j.tokens);
}
const int32_t n_steps = (int32_t)j.sigmas.size() - 1;
for (int b = 0; b < j.n_branch; ++b) {
Cond& c = j.cond[b];
c.rope_img.assign((size_t)(3 * j.tokens), 0);
image_rope(c.lay.next_pos, j.h_lat, j.w_lat, c.rope_img.data(), j.tokens);
if (joint()) {
c.rope_img_f.assign((size_t)(4 * j.tokens), 0.0f);
grid_rope_f(decl_.rope_hw_scale, 0.0f, j.h_lat, j.w_lat, c.rope_img_f.data(),
j.tokens);
} else {
c.rope_img.assign((size_t)(3 * j.tokens), 0);
image_rope(c.lay.next_pos, j.h_lat, j.w_lat, c.rope_img.data(), j.tokens);
}
}
for (int32_t i = 0; i < r.n; ++i) {
const int32_t l = free_lanes_.back();
@@ -413,8 +488,8 @@ void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int ste
K.seqused = dptr<int32_t>(ri, R_USED);
K.block_size = block_size_;
K.max_blocks = max_blocks_;
B.n_kv_groups = 1;
B.kv = &K;
B.n_kv_groups = joint() ? 0 : 1;
B.kv = joint() ? nullptr : &K;
B.gen_b = &G;
G.src = dptr<int32_t>(ri, R_SRC);
G.rope = dptr<int32_t>(ri, R_GROPE);
@@ -431,6 +506,30 @@ void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int ste
G.lane_dh = hptr<int32_t>(R_LANE);
G.flags = dptr<int32_t>(ri, R_FLAGS);
G.seed = dptr<uint32_t>(ri, R_SEED);
/* The joint layout's fields, which only the passes that use them set. */
G.branch = 0;
G.n_pad = 0;
G.valid_cu = nullptr;
G.n_img = 0;
G.img_cu = nullptr;
G.img_rows = nullptr;
G.mode_cu = nullptr;
G.rope_f = nullptr;
G.mode_rows = nullptr;
G.mode_src = nullptr;
G.mode_ccu = nullptr;
G.n_mode_h = nullptr;
G.mode_rope_f = nullptr;
G.n_aux = 0;
G.aux_ids = nullptr;
G.aux_cu = nullptr;
G.sigma_prev = nullptr;
G.timestep = nullptr;
G.sampler = nullptr;
G.step = nullptr;
G.size_px = nullptr;
G.entry_h = nullptr;
G.tokens_h = nullptr;
}
}
@@ -469,28 +568,35 @@ const RadBatch* Driver::next(int step) {
for (int b = 0; b < j.n_branch; ++b)
if (!j.cond[b].encoded) return build_cond(j, b, step);
}
/* 3. A denoise step over what is in flight, oldest request first. */
/* 3. A denoise step over what is in flight, oldest request first, with the oldest one's
* adapters: a pass runs one runtime LoRA slot in every row. */
std::vector<int32_t> take;
int64_t rows = 0, entries = 0;
int32_t lora = -2;
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed) continue;
bool ready = true;
for (int b = 0; b < j.n_branch; ++b) ready = ready && j.cond[b].encoded;
if (!ready) continue;
if (lora != -2 && j.req->lora_slot != lora) continue;
const int32_t n_steps = (int32_t)j.sigmas.size() - 1;
for (int32_t l : j.lanes) {
const Lane& ln = lanes_[(size_t)l];
if (ln.finished || ln.final_due || ln.preview_due || ln.step >= n_steps) continue;
const int64_t need = j.tokens * j.n_branch;
int64_t need = 0;
for (int b = 0; b < j.n_branch; ++b) need += entry_rows(j, b);
if (rows + need > max_tok_ || entries + j.n_branch > max_seqs_) break;
rows += need;
entries += j.n_branch;
take.push_back(l);
lora = j.req->lora_slot;
}
}
if (take.empty()) return nullptr;
return build_denoise(take, step);
const RadBatch* b = build_denoise(take, step);
pass_.lora_slot = lora;
return b;
}
const RadBatch* Driver::batch_for(int rank) const {
@@ -503,15 +609,19 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
const Request& r = *j.req;
const Branch& br = branch ? r.neg : r.pos;
const Cond& c = j.cond[branch];
const int64_t T = (int64_t)br.tokens.size(), P = c.lay.rows;
/* The joint layout's padding tokens follow the prompt's; each sits at position 1 and sees
* only the prompt (`valid_cu`), as a masked padding token does in the reference. */
const int64_t T_valid = (int64_t)br.tokens.size();
const int64_t T = T_valid + (joint() ? c.lay.n_pad : 0), P = c.lay.rows;
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* pos = hptr<int32_t>(R_POS);
int32_t* rope = hptr<int32_t>(R_ROPE);
std::memcpy(tok, br.tokens.data(), (size_t)T * 4);
for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)i;
std::memcpy(tok, br.tokens.data(), (size_t)T_valid * 4);
for (int64_t i = T_valid; i < T; ++i) tok[i] = decl_.pad_token;
for (int64_t i = 0; i < T; ++i) pos[i] = i < T_valid ? (int32_t)i : 1;
for (int64_t i = 0; i < T; ++i) {
int32_t p3[3] = { (int32_t)i, (int32_t)i, (int32_t)i };
int32_t p3[3] = { pos[i], pos[i], pos[i] };
if (br.media) br.media->rope.at(i, p3);
rope[i] = p3[0];
rope[T + i] = p3[1];
@@ -571,7 +681,8 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
std::memcpy(segp, c.lay.seg.data(), (size_t)(nsg + 1) * 4);
for (int64_t s = 0; s < nsg; ++s) {
const int32_t a = c.lay.seg[(size_t)s], len = c.lay.seg[(size_t)s + 1] - a;
for (int cc = 0; cc < 3; ++cc)
/* The joint layout's positions are f32, staged whole below. */
for (int cc = 0; cc < 3 && !joint(); ++cc)
std::memcpy(grope + 3 * (int64_t)a + cc * (int64_t)len,
&c.lay.rope[(size_t)(cc * P + a)], (size_t)len * 4);
segp[nsg + 1 + 2 * s] = 0;
@@ -579,21 +690,31 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
segp[nsg + 1 + 2 * nsg + s] = a;
}
reg_[R_SRC].used = P * 4;
reg_[R_GROPE].used = 3 * P * 4;
reg_[R_GROPE].used = joint() ? 0 : 3 * P * 4;
reg_[R_SEG].used = (4 * nsg + 1) * 4;
const std::vector<int32_t>& bt = kv_->block_table(c.seq, kv_group_);
int32_t* slot = hptr<int32_t>(R_SLOT);
for (int64_t p = 0; p < P; ++p) {
const int64_t bi = p / block_size_;
slot[p] = bi < (int64_t)bt.size() ? (int32_t)(bt[(size_t)bi] * block_size_ + p % block_size_)
: -1;
static const std::vector<int32_t> no_bt;
const std::vector<int32_t>& bt = joint() ? no_bt : kv_->block_table(c.seq, kv_group_);
if (joint()) {
std::memcpy(hptr<float>(R_ROPEF), c.lay.rope_f.data(), (size_t)(4 * P) * 4);
reg_[R_ROPEF].used = 4 * P * 4;
int32_t* vcu = hptr<int32_t>(R_VCU);
vcu[0] = 0;
vcu[1] = (int32_t)T_valid;
reg_[R_VCU].used = 2 * 4;
} else {
int32_t* slot = hptr<int32_t>(R_SLOT);
for (int64_t p = 0; p < P; ++p) {
const int64_t bi = p / block_size_;
slot[p] = bi < (int64_t)bt.size()
? (int32_t)(bt[(size_t)bi] * block_size_ + p % block_size_) : -1;
}
reg_[R_SLOT].used = P * 4;
int32_t* btab = hptr<int32_t>(R_BT);
for (size_t i = 0; i < bt.size(); ++i) btab[i] = bt[i];
reg_[R_BT].used = (int64_t)bt.size() * 4;
hptr<int32_t>(R_USED)[0] = (int32_t)P;
reg_[R_USED].used = 4;
}
reg_[R_SLOT].used = P * 4;
int32_t* btab = hptr<int32_t>(R_BT);
for (size_t i = 0; i < bt.size(); ++i) btab[i] = bt[i];
reg_[R_BT].used = (int64_t)bt.size() * 4;
hptr<int32_t>(R_USED)[0] = (int32_t)P;
reg_[R_USED].used = 4;
/* Pictures again for the generator's own encoder, plus the inpainting source when masked.
* Only the positive conditioning's pass writes the lanes. */
@@ -628,11 +749,21 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
/* The conditioning is modulated at t = 0. */
hptr<float>(R_SIG)[0] = 0.0f;
reg_[R_SIG].used = 4;
/* The prompt through the second tokenizer, for a model that reads it. */
const int64_t n_aux = decl_.aux_tokens ? (int64_t)br.aux.size() : 0;
if (n_aux) {
int32_t* ax = hptr<int32_t>(R_AUX);
ax[0] = 0;
ax[1] = (int32_t)n_aux;
std::memcpy(ax + 2, br.aux.data(), (size_t)n_aux * 4);
reg_[R_AUX].used = (n_aux + 2) * 4;
}
/* Host-side arrays the plugin reads (segment kinds, pixel blocks, lanes), owned by the driver
* for the life of the pass. */
host_bidi_ = c.lay.bidi;
host_px_ = pxh;
host_lanes_ = inp ? j.lanes : std::vector<int32_t>{};
/* The joint layout's conditioning goes to every lane of the request. */
host_lanes_ = inp || joint() ? j.lanes : std::vector<int32_t>{};
/* The lanes on the device too: an op copies the inpainting latent and mask into each. */
if (!host_lanes_.empty()) {
std::memcpy(hptr<int32_t>(R_LANE), host_lanes_.data(), host_lanes_.size() * 4);
@@ -681,9 +812,25 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
G.n_lane = (int64_t)host_lanes_.size();
G.lane_h = host_lanes_.data();
G.lane = G.n_lane ? dptr<int32_t>(ri, R_LANE) : nullptr;
G.n_aux = n_aux;
G.aux_cu = n_aux ? dptr<int32_t>(ri, R_AUX) : nullptr;
G.aux_ids = n_aux ? dptr<int32_t>(ri, R_AUX) + 2 : nullptr;
G.tokens_h = hptr<int32_t>(R_TOK);
G.cond_opts = j.req->cond_opts;
if (joint()) {
B.n_kv_groups = 0;
B.kv = nullptr;
G.slot_mapping = nullptr;
G.branch = branch;
G.n_pad = c.lay.n_pad;
G.valid_cu = dptr<int32_t>(ri, R_VCU);
G.rope = nullptr;
G.rope_f = dptr<float>(ri, R_ROPEF);
}
}
pass_.kind = RAD_GEN_PASS_COND;
pass_.job = j.id;
pass_.lora_slot = j.req->lora_slot;
pass_.branch = branch;
return &out_[0];
}
@@ -699,15 +846,28 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
for (int b = 0; b < j->n_branch; ++b) es.push_back({ j, l, b });
}
const int64_t S = (int64_t)es.size();
int64_t n_tok = 0;
int64_t n_tok = 0, n_img = 0;
int32_t max_q = 0, max_ctx = 0;
int64_t pitch = 1;
for (const E& e : es) {
n_tok += e.j->tokens;
max_q = std::max<int32_t>(max_q, (int32_t)e.j->tokens);
const int64_t rows = entry_rows(*e.j, e.branch);
n_tok += rows;
n_img += e.j->tokens;
max_q = std::max<int32_t>(max_q, (int32_t)rows);
max_ctx = std::max<int32_t>(max_ctx, (int32_t)e.j->cond[e.branch].lay.rows);
pitch = std::max<int64_t>(pitch, (int64_t)kv_->block_table(e.j->cond[e.branch].seq, kv_group_).size());
if (!joint())
pitch = std::max<int64_t>(pitch, (int64_t)kv_->block_table(e.j->cond[e.branch].seq,
kv_group_).size());
}
/* The joint layout's per-row arrays: each row's source, the compact image order's bounds and
* rows, each entry's three modes, and the f32 positions. */
int32_t* src = hptr<int32_t>(R_SRC);
int32_t* icu = hptr<int32_t>(R_ICU);
int32_t* irows = hptr<int32_t>(R_IROWS);
int32_t* mcu = hptr<int32_t>(R_MCU);
float* ropef = hptr<float>(R_ROPEF);
int64_t img = 0;
if (joint()) icu[0] = 0;
int32_t* cu = hptr<int32_t>(R_CU);
int32_t* pos = hptr<int32_t>(R_POS);
int32_t* tok = hptr<int32_t>(R_TOK);
@@ -721,6 +881,12 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
uint32_t* seed = hptr<uint32_t>(R_SEED);
int32_t* btab = hptr<int32_t>(R_BT);
int32_t* used = hptr<int32_t>(R_USED);
float* sigp = hptr<float>(R_SIGP);
float* tstep = hptr<float>(R_TSTEP);
int32_t* samp = hptr<int32_t>(R_SAMP);
int32_t* stepi = hptr<int32_t>(R_STEPI);
float* size = hptr<float>(R_SIZE);
host_entry_.assign((size_t)(4 * S), 0);
int64_t row = 0;
cu[0] = 0;
pass_.lanes.clear();
@@ -731,13 +897,51 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
const Lane& ln = lanes_[(size_t)e.lane];
const Cond& c = j.cond[e.branch];
const int64_t N = j.tokens;
for (int64_t k = 0; k < N; ++k) { pos[row + k] = (int32_t)k; tok[row + k] = 0; }
for (int cc = 0; cc < 3; ++cc)
std::memcpy(grope + cc * n_tok + row, c.rope_img.data() + cc * N, (size_t)N * 4);
if (joint()) {
/* [conditioning | image]: the conditioning's rows from the plugin's copy at this lane
* and branch, the image's from the compact order. */
const int64_t P = c.lay.rows;
const int64_t base = (2 * (int64_t)e.lane + e.branch) * decl_.cond_rows;
for (int64_t k = 0; k < P; ++k) {
src[row + k] = (int32_t)(base + k);
pos[row + k] = (int32_t)k;
tok[row + k] = 0;
}
for (int cc = 0; cc < 4; ++cc)
std::memcpy(ropef + cc * n_tok + row, c.lay.rope_f.data() + cc * P, (size_t)P * 4);
mcu[3 * i] = (int32_t)row;
mcu[3 * i + 1] = (int32_t)(row + c.lay.text);
mcu[3 * i + 2] = (int32_t)(row + P);
row += P;
for (int64_t k = 0; k < N; ++k) {
src[row + k] = (int32_t)(-(1 + img + k));
irows[img + k] = (int32_t)(row + k);
pos[row + k] = (int32_t)k;
tok[row + k] = 0;
}
for (int cc = 0; cc < 4; ++cc)
std::memcpy(ropef + cc * n_tok + row, c.rope_img_f.data() + cc * N, (size_t)N * 4);
img += N;
icu[i + 1] = (int32_t)img;
} else {
for (int64_t k = 0; k < N; ++k) { pos[row + k] = (int32_t)k; tok[row + k] = 0; }
for (int cc = 0; cc < 3; ++cc)
std::memcpy(grope + cc * n_tok + row, c.rope_img.data() + cc * N, (size_t)N * 4);
}
row += N;
cu[i + 1] = (int32_t)row;
sig[i] = j.sigmas[(size_t)ln.step];
sign[i] = j.sigmas[(size_t)ln.step + 1];
sigp[i] = ln.step > 0 ? j.sigmas[(size_t)ln.step - 1] : 0.0f;
tstep[i] = discrete() ? j.tsteps[(size_t)ln.step] : 0.0f;
samp[i] = j.req->sampler;
stepi[i] = ln.step;
size[2 * i] = (float)j.req->height;
size[2 * i + 1] = (float)j.req->width;
host_entry_[(size_t)(4 * i)] = joint() ? (int32_t)c.lay.rows : 0;
host_entry_[(size_t)(4 * i + 1)] = j.req->height;
host_entry_[(size_t)(4 * i + 2)] = j.req->width;
host_entry_[(size_t)(4 * i + 3)] = e.branch;
const bool neg = e.branch == 1;
cfg[i] = neg ? 0.0f : (j.n_branch > 1 ? j.req->cfg : 1.0f);
pair[i] = neg ? -2 : (j.n_branch > 1 ? (int32_t)(i + 1) : -1);
@@ -758,6 +962,7 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
flags[i] = f;
seed[2 * i] = (uint32_t)(ln.seed & 0xffffffffu);
seed[2 * i + 1] = (uint32_t)(ln.seed >> 32);
if (joint()) continue;
const std::vector<int32_t>& bt = kv_->block_table(c.seq, kv_group_);
for (int64_t b = 0; b < pitch; ++b)
btab[i * pitch + b] = b < (int64_t)bt.size() ? bt[(size_t)b] : -1;
@@ -765,12 +970,48 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
}
reg_[R_CU].used = (S + 1) * 4;
reg_[R_POS].used = reg_[R_TOK].used = n_tok * 4;
reg_[R_GROPE].used = 3 * n_tok * 4;
if (joint()) {
mcu[3 * S] = (int32_t)n_tok;
/* The mode-major order: every entry's text, then pictures, then image. */
int32_t* mrows = hptr<int32_t>(R_MROWS);
int32_t* msrc = hptr<int32_t>(R_MSRC);
int32_t* mccu = hptr<int32_t>(R_MCCU);
float* mrope = hptr<float>(R_MROPE);
int64_t k = 0;
for (int mode = 0; mode < 3; ++mode) {
const int64_t k0 = k;
int64_t nm = 0;
for (int64_t i = 0; i < S; ++i) nm += mcu[3 * i + mode + 1] - mcu[3 * i + mode];
for (int64_t i = 0; i < S; ++i) {
mccu[mode * (S + 1) + i] = (int32_t)(k - k0);
for (int32_t r = mcu[3 * i + mode]; r < mcu[3 * i + mode + 1]; ++r, ++k) {
mrows[k] = r;
msrc[k] = src[r];
for (int cc = 0; cc < 4; ++cc)
mrope[4 * k0 + cc * nm + (k - k0)] = ropef[cc * n_tok + r];
}
}
mccu[mode * (S + 1) + S] = (int32_t)(k - k0);
host_nmode_[mode] = k - k0;
}
reg_[R_MROWS].used = reg_[R_MSRC].used = n_tok * 4;
reg_[R_MCCU].used = 3 * (S + 1) * 4;
reg_[R_MROPE].used = 4 * n_tok * 4;
reg_[R_SRC].used = n_tok * 4;
reg_[R_IROWS].used = n_img * 4;
reg_[R_ICU].used = (S + 1) * 4;
reg_[R_MCU].used = (3 * S + 1) * 4;
reg_[R_ROPEF].used = 4 * n_tok * 4;
} else {
reg_[R_GROPE].used = 3 * n_tok * 4;
}
reg_[R_SIG].used = reg_[R_SIGN].used = reg_[R_CFG].used = S * 4;
reg_[R_SIGP].used = reg_[R_TSTEP].used = reg_[R_SAMP].used = reg_[R_STEPI].used = S * 4;
reg_[R_SIZE].used = 2 * S * 4;
reg_[R_PAIR].used = reg_[R_LANE].used = reg_[R_FLAGS].used = S * 4;
reg_[R_SEED].used = 2 * S * 4;
reg_[R_BT].used = S * pitch * 4;
reg_[R_USED].used = S * 4;
reg_[R_BT].used = joint() ? 0 : S * pitch * 4;
reg_[R_USED].used = joint() ? 0 : S * 4;
if (upload() < 0) return nullptr;
finish_batches(n_tok, S, max_q, step);
for (size_t rr = 0; rr < ranks_.size(); ++rr) {
@@ -789,8 +1030,28 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
G.inpaint = 0;
G.n_lane = 0;
G.lane_h = nullptr;
G.rope = dptr<int32_t>(ri, R_GROPE);
G.rope = joint() ? nullptr : dptr<int32_t>(ri, R_GROPE);
G.lane_dh = hptr<int32_t>(R_LANE);
G.sigma_prev = dptr<float>(ri, R_SIGP);
G.timestep = dptr<float>(ri, R_TSTEP);
G.sampler = dptr<int32_t>(ri, R_SAMP);
G.step = dptr<int32_t>(ri, R_STEPI);
G.size_px = dptr<float>(ri, R_SIZE);
G.entry_h = host_entry_.data();
if (joint()) {
G.src = dptr<int32_t>(ri, R_SRC);
G.n_img = n_img;
G.img_cu = dptr<int32_t>(ri, R_ICU);
G.img_rows = dptr<int32_t>(ri, R_IROWS);
G.mode_cu = dptr<int32_t>(ri, R_MCU);
G.rope_f = dptr<float>(ri, R_ROPEF);
G.slot_mapping = nullptr;
G.mode_rows = dptr<int32_t>(ri, R_MROWS);
G.mode_src = dptr<int32_t>(ri, R_MSRC);
G.mode_ccu = dptr<int32_t>(ri, R_MCCU);
G.n_mode_h = host_nmode_;
G.mode_rope_f = dptr<float>(ri, R_MROPE);
}
}
pass_.kind = RAD_GEN_PASS_DENOISE;
return &out_[0];
+20 -1
View File
@@ -60,6 +60,7 @@ public:
/* ---------------------------------------------------------- the engine thread */
const RadBatch* next(int step) override;
const RadBatch* batch_for(int rank) const override;
int32_t lora_slot() const override { return pass_.lora_slot; }
/* A decode pass's pixels: `image_out` into the pinned image buffer. */
const std::vector<Readback>& readbacks() const override { return rb_; }
int done() override;
@@ -75,6 +76,7 @@ private:
bool have_kv = false;
bool encoded = false;
std::vector<int32_t> rope_img; /* [3, image tokens]: the image's rows at this sequence */
std::vector<float> rope_img_f; /* JOINT_STEP: [4, image tokens] */
};
struct Job {
uint64_t id = 0;
@@ -84,6 +86,8 @@ private:
int32_t h_lat = 0, w_lat = 0;
int64_t tokens = 0;
std::vector<float> sigmas;
/* A discrete-time model's: each step's timestep, beside `sigmas`. */
std::vector<float> tsteps;
std::vector<int32_t> lanes;
std::vector<std::pair<int32_t, int32_t>> ref_hw;
int32_t images_done = 0;
@@ -111,13 +115,15 @@ private:
bool preview = false;
std::vector<int32_t> lanes; /* DENOISE: the lanes it stepped, one per image */
std::vector<char> marks; /* ... and whether each was marked for a preview */
int32_t lora_slot = -1; /* every image of a pass runs with the same adapters */
};
/* Staging regions: their offsets in the host span and every rank's slab. */
struct Region { int64_t off = 0, bytes = 0, used = 0; };
enum { R_TOK, R_POS, R_ROPE, R_CU, R_MMROW, R_ENCPIX, R_ENCCRD, R_ENCCU, R_SRC, R_GROPE,
R_SEG, R_SLOT, R_PX, R_MASK, R_SIG, R_SIGN, R_CFG, R_PAIR, R_LANE, R_FLAGS, R_SEED,
R_BT, R_USED, R_N };
R_BT, R_USED, R_ROPEF, R_ICU, R_IROWS, R_MCU, R_VCU, R_MROWS, R_MSRC, R_MCCU, R_MROPE,
R_AUX, R_SIGP, R_TSTEP, R_SAMP, R_STEPI, R_SIZE, R_N };
int layout_regions();
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
@@ -133,12 +139,22 @@ private:
void fail_locked(Job& j, int status, const std::string& why);
Job* job_locked(uint64_t id);
/* The JOINT_STEP layout: the conditioning rides in every denoising entry, and no KV. */
bool joint() const { return decl_.layout == RAD_GEN_LAYOUT_JOINT_STEP; }
/* An entry's rows in a denoising pass. */
int64_t entry_rows(const Job& j, int branch) const {
return j.tokens + (joint() ? j.cond[branch].lay.rows : 0);
}
const RadBatch* build_cond(Job& j, int branch, int step);
const RadBatch* build_denoise(const std::vector<int32_t>& lanes, int step);
const RadBatch* build_decode(int32_t lane, bool preview, int step);
RadGeneratorDecl decl_{};
std::vector<double> fixed_;
/* A discrete-time model's sigma table (RadGeneratorDecl::train_steps), empty otherwise. */
DiscreteTable table_;
bool discrete() const { return decl_.train_steps > 0; }
int64_t max_tok_ = 0, max_seqs_ = 0, max_enc_ = 0, patch_dim_ = 0;
int64_t max_rows_ = 0; /* the longest conditioning sequence */
int64_t max_px_ = 0; /* pixels the staging holds */
@@ -162,6 +178,9 @@ private:
Pass pass_;
/* Host arrays a COND pass's plugin reads on the host (RadGenBatch's _h fields). */
std::vector<int32_t> host_bidi_, host_px_, host_lanes_;
/* A DENOISE pass's per-entry host array (RadGenBatch::entry_h). */
std::vector<int32_t> host_entry_;
int64_t host_nmode_[3] = { 0, 0, 0 };
mutable std::mutex mu_;
std::deque<std::unique_ptr<Job>> jobs_; /* arrival order */
+192
View File
@@ -67,6 +67,16 @@ std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>
std::vector<float> s;
if (!fixed.empty()) {
for (double v : fixed) s.push_back((float)v);
} else if (d.sigma_grid > 0) {
/* ComfyUI's `simple` scheduler: the model's table holds t = k / N for k = 1..N (an f32
* quotient), and step i reads entry N - 1 - floor(i N / n), the floor of a Python float. */
const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps;
const int64_t N = d.sigma_grid;
const double ss = (double)N / (double)n;
for (int32_t i = 0; i < n; ++i) {
const int64_t k = N - (int64_t)((double)i * ss);
s.push_back((float)k / (float)N);
}
} else {
const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps;
/* np.linspace(1.0, 1 / n, n) in f64, then astype(f32). */
@@ -94,6 +104,127 @@ std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>
return s;
}
/* ================================================================== a discrete-time schedule */
float DiscreteTable::sigma_at(double t) const {
const double hi = (double)(log_sigmas.size() - 1);
t = t < 0.0 ? 0.0 : t > hi ? hi : t;
const size_t lo = (size_t)std::floor(t), up = (size_t)std::ceil(t);
const float w = (float)(t - std::floor(t));
return std::exp((1.0f - w) * log_sigmas[lo] + w * log_sigmas[up]);
}
int32_t DiscreteTable::timestep(float sigma) const {
const float l = std::log(sigma);
int32_t best = 0;
float bd = std::fabs(l - log_sigmas[0]);
for (size_t i = 1; i < log_sigmas.size(); ++i) {
const float d = std::fabs(l - log_sigmas[i]);
if (d < bd) { bd = d; best = (int32_t)i; }
}
return best;
}
int discrete_table(const RadGeneratorDecl& d, DiscreteTable* out, std::string* why) {
const int32_t n = d.train_steps;
if (n < 2 || !(d.beta_start > 0) || !(d.beta_end > d.beta_start) || d.beta_end >= 1 ||
(d.beta_schedule != RAD_GEN_BETAS_SCALED_LINEAR && d.beta_schedule != RAD_GEN_BETAS_LINEAR)) {
if (why) *why = "the discrete schedule needs two or more timesteps and betas rising in (0, 1)";
return RAD_E_INVAL;
}
std::vector<double> sig((size_t)n);
double abar = 1.0;
const bool sq = d.beta_schedule == RAD_GEN_BETAS_SCALED_LINEAR;
const double a = sq ? std::sqrt(d.beta_start) : d.beta_start;
const double b = sq ? std::sqrt(d.beta_end) : d.beta_end;
for (int32_t i = 0; i < n; ++i) {
const double v = a + (b - a) * (double)i / (double)(n - 1);
abar *= 1.0 - (sq ? v * v : v);
sig[(size_t)i] = std::sqrt((1.0 - abar) / abar);
}
if (d.zero_snr) {
/* ComfyUI's rescale_zero_terminal_snr_sigmas: sqrt(abar) shifted to end at 0 and scaled
* to keep its start, the last abar then set to a small positive value. */
std::vector<double> s((size_t)n);
for (int32_t i = 0; i < n; ++i) s[(size_t)i] = std::sqrt(1.0 / (sig[(size_t)i] * sig[(size_t)i] + 1.0));
const double s0 = s.front(), sT = s.back();
for (int32_t i = 0; i < n; ++i) {
double v = (s[(size_t)i] - sT) * (s0 / (s0 - sT));
double ab = v * v;
if (i == n - 1) ab = 4.8973451890853435e-08;
sig[(size_t)i] = std::sqrt((1.0 - ab) / ab);
}
}
out->sigmas.resize((size_t)n);
out->log_sigmas.resize((size_t)n);
for (int32_t i = 0; i < n; ++i) {
out->sigmas[(size_t)i] = (float)sig[(size_t)i];
out->log_sigmas[(size_t)i] = (float)std::log(sig[(size_t)i]);
}
return RAD_OK;
}
std::vector<float> schedule_discrete(const RadGeneratorDecl& d, const DiscreteTable& t,
int32_t scheduler, int32_t steps) {
const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps;
std::vector<float> s;
const double smin = t.sigma_min(), smax = t.sigma_max();
/* A point i of n evenly spaced from `a` to `b`, both ends included. */
auto lin = [](double a, double b, int32_t i, int32_t cnt) {
return cnt <= 1 ? a : a + (b - a) * (double)i / (double)(cnt - 1);
};
switch (scheduler) {
case RAD_GEN_SCHED_KARRAS: {
const double rho = 7.0, lo = std::pow(smin, 1.0 / rho), hi = std::pow(smax, 1.0 / rho);
for (int32_t i = 0; i < n; ++i) s.push_back((float)std::pow(lin(hi, lo, i, n), rho));
break;
}
case RAD_GEN_SCHED_EXPONENTIAL:
for (int32_t i = 0; i < n; ++i)
s.push_back((float)std::exp(lin(std::log(smax), std::log(smin), i, n)));
break;
case RAD_GEN_SCHED_SIMPLE: {
const double stride = (double)t.sigmas.size() / (double)n;
for (int32_t i = 0; i < n; ++i)
s.push_back(t.sigmas[t.sigmas.size() - 1 - (size_t)((double)i * stride)]);
break;
}
case RAD_GEN_SCHED_SGM_UNIFORM:
case RAD_GEN_SCHED_NORMAL:
default: {
/* Timesteps from the largest sigma's to the smallest's, evenly spaced; sgm_uniform
* spaces n + 1 and drops the last. The model's clock ends at 0. */
const double a = (double)t.timestep(t.sigma_max()), b = (double)t.timestep(t.sigma_min());
const bool sgm = scheduler == RAD_GEN_SCHED_SGM_UNIFORM;
const int32_t cnt = sgm ? n + 1 : n;
for (int32_t i = 0; i < n; ++i) s.push_back(t.sigma_at(lin(a, b, i, cnt)));
break;
}
}
s.push_back(0.0f);
return s;
}
namespace {
const char* const kSamplers[RAD_GEN_SAMPLER_COUNT] = { "euler", "euler_ancestral", "dpmpp_2m" };
const char* const kScheds[RAD_GEN_SCHED_COUNT] = { "normal", "karras", "exponential",
"sgm_uniform", "simple" };
} /* namespace */
const char* sampler_name(int32_t id) {
return id >= 0 && id < RAD_GEN_SAMPLER_COUNT ? kSamplers[id] : "";
}
const char* scheduler_name(int32_t id) {
return id >= 0 && id < RAD_GEN_SCHED_COUNT ? kScheds[id] : "";
}
int32_t sampler_id(const std::string& name) {
for (int32_t i = 0; i < RAD_GEN_SAMPLER_COUNT; ++i) if (name == kSamplers[i]) return i;
return -1;
}
int32_t scheduler_id(const std::string& name) {
for (int32_t i = 0; i < RAD_GEN_SCHED_COUNT; ++i) if (name == kScheds[i]) return i;
return -1;
}
/* ================================================================== the sequence */
void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_total) {
const int32_t h0 = -(h - h / 2), w0 = -(w - w / 2);
@@ -106,6 +237,67 @@ void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_to
}
}
void grid_rope_f(double hw_scale, float l, int32_t h, int32_t w, float* planes, int64_t n_total) {
const float s = (float)hw_scale;
int64_t k = 0;
for (int32_t r = 0; r < h; ++r)
for (int32_t c = 0; c < w; ++c, ++k) {
planes[k] = 0.0f;
planes[n_total + k] = s * (float)r;
planes[2 * n_total + k] = s * (float)c;
planes[3 * n_total + k] = l;
}
}
int build_joint_layout(const Branch& b, int32_t pad_multiple, double hw_scale, bool text_l,
const std::vector<std::pair<int32_t, int32_t>>& ref_hw, Layout* out,
std::string* why) {
*out = Layout{};
const int64_t T = (int64_t)b.tokens.size();
if (b.n_drop < 0 || b.n_drop >= T) {
if (why) *why = "the conditioning prompt is no longer than its fixed prefix";
return RAD_E_INVAL;
}
if (b.media) {
if (why) *why = "the joint layout reads no pictures in the prompt";
return RAD_E_INVAL;
}
const int64_t text = T - b.n_drop;
const int64_t padded = pad_multiple > 0 ? (text + pad_multiple - 1) / pad_multiple * pad_multiple
: text;
int64_t refs = 0;
for (const auto& hw : ref_hw) refs += (int64_t)hw.first * hw.second;
const int64_t rows = padded + refs;
out->rows = rows;
out->text = padded;
out->n_pad = (int32_t)(padded - text);
out->src.resize((size_t)rows);
out->rope_f.assign((size_t)(4 * rows), 0.0f);
for (int64_t i = 0; i < padded; ++i) {
out->src[(size_t)i] = (int32_t)(b.n_drop + i);
if (text_l) out->rope_f[(size_t)(3 * rows + i)] = (float)i;
}
out->seg.push_back(0);
out->bidi.push_back(0);
int64_t row = padded, lat = 0;
for (size_t k = 0; k < ref_hw.size(); ++k) {
const int32_t h = ref_hw[k].first, w = ref_hw[k].second;
const int64_t n = (int64_t)h * w;
std::vector<float> pl((size_t)(4 * n));
grid_rope_f(hw_scale, -(float)(1 + k), h, w, pl.data(), n);
for (int cc = 0; cc < 4; ++cc)
std::memcpy(&out->rope_f[(size_t)(cc * rows + row)], &pl[(size_t)(cc * n)],
(size_t)n * sizeof(float));
for (int64_t i = 0; i < n; ++i) out->src[(size_t)(row + i)] = (int32_t)(-(1 + lat + i));
out->seg.push_back((int32_t)row);
out->bidi.push_back(1);
row += n;
lat += n;
}
out->seg.push_back((int32_t)rows);
return RAD_OK;
}
int build_layout(const Branch& b, int64_t slot_rows,
const std::vector<std::pair<int32_t, int32_t>>& ref_hw, Layout* out,
std::string* why) {
+52
View File
@@ -48,6 +48,9 @@ struct Branch {
std::vector<int32_t> tokens;
std::shared_ptr<mm::PromptMedia> media; /* null for a prompt with no pictures */
int32_t n_drop = 0;
/* The user's prompt through the model's second tokenizer (RadGeneratorDecl::aux_tokens);
* empty otherwise. */
std::vector<int32_t> aux;
};
/* One finished image, or a preview of one. */
@@ -99,6 +102,8 @@ struct Request {
float cfg = 1.0f;
int32_t width = 0, height = 0; /* pixels, whole multiples of the declared multiple */
int32_t steps = 0; /* 0: the model's default (or its fixed schedule) */
/* A discrete-time model's sampler and scheduler (RAD_GEN_SAMPLER_*, RAD_GEN_SCHED_*). */
int32_t sampler = 0, scheduler = 0;
int32_t n = 1;
uint64_t seed = 0; /* image i draws its noise from seed + i */
int32_t previews = 0; /* partial images per image, 0..3 */
@@ -109,6 +114,12 @@ struct Request {
bool inpaint = false;
Pixels inp_src;
std::vector<float> inp_mask;
/* The runtime LoRA slot every pass of the request runs with (Engine::gen_lora_acquire), -1
* for none, and the hold that keeps the slot's adapters in it until the request is done. */
int32_t lora_slot = -1;
std::shared_ptr<void> lora_hold;
/* RAD_GEN_COND_* for the plugin's COND passes (`rebalance`: Krea 2's tap gains). */
int32_t cond_opts = 0;
std::shared_ptr<Ticket> ticket;
};
@@ -119,6 +130,31 @@ struct Request {
std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>& fixed,
int32_t steps, int64_t tokens);
/* ================================================================== a discrete-time schedule */
/* The sigma table of a model trained on discrete timesteps (RadGeneratorDecl::train_steps), as
* ComfyUI's ModelSamplingDiscrete builds it: betas in f64, their cumulative product, sigma_t =
* sqrt((1 - abar_t) / abar_t), then f32, and the f32 logs. */
struct DiscreteTable {
std::vector<float> sigmas; /* [train_steps], ascending: sigmas[t] is timestep t's */
std::vector<float> log_sigmas;
float sigma_min() const { return sigmas.front(); }
float sigma_max() const { return sigmas.back(); }
/* sigma at a fractional timestep: the logs interpolated linearly, t clamped to the table. */
float sigma_at(double t) const;
/* The timestep a sigma is conditioned at: the table's nearest in log sigma. */
int32_t timestep(float sigma) const;
};
/* RAD_E_INVAL with `why` for a declaration whose schedule cannot be built. */
int discrete_table(const RadGeneratorDecl& d, DiscreteTable* out, std::string* why);
/* The n + 1 sigmas `scheduler` places for `steps` (0: the default) steps, the last 0. */
std::vector<float> schedule_discrete(const RadGeneratorDecl& d, const DiscreteTable& t,
int32_t scheduler, int32_t steps);
/* The names a request spells samplers and schedulers by, and their ids (-1: none). */
const char* sampler_name(int32_t id);
const char* scheduler_name(int32_t id);
int32_t sampler_id(const std::string& name);
int32_t scheduler_id(const std::string& name);
/* ================================================================== the generator's sequence */
/* One conditioning sequence as the generator sees it (RadGeneratorDecl::layout): the prompt row or
* reference latent row behind each row, rotary positions, segments, and the output image's frame. */
@@ -129,6 +165,11 @@ struct Layout {
std::vector<int32_t> seg; /* [n_seg + 1] */
std::vector<int32_t> bidi; /* [n_seg] */
int32_t next_pos = 0; /* the rotary count after the last row: the image's frame */
/* JOINT_STEP only: the text's rows (padding included), the padding rows among them, and the
* f32 positions, [4, rows] component-major (`rope` is then empty). */
int64_t text = 0;
int32_t n_pad = 0;
std::vector<float> rope_f;
};
/* `ref_hw` is each reference's latent grid (h, w), in media order. RAD_E_INVAL with `why` when the
* prompt does not start with its drop prefix or a picture's slots do not tile its latent grid. */
@@ -137,5 +178,16 @@ int build_layout(const Branch& b, int64_t slot_rows, const std::vector<std::pair
/* The rotary positions of an h x w image at frame `pos`: [3, h * w] component-major. */
void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_total);
/* A conditioning in the JOINT_STEP layout (RadGeneratorDecl): the prompt's rows after its drop
* prefix, padding to a multiple of `pad_multiple` (0: none), then each reference picture's latent
* tokens. `src` is the prompt row behind a text row -- a padding row's is past the prompt's last,
* where the COND pass appends the padding tokens -- or -(1 + i) for reference latent row i. One
* text segment (causal) and a segment per picture (bidirectional). */
int build_joint_layout(const Branch& b, int32_t pad_multiple, double hw_scale, bool text_l,
const std::vector<std::pair<int32_t, int32_t>>& ref_hw, Layout* out,
std::string* why);
/* The f32 positions (0, s h, s w, l) of an h x w grid: [4, h * w] component-major. */
void grid_rope_f(double hw_scale, float l, int32_t h, int32_t w, float* planes, int64_t n_total);
} /* namespace gen */
} /* namespace rad */
+2
View File
@@ -29,6 +29,8 @@ struct IPassDriver {
* `step` is the engine's pass counter, carried into RadBatch::step. */
virtual const RadBatch* next(int step) = 0;
virtual const RadBatch* batch_for(int rank) const = 0;
/* The runtime LoRA slot every row of the staged pass runs with, -1 for none. */
virtual int32_t lora_slot() const { return -1; }
/* What the staged pass's results are, valid until done(). */
virtual const std::vector<Readback>& readbacks() const = 0;
/* The pass has run on every rank, its streams are drained and the readbacks have landed. */
+33 -10
View File
@@ -11,6 +11,7 @@
#include "mm/processor.h"
#include <atomic>
#include <cmath>
#include <condition_variable>
#include <deque>
#include <memory>
@@ -23,12 +24,13 @@ namespace gen {
/* One thing a request has made. */
struct VideoEvent {
enum Kind { STEP = 1, AUDIO = 2, FRAMES = 3 };
enum Kind { STEP = 1, AUDIO = 2, FRAMES = 3, LENGTH = 4 };
int kind = 0;
int32_t steps_done = 0; /* STEP: denoising steps finished */
/* AUDIO: the whole soundtrack, interleaved, in [-1, 1]. */
std::vector<float> samples;
/* FRAMES: frames [first, first + n) of the video, each [height, width, 3] u8 RGB. */
/* FRAMES: frames [first, first + n) of the video, each [height, width, 3] u8 RGB. LENGTH:
* the `n` frames the model chose for a request that named no length, before any step. */
int32_t first = 0, n = 0;
std::vector<uint8_t> rgb;
};
@@ -50,7 +52,8 @@ public:
std::atomic<bool> cancel{false};
/* What the request makes, written by the driver at submit: the frames and their size, the
* steps, and the soundtrack's rate and channels. */
* steps, and the soundtrack's rate and channels. A request whose length the model predicts
* has its `frames`, `steps` and `rows` rewritten once, before its LENGTH event. */
int32_t frames = 0, width = 0, height = 0, steps = 0;
int64_t sample_rate = 0, channels = 0;
double fps = 0.0;
@@ -153,6 +156,22 @@ struct VideoRequest {
* image generator's driver does. Null for a request whose references carry nothing the TE
* sees — audios are label-only, and a text-only request has none. */
std::shared_ptr<mm::PromptMedia> media;
/* Guidance (RadVideoGenDecl::guidance): the eight terms, NaN for the model's default, and the
* negative prompt, rendered and tokenised; `has_neg` false for the model's default. */
double guidance[8] = { NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN };
std::vector<int32_t> neg_tokens;
bool has_neg = false;
/* A first frame (RadVideoGenDecl::image_cond): [height, width, 3] u8 RGB at the size the
* first evaluations run at (video_small_size under upscaling, else the video's), already
* prepared as the model's pipeline prepares it; empty for none. */
std::vector<uint8_t> image;
/* The decoder (RadVideoGenDecl::decoders) by its index; 0 the model's default. */
int32_t decoder = 0;
/* The runtime LoRA slot the request's conditioning and denoising passes run with
* (Engine::gen_lora_acquire), -1 for none, and the hold that keeps it until the request is
* done. */
int32_t lora_slot = -1;
std::shared_ptr<void> lora_hold;
std::shared_ptr<VideoTicket> ticket;
};
@@ -170,17 +189,21 @@ VideoShape video_shape(const RadVideoGenDecl& d, int32_t width, int32_t height,
void video_small_size(const RadVideoGenDecl& d, int32_t width, int32_t height, double factor,
int32_t* small_w, int32_t* small_h);
/* The two schedules a request of `steps` grid points runs (RadVideoGenDecl, "The sampler"): each
* the f32 sigmas, last 0, and the model evaluations it takes, the shorter of the two. With a
* trained schedule any other step count than n_rungs + 1 gives no steps. `shift_video`/`shift_audio`
* above 0 override the declaration's per-stream shift for the exponential sigma shift; 0 keeps the
* declaration's. The shift only re-shapes the staged sigmas, so it reaches the plugin through the
* schedule region, not the batch. */
/* The two schedules a request of `steps` runs (RadVideoGenDecl, "The sampler": grid points under
* form 0, evaluations under form 1): each the f32 sigmas, last 0, and the model evaluations it
* takes, the shorter of the two. With a trained schedule any other step count than the declared
* one gives no steps. `video_tokens` are the video's latent tokens, which form 1's dynamic shift
* reads. With `refine` (form 1 and refinement rungs) the rungs are followed by the refinement
* rungs instead of a 0, the evaluations their sum. `shift_video`/`shift_audio` above 0 override
* the declaration's per-stream shift for the exponential sigma shift; 0 keeps the declaration's.
* The shift only re-shapes the staged sigmas, so it reaches the plugin through the schedule
* region, not the batch. */
struct VideoSchedule {
std::vector<float> sig_v, sig_a;
int32_t steps = 0;
};
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps, double shift_video = 0.0,
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps, int64_t video_tokens = 0,
bool refine = false, double shift_video = 0.0,
double shift_audio = 0.0);
} /* namespace gen */
+522 -298
View File
@@ -2,6 +2,7 @@
* waits on, and a request's shape and schedule (video.h). */
#include "video_driver.h"
#include "rad_internal.h"
#include "rad_plugin.h"
#include <algorithm>
#include <chrono>
@@ -78,7 +79,7 @@ VideoShape video_shape(const RadVideoGenDecl& d, int32_t width, int32_t height,
if (r2 > den || (r2 == den && (q & 1))) ++q;
s.n_audio = (int32_t)q;
s.video_rows = (int64_t)s.lat_frames * (s.lat_h / d.patch) * (s.lat_w / d.patch);
s.audio_rows = d.audio_channels * (int64_t)s.n_audio;
s.audio_rows = (d.audio_streams > 0 ? d.audio_streams : d.audio_channels) * (int64_t)s.n_audio;
return s;
}
@@ -123,12 +124,51 @@ static std::vector<float> rung_sigmas(double shift, const double* rungs, int32_t
return s;
}
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps, double shift_video,
double shift_audio) {
/* A request's shift overrides the declaration's per stream; 0 keeps the trained value. */
/* Form 1 (RadVideoGenDecl::sched_kind): FlowMatchEulerDiscreteScheduler.set_timesteps with
* LTX-2's sigmas. numpy's linspace in f64 (i * step + start, the last exactly the stop) taken to
* f32; the shift and the terminal stretch in f32, as numpy computes on an f32 array with Python
* scalars. */
static std::vector<float> flow_sigmas(const RadVideoGenDecl& d, int32_t n, int64_t tokens) {
std::vector<float> s((size_t)n);
const double stop = 1.0 / n, step = n > 1 ? (stop - 1.0) / (n - 1) : 0.0;
for (int32_t i = 0; i < n; ++i) s[(size_t)i] = (float)(i == n - 1 && n > 1 ? stop : i * step + 1.0);
if (d.dyn_shift) {
const double m = (d.max_shift - d.base_shift) / (double)(d.max_seq - d.base_seq);
const double mu = (double)tokens * m + (d.base_shift - m * (double)d.base_seq);
const float e = (float)std::exp(mu);
for (float& v : s) v = e / (e + (1.0f / v - 1.0f));
}
if (d.shift_terminal > 0.0) {
const float sf = (1.0f - s.back()) / (float)(1.0 - d.shift_terminal);
for (float& v : s) v = 1.0f - (1.0f - v) / sf;
}
s.push_back(0.0f);
return s;
}
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps, int64_t video_tokens,
bool refine, double shift_video, double shift_audio) {
/* A request's shift overrides the declaration's per stream; 0 keeps the trained value. Form 1
* ignores both: its shift is the declaration's, dynamic or terminal. */
const double sv = shift_video > 0.0 ? shift_video : d.shift_video;
const double sa = shift_audio > 0.0 ? shift_audio : d.shift_audio;
VideoSchedule v;
if (d.sched_kind == 1) {
if (d.n_rungs > 0) {
if (steps != d.n_rungs) return v;
for (int32_t i = 0; i < d.n_rungs; ++i) v.sig_v.push_back((float)d.rungs[i]);
if (refine)
for (int32_t i = 0; i < d.n_refine_rungs; ++i)
v.sig_v.push_back((float)d.refine_rungs[i]);
v.sig_v.push_back(0.0f);
} else {
if (steps < 1) return v;
v.sig_v = flow_sigmas(d, steps, video_tokens);
}
v.sig_a = v.sig_v;
v.steps = (int32_t)v.sig_v.size() - 1;
return v;
}
if (d.n_rungs > 0) {
if (steps != d.n_rungs + 1) return v;
v.sig_v = rung_sigmas(sv, d.rungs, d.n_rungs);
@@ -163,10 +203,12 @@ int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
* vision encoder: the media regions then hold nothing. */
int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd,
int64_t (*bytes)[2], int n) {
/* A guided model's VCOND carries the negative prompt after the positive. */
const int64_t prompts = d.guidance ? 2 : 1;
const int64_t want[] = {
d.max_text * 4, /* R_TOK */
d.max_text * 4, /* R_POS */
2 * 4, /* R_CU */
prompts * d.max_text * 4, /* R_TOK */
prompts * d.max_text * 4, /* R_POS */
3 * 4, /* R_CU */
3 * max_tok * 4, /* R_ROPE: a step's rotary positions, a conditioning's [3,T] M-RoPE */
RAD_VGEOM_N * 4, /* R_GEOM */
16 * 4, /* R_SCHED: the Euler scalars [0..5], then the res_multistep
@@ -190,6 +232,8 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd,
d.max_enc_samples * d.audio_channels * 4, /* R_ENCSM: [ch,n] f32 */
25 * 4, /* R_ENCG: rad_arch_encode_geom's 25 i32 (the video geom) */
kSegCap * 4, /* R_MOD: the merged modulation-group boundaries (<= R_SEG) */
d.image_cond ? d.max_area * 3 * 2 : 0, /* R_IMG: a first frame, bf16 */
8 * 4, /* R_GUIDE */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
@@ -252,9 +296,17 @@ int VideoDriver::init(const Program& prog, PositionsFn positions,
"video generator must", name_.c_str());
return RAD_E_UNSUPPORTED;
}
if (max_tok_ < decl_.max_text) {
RAD_ERR("video generator '%s': a pass carries %lld rows and a prompt may be %lld tokens",
name_.c_str(), (long long)max_tok_, (long long)decl_.max_text);
decoder_names_ = prog.vgen_str.decoders;
decoder_area_ = prog.vgen_str.decoder_max_area;
refine_rungs_ = prog.vgen_str.refine_rungs;
decl_.refine_rungs = refine_rungs_.empty() ? nullptr : refine_rungs_.data();
default_negative_ = prog.vgen_str.default_negative;
decl_.default_negative = default_negative_.c_str();
const int64_t prompts = decl_.guidance ? 2 : 1;
if (max_tok_ < prompts * decl_.max_text) {
RAD_ERR("video generator '%s': a pass carries %lld rows and %s may be %lld tokens",
name_.c_str(), (long long)max_tok_, prompts == 2 ? "a prompt and its negative" :
"a prompt", (long long)(prompts * decl_.max_text));
return RAD_E_UNSUPPORTED;
}
int64_t b[R_N][2];
@@ -268,7 +320,8 @@ int VideoDriver::init(const Program& prog, PositionsFn positions,
host_ = static_cast<char*>(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED));
frames_host_ = static_cast<uint8_t*>(rad_dev_alloc(frames_bytes_, RAD_MEM_HOST_PINNED));
audio_host_ = static_cast<float*>(rad_dev_alloc(audio_bytes_, RAD_MEM_HOST_PINNED));
if (!host_ || !frames_host_ || !audio_host_) {
duration_host_ = static_cast<float*>(rad_dev_alloc(64, RAD_MEM_HOST_PINNED));
if (!host_ || !frames_host_ || !audio_host_ || !duration_host_) {
RAD_ERR("video generator: no pinned host memory for the pass staging and outputs (%lld + "
"%lld + %lld bytes)", (long long)bytes_, (long long)frames_bytes_,
(long long)audio_bytes_);
@@ -362,6 +415,8 @@ void VideoDriver::fini() {
if (audio_host_) rad_dev_free(audio_host_, RAD_MEM_HOST_PINNED);
if (enc_dbg_host_) rad_dev_free(enc_dbg_host_, RAD_MEM_HOST_PINNED);
if (dit_host_) rad_dev_free(dit_host_, RAD_MEM_HOST_PINNED);
if (duration_host_) rad_dev_free(duration_host_, RAD_MEM_HOST_PINNED);
duration_host_ = nullptr;
host_ = nullptr;
frames_host_ = nullptr;
audio_host_ = nullptr;
@@ -370,6 +425,358 @@ void VideoDriver::fini() {
}
/* ================================================================== requests */
/* A length head's prediction (RadVideoGenDecl::duration_out) in chunks: diffusers'
* LTX2DurationHead.predict_num_frames on the chunk grid -- the seconds clamped to the declared
* bounds, rounded to frames, floored to the grid and lifted one chunk when that falls under the
* minimum -- then held to min_chunks..max_chunks. `note` says what was clamped. */
int32_t VideoDriver::predicted_chunks(double log_seconds, std::string* note) const {
const RadVideoGenDecl& d = decl_;
const double fps = (double)d.fps_num / (double)d.fps_den;
float e = std::exp((float)log_seconds);
if (d.duration_dtype == RAD_BF16) e = rad_bf16_to_f32(rad_f32_to_bf16(e));
const double sec = e;
auto round_even = [](double v) { return (int64_t)std::nearbyint(v); };
const int64_t lo = std::max<int64_t>(1, round_even(d.duration_min * fps));
const int64_t hi = round_even(d.duration_max * fps);
const int64_t want = std::isfinite(sec) ? round_even(sec * fps) : hi;
const int64_t frames = std::max(lo, std::min(want, hi));
int64_t n = std::max<int64_t>(0, (frames - d.frames_tail) / d.frames_per_chunk);
if (d.frames_per_chunk * n + d.frames_tail < lo &&
d.frames_per_chunk * (n + 1) + d.frames_tail <= hi)
++n;
std::string what = fmt(": %.3f s predicted", sec);
if (!(sec >= d.duration_min && sec <= d.duration_max))
what += fmt(", held to %g..%g s", d.duration_min, d.duration_max);
if (n < d.min_chunks || n > d.max_chunks) {
n = std::max<int64_t>(d.min_chunks, std::min<int64_t>(n, d.max_chunks));
what += fmt(", within the %lld..%lld frames this model makes",
(long long)(d.frames_per_chunk * d.min_chunks + d.frames_tail),
(long long)(d.frames_per_chunk * d.max_chunks + d.frames_tail));
}
if (note) *note = what;
return (int32_t)n;
}
/* The request's shape at `chunks` long: its geometry, rows and positions, its schedule, the
* upscale's split and what its ticket says it makes. Run at submit, and again for a request whose
* length the model predicts once its VCOND pass has written the prediction. */
int VideoDriver::shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_t steps,
std::string* why) {
const RadVideoGenDecl& d = decl_;
auto no = [&](const std::string& w) {
if (why) *why = w;
return RAD_E_INVAL;
};
const int64_t T = (int64_t)r.tokens.size();
const VideoShape s = video_shape(d, r.width, r.height, chunks);
j.geom.n_text = (int32_t)(d.step_text_rows > 0 ? d.step_text_rows : T);
j.geom.frames = s.frames;
j.geom.lat_frames = s.lat_frames;
j.geom.lat_h = s.lat_h;
j.geom.lat_w = s.lat_w;
j.geom.n_audio = s.n_audio;
/* The step's row count and its positions. A reference-conditioned step widens them; the
* encode queue and the pack's table are built first because the layout depends on them. */
j.ref_tab.clear();
j.enc_q.clear();
/* The pack's reference table (RadVideoGenBatch::ref_tab): every reference the DiT conditions
* on, in presentation order, in ITS OWN latent grid -- {kind, slot, h, w, frames, audio} six
* words after the reference and keyframe counts. `kind` is a pack Ref2VARefKind (picture 0,
* standalone audio 1, video 2), the server's VIDEO_AUDIO being folded into its video's `audio`
* word rather than a row of its own. Each reference's slot is the one its encode pass folds its
* latents into, and its latent counts come from the encoder's own geometry, not hand arithmetic:
* a picture is one latent frame (its grid the encoder's sides over the VAE ratio); a video's
* frames and its soundtrack's are the Vencode/Aencode latent counts rad_arch_encode_geom gives
* (a video's are the same before and after the encode pass clip-pads its short final clip). The
* table must exist before the step layout is decided, because when the denoiser consumes it the
* reference rows are part of that layout. Endpoint keyframes (a first and/or last frame pinned
* at the output's ends) are appended after the reference rows as {frame, video_t, audio_t}
* triples; a request carries either references or keyframes, never both. */
if (d.encodes) {
bool need_geom = false;
for (const VideoRefMedia& m : r.refs)
if (m.kind != VideoRefMedia::IMAGE && m.kind != VideoRefMedia::FIRST_FRAME &&
m.kind != VideoRefMedia::LAST_FRAME) need_geom = true;
if (need_geom && !enc_geom_)
return no("the request carries a reference video or audio, but this plugin exports no "
"rad_arch_encode_geom, so their encoder geometry cannot be sized");
int32_t eg[25];
/* A reference's latent frame counts, straight from the encoder's geometry. */
auto video_lat = [&](const VideoRefMedia& m) -> int64_t {
int64_t in[4] = { m.enc_frames, m.enc_h, m.enc_w, 3 };
return enc_geom_(RAD_GEN_PASS_VENCODE, in, eg, 25) < 0 ? -1 : (int64_t)eg[24];
};
auto audio_lat = [&](const VideoRefMedia& m) -> int64_t {
int64_t in[4] = { m.enc_n, 0, 0, m.enc_channels };
return enc_geom_(RAD_GEN_PASS_AENCODE, in, eg, 25) < 0 ? -1 : (int64_t)eg[12];
};
/* Pictures and videos share a side-grid check against the VAE ratio. */
auto bad_side = [&](const VideoRefMedia& m) {
return d.enc_ratio < 1 || m.enc_h < d.enc_ratio || m.enc_w < d.enc_ratio ||
m.enc_h % d.enc_ratio || m.enc_w % d.enc_ratio;
};
for (size_t i = 0; i < r.refs.size(); ++i) {
const VideoRefMedia& m = r.refs[i];
if (m.kind == VideoRefMedia::IMAGE) {
if (m.enc_pixels.empty())
return no("'" + m.name + "' was not prepared for the video encoder");
if (m.index < 1)
return no("'" + m.name + "' has no slot in the conditioning");
if (bad_side(m))
return no("'" + m.name + "' has encoder sides (" + std::to_string(m.enc_h) +
"x" + std::to_string(m.enc_w) + ") the VAE grid of " +
std::to_string(d.enc_ratio) + " does not divide");
j.enc_q.push_back({RAD_ENC_IMAGE, m.index, (int32_t)i});
if (j.ref_tab.empty()) j.ref_tab.assign(2, 0); /* [n_refs, n_keys] */
++j.ref_tab[0];
j.ref_tab.insert(j.ref_tab.end(),
{0 /*a picture*/, m.index, (int32_t)(m.enc_h / d.enc_ratio),
(int32_t)(m.enc_w / d.enc_ratio), 1 /*one latent frame*/,
0 /*no soundtrack*/});
} else if (m.kind == VideoRefMedia::VIDEO) {
if (m.enc_pixels.empty())
return no("'" + m.name + "' was not prepared for the video encoder");
if (m.index < 1 || m.index > 3)
return no("'" + m.name + "' has no video slot (1..3)");
if (bad_side(m))
return no("'" + m.name + "' has encoder sides (" + std::to_string(m.enc_h) +
"x" + std::to_string(m.enc_w) + ") the VAE grid of " +
std::to_string(d.enc_ratio) + " does not divide");
/* A soundtrack given for this video (ref_video_audio_N) is folded into THIS row's
* `audio` word, not a row of its own; the pack lays its block right before the
* video's and the scatter reads the two back as the pair they are. It is encoded at
* the VIDEO's slot, since aenc_slot_row numbers a soundtrack by its video. */
int64_t a_t = 0;
for (size_t k = 0; k < r.refs.size(); ++k) {
const VideoRefMedia& a = r.refs[k];
if (a.kind != VideoRefMedia::VIDEO_AUDIO || a.index != m.index) continue;
if (a.enc_samples.empty() || a.enc_n < 1 || a.enc_channels < 1)
return no("'" + a.name + "' (the soundtrack of '" + m.name +
"') was not prepared for the audio encoder");
a_t = audio_lat(a);
if (a_t < 1)
return no("the audio encoder refuses the soundtrack '" + a.name + "'");
j.enc_q.push_back({RAD_ENC_VAUDIO, m.index, (int32_t)k});
}
const int64_t v_t = video_lat(m);
if (v_t < 1) return no("the video encoder refuses '" + m.name + "'");
j.enc_q.push_back({RAD_ENC_VIDEO, m.index, (int32_t)i});
if (j.ref_tab.empty()) j.ref_tab.assign(2, 0);
++j.ref_tab[0];
j.ref_tab.insert(j.ref_tab.end(),
{2 /*a video*/, m.index, (int32_t)(m.enc_h / d.enc_ratio),
(int32_t)(m.enc_w / d.enc_ratio), (int32_t)v_t, (int32_t)a_t});
} else if (m.kind == VideoRefMedia::AUDIO) {
if (m.enc_samples.empty() || m.enc_n < 1 || m.enc_channels < 1)
return no("'" + m.name + "' was not prepared for the audio encoder");
if (m.index < 1 || m.index > 3)
return no("'" + m.name + "' has no audio slot (1..3)");
const int64_t a_t = audio_lat(m);
if (a_t < 1) return no("the audio encoder refuses '" + m.name + "'");
j.enc_q.push_back({RAD_ENC_AUDIO, m.index, (int32_t)i});
if (j.ref_tab.empty()) j.ref_tab.assign(2, 0);
++j.ref_tab[0];
j.ref_tab.insert(j.ref_tab.end(),
{1 /*a standalone audio*/, m.index, 0, 0, 0, (int32_t)a_t});
}
/* VIDEO_AUDIO rows are folded into their video above, so they take no row here. */
}
/* Endpoint keyframes: each FIRST_FRAME/LAST_FRAME the server resized to the target canvas
* and staged in enc_pixels folds into the pack's KEYFRAME table -- not a reference row. The
* DiT reads its latent rows PINNED at that frame's moment on the target timeline (denoised
* never): the first pins output frame 0, the last the final frame, and the gap between is
* diffused. The key triple is {pixel frame, video_t, audio_t}; a picture anchor is video-only
* (video_t = one latent frame, audio_t = 0), and its pixel frame is 0 or frames-1 -- the same
* resolved frame index the reference's MiniMaxH3ImageToVideo assigns. Its latents ride the
* image slot its keyframe ORDER names (1, then 2): a keyframe request carries no references,
* so those slots are free, and ref_parts -- and the scatter -- read them back by the same
* order. Keyframe rows are appended after every reference row, which is where ref_pack_of
* reads the table's key block. */
for (size_t i = 0; i < r.refs.size(); ++i) {
const VideoRefMedia& m = r.refs[i];
const bool first = m.kind == VideoRefMedia::FIRST_FRAME;
if (!first && m.kind != VideoRefMedia::LAST_FRAME) continue;
if (m.enc_pixels.empty())
return no("'" + m.name + "' was not prepared for the video encoder");
if (bad_side(m))
return no("'" + m.name + "' has encoder sides (" + std::to_string(m.enc_h) +
"x" + std::to_string(m.enc_w) + ") the VAE grid of " +
std::to_string(d.enc_ratio) + " does not divide");
if (j.ref_tab.empty()) j.ref_tab.assign(2, 0); /* [n_refs, n_keys] */
const int32_t slot = ++j.ref_tab[1]; /* keyframe order -> image slot 1, 2 */
j.enc_q.push_back({RAD_ENC_IMAGE, slot, (int32_t)i});
j.ref_tab.insert(j.ref_tab.end(),
{first ? 0 : s.frames - 1, 1 /*one latent frame*/, 0 /*no soundtrack*/});
}
}
/* The step's packed sequence. When the denoiser consumes the reference table the pack is the
* only source of its rows, segment boundaries and positions -- the reference rows sit between
* the text and the target streams, so the plain `text + audio + video` arithmetic and the plain
* position layout no longer describe it. rad_arch_video_pack returns the total rows and, when
* roomy, the boundaries and the full [3, rows] planar RoPE in one call. Otherwise the plain
* layout is computed exactly as before, and a staged reference table (if any) rides inert. */
const int64_t nd = positions_(RAD_VPOS_DECODE, &j.geom, nullptr, 0);
if (nd <= 0 || nd > max_tok_)
return no("the model lays this video's decoder in " + std::to_string(nd) + " rows, which "
"this server cannot run");
j.dec_rows = nd;
if (d.ref_rows && !j.ref_tab.empty()) {
if (r.upscale > 1.0)
return no("reference conditioning does not yet combine with latent upscale; ask for "
"the size you want without latent_upscale");
if (!pack_)
return no("the generator says it conditions on references but exports no "
"rad_arch_video_pack");
const int64_t pr = pack_(&j.geom, j.ref_tab.data(), nullptr, 0, nullptr, 0);
if (pr <= 0)
return no("the model refused the reference conditioning layout");
if (pr > max_tok_)
return no("a conditioned step is " + std::to_string(pr) + " rows and a pass carries " +
std::to_string(max_tok_) + "; ask for a shorter or smaller video, or fewer "
"references");
j.seg.assign((size_t)kSegCap, 0);
j.pos.assign((size_t)(3 * pr), 0.0f);
if (pack_(&j.geom, j.ref_tab.data(), j.seg.data(), kSegCap, j.pos.data(), 3 * pr) != pr)
return no("the model could not lay the reference conditioning out");
int nseg = -1;
for (int k = 0; k < kSegCap; ++k)
if (j.seg[(size_t)k] == (int32_t)pr) { nseg = k + 1; break; } /* video grid ends here */
if (nseg < 0 || nseg > kSegCap)
return no("the reference conditioning layout has no closing segment boundary");
j.seg.resize((size_t)nseg);
j.nseg = nseg;
/* The modulation groups. A modulation cell is fixed by a segment's kind, so the denoiser
* merges runs of consecutive same-cell segments and pitches its fixed-width table by the
* GROUP count, not the reference count -- which is how nine reference photos (four groups:
* prompt, all-photos, soundtrack, video) ride a table the fine layout (twelve segments)
* would overrun. The plugin merges for us (rad_arch_video_mod_segs); one that exports none
* merges nothing, so the group table is the fine one and the older per-segment ceiling
* applies. Refuse over-wide merges here, at submit, where a clean answer is still possible. */
int nmod = -1;
if (mod_segs_) {
j.mod_seg.assign((size_t)kSegCap, 0);
nmod = (int)mod_segs_(&j.geom, j.ref_tab.data(), j.mod_seg.data(), kSegCap);
if (nmod < 0 || nmod > kSegCap)
return no("the model could not merge the reference conditioning into its "
"modulation groups");
j.mod_seg.resize((size_t)nmod);
} else {
nmod = nseg; /* nothing merges: the groups are the fine segments */
j.mod_seg = j.seg;
}
j.nmod = nmod;
const int ngroups = nmod - 1; /* `mod_seg` is boundaries: one more than the groups */
if (d.max_ref_segs > 0 && ngroups > d.max_ref_segs)
return no("these references change the conditioning's modulation cell " +
std::to_string(ngroups) + " times, but this deployment's modulation table holds " +
std::to_string(d.max_ref_segs) + " cells -- ask for references that share their "
"modalities and target, or fewer of them");
/* `rows` stays the plain text+audio+video count: every non-step pass (encode, decode,
* audio, upscale) stages its own segment table and target counts from it and must see the
* bytes it sees today. Only build_step runs at the widened `step_rows`. */
j.rows = j.geom.n_text + s.audio_rows + s.video_rows;
j.step_rows = pr;
/* The last segment (the video target) runs [seg[nseg-2], seg[nseg-1]); seg[nseg-1] is the
* total rows, so the video start is the boundary before it -- the same one the VSA takes as
* its video base (it works in segments, one fewer than the boundaries it is handed). */
j.lat_v = pr - j.seg[(size_t)(nseg - 2)];
j.lat_a = decl_.audio_channels * (int64_t)j.geom.n_audio;
j.ref_wide = true;
} else {
j.rows = j.geom.n_text + s.audio_rows + s.video_rows;
if (j.rows > max_tok_)
return no("a step of this video is " + std::to_string(j.rows) + " rows and a pass "
"carries " + std::to_string(max_tok_) + "; ask for a shorter or smaller video");
const int64_t nr = positions_(RAD_VPOS_STEP, &j.geom, nullptr, 0);
if (nr != j.rows)
return no("the model lays this video out in " + std::to_string(nr) + " step rows, "
"which this server cannot run");
j.pos.assign((size_t)(3 * nr), 0.0f);
if (positions_(RAD_VPOS_STEP, &j.geom, j.pos.data(), nr) != nr)
return no("the model could not lay this video out");
j.step_rows = j.rows;
}
/* The schedule follows the upscale's split, which needs the small size first. */
const bool upscaling = r.upscale > 1.0;
const bool own_refine = upscaling && d.n_refine_rungs > 0;
int64_t first_tokens = s.video_rows;
if (upscaling) {
int32_t sw = 0, sh = 0;
video_small_size(d, r.width, r.height, r.upscale, &sw, &sh);
first_tokens = video_shape(d, sw, sh, chunks).video_rows;
}
j.sched = video_schedule(d, steps, first_tokens, own_refine, r.shift_video, r.shift_audio);
if (j.sched.steps < 1) return no("the schedule has no steps");
int32_t first_w = r.width, first_h = r.height;
if (upscaling) {
if (!(d.upscale_max > 1.0)) return no("this model has no latent upscaler");
if (d.upscale_exact) {
const int64_t m = (int64_t)std::llround(d.size_multiple * d.upscale_max);
if (r.upscale != d.upscale_max || r.width % m || r.height % m)
return no("this model's latent upscaler enlarges by exactly " +
fmt("%g", d.upscale_max) + ": latent_upscale must be that, and both "
"sides multiples of " + std::to_string(m));
}
if (r.upscale > d.upscale_max)
return no("latent_upscale is at most " + fmt("%g", d.upscale_max) + " for this model");
int32_t sw = 0, sh = 0;
video_small_size(d, r.width, r.height, r.upscale, &sw, &sh);
if (sw == r.width && sh == r.height)
return no("latent_upscale " + fmt("%g", r.upscale) + " leaves " +
std::to_string(r.width) + "x" + std::to_string(r.height) + " as it is: "
"the small size is each side over the factor, rounded to a multiple of " +
std::to_string(d.size_multiple));
const int32_t evals = j.sched.steps;
int32_t refine = r.refine;
if (own_refine) {
if (refine != 0 && refine != d.n_refine_rungs)
return no("upscale_refine_steps must be " + std::to_string(d.n_refine_rungs) +
": this model refines the upscaled video over the schedule it was "
"trained on");
refine = d.n_refine_rungs;
}
if (refine == 0) refine = std::min<int32_t>(d.upscale_refine, evals - 1);
if (refine < 1 || refine >= evals)
return no("upscale_refine_steps must be 1.." + std::to_string(evals - 1) + ": the "
"schedule takes " + std::to_string(evals) + " evaluations and the small "
"size at least one of them");
const VideoShape ss = video_shape(d, sw, sh, chunks);
j.geom_small = j.geom;
j.geom_small.lat_h = ss.lat_h;
j.geom_small.lat_w = ss.lat_w;
j.rows_small = j.geom.n_text + ss.audio_rows + ss.video_rows;
const int64_t ns = positions_(RAD_VPOS_STEP, &j.geom_small, nullptr, 0);
if (ns != j.rows_small)
return no("the model lays the small size " + std::to_string(sw) + "x" +
std::to_string(sh) + " out in " + std::to_string(ns) + " step rows, which "
"this server cannot run");
j.pos_small.assign((size_t)(3 * ns), 0.0f);
if (positions_(RAD_VPOS_STEP, &j.geom_small, j.pos_small.data(), ns) != ns)
return no("the model could not lay the small size out");
j.split = evals - refine;
j.factor = (float)(((double)r.width / sw + (double)r.height / sh) / 2.0);
r.ticket->small_width = sw;
r.ticket->small_height = sh;
r.ticket->refine = refine;
first_w = sw;
first_h = sh;
}
if (!r.image.empty()) {
if (!d.image_cond) return no("this model cannot start from a picture");
if (r.image.size() != (size_t)first_w * first_h * 3)
return no("the first frame is not " + std::to_string(first_w) + "x" +
std::to_string(first_h) + " RGB");
}
j.n_chunks = chunks;
j.n_samples = (int64_t)s.n_audio * (d.sample_rate / d.audio_rate);
VideoTicket& t = *r.ticket;
t.frames = s.frames;
t.steps = j.sched.steps;
t.rows = j.step_rows; /* the conditioned step's real length, references included */
return RAD_OK;
}
int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
if (!r || !r->ticket) return RAD_E_INVAL;
const RadVideoGenDecl& d = decl_;
@@ -436,7 +843,7 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
return no("the references are " + std::to_string(n_patch) + " patches; this model "
"encodes at most " + std::to_string(max_enc_) + " in one pass");
}
if (r->chunks < d.min_chunks || r->chunks > d.max_chunks)
if (r->chunks != 0 && (r->chunks < d.min_chunks || r->chunks > d.max_chunks))
return no("the length must be " + std::to_string(d.min_chunks) + ".." +
std::to_string(d.max_chunks) + " chunks");
const int64_t W = r->width, H = r->height;
@@ -448,287 +855,46 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
" pixels, the long side at most " + std::to_string(d.max_aspect) +
" times the short");
const int32_t steps = r->steps > 0 ? r->steps : (int32_t)d.default_steps;
if (d.n_rungs > 0 && steps != d.n_rungs + 1)
return no("num_inference_steps must be " + std::to_string(d.n_rungs + 1) + ": this model "
const bool evals = d.sched_kind == 1; /* form 1 counts evaluations, form 0 grid points */
const int32_t rung_steps = evals ? d.n_rungs : d.n_rungs + 1;
if (d.n_rungs > 0 && steps != rung_steps)
return no("num_inference_steps must be " + std::to_string(rung_steps) + ": this model "
"runs the schedule it was trained on, " + std::to_string(d.n_rungs) +
" evaluations");
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 0)");
if (steps < (evals ? 1 : 2) || steps > d.max_steps)
return no("num_inference_steps must be " + std::to_string(evals ? 1 : 2) + ".." +
std::to_string(d.max_steps) + (evals ? " (model evaluations)" :
" (sigma grid points, the last one 0)"));
auto j = std::make_unique<Job>();
const VideoShape s = video_shape(d, r->width, r->height, r->chunks);
j->geom.n_text = (int32_t)T;
j->geom.frames = s.frames;
j->geom.lat_frames = s.lat_frames;
j->geom.lat_h = s.lat_h;
j->geom.lat_w = s.lat_w;
j->geom.n_audio = s.n_audio;
/* The pack's reference table (RadVideoGenBatch::ref_tab): every reference the DiT conditions
* on, in presentation order, in ITS OWN latent grid -- {kind, slot, h, w, frames, audio} six
* words after the reference and keyframe counts. `kind` is a pack Ref2VARefKind (picture 0,
* standalone audio 1, video 2), the server's VIDEO_AUDIO being folded into its video's `audio`
* word rather than a row of its own. Each reference's slot is the one its encode pass folds its
* latents into, and its latent counts come from the encoder's own geometry, not hand arithmetic:
* a picture is one latent frame (its grid the encoder's sides over the VAE ratio); a video's
* frames and its soundtrack's are the Vencode/Aencode latent counts rad_arch_encode_geom gives
* (a video's are the same before and after the encode pass clip-pads its short final clip). The
* table must exist before the step layout is decided, because when the denoiser consumes it the
* reference rows are part of that layout. Endpoint keyframes (a first and/or last frame pinned
* at the output's ends) are appended after the reference rows as {frame, video_t, audio_t}
* triples; a request carries either references or keyframes, never both. */
if (d.encodes) {
bool need_geom = false;
for (const VideoRefMedia& m : r->refs)
if (m.kind != VideoRefMedia::IMAGE && m.kind != VideoRefMedia::FIRST_FRAME &&
m.kind != VideoRefMedia::LAST_FRAME) need_geom = true;
if (need_geom && !enc_geom_)
return no("the request carries a reference video or audio, but this plugin exports no "
"rad_arch_encode_geom, so their encoder geometry cannot be sized");
int32_t eg[25];
/* A reference's latent frame counts, straight from the encoder's geometry. */
auto video_lat = [&](const VideoRefMedia& m) -> int64_t {
int64_t in[4] = { m.enc_frames, m.enc_h, m.enc_w, 3 };
return enc_geom_(RAD_GEN_PASS_VENCODE, in, eg, 25) < 0 ? -1 : (int64_t)eg[24];
};
auto audio_lat = [&](const VideoRefMedia& m) -> int64_t {
int64_t in[4] = { m.enc_n, 0, 0, m.enc_channels };
return enc_geom_(RAD_GEN_PASS_AENCODE, in, eg, 25) < 0 ? -1 : (int64_t)eg[12];
};
/* Pictures and videos share a side-grid check against the VAE ratio. */
auto bad_side = [&](const VideoRefMedia& m) {
return d.enc_ratio < 1 || m.enc_h < d.enc_ratio || m.enc_w < d.enc_ratio ||
m.enc_h % d.enc_ratio || m.enc_w % d.enc_ratio;
};
for (size_t i = 0; i < r->refs.size(); ++i) {
const VideoRefMedia& m = r->refs[i];
if (m.kind == VideoRefMedia::IMAGE) {
if (m.enc_pixels.empty())
return no("'" + m.name + "' was not prepared for the video encoder");
if (m.index < 1)
return no("'" + m.name + "' has no slot in the conditioning");
if (bad_side(m))
return no("'" + m.name + "' has encoder sides (" + std::to_string(m.enc_h) +
"x" + std::to_string(m.enc_w) + ") the VAE grid of " +
std::to_string(d.enc_ratio) + " does not divide");
j->enc_q.push_back({RAD_ENC_IMAGE, m.index, (int32_t)i});
if (j->ref_tab.empty()) j->ref_tab.assign(2, 0); /* [n_refs, n_keys] */
++j->ref_tab[0];
j->ref_tab.insert(j->ref_tab.end(),
{0 /*a picture*/, m.index, (int32_t)(m.enc_h / d.enc_ratio),
(int32_t)(m.enc_w / d.enc_ratio), 1 /*one latent frame*/,
0 /*no soundtrack*/});
} else if (m.kind == VideoRefMedia::VIDEO) {
if (m.enc_pixels.empty())
return no("'" + m.name + "' was not prepared for the video encoder");
if (m.index < 1 || m.index > 3)
return no("'" + m.name + "' has no video slot (1..3)");
if (bad_side(m))
return no("'" + m.name + "' has encoder sides (" + std::to_string(m.enc_h) +
"x" + std::to_string(m.enc_w) + ") the VAE grid of " +
std::to_string(d.enc_ratio) + " does not divide");
/* A soundtrack given for this video (ref_video_audio_N) is folded into THIS row's
* `audio` word, not a row of its own; the pack lays its block right before the
* video's and the scatter reads the two back as the pair they are. It is encoded at
* the VIDEO's slot, since aenc_slot_row numbers a soundtrack by its video. */
int64_t a_t = 0;
for (size_t k = 0; k < r->refs.size(); ++k) {
const VideoRefMedia& a = r->refs[k];
if (a.kind != VideoRefMedia::VIDEO_AUDIO || a.index != m.index) continue;
if (a.enc_samples.empty() || a.enc_n < 1 || a.enc_channels < 1)
return no("'" + a.name + "' (the soundtrack of '" + m.name +
"') was not prepared for the audio encoder");
a_t = audio_lat(a);
if (a_t < 1)
return no("the audio encoder refuses the soundtrack '" + a.name + "'");
j->enc_q.push_back({RAD_ENC_VAUDIO, m.index, (int32_t)k});
}
const int64_t v_t = video_lat(m);
if (v_t < 1) return no("the video encoder refuses '" + m.name + "'");
j->enc_q.push_back({RAD_ENC_VIDEO, m.index, (int32_t)i});
if (j->ref_tab.empty()) j->ref_tab.assign(2, 0);
++j->ref_tab[0];
j->ref_tab.insert(j->ref_tab.end(),
{2 /*a video*/, m.index, (int32_t)(m.enc_h / d.enc_ratio),
(int32_t)(m.enc_w / d.enc_ratio), (int32_t)v_t, (int32_t)a_t});
} else if (m.kind == VideoRefMedia::AUDIO) {
if (m.enc_samples.empty() || m.enc_n < 1 || m.enc_channels < 1)
return no("'" + m.name + "' was not prepared for the audio encoder");
if (m.index < 1 || m.index > 3)
return no("'" + m.name + "' has no audio slot (1..3)");
const int64_t a_t = audio_lat(m);
if (a_t < 1) return no("the audio encoder refuses '" + m.name + "'");
j->enc_q.push_back({RAD_ENC_AUDIO, m.index, (int32_t)i});
if (j->ref_tab.empty()) j->ref_tab.assign(2, 0);
++j->ref_tab[0];
j->ref_tab.insert(j->ref_tab.end(),
{1 /*a standalone audio*/, m.index, 0, 0, 0, (int32_t)a_t});
}
/* VIDEO_AUDIO rows are folded into their video above, so they take no row here. */
}
/* Endpoint keyframes: each FIRST_FRAME/LAST_FRAME the server resized to the target canvas
* and staged in enc_pixels folds into the pack's KEYFRAME table -- not a reference row. The
* DiT reads its latent rows PINNED at that frame's moment on the target timeline (denoised
* never): the first pins output frame 0, the last the final frame, and the gap between is
* diffused. The key triple is {pixel frame, video_t, audio_t}; a picture anchor is video-only
* (video_t = one latent frame, audio_t = 0), and its pixel frame is 0 or frames-1 -- the same
* resolved frame index the reference's MiniMaxH3ImageToVideo assigns. Its latents ride the
* image slot its keyframe ORDER names (1, then 2): a keyframe request carries no references,
* so those slots are free, and ref_parts -- and the scatter -- read them back by the same
* order. Keyframe rows are appended after every reference row, which is where ref_pack_of
* reads the table's key block. */
for (size_t i = 0; i < r->refs.size(); ++i) {
const VideoRefMedia& m = r->refs[i];
const bool first = m.kind == VideoRefMedia::FIRST_FRAME;
if (!first && m.kind != VideoRefMedia::LAST_FRAME) continue;
if (m.enc_pixels.empty())
return no("'" + m.name + "' was not prepared for the video encoder");
if (bad_side(m))
return no("'" + m.name + "' has encoder sides (" + std::to_string(m.enc_h) +
"x" + std::to_string(m.enc_w) + ") the VAE grid of " +
std::to_string(d.enc_ratio) + " does not divide");
if (j->ref_tab.empty()) j->ref_tab.assign(2, 0); /* [n_refs, n_keys] */
const int32_t slot = ++j->ref_tab[1]; /* keyframe order -> image slot 1, 2 */
j->enc_q.push_back({RAD_ENC_IMAGE, slot, (int32_t)i});
j->ref_tab.insert(j->ref_tab.end(),
{first ? 0 : s.frames - 1, 1 /*one latent frame*/, 0 /*no soundtrack*/});
}
/* Guidance: the request's terms over the model's defaults; a negative prompt only when a
* scale asks for the unconditional branch. */
bool named = r->has_neg;
for (int i = 0; i < 8; ++i) {
named = named || !std::isnan(r->guidance[i]);
j->guidance[i] = (float)(std::isnan(r->guidance[i]) ? d.guidance_default[i] : r->guidance[i]);
if (!(j->guidance[i] >= 0.0f) || !std::isfinite(j->guidance[i]))
return no("guidance terms must be finite and not negative");
}
/* The step's packed sequence. When the denoiser consumes the reference table the pack is the
* only source of its rows, segment boundaries and positions -- the reference rows sit between
* the text and the target streams, so the plain `text + audio + video` arithmetic and the plain
* position layout no longer describe it. rad_arch_video_pack returns the total rows and, when
* roomy, the boundaries and the full [3, rows] planar RoPE in one call. Otherwise the plain
* layout is computed exactly as before, and a staged reference table (if any) rides inert. */
const int64_t nd = positions_(RAD_VPOS_DECODE, &j->geom, nullptr, 0);
if (nd <= 0 || nd > max_tok_)
return no("the model lays this video's decoder in " + std::to_string(nd) + " rows, which "
"this server cannot run");
j->dec_rows = nd;
if (d.ref_rows && !j->ref_tab.empty()) {
if (r->upscale > 1.0)
return no("reference conditioning does not yet combine with latent upscale; ask for "
"the size you want without latent_upscale");
if (!pack_)
return no("the generator says it conditions on references but exports no "
"rad_arch_video_pack");
const int64_t pr = pack_(&j->geom, j->ref_tab.data(), nullptr, 0, nullptr, 0);
if (pr <= 0)
return no("the model refused the reference conditioning layout");
if (pr > max_tok_)
return no("a conditioned step is " + std::to_string(pr) + " rows and a pass carries " +
std::to_string(max_tok_) + "; ask for a shorter or smaller video, or fewer "
"references");
j->seg.assign((size_t)kSegCap, 0);
j->pos.assign((size_t)(3 * pr), 0.0f);
if (pack_(&j->geom, j->ref_tab.data(), j->seg.data(), kSegCap, j->pos.data(), 3 * pr) != pr)
return no("the model could not lay the reference conditioning out");
int nseg = -1;
for (int k = 0; k < kSegCap; ++k)
if (j->seg[(size_t)k] == (int32_t)pr) { nseg = k + 1; break; } /* video grid ends here */
if (nseg < 0 || nseg > kSegCap)
return no("the reference conditioning layout has no closing segment boundary");
j->seg.resize((size_t)nseg);
j->nseg = nseg;
/* The modulation groups. A modulation cell is fixed by a segment's kind, so the denoiser
* merges runs of consecutive same-cell segments and pitches its fixed-width table by the
* GROUP count, not the reference count -- which is how nine reference photos (four groups:
* prompt, all-photos, soundtrack, video) ride a table the fine layout (twelve segments)
* would overrun. The plugin merges for us (rad_arch_video_mod_segs); one that exports none
* merges nothing, so the group table is the fine one and the older per-segment ceiling
* applies. Refuse over-wide merges here, at submit, where a clean answer is still possible. */
int nmod = -1;
if (mod_segs_) {
j->mod_seg.assign((size_t)kSegCap, 0);
nmod = (int)mod_segs_(&j->geom, j->ref_tab.data(), j->mod_seg.data(), kSegCap);
if (nmod < 0 || nmod > kSegCap)
return no("the model could not merge the reference conditioning into its "
"modulation groups");
j->mod_seg.resize((size_t)nmod);
} else {
nmod = nseg; /* nothing merges: the groups are the fine segments */
j->mod_seg = j->seg;
}
j->nmod = nmod;
const int ngroups = nmod - 1; /* `mod_seg` is boundaries: one more than the groups */
if (d.max_ref_segs > 0 && ngroups > d.max_ref_segs)
return no("these references change the conditioning's modulation cell " +
std::to_string(ngroups) + " times, but this deployment's modulation table holds " +
std::to_string(d.max_ref_segs) + " cells -- ask for references that share their "
"modalities and target, or fewer of them");
/* `rows` stays the plain text+audio+video count: every non-step pass (encode, decode,
* audio, upscale) stages its own segment table and target counts from it and must see the
* bytes it sees today. Only build_step runs at the widened `step_rows`. */
j->rows = T + s.audio_rows + s.video_rows;
j->step_rows = pr;
/* The last segment (the video target) runs [seg[nseg-2], seg[nseg-1]); seg[nseg-1] is the
* total rows, so the video start is the boundary before it -- the same one the VSA takes as
* its video base (it works in segments, one fewer than the boundaries it is handed). */
j->lat_v = pr - j->seg[(size_t)(nseg - 2)];
j->lat_a = decl_.audio_channels * (int64_t)j->geom.n_audio;
j->ref_wide = true;
} else {
j->rows = T + s.audio_rows + s.video_rows;
if (j->rows > max_tok_)
return no("a step of this video is " + std::to_string(j->rows) + " rows and a pass "
"carries " + std::to_string(max_tok_) + "; ask for a shorter or smaller video");
const int64_t nr = positions_(RAD_VPOS_STEP, &j->geom, nullptr, 0);
if (nr != j->rows)
return no("the model lays this video out in " + std::to_string(nr) + " step rows, "
"which this server cannot run");
j->pos.assign((size_t)(3 * nr), 0.0f);
if (positions_(RAD_VPOS_STEP, &j->geom, j->pos.data(), nr) != nr)
return no("the model could not lay this video out");
j->step_rows = j->rows;
if (!d.guidance && named)
return no("this model takes no guidance or negative prompt");
j->n_neg = 0;
if (d.guidance && (j->guidance[0] != 1.0f || j->guidance[4] != 1.0f)) {
const int64_t N = (int64_t)r->neg_tokens.size();
if (N < 1 || N > d.max_text)
return no("the negative prompt is " + std::to_string(N) + " tokens; this model takes "
"1.." + std::to_string(d.max_text));
j->n_neg = (int32_t)N;
}
j->sched = video_schedule(d, steps, r->shift_video, r->shift_audio);
if (j->sched.steps < 1) return no("the schedule has no steps");
if (r->upscale > 1.0) {
if (!(d.upscale_max > 1.0)) return no("this model has no latent upscaler");
if (r->upscale > d.upscale_max)
return no("latent_upscale is at most " + fmt("%g", d.upscale_max) + " for this model");
int32_t sw = 0, sh = 0;
video_small_size(d, r->width, r->height, r->upscale, &sw, &sh);
if (sw == r->width && sh == r->height)
return no("latent_upscale " + fmt("%g", r->upscale) + " leaves " +
std::to_string(r->width) + "x" + std::to_string(r->height) + " as it is: "
"the small size is each side over the factor, rounded to a multiple of " +
std::to_string(d.size_multiple));
const int32_t evals = j->sched.steps;
int32_t refine = r->refine;
if (refine == 0) refine = std::min<int32_t>(d.upscale_refine, evals - 1);
if (refine < 1 || refine >= evals)
return no("upscale_refine_steps must be 1.." + std::to_string(evals - 1) + ": the "
"schedule takes " + std::to_string(evals) + " evaluations and the small "
"size at least one of them");
const VideoShape ss = video_shape(d, sw, sh, r->chunks);
j->geom_small = j->geom;
j->geom_small.lat_h = ss.lat_h;
j->geom_small.lat_w = ss.lat_w;
j->rows_small = T + ss.audio_rows + ss.video_rows;
const int64_t ns = positions_(RAD_VPOS_STEP, &j->geom_small, nullptr, 0);
if (ns != j->rows_small)
return no("the model lays the small size " + std::to_string(sw) + "x" +
std::to_string(sh) + " out in " + std::to_string(ns) + " step rows, which "
"this server cannot run");
j->pos_small.assign((size_t)(3 * ns), 0.0f);
if (positions_(RAD_VPOS_STEP, &j->geom_small, j->pos_small.data(), ns) != ns)
return no("the model could not lay the small size out");
j->split = evals - refine;
j->factor = (float)(((double)r->width / sw + (double)r->height / sh) / 2.0);
r->ticket->small_width = sw;
r->ticket->small_height = sh;
r->ticket->refine = refine;
}
j->n_chunks = r->chunks;
j->n_samples = (int64_t)s.n_audio * (d.sample_rate / d.audio_rate);
/* The reference table and the VAE encode queue were built above, before the step layout was
* chosen. Each reference the server decoded into encoder form rides one encode pass at the slot
* its index numbers within its kind -- a picture or video a Vencode pass, a standalone audio and
* every video's soundtrack an Aencode pass (a soundtrack at its video's slot, since the encoder
* and the scatter both number it by its video). Endpoint keyframes ride the same queue as
* picture anchors -- a Vencode pass at the image slot their keyframe order names. */
/* The soundtrack's length, exactly the samples the decode will hand the encoder — the
if (r->decoder < 0 || (r->decoder > 0 && (size_t)r->decoder >= decoder_area_.size()))
return no("this model has no decoder " + std::to_string(r->decoder));
if (r->decoder > 0 && W * H > decoder_area_[(size_t)r->decoder])
return no("the " + decoder_names_[(size_t)r->decoder] + " decoder makes frames of " +
std::to_string(decoder_area_[(size_t)r->decoder]) + " pixels at most");
j->auto_len = r->chunks == 0 && d.duration_out != RAD_NULL_HANDLE;
const int32_t chunks = r->chunks == 0 ? (int32_t)d.default_chunks : r->chunks;
if (shape_job(*j, *r, chunks, steps, why) < 0) return RAD_E_INVAL;
/* The soundtrack's length, exactly the samples the decode will hand the encoder -- the
* number a caller that chains clips against an audio floor checks. A build without
* libavcodec never gets the muxed file to read it back from, so it is logged here. */
RAD_INFO("video: soundtrack %.2f s, %lld samples at %lld Hz x %lld ch",
@@ -736,15 +902,12 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
(long long)d.sample_rate, (long long)d.audio_channels);
VideoTicket& t = *r->ticket;
t.frames = s.frames;
t.width = r->width;
t.height = r->height;
t.steps = j->sched.steps;
t.sample_rate = d.sample_rate;
t.channels = d.audio_channels;
t.fps = (double)d.fps_num / (double)d.fps_den;
t.in_tokens = T;
t.rows = j->step_rows; /* the conditioned step's real length, references included */
t.t_submit_ns = (int64_t)rad_mono_ns();
std::lock_guard<std::mutex> lk(mu_);
if (closed_) {
@@ -850,9 +1013,17 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows,
b.lat_frames, b.lat_h / p, b.lat_w / p };
std::memcpy(g + RAD_VGEOM_UP_SRC, up, sizeof up);
}
g[RAD_VGEOM_AUDIO_VOL] = g0.n_audio;
g[RAD_VGEOM_AUDIO_VOL + 1] = 1;
g[RAD_VGEOM_AUDIO_VOL + 2] = 1;
const int32_t ppf = (int32_t)((g0.lat_h / decl_.patch) * (g0.lat_w / decl_.patch));
g[RAD_VGEOM_FIRST_CU] = 0;
g[RAD_VGEOM_FIRST_CU + 1] = ppf;
g[RAD_VGEOM_FIRST_CU + 2] = ppf * g0.lat_frames;
reg_[R_GEOM].used = RAD_VGEOM_N * 4;
const bool wide = j.ref_wide && ref_step;
const int64_t audio_rows = decl_.audio_channels * (int64_t)g0.n_audio;
const int64_t audio_rows =
(decl_.audio_streams > 0 ? decl_.audio_streams : decl_.audio_channels) * (int64_t)g0.n_audio;
/* With references riding, the sampler owns only the target video rows -- not the reference
* rows the pack placed ahead of them -- so the target count is the pack's, not the plain
* rows-minus-text-minus-audio. The audio target is the whole soundtrack either way. */
@@ -909,6 +1080,8 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows,
lat[1] = (int32_t)video_rows;
lat[2] = 0;
lat[3] = (int32_t)audio_rows;
std::memcpy(hptr<float>(R_GUIDE), j.guidance, sizeof j.guidance);
reg_[R_GUIDE].used = sizeof j.guidance;
reg_[R_LANE].used = 4;
reg_[R_FIRST].used = 4;
reg_[R_LAT].used = 4 * 4;
@@ -953,6 +1126,10 @@ void VideoDriver::base_batches(const Job& j, const RadVideoGeom& g, int64_t n_to
V.n_samples = j.n_samples;
V.upscale = dptr<float>(ri, R_UP);
V.ref_tab = j.ref_tab.empty() ? nullptr : j.ref_tab.data();
V.guidance_h = j.guidance;
V.guidance = dptr<float>(ri, R_GUIDE);
V.has_image = !j.req->image.empty();
V.decoder = j.req->decoder;
B.vgen_b = &V;
}
}
@@ -1013,23 +1190,39 @@ const RadBatch* VideoDriver::batch_for(int rank) const {
const RadBatch* VideoDriver::build_cond(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const int64_t T = j.geom.n_text;
/* The prompt, then the negative prompt when the request is guided against one, each its own
* sequence from position 0. */
const int64_t T = (int64_t)j.req->tokens.size(), N = j.n_neg;
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* pos = hptr<int32_t>(R_POS);
std::memcpy(tok, j.req->tokens.data(), (size_t)T * 4);
for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)i;
if (N > 0) std::memcpy(tok + T, j.req->neg_tokens.data(), (size_t)N * 4);
/* A left-padded encoder's prompt ends at text_left_pad - 1. */
const int64_t lp = decl_.text_left_pad;
for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)(lp > 0 ? lp - T + i : i);
for (int64_t i = 0; i < N; ++i) pos[T + i] = (int32_t)(lp > 0 ? lp - N + i : i);
int32_t* cu = hptr<int32_t>(R_CU);
cu[0] = 0;
cu[1] = (int32_t)T;
cu[2] = (int32_t)(T + N);
/* The first frame as the reference's image processor hands it to the VAE: x / 255 * 2 - 1 in
* f32, then bf16. */
const std::vector<uint8_t>& img = j.req->image;
if (!img.empty()) {
uint16_t* px = hptr<uint16_t>(R_IMG);
for (size_t i = 0; i < img.size(); ++i)
px[i] = rad_f32_to_bf16(2.0f * ((float)img[i] / 255.0f) - 1.0f);
reg_[R_IMG].used = (int64_t)img.size() * 2;
}
float* tv = hptr<float>(R_TV);
float* ta = hptr<float>(R_TA);
for (int32_t i = 0; i < j.sched.steps; ++i) {
tv[i] = 1.0f - j.sched.sig_v[(size_t)i];
ta[i] = 1.0f - j.sched.sig_a[(size_t)i];
}
reg_[R_TOK].used = T * 4;
reg_[R_POS].used = T * 4;
reg_[R_CU].used = 2 * 4;
reg_[R_TOK].used = (T + N) * 4;
reg_[R_POS].used = (T + N) * 4;
reg_[R_CU].used = (N > 0 ? 3 : 2) * 4;
reg_[R_TV].used = j.sched.steps * 4;
reg_[R_TA].used = j.sched.steps * 4;
if (dit_dbg_)
@@ -1090,7 +1283,7 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) {
}
if (upload() < 0) return nullptr;
base_batches(j, g, T, step);
base_batches(j, g, T + N, step);
if (j.req->media) {
for (size_t r = 0; r < ranks_.size(); ++r) {
RadBatch& B = out_[r];
@@ -1108,9 +1301,18 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) {
B.enc_max_seg = max_seg;
}
}
for (auto& B : out_) B.gen = RAD_GEN_PASS_VCOND;
for (size_t r = 0; r < out_.size(); ++r) {
RadBatch& B = out_[r];
B.gen = RAD_GEN_PASS_VCOND;
B.n_seq = N > 0 ? 2 : 1;
B.max_q_len = B.max_q_len_prefill = (int32_t)std::max(T, N);
vout_[r].n_neg = (int32_t)N;
if (!img.empty()) vout_[r].image = dptr<uint16_t>((int)r, R_IMG);
}
if (j.auto_len) rb_.assign(1, Readback{ decl_.duration_out, 4, duration_host_ });
pass_.kind = RAD_GEN_PASS_VCOND;
pass_.job = j.id;
pass_.lora_slot = j.req->lora_slot;
return &out_[0];
}
@@ -1241,6 +1443,7 @@ const RadBatch* VideoDriver::build_step(Job& j, int step) {
}
pass_.kind = RAD_GEN_PASS_VSTEP;
pass_.job = j.id;
pass_.lora_slot = j.req->lora_slot;
return &out_[0];
}
@@ -1276,6 +1479,7 @@ const RadBatch* VideoDriver::build_audio(Job& j, int step) {
const RadBatch* VideoDriver::build_chunk(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
stage_geom(j, j.geom, j.rows, j.chunk);
stage_seed(j); /* a decoder that denoises draws from the request's seed */
if (upload() < 0) return nullptr;
base_batches(j, j.geom, j.dec_rows, step);
const bool last = j.chunk == j.n_chunks - 1;
@@ -1495,6 +1699,26 @@ int VideoDriver::done() {
case RAD_GEN_PASS_VCOND:
j->cond_done = true;
j->req->ticket->t_cond_ns = now;
if (j->auto_len) {
j->auto_len = false;
std::string note, why;
int32_t n = predicted_chunks((double)duration_host_[0], &note);
/* Shaped as at submit, which passed at default_chunks; a longer video than a pass
* can carry is shortened until it fits. */
const int32_t steps = j->req->steps > 0 ? j->req->steps : (int32_t)decl_.default_steps;
const int32_t at_submit = j->n_chunks;
while (n > at_submit && shape_job(*j, *j->req, n, steps, &why) < 0) --n;
if (n <= at_submit && shape_job(*j, *j->req, n, steps, &why) < 0) {
fail_locked(*j, RAD_E_INVAL, why);
break;
}
RAD_INFO("video: the model gives the prompt %d frames (%.2f s)%s", j->geom.frames,
(double)j->geom.frames * decl_.fps_den / decl_.fps_num, note.c_str());
VideoEvent e;
e.kind = VideoEvent::LENGTH;
e.n = j->geom.frames;
j->req->ticket->push(std::move(e));
}
break;
case RAD_GEN_PASS_VENCODE:
case RAD_GEN_PASS_AENCODE:
+19 -2
View File
@@ -6,7 +6,8 @@
* threads through `submit()` and leave through their VideoTicket.
*
* A request holds a lane from admission to its last chunk. Its geometry, schedule and rotary
* positions are fixed at submit, so nothing is computed between passes but the staging.
* positions are fixed at submit, so nothing is computed between passes but the staging; a request
* whose length the model predicts is shaped again once, after its VCOND pass.
*
* Pass priority, one pass at a time:
*
@@ -67,6 +68,7 @@ public:
/* ---------------------------------------------------------- the engine thread */
const RadBatch* next(int step) override;
const RadBatch* batch_for(int rank) const override;
int32_t lora_slot() const override { return pass_.lora_slot; }
const std::vector<Readback>& readbacks() const override { return rb_; }
int done() override;
@@ -130,6 +132,13 @@ private:
std::vector<float> pos_small;
float factor = 0.0f;
bool upscaled = false;
/* Guidance resolved against the model's defaults (RadVideoGenBatch::guidance_h) and the
* negative prompt's tokens the VCOND pass carries (0: none). */
float guidance[8] = {};
int32_t n_neg = 0;
/* The request named no length and the model predicts one (RadVideoGenDecl::duration_out):
* shaped at default_chunks until its VCOND pass is done. */
bool auto_len = false;
int32_t lane = -1;
bool admitted = false;
bool cond_done = false;
@@ -145,6 +154,7 @@ private:
int kind = 0;
uint64_t job = 0;
int32_t n_frames = 0;
int32_t lora_slot = -1;
};
/* Staging regions: their offsets in the host span and every rank's slab. */
@@ -161,7 +171,7 @@ private:
* path, stages R_SEG's bytes into it as well. */
enum { R_TOK, R_POS, R_CU, R_ROPE, R_GEOM, R_SCHED, R_TV, R_TA, R_SEED, R_LANE, R_FIRST,
R_SEG, R_LAT, R_UP, R_MMROW, R_ENCPIX, R_ENCCRD, R_ENCCU,
R_ENCPX, R_ENCSM, R_ENCG, R_MOD, R_N };
R_ENCPX, R_ENCSM, R_ENCG, R_MOD, R_IMG, R_GUIDE, 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 {
@@ -170,6 +180,8 @@ private:
int upload();
/* The geometry and rows of the job's next step: the small ones before its upscale. */
bool small_now(const Job& j) const { return j.split > 0 && !j.upscaled; }
int shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_t steps, std::string* why);
int32_t predicted_chunks(double log_seconds, std::string* note) const;
void base_batches(const Job& j, const RadVideoGeom& g, int64_t n_tok, int step);
void stage_geom(const Job& j, const RadVideoGeom& g, int64_t rows, int32_t chunk,
bool ref_step = false);
@@ -193,6 +205,10 @@ private:
RadVideoGenDecl decl_{};
std::vector<double> rungs_; /* decl_.rungs points here */
std::vector<double> refine_rungs_; /* decl_.refine_rungs */
std::string default_negative_;
std::vector<std::string> decoder_names_; /* RadVideoGenDecl::decoders */
std::vector<int64_t> decoder_area_; /* each one's largest frame */
std::string name_;
PositionsFn positions_ = nullptr;
SegsFn segs_ = nullptr;
@@ -214,6 +230,7 @@ private:
int64_t frames_bytes_ = 0;
float* audio_host_ = nullptr;
int64_t audio_bytes_ = 0;
float* duration_host_ = nullptr; /* duration_out's readback, f32 [1] */
std::vector<Readback> rb_;
/* Debug-only (R4D_ENC_DEBUG): a pinned slab the encoder's audio / video latent buffer is read
+986
View File
@@ -0,0 +1,986 @@
/* lora/adapter.cpp -- see adapter.h. Host code only. */
#include "adapter.h"
#include "rad_plugin.h"
#include <algorithm>
#include <atomic>
#include <cmath>
#include <cstdarg>
#include <cstdlib>
#include <cstring>
#include <map>
#include <regex>
#include <thread>
#include <unordered_map>
namespace rad {
namespace lora {
namespace {
#define TRY(x) do { const int s_ = (x); if (s_ < 0) return s_; } while (0)
std::string fmt(const char* f, ...) __attribute__((format(printf, 1, 2)));
std::string fmt(const char* f, ...) {
char buf[2048];
va_list ap;
va_start(ap, f);
vsnprintf(buf, sizeof buf, f, ap);
va_end(ap);
return buf;
}
int fail(std::string* err, int code, const std::string& m) {
if (err) *err = m;
return code;
}
bool ends_with(const std::string& s, const char* p) {
const size_t n = std::strlen(p);
return s.size() >= n && s.compare(s.size() - n, n, p) == 0;
}
std::string shape_str(const std::vector<int64_t>& s) {
std::string r = "[";
for (size_t i = 0; i < s.size(); ++i) r += (i ? ", " : "") + std::to_string(s[i]);
return r + "]";
}
/* ---------------------------------------------------------------- tensors as f32 */
bool float_dtype(uint32_t dt) { return dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32; }
float elem(const StTensor& t, int64_t i) {
switch (t.dtype) {
case RAD_BF16: { uint16_t v; std::memcpy(&v, t.data + 2 * i, 2); return rad_bf16_to_f32(v); }
case RAD_F16: { uint16_t v; std::memcpy(&v, t.data + 2 * i, 2); return rad_f16_to_f32(v); }
default: { float v; std::memcpy(&v, t.data + 4 * i, 4); return v; }
}
}
/* A tensor as a row-major matrix [shape[0], product of the rest]. */
int as_matrix(const StTensor* t, const char* what, int64_t* rows, int64_t* cols,
std::vector<float>* out, std::string* err) {
if (!t) return fail(err, RAD_E_FORMAT, fmt("no %s tensor", what));
if (!float_dtype(t->dtype))
return fail(err, RAD_E_DTYPE, fmt("%s is %s; expected BF16, F16 or F32", t->name.c_str(),
t->dtype_str.c_str()));
if (t->shape.size() < 2 || !t->data)
return fail(err, RAD_E_SHAPE, fmt("%s has shape %s; expected a matrix", t->name.c_str(),
shape_str(t->shape).c_str()));
*rows = t->shape[0];
*cols = t->numel() / (t->shape[0] ? t->shape[0] : 1);
if (out) {
out->resize((size_t)(*rows * *cols));
for (int64_t i = 0; i < *rows * *cols; ++i) (*out)[(size_t)i] = elem(*t, i);
}
return RAD_OK;
}
/* The trailing dims past the first two, all 1 (an up projection of a convolution is 1 x 1). */
bool trailing_ones(const StTensor* t) {
for (size_t i = 2; i < t->shape.size(); ++i) if (t->shape[i] != 1) return false;
return true;
}
/* One number: shape [] (numel() counts it as no element) or [1], a float or (as some trainers
* write an alpha) an integer or F64. */
int scalar(const StTensor* t, double* v, std::string* err) {
const int64_t n = t->shape.empty() ? 1 : t->numel();
if (n != 1 || !t->data)
return fail(err, RAD_E_FORMAT, fmt("%s is not one number", t->name.c_str()));
if (float_dtype(t->dtype)) {
*v = elem(*t, 0);
} else if (t->dtype == RAD_I64 && t->bytes >= 8) {
int64_t x; std::memcpy(&x, t->data, 8); *v = (double)x;
} else if (t->dtype == RAD_I32 && t->bytes >= 4) {
int32_t x; std::memcpy(&x, t->data, 4); *v = (double)x;
} else if (t->dtype_str == "F64" && t->bytes >= 8) {
std::memcpy(v, t->data, 8);
} else {
return fail(err, RAD_E_FORMAT, fmt("%s is %s, not a number this reader knows",
t->name.c_str(), t->dtype_str.c_str()));
}
return std::isfinite(*v) ? RAD_OK : fail(err, RAD_E_FORMAT, t->name + " is not finite");
}
/* ---------------------------------------------------------------- dense f32 kernels */
/* C[m, n] (+)= A[m, k] B[k, n], row-major. */
void mm(const float* A, const float* B, float* C, int64_t m, int64_t k, int64_t n, bool add = false) {
if (!add) std::fill(C, C + m * n, 0.0f);
for (int64_t i = 0; i < m; ++i) {
float* c = C + i * n;
for (int64_t p = 0; p < k; ++p) {
const float a = A[i * k + p];
if (a == 0.0f) continue;
const float* b = B + p * n;
for (int64_t j = 0; j < n; ++j) c[j] += a * b[j];
}
}
}
/* C[m, n] (+)= A[k, m]^T B[k, n]. */
void mm_tn(const float* A, const float* B, float* C, int64_t m, int64_t k, int64_t n, bool add = false) {
if (!add) std::fill(C, C + m * n, 0.0f);
for (int64_t p = 0; p < k; ++p) {
const float* a = A + p * m;
const float* b = B + p * n;
for (int64_t i = 0; i < m; ++i) {
const float x = a[i];
if (x == 0.0f) continue;
float* c = C + i * n;
for (int64_t j = 0; j < n; ++j) c[j] += x * b[j];
}
}
}
/* Orthonormalise the l columns of Y [n, l] in place (modified Gram-Schmidt, twice). A column
* that vanishes is left zero. */
void orth(float* Y, int64_t n, int64_t l) {
std::vector<double> col((size_t)n);
for (int64_t j = 0; j < l; ++j) {
for (int pass = 0; pass < 2; ++pass)
for (int64_t i = 0; i < j; ++i) {
double d = 0.0;
for (int64_t r = 0; r < n; ++r) d += (double)Y[r * l + i] * Y[r * l + j];
for (int64_t r = 0; r < n; ++r) Y[r * l + j] -= (float)(d * Y[r * l + i]);
}
double nn = 0.0;
for (int64_t r = 0; r < n; ++r) nn += (double)Y[r * l + j] * Y[r * l + j];
const double inv = nn > 1e-30 ? 1.0 / std::sqrt(nn) : 0.0;
for (int64_t r = 0; r < n; ++r) Y[r * l + j] = (float)(Y[r * l + j] * inv);
}
}
/* Eigen-decomposition of a symmetric l x l matrix (cyclic Jacobi): eigenvalues in `w`, sorted
* descending, and eigenvectors as the columns of V [l, l]. */
void sym_eig(std::vector<double> G, int64_t l, std::vector<double>* w, std::vector<double>* V) {
V->assign((size_t)(l * l), 0.0);
for (int64_t i = 0; i < l; ++i) (*V)[(size_t)(i * l + i)] = 1.0;
for (int sweep = 0; sweep < 60; ++sweep) {
double off = 0.0, tot = 0.0;
for (int64_t i = 0; i < l; ++i)
for (int64_t j = 0; j < l; ++j) {
const double g = G[(size_t)(i * l + j)];
tot += g * g;
if (i != j) off += g * g;
}
if (off <= 1e-24 * (tot > 0 ? tot : 1.0)) break;
for (int64_t p = 0; p < l; ++p)
for (int64_t q = p + 1; q < l; ++q) {
const double gpq = G[(size_t)(p * l + q)];
if (std::fabs(gpq) < 1e-300) continue;
const double gpp = G[(size_t)(p * l + p)], gqq = G[(size_t)(q * l + q)];
const double th = (gqq - gpp) / (2.0 * gpq);
const double t = (th >= 0 ? 1.0 : -1.0) / (std::fabs(th) + std::sqrt(th * th + 1.0));
const double c = 1.0 / std::sqrt(t * t + 1.0), s = t * c;
for (int64_t k = 0; k < l; ++k) {
const double gkp = G[(size_t)(k * l + p)], gkq = G[(size_t)(k * l + q)];
G[(size_t)(k * l + p)] = c * gkp - s * gkq;
G[(size_t)(k * l + q)] = s * gkp + c * gkq;
}
for (int64_t k = 0; k < l; ++k) {
const double gpk = G[(size_t)(p * l + k)], gqk = G[(size_t)(q * l + k)];
G[(size_t)(p * l + k)] = c * gpk - s * gqk;
G[(size_t)(q * l + k)] = s * gpk + c * gqk;
}
for (int64_t k = 0; k < l; ++k) {
const double vkp = (*V)[(size_t)(k * l + p)], vkq = (*V)[(size_t)(k * l + q)];
(*V)[(size_t)(k * l + p)] = c * vkp - s * vkq;
(*V)[(size_t)(k * l + q)] = s * vkp + c * vkq;
}
}
}
std::vector<int64_t> ord((size_t)l);
for (int64_t i = 0; i < l; ++i) ord[(size_t)i] = i;
std::sort(ord.begin(), ord.end(), [&](int64_t a, int64_t b) {
return G[(size_t)(a * l + a)] > G[(size_t)(b * l + b)];
});
std::vector<double> V2((size_t)(l * l));
w->resize((size_t)l);
for (int64_t c = 0; c < l; ++c) {
(*w)[(size_t)c] = G[(size_t)(ord[(size_t)c] * l + ord[(size_t)c])];
for (int64_t r = 0; r < l; ++r) V2[(size_t)(r * l + c)] = (*V)[(size_t)(r * l + ord[(size_t)c])];
}
*V = std::move(V2);
}
/* ||B A||_F^2 for B [n, r], A [r, k]: trace((B^T B)(A A^T)). */
double lowrank_energy(const std::vector<float>& B, const std::vector<float>& A, int64_t n, int64_t r,
int64_t k) {
std::vector<double> bb((size_t)(r * r), 0.0), aa((size_t)(r * r), 0.0);
for (int64_t i = 0; i < n; ++i)
for (int64_t p = 0; p < r; ++p) {
const double x = B[(size_t)(i * r + p)];
if (x == 0.0) continue;
for (int64_t q = 0; q < r; ++q) bb[(size_t)(p * r + q)] += x * B[(size_t)(i * r + q)];
}
for (int64_t p = 0; p < r; ++p)
for (int64_t q = p; q < r; ++q) {
double d = 0.0;
for (int64_t j = 0; j < k; ++j) d += (double)A[(size_t)(p * k + j)] * A[(size_t)(q * k + j)];
aa[(size_t)(p * r + q)] = aa[(size_t)(q * r + p)] = d;
}
double e = 0.0;
for (size_t i = 0; i < bb.size(); ++i) e += bb[i] * aa[i];
return e;
}
/* ---------------------------------------------------------------- the key suffixes */
struct Suffix {
const char* s;
int kind; /* FileModule::Kind, or -1 alpha, -2 refused, -3 skipped */
int slot;
const char* why;
};
const Suffix kSuffix[] = {
{ ".lora_down.weight", FileModule::LORA, 0, nullptr },
{ ".lora_up.weight", FileModule::LORA, 1, nullptr },
{ ".lora_A.default.weight", FileModule::LORA, 0, nullptr },
{ ".lora_B.default.weight", FileModule::LORA, 1, nullptr },
{ ".lora_A.weight", FileModule::LORA, 0, nullptr },
{ ".lora_B.weight", FileModule::LORA, 1, nullptr },
{ ".lora_linear_layer.down.weight", FileModule::LORA, 0, nullptr },
{ ".lora_linear_layer.up.weight", FileModule::LORA, 1, nullptr },
{ ".lora.down.weight", FileModule::LORA, 0, nullptr },
{ ".lora.up.weight", FileModule::LORA, 1, nullptr },
{ ".hada_w1_a", FileModule::LOHA, 0, nullptr },
{ ".hada_w1_b", FileModule::LOHA, 1, nullptr },
{ ".hada_w2_a", FileModule::LOHA, 2, nullptr },
{ ".hada_w2_b", FileModule::LOHA, 3, nullptr },
{ ".lokr_w1", FileModule::LOKR, 0, nullptr },
{ ".lokr_w1_a", FileModule::LOKR, 1, nullptr },
{ ".lokr_w1_b", FileModule::LOKR, 2, nullptr },
{ ".lokr_w2", FileModule::LOKR, 3, nullptr },
{ ".lokr_w2_a", FileModule::LOKR, 4, nullptr },
{ ".lokr_w2_b", FileModule::LOKR, 5, nullptr },
{ ".diff", FileModule::FULL, 0, nullptr },
{ ".alpha", -1, 0, nullptr },
{ ".lora_alpha", -1, 0, nullptr },
{ ".dora_scale", -2, 0, "a DoRA magnitude, which rescales the base weight's columns" },
{ ".lora_magnitude_vector.default.weight", -2, 0, "a DoRA magnitude, which rescales the base "
"weight's columns" },
{ ".lora_magnitude_vector.weight", -2, 0, "a DoRA magnitude, which rescales the base weight's "
"columns" },
{ ".lora_magnitude_vector", -2, 0, "a DoRA magnitude, which rescales the base weight's columns" },
{ ".hada_t1", -2, 0, "a LoHa Tucker core" },
{ ".hada_t2", -2, 0, "a LoHa Tucker core" },
{ ".lokr_t2", -2, 0, "a LoKr Tucker core" },
{ ".lora_mid.weight", -2, 0, "a LoCon Tucker core" },
{ ".oft_blocks", -2, 0, "an OFT rotation" },
{ ".oft_diag", -2, 0, "an OFT rotation" },
{ ".oft_R.weight", -2, 0, "an OFT rotation" },
{ ".boft_R", -2, 0, "a BOFT rotation" },
{ ".diff_b", -3, 0, "a bias delta" },
{ ".w_norm", -3, 0, "a norm's weight delta" },
{ ".b_norm", -3, 0, "a norm's bias delta" },
{ ".lora_B.bias", -3, 0, "a bias on lora_B" },
{ ".lora_up.bias", -3, 0, "a bias on lora_up" },
{ ".set_weight", -2, 0, "a replacement weight" },
};
} /* namespace */
/* ================================================================== the file */
int AdapterFile::open(const std::string& path, std::string* err) {
mods_.clear();
skipped_.clear();
if (st_.open(path) != RAD_OK) return fail(err, RAD_E_IO, path + ": cannot open as safetensors");
std::map<std::string, FileModule> by;
std::map<std::string, const StTensor*> alphas;
for (const StTensor& t : st_.tensors()) {
const Suffix* hit = nullptr;
for (const Suffix& s : kSuffix)
if (ends_with(t.name, s.s) && (!hit || std::strlen(s.s) > std::strlen(hit->s))) hit = &s;
if (!hit) {
skipped_.push_back({ t.name, "not an adapter tensor" });
continue;
}
const std::string key = t.name.substr(0, t.name.size() - std::strlen(hit->s));
if (hit->kind == -2)
return fail(err, RAD_E_UNSUPPORTED, fmt("%s: %s is %s; that kind of adapter is not "
"served", path.c_str(), t.name.c_str(), hit->why));
if (hit->kind == -3) { skipped_.push_back({ t.name, hit->why }); continue; }
if (hit->kind == -1) { alphas[key] = &t; continue; }
FileModule& m = by[key];
if (m.key.empty()) { m.key = key; m.kind = (FileModule::Kind)hit->kind; }
else if (m.kind != hit->kind)
return fail(err, RAD_E_FORMAT, fmt("%s: module %s mixes adapter kinds", path.c_str(),
key.c_str()));
if (m.t[hit->slot])
return fail(err, RAD_E_FORMAT, fmt("%s: module %s has two %s tensors", path.c_str(),
key.c_str(), hit->s));
m.t[hit->slot] = &t;
}
for (auto& [k, a] : alphas) {
auto it = by.find(k);
if (it == by.end()) { skipped_.push_back({ a->name, "an alpha of no module" }); continue; }
it->second.alpha = a;
}
for (auto& [k, m] : by) {
const char* missing = nullptr;
switch (m.kind) {
case FileModule::LORA:
if (!m.t[0] || !m.t[1]) missing = m.t[0] ? "up/B" : "down/A";
break;
case FileModule::LOHA:
if (!m.t[0] || !m.t[1] || !m.t[2] || !m.t[3]) missing = "a hada_w factor";
break;
case FileModule::LOKR:
if (!m.t[0] && !(m.t[1] && m.t[2])) missing = "lokr_w1 (or lokr_w1_a and _b)";
else if (!m.t[3] && !(m.t[4] && m.t[5])) missing = "lokr_w2 (or lokr_w2_a and _b)";
break;
case FileModule::FULL: break;
}
if (missing)
return fail(err, RAD_E_FORMAT, fmt("%s: module %s has no %s", path.c_str(), k.c_str(),
missing));
mods_.push_back(m);
}
if (mods_.empty()) return fail(err, RAD_E_FORMAT, path + ": no adapter modules in the file");
return RAD_OK;
}
const char* AdapterFile::kind_name() const {
int n[4] = { 0, 0, 0, 0 };
for (const FileModule& m : mods_) ++n[m.kind];
const int k = (int)(std::max_element(n, n + 4) - n);
static const char* const kName[] = { "LoRA", "LoHa", "LoKr", "full" };
return kName[k];
}
/* ================================================================== deltas */
int module_delta(const FileModule& m, double w, Delta* out, std::string* err) {
*out = Delta{};
double alpha = 0.0;
const bool has_alpha = m.alpha != nullptr;
if (has_alpha) TRY(scalar(m.alpha, &alpha, err));
if (m.kind == FileModule::LORA) {
int64_t r = 0, K = 0, N = 0, r2 = 0;
std::vector<float> A, B;
TRY(as_matrix(m.t[0], "down", &r, &K, &A, err));
TRY(as_matrix(m.t[1], "up", &N, &r2, &B, err));
if (!trailing_ones(m.t[1]) || r2 != r)
return fail(err, RAD_E_SHAPE, fmt("module %s: down %s and up %s are not one rank-%lld "
"pair", m.key.c_str(), shape_str(m.t[0]->shape).c_str(),
shape_str(m.t[1]->shape).c_str(), (long long)r));
const double s = w * (has_alpha && r > 0 ? alpha / (double)r : 1.0);
for (float& x : B) x = (float)(x * s);
out->N = N; out->K = K; out->r = r; out->rank_bound = r; out->low_rank = true;
out->A = std::move(A); out->B = std::move(B);
out->energy = lowrank_energy(out->B, out->A, N, r, K);
return RAD_OK;
}
if (m.kind == FileModule::LOHA) {
int64_t N1 = 0, r1 = 0, r1b = 0, K1 = 0, N2 = 0, r2 = 0, r2b = 0, K2 = 0;
std::vector<float> w1a, w1b, w2a, w2b;
TRY(as_matrix(m.t[0], "hada_w1_a", &N1, &r1, &w1a, err));
TRY(as_matrix(m.t[1], "hada_w1_b", &r1b, &K1, &w1b, err));
TRY(as_matrix(m.t[2], "hada_w2_a", &N2, &r2, &w2a, err));
TRY(as_matrix(m.t[3], "hada_w2_b", &r2b, &K2, &w2b, err));
if (r1 != r1b || r2 != r2b || N1 != N2 || K1 != K2)
return fail(err, RAD_E_SHAPE, fmt("module %s: LoHa factors %s %s %s %s do not pair",
m.key.c_str(), shape_str(m.t[0]->shape).c_str(),
shape_str(m.t[1]->shape).c_str(),
shape_str(m.t[2]->shape).c_str(),
shape_str(m.t[3]->shape).c_str()));
/* (w1a w1b) o (w2a w2b) = sum over (i, j) of (w1a[:, i] o w2a[:, j]) (w1b[i] o w2b[j]):
* exactly rank r1 r2. */
const double s = w * (has_alpha && r1 > 0 ? alpha / (double)r1 : 1.0);
const int64_t R = r1 * r2, N = N1, K = K1;
out->B.assign((size_t)(N * R), 0.0f);
out->A.assign((size_t)(R * K), 0.0f);
for (int64_t n = 0; n < N; ++n)
for (int64_t i = 0; i < r1; ++i)
for (int64_t j = 0; j < r2; ++j)
out->B[(size_t)(n * R + i * r2 + j)] =
(float)(s * w1a[(size_t)(n * r1 + i)] * w2a[(size_t)(n * r2 + j)]);
for (int64_t i = 0; i < r1; ++i)
for (int64_t j = 0; j < r2; ++j)
for (int64_t k = 0; k < K; ++k)
out->A[(size_t)((i * r2 + j) * K + k)] = w1b[(size_t)(i * K + k)] * w2b[(size_t)(j * K + k)];
out->N = N; out->K = K; out->r = R; out->rank_bound = R; out->low_rank = true;
out->energy = lowrank_energy(out->B, out->A, N, R, K);
return RAD_OK;
}
if (m.kind == FileModule::LOKR) {
/* kron(w1 [a, b], w2 [c, e]) is [a c, b e]: element (i1 c + i2, j1 e + j2) is
* w1[i1, j1] w2[i2, j2]. A convolution's w2 [c, d, kh, kw] flattens to e = d kh kw, which
* is the flattened kron of the 4-D tensors. */
int64_t a = 0, b = 0, dim = 0;
std::vector<float> W1;
if (m.t[0]) {
TRY(as_matrix(m.t[0], "lokr_w1", &a, &b, &W1, err));
} else {
int64_t r = 0, r2 = 0;
std::vector<float> x, y;
TRY(as_matrix(m.t[1], "lokr_w1_a", &a, &r, &x, err));
TRY(as_matrix(m.t[2], "lokr_w1_b", &r2, &b, &y, err));
if (r != r2) return fail(err, RAD_E_SHAPE, "module " + m.key + ": lokr_w1_a/_b ranks differ");
W1.resize((size_t)(a * b));
mm(x.data(), y.data(), W1.data(), a, r, b);
dim = r;
}
int64_t c = 0, e = 0, r2 = 0;
auto W2 = std::make_shared<std::vector<float>>();
auto W2a = std::make_shared<std::vector<float>>();
auto W2b = std::make_shared<std::vector<float>>();
if (m.t[3]) {
TRY(as_matrix(m.t[3], "lokr_w2", &c, &e, W2.get(), err));
} else {
int64_t rr = 0;
TRY(as_matrix(m.t[4], "lokr_w2_a", &c, &r2, W2a.get(), err));
TRY(as_matrix(m.t[5], "lokr_w2_b", &rr, &e, W2b.get(), err));
if (rr != r2) return fail(err, RAD_E_SHAPE, "module " + m.key + ": lokr_w2_a/_b ranks differ");
dim = r2;
}
const double s = w * (has_alpha && dim > 0 ? alpha / (double)dim : 1.0);
for (float& x : W1) x = (float)(x * s);
auto w1 = std::make_shared<std::vector<float>>(std::move(W1));
const int64_t N = a * c, K = b * e;
out->N = N; out->K = K;
out->rank_bound = std::min(a, b) * (r2 ? r2 : std::min(c, e));
const bool full2 = !W2->empty();
/* ||kron(w1, w2)|| = ||w1|| ||w2|| */
{
double e1 = 0.0;
for (float x : *w1) e1 += (double)x * x;
double e2 = 0.0;
if (full2) for (float x : *W2) e2 += (double)x * x;
else e2 = lowrank_energy(*W2a, *W2b, c, r2, e);
out->energy = e1 * e2;
}
/* Column x of X [K, l], as the matrix [b, e]: kron(w1, w2) x = w1 X w2^T, read as [a, c]. */
out->apply = [=](const float* X, int64_t l, float* Y) {
std::vector<float> xm((size_t)(b * e)), t((size_t)(b * c)), y((size_t)(a * c)), u;
for (int64_t col = 0; col < l; ++col) {
for (int64_t k = 0; k < K; ++k) xm[(size_t)k] = X[k * l + col];
if (full2) {
/* t[j1, i2] = sum_j2 xm[j1, j2] w2[i2, j2] */
for (int64_t j1 = 0; j1 < b; ++j1)
for (int64_t i2 = 0; i2 < c; ++i2) {
float d = 0.0f;
const float* xr = xm.data() + j1 * e;
const float* wr = W2->data() + i2 * e;
for (int64_t j2 = 0; j2 < e; ++j2) d += xr[j2] * wr[j2];
t[(size_t)(j1 * c + i2)] = d;
}
} else {
u.assign((size_t)(b * r2), 0.0f);
for (int64_t j1 = 0; j1 < b; ++j1)
for (int64_t p = 0; p < r2; ++p) {
float d = 0.0f;
const float* xr = xm.data() + j1 * e;
const float* wr = W2b->data() + p * e;
for (int64_t j2 = 0; j2 < e; ++j2) d += xr[j2] * wr[j2];
u[(size_t)(j1 * r2 + p)] = d;
}
for (int64_t j1 = 0; j1 < b; ++j1)
for (int64_t i2 = 0; i2 < c; ++i2) {
float d = 0.0f;
for (int64_t p = 0; p < r2; ++p) d += u[(size_t)(j1 * r2 + p)] * (*W2a)[(size_t)(i2 * r2 + p)];
t[(size_t)(j1 * c + i2)] = d;
}
}
mm(w1->data(), t.data(), y.data(), a, b, c);
for (int64_t n = 0; n < N; ++n) Y[n * l + col] = y[(size_t)n];
}
};
/* The transpose: kron(w1, w2)^T y = w1^T Y w2, Y the column as [a, c], read as [b, e]. */
out->apply_t = [=](const float* Yin, int64_t l, float* X) {
std::vector<float> ym((size_t)(a * c)), t((size_t)(b * c)), x((size_t)(b * e)), u;
for (int64_t col = 0; col < l; ++col) {
for (int64_t n = 0; n < N; ++n) ym[(size_t)n] = Yin[n * l + col];
mm_tn(w1->data(), ym.data(), t.data(), b, a, c); /* [b, c] */
if (full2) {
mm(t.data(), W2->data(), x.data(), b, c, e);
} else {
u.assign((size_t)(b * r2), 0.0f);
mm(t.data(), W2a->data(), u.data(), b, c, r2);
mm(u.data(), W2b->data(), x.data(), b, r2, e);
}
for (int64_t k = 0; k < K; ++k) X[k * l + col] = x[(size_t)k];
}
};
return RAD_OK;
}
/* FULL */
int64_t N = 0, K = 0;
auto D = std::make_shared<std::vector<float>>();
TRY(as_matrix(m.t[0], "diff", &N, &K, D.get(), err));
for (float& x : *D) x = (float)(x * w);
out->N = N; out->K = K; out->rank_bound = std::min(N, K);
out->energy = 0.0;
for (float x : *D) out->energy += (double)x * x;
out->apply = [D, N, K](const float* X, int64_t l, float* Y) { mm(D->data(), X, Y, N, K, l); };
out->apply_t = [D, N, K](const float* Yin, int64_t l, float* X) { mm_tn(D->data(), Yin, X, K, N, l); };
return RAD_OK;
}
void truncate(const Delta& d, int64_t r, std::vector<float>* B, std::vector<float>* A, double* kept) {
const int64_t N = d.N, K = d.K;
r = std::max<int64_t>(0, std::min({ r, N, K, d.rank_bound > 0 ? d.rank_bound : r }));
if (kept) *kept = 1.0;
if (d.low_rank && d.r <= r) { *B = d.B; *A = d.A; return; }
auto fwd = [&](const float* X, int64_t l, float* Y) {
if (!d.low_rank) { d.apply(X, l, Y); return; }
std::vector<float> t((size_t)(d.r * l));
mm(d.A.data(), X, t.data(), d.r, K, l);
mm(d.B.data(), t.data(), Y, N, d.r, l);
};
auto bwd = [&](const float* Y, int64_t l, float* X) {
if (!d.low_rank) { d.apply_t(Y, l, X); return; }
std::vector<float> t((size_t)(d.r * l));
mm_tn(d.B.data(), Y, t.data(), d.r, N, l);
mm_tn(d.A.data(), t.data(), X, K, d.r, l);
};
const int64_t l = std::min({ r + 8, N, K });
/* A fixed sketch: the same adapter composes to the same bytes on every rank and every load. */
std::vector<float> Om((size_t)(K * l));
uint64_t st = 0x2545F4914F6CDD1Dull ^ (uint64_t)(N * 1315423911ull + K);
for (float& x : Om) {
st ^= st << 13; st ^= st >> 7; st ^= st << 17;
x = (float)((double)(st >> 11) / (double)(1ull << 53) - 0.5);
}
std::vector<float> Y((size_t)(N * l)), Z((size_t)(K * l));
fwd(Om.data(), l, Y.data());
orth(Y.data(), N, l);
for (int it = 0; it < 2; ++it) {
bwd(Y.data(), l, Z.data());
orth(Z.data(), K, l);
fwd(Z.data(), l, Y.data());
orth(Y.data(), N, l);
}
/* C^T = D^T Q [K, l]; the SVD of C = Q^T D from the eigen-decomposition of C C^T. */
bwd(Y.data(), l, Z.data());
std::vector<double> G((size_t)(l * l), 0.0);
for (int64_t k = 0; k < K; ++k)
for (int64_t i = 0; i < l; ++i) {
const double x = Z[(size_t)(k * l + i)];
if (x == 0.0) continue;
for (int64_t j = i; j < l; ++j) G[(size_t)(i * l + j)] += x * Z[(size_t)(k * l + j)];
}
for (int64_t i = 0; i < l; ++i)
for (int64_t j = 0; j < i; ++j) G[(size_t)(i * l + j)] = G[(size_t)(j * l + i)];
std::vector<double> w, V;
sym_eig(G, l, &w, &V);
double tot = 0.0, top = 0.0;
for (int64_t i = 0; i < l; ++i) tot += std::max(0.0, w[(size_t)i]);
for (int64_t i = 0; i < r; ++i) top += std::max(0.0, w[(size_t)i]);
if (d.energy > 0.0) tot = std::max(tot, d.energy);
if (kept) *kept = tot > 0.0 ? std::min(1.0, top / tot) : 1.0;
B->assign((size_t)(N * r), 0.0f);
A->assign((size_t)(r * K), 0.0f);
for (int64_t i = 0; i < r; ++i) {
const double sg = std::sqrt(std::max(0.0, w[(size_t)i]));
if (sg <= 1e-20) continue;
/* B[:, i] = Q V[:, i] sigma_i; A[i] = V[:, i]^T C / sigma_i. */
for (int64_t n = 0; n < N; ++n) {
double acc = 0.0;
for (int64_t j = 0; j < l; ++j) acc += (double)Y[(size_t)(n * l + j)] * V[(size_t)(j * l + i)];
(*B)[(size_t)(n * r + i)] = (float)(acc * sg);
}
for (int64_t k = 0; k < K; ++k) {
double acc = 0.0;
for (int64_t j = 0; j < l; ++j) acc += V[(size_t)(j * l + i)] * Z[(size_t)(k * l + j)];
(*A)[(size_t)(i * K + k)] = (float)(acc / sg);
}
}
}
/* ================================================================== the key map */
namespace {
std::string underscored(std::string s) {
for (char& c : s) if (c == '.') c = '_';
return s;
}
std::regex pattern(const std::string& from, bool kohya) {
std::string re = "^";
for (char c : kohya ? underscored(from) : from) {
if (c == '#') re += "([0-9]+)";
else if (std::strchr(".^$|()[]{}*+?\\", c)) { re += '\\'; re += c; }
else re += c;
}
return std::regex(re + "$", std::regex::ECMAScript | std::regex::optimize);
}
std::string module_of(const std::string& src) {
return ends_with(src, ".weight") ? src.substr(0, src.size() - 7) : std::string();
}
} /* namespace */
KeyMap::KeyMap(const Program& prog, const std::vector<Site>& sites) : prog_(&prog) {
for (const Site& s : sites)
for (size_t i = 0; i < s.sources.size(); ++i) {
const SiteSource& src = s.sources[i];
if (!src.targeted) continue;
const size_t at = src.module.find('@');
if (at != std::string::npos) {
/* A row piece: the module stays adaptable, its rows open (the adapter's say). */
Piece p;
p.name = src.module;
p.lo = std::strtoll(src.module.c_str() + at + 1, nullptr, 10);
const size_t plus = src.module.find('+', at);
p.n = plus == std::string::npos ? 0 : std::strtoll(src.module.c_str() + plus + 1, nullptr, 10);
const std::string real = src.module.substr(0, at);
std::vector<Piece>& ps = pieces_[real];
bool dup = false;
for (const Piece& q : ps) dup = dup || q.name == p.name;
if (!dup) ps.push_back(p);
adaptable_[real] = { -1, s.K_full > 0 ? s.K_full : -1 };
continue;
}
whole_.insert(src.module);
int64_t rows = -1;
if (src.part_lo >= 0) {
rows = 0;
for (int g = src.part_lo; g < src.part_hi; ++g) {
const int64_t t = s.part_total[(size_t)g];
if (t <= 0) { rows = -1; break; }
rows += t;
}
} else if (s.sources.size() == 1 && s.part_total.size() == 1 && s.part_total[0] > 0) {
rows = s.part_total[0];
}
adaptable_[src.module] = { rows, s.K_full > 0 ? s.K_full : -1 };
}
for (const LoraRoot& r : prog.lora_roots) {
Root R;
R.native = r.native;
R.spellings = r.spellings;
R.spellings.push_back(r.native);
std::sort(R.spellings.begin(), R.spellings.end(),
[](const std::string& a, const std::string& b) { return a.size() > b.size(); });
R.spellings.erase(std::unique(R.spellings.begin(), R.spellings.end()), R.spellings.end());
roots_.push_back(std::move(R));
}
for (const RadNameMap& m : prog.name_map)
for (int k = 0; k < m.n_src && k < 8; ++k) {
if (!m.src[k]) continue;
const std::string mod = module_of(m.src[k]);
if (mod.empty()) continue;
for (Root& R : roots_) {
if (mod.compare(0, R.native.size(), R.native) != 0) continue;
if (!adaptable_.count(mod) && !known_.count(mod))
known_[mod] = "the base reads it with an op no adapter path follows (a fused "
"activation, a rotated input, or not a GEMM)";
const std::string u = underscored(mod.substr(R.native.size()));
auto it = R.kohya.find(u);
if (it == R.kohya.end()) R.kohya[u] = mod;
else if (it->second != mod) it->second.clear(); /* ambiguous */
}
}
for (const LoraAlias& a : prog.lora_aliases) {
for (size_t ri = 0; ri < roots_.size(); ++ri) {
if (roots_[ri].native != a.root) continue;
Alias x;
x.root = ri;
x.from = a.from; x.to = a.to;
x.from_lo = a.from_lo; x.from_hi = a.from_hi; x.to_lo = a.to_lo;
x.dotted = pattern(a.from, false);
x.kohya = pattern(a.from, true);
aliases_.push_back(std::move(x));
}
}
}
int64_t KeyMap::rows(const std::string& module) const {
auto it = adaptable_.find(module);
return it == adaptable_.end() ? -1 : it->second.first;
}
const std::vector<KeyMap::Piece>& KeyMap::pieces(const std::string& module) const {
static const std::vector<Piece> none;
auto it = pieces_.find(module);
return it == pieces_.end() ? none : it->second;
}
int64_t KeyMap::cols(const std::string& module) const {
auto it = adaptable_.find(module);
return it == adaptable_.end() ? -1 : it->second.second;
}
bool KeyMap::lookup(const Root& r, const std::string& rel, bool kohya, std::vector<Target>* out,
std::string* why) const {
auto take = [&](const std::string& mod, int64_t lo, int64_t hi, int64_t to) {
if (adaptable_.count(mod)) {
Target t;
t.module = mod; t.from_lo = lo; t.from_hi = hi; t.to_lo = to;
out->push_back(t);
return true;
}
auto k = known_.find(mod);
if (k != known_.end() && why) *why = mod + ": " + k->second;
return false;
};
if (kohya) {
auto it = r.kohya.find(rel);
if (it != r.kohya.end()) {
if (it->second.empty()) { if (why) *why = "its kohya name matches two modules of the base"; }
else if (take(it->second, 0, 0, 0)) return true;
}
} else if (take(r.native + rel, 0, 0, 0)) {
return true;
}
const size_t ri = (size_t)(&r - roots_.data());
for (const Alias& a : aliases_) {
if (a.root != ri) continue;
std::smatch m;
if (!std::regex_match(rel, m, kohya ? a.kohya : a.dotted)) continue;
std::string to;
size_t g = 1;
for (char c : a.to) {
if (c == '#' && g < m.size()) to += m[g++].str();
else to += c;
}
take(r.native + to, a.from_lo, a.from_hi, a.to_lo);
}
return !out->empty();
}
std::vector<Target> KeyMap::resolve(const std::string& key, std::string* why) const {
struct Cand { size_t root; size_t len; bool kohya; };
std::vector<Cand> cs;
for (size_t ri = 0; ri < roots_.size(); ++ri)
for (const std::string& sp : roots_[ri].spellings)
if (key.compare(0, sp.size(), sp) == 0)
cs.push_back({ ri, sp.size(), !sp.empty() && sp.back() == '_' });
std::stable_sort(cs.begin(), cs.end(), [](const Cand& a, const Cand& b) { return a.len > b.len; });
std::vector<Target> out;
std::string first_why;
for (const Cand& c : cs) {
std::string w;
if (lookup(roots_[c.root], key.substr(c.len), c.kohya, &out, &w)) return out;
if (first_why.empty()) first_why = w;
}
if (why) *why = !first_why.empty() ? first_why
: cs.empty() ? std::string("its prefix names no network of this model")
: std::string("no module of this model is named so");
return out;
}
/* ================================================================== composition */
namespace {
struct Part {
std::shared_ptr<Delta> d;
int64_t from_lo = 0, n = 0, to_lo = 0;
};
} /* namespace */
int compose(const KeyMap& km, const std::vector<Strength>& ads, int max_rank,
std::map<std::string, Composite>* out, ComposeReport* rep, std::string* err) {
out->clear();
*rep = ComposeReport{};
std::map<std::string, std::vector<Part>> by;
for (const Strength& s : ads) {
if (!s.file) return fail(err, RAD_E_INVAL, "adapter '" + s.name + "' is not open");
for (const auto& [t, why] : s.file->skipped()) rep->skipped.push_back(s.name + ": " + t + ": " + why);
if (s.weight == 0.0) continue;
for (const FileModule& fm : s.file->modules()) {
std::string why;
const std::vector<Target> ts = km.resolve(fm.key, &why);
if (ts.empty()) { rep->unplaced.push_back(s.name + ": " + fm.key + ": " + why); continue; }
auto d = std::make_shared<Delta>();
std::string e;
if (module_delta(fm, s.weight, d.get(), &e) < 0)
return fail(err, RAD_E_FORMAT, s.name + ": " + e);
for (const Target& t : ts) {
Part p;
p.d = d;
p.from_lo = t.from_lo;
p.n = (t.from_hi > 0 ? t.from_hi : d->N) - t.from_lo;
p.to_lo = t.to_lo;
if (p.n <= 0 || t.from_lo + p.n > d->N)
return fail(err, RAD_E_SHAPE, fmt("%s: %s has %lld output rows; the base's alias "
"takes rows [%lld, %lld) of it for %s",
s.name.c_str(), fm.key.c_str(), (long long)d->N,
(long long)t.from_lo, (long long)(t.from_lo + p.n),
t.module.c_str()));
by[t.module].push_back(p);
}
}
}
std::vector<std::string> names;
for (auto& [k, v] : by) { names.push_back(k); (*out)[k]; }
std::vector<std::string> errs(names.size());
std::vector<double> kept(names.size(), 1.0);
std::vector<char> exact(names.size(), 1);
std::atomic<size_t> next{ 0 };
auto work = [&]() {
for (size_t i; (i = next.fetch_add(1)) < names.size();) {
const std::string& mod = names[i];
const std::vector<Part>& ps = by.find(mod)->second;
Composite& c = out->find(mod)->second;
int64_t rows = km.rows(mod), K = km.cols(mod);
int64_t extent = 0;
for (const Part& p : ps) extent = std::max(extent, p.to_lo + p.n);
for (const KeyMap::Piece& pc : km.pieces(mod)) extent = std::max(extent, pc.lo + pc.n);
if (rows < 0) rows = extent;
if (K < 0) K = ps[0].d->K;
bool lr = true;
int64_t R = 0, bound = 0;
for (const Part& p : ps) {
if (p.d->K != K) {
errs[i] = fmt("%s: an adapter's delta has %lld input columns, the base's module "
"%lld", mod.c_str(), (long long)p.d->K, (long long)K);
break;
}
if (p.to_lo + p.n > rows) {
errs[i] = fmt("%s: an adapter's delta reaches row %lld of a module of %lld rows",
mod.c_str(), (long long)(p.to_lo + p.n), (long long)rows);
break;
}
lr = lr && p.d->low_rank;
R += p.d->low_rank ? p.d->r : 0;
bound += p.d->rank_bound;
}
if (!errs[i].empty()) continue;
c.rows = rows; c.K = K;
if (lr && R <= max_rank) {
/* Side by side: every delta its own block of ranks. */
c.r = R;
c.B.assign((size_t)(rows * R), 0.0f);
c.A.assign((size_t)(R * K), 0.0f);
int64_t o = 0;
for (const Part& p : ps) {
const Delta& d = *p.d;
for (int64_t row = 0; row < p.n; ++row)
std::memcpy(&c.B[(size_t)((p.to_lo + row) * R + o)],
&d.B[(size_t)((p.from_lo + row) * d.r)], (size_t)d.r * 4);
std::memcpy(&c.A[(size_t)(o * K)], d.A.data(), (size_t)(d.r * K) * 4);
o += d.r;
}
continue;
}
/* The sum, as one operator over the module's rows, truncated to the slot's rank. */
exact[i] = 0;
Delta sum;
sum.N = rows; sum.K = K; sum.rank_bound = bound;
/* One whole delta's energy is known; a sum's or a row slice's is what the sketch
* holds, exact when its rank is within the sketch's. */
sum.energy = ps.size() == 1 && ps[0].from_lo == 0 && ps[0].n == ps[0].d->N
? ps[0].d->energy : -1.0;
sum.apply = [&ps, rows](const float* X, int64_t l, float* Y) {
std::fill(Y, Y + rows * l, 0.0f);
for (const Part& p : ps) {
const Delta& d = *p.d;
std::vector<float> y((size_t)(d.N * l));
if (d.low_rank) {
std::vector<float> t((size_t)(d.r * l));
mm(d.A.data(), X, t.data(), d.r, d.K, l);
mm(d.B.data(), t.data(), y.data(), d.N, d.r, l);
} else {
d.apply(X, l, y.data());
}
for (int64_t row = 0; row < p.n; ++row)
for (int64_t j = 0; j < l; ++j)
Y[(p.to_lo + row) * l + j] += y[(size_t)((p.from_lo + row) * l + j)];
}
};
sum.apply_t = [&ps, K](const float* Yin, int64_t l, float* X) {
std::fill(X, X + K * l, 0.0f);
std::vector<float> x((size_t)(K * l));
for (const Part& p : ps) {
const Delta& d = *p.d;
std::vector<float> y((size_t)(d.N * l), 0.0f);
for (int64_t row = 0; row < p.n; ++row)
for (int64_t j = 0; j < l; ++j)
y[(size_t)((p.from_lo + row) * l + j)] = Yin[(p.to_lo + row) * l + j];
if (d.low_rank) {
std::vector<float> t((size_t)(d.r * l));
mm_tn(d.B.data(), y.data(), t.data(), d.r, d.N, l);
mm_tn(d.A.data(), t.data(), x.data(), d.K, d.r, l);
} else {
d.apply_t(y.data(), l, x.data());
}
for (int64_t k = 0; k < K * l; ++k) X[k] += x[(size_t)k];
}
};
truncate(sum, max_rank, &c.B, &c.A, &kept[i]);
c.r = (int64_t)(c.A.size() / (size_t)(K > 0 ? K : 1));
/* Kept energy is exact when the sum is low-rank: ||B A||^2 of the parts side by side. */
if (lr) {
std::vector<float> Bc((size_t)(rows * R), 0.0f), Ac((size_t)(R * K), 0.0f);
int64_t o = 0;
for (const Part& p : ps) {
const Delta& d = *p.d;
for (int64_t row = 0; row < p.n; ++row)
std::memcpy(&Bc[(size_t)((p.to_lo + row) * R + o)],
&d.B[(size_t)((p.from_lo + row) * d.r)], (size_t)d.r * 4);
std::memcpy(&Ac[(size_t)(o * K)], d.A.data(), (size_t)(d.r * K) * 4);
o += d.r;
}
const double tot = lowrank_energy(Bc, Ac, rows, R, K);
const double got = lowrank_energy(c.B, c.A, rows, c.r, K);
kept[i] = tot > 0.0 ? std::min(1.0, got / tot) : 1.0;
}
}
};
const unsigned hw = std::max(1u, std::min(16u, std::thread::hardware_concurrency()));
std::vector<std::thread> th;
for (unsigned t = 1; t < hw && t < names.size(); ++t) th.emplace_back(work);
work();
for (std::thread& t : th) t.join();
for (size_t i = 0; i < names.size(); ++i) {
if (!errs[i].empty()) return fail(err, RAD_E_SHAPE, errs[i]);
++rep->modules;
/* Held exactly: side by side, or an operator whose rank fits (LoKr, LoHa within R). */
if (exact[i] || kept[i] >= 0.9999) ++rep->exact;
else if (kept[i] < rep->worst_kept) { rep->worst_kept = kept[i]; rep->worst_module = names[i]; }
}
return RAD_OK;
}
std::map<std::string, AdModule> as_modules(std::map<std::string, Composite>& c, const KeyMap& km) {
std::map<std::string, AdModule> m;
for (auto& [name, x] : c) {
if (x.r <= 0) continue;
const std::vector<KeyMap::Piece>& pcs = km.pieces(name);
x.tPieces.assign(pcs.size(), StTensor{});
x.tA = StTensor{};
x.tA.name = name + ".A";
x.tA.dtype = RAD_F32;
x.tA.dtype_str = "F32";
x.tA.shape = { x.r, x.K };
x.tA.bytes = x.A.size() * 4;
x.tA.data = (const uint8_t*)x.A.data();
x.tB = StTensor{};
x.tB.name = name + ".B";
x.tB.dtype = RAD_F32;
x.tB.dtype_str = "F32";
x.tB.shape = { x.rows, x.r };
x.tB.bytes = x.B.size() * 4;
x.tB.data = (const uint8_t*)x.B.data();
AdModule a;
a.name = name;
a.A = &x.tA;
a.B = &x.tB;
a.rank = x.r;
a.alpha = (double)x.r;
a.scale = 1.0f;
if (pcs.empty() || km.whole(name)) m[name] = a;
for (size_t i = 0; i < pcs.size(); ++i) {
StTensor& t = x.tPieces[i];
t = x.tB;
t.name = pcs[i].name + ".B";
t.shape = { pcs[i].n, x.r };
t.bytes = (uint64_t)(pcs[i].n * x.r) * 4;
t.data = (const uint8_t*)(x.B.data() + pcs[i].lo * x.r);
AdModule p = a;
p.name = pcs[i].name;
p.B = &t;
m[p.name] = p;
}
}
return m;
}
} /* namespace lora */
} /* namespace rad */
+183
View File
@@ -0,0 +1,183 @@
/* lora/adapter.h -- adapter files as image and video generators receive them, and the bytes of a
* slot holding one or several of them at chosen strengths.
*
* An adapter for a generator is one safetensors file, written by whichever tool trained or
* converted it, so the same delta arrives under several spellings:
*
* LoRA `<m>.lora_down.weight` / `<m>.lora_up.weight` (+ `<m>.alpha`): kohya, ComfyUI;
* `<m>.lora_A[.default].weight` / `<m>.lora_B[...]` (+ `.alpha`): PEFT, diffusers, ai-toolkit;
* `<m>.lora.down.weight` / `<m>.lora.up.weight`; `<m>.lora_linear_layer.down/up.weight`.
* delta = alpha / rank * up @ down; no alpha is a scale of 1. A convolution's down is
* [rank, cin, kh, kw] and its up [cout, rank, 1, 1], read as the flattened matrices.
* LoHa `<m>.hada_w1_a/_w1_b/_w2_a/_w2_b` (+ alpha): delta = alpha / rank1 *
* (w1_a @ w1_b) * (w2_a @ w2_b), elementwise; exactly a rank1 * rank2 product of
* row-wise Kronecker factors.
* LoKr `<m>.lokr_w1` or `_w1_a`/`_w1_b`, `<m>.lokr_w2` or `_w2_a`/`_w2_b` (+ alpha):
* delta = scale * kron(w1, w2), scale alpha / rank of a decomposed factor, else 1.
* full `<m>.diff`: the delta itself.
*
* Every module becomes a Delta, a linear map with its strength folded in. A slot holds, for each
* checkpoint module the adapters reach, the sum of the deltas that land there: the low-rank ones
* side by side while their ranks fit the slot's rank (exact), otherwise the sum's best rank-R
* approximation (a randomized SVD; the fraction of the delta's energy it keeps is reported).
*
* Where a module lands is the generator's own declaration (rad_lora_root, rad_lora_alias): a
* key's prefix names the network, its path the checkpoint module directly or through an alias,
* kohya's underscore form matched against the same names. */
#pragma once
#include "lora.h"
#include "../format/safetensors.h"
#include <functional>
#include <map>
#include <memory>
#include <regex>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
namespace rad {
namespace lora {
/* One module of an adapter file, before it is mapped onto the base. */
struct FileModule {
enum Kind { LORA, LOHA, LOKR, FULL };
std::string key; /* the module as the file spells it, tensor suffix removed */
Kind kind = LORA;
/* LORA: down, up. LOHA: w1_a, w1_b, w2_a, w2_b. LOKR: w1, w1_a, w1_b, w2, w2_a, w2_b.
* FULL: diff. */
const StTensor* t[6] = {};
const StTensor* alpha = nullptr;
};
class AdapterFile {
public:
/* Opens and groups the file's tensors by module. Refuses a file holding a form whose effect
* this engine cannot reproduce (DoRA's magnitude, OFT, Tucker cores), naming it. */
int open(const std::string& path, std::string* err);
const std::string& path() const { return st_.path(); }
const std::vector<FileModule>& modules() const { return mods_; }
/* Tensors that change no linear (a trained bias, a norm's weight), with why; reported, not
* applied. */
const std::vector<std::pair<std::string, std::string>>& skipped() const { return skipped_; }
/* The most common kind among the modules, for messages ("LoRA", "LoHa", ...). */
const char* kind_name() const;
private:
SafeTensorsFile st_;
std::vector<FileModule> mods_;
std::vector<std::pair<std::string, std::string>> skipped_;
};
/* A module's delta as a linear map [N, K] with its scale and strength folded in. Low-rank forms
* keep their factors (B [N, r] and A [r, K], row-major); the rest are applied as operators to
* blocks of `l` column vectors (X [K, l] -> Y [N, l], and the transpose), all f32. */
struct Delta {
int64_t N = 0, K = 0;
int64_t rank_bound = 0;
double energy = -1.0; /* ||delta||_F^2, -1 when not known */
bool low_rank = false;
int64_t r = 0;
std::vector<float> B, A;
std::function<void(const float* X, int64_t l, float* Y)> apply, apply_t;
};
/* The delta of one module at strength `w`. RAD_E_SHAPE / RAD_E_DTYPE / RAD_E_FORMAT name the
* tensor. */
int module_delta(const FileModule& m, double w, Delta* out, std::string* err);
/* Rank-`r` factors of a delta given as an operator (randomized range finder, two power
* iterations): B [N, r], A [r, K]. `kept` is the fraction of the squared Frobenius norm kept, of
* Delta::energy when known and of what the sketch holds otherwise (1 when the delta's rank is at
* most r). */
void truncate(const Delta& d, int64_t r, std::vector<float>* B, std::vector<float>* A,
double* kept);
/* Where an adapter module lands in the base: rows [from_lo, from_hi) of its output (from_hi 0 =
* all) at rows from `to_lo` of the checkpoint module `module`. */
struct Target {
std::string module;
int64_t from_lo = 0, from_hi = 0, to_lo = 0;
};
/* The generator's key names over one rank's Program and sites. */
class KeyMap {
public:
KeyMap(const Program& prog, const std::vector<Site>& sites);
/* The targets of a file's module key; empty with `why` when it lands nowhere adaptable. */
std::vector<Target> resolve(const std::string& key, std::string* why) const;
/* A checkpoint module's full rows and columns as the sites record them, or -1 when the
* declaration leaves them open. */
int64_t rows(const std::string& module) const;
int64_t cols(const std::string& module) const;
/* The row pieces a module is cut into (RAD_MAP_ROWS; core/lora/lora.cpp names each
* `<module>@<first row>+<rows>`), empty for a module the sites read whole; and whether a site
* also reads it whole. */
struct Piece { std::string name; int64_t lo = 0, n = 0; };
const std::vector<Piece>& pieces(const std::string& module) const;
bool whole(const std::string& module) const { return whole_.count(module) != 0; }
private:
struct Root {
std::string native;
std::vector<std::string> spellings;
std::unordered_map<std::string, std::string> kohya; /* underscored rel -> module */
};
struct Alias {
size_t root;
std::string from, to;
int64_t from_lo, from_hi, to_lo;
std::regex dotted, kohya;
};
bool lookup(const Root& r, const std::string& rel, bool kohya, std::vector<Target>* out,
std::string* why) const;
const Program* prog_;
std::vector<Root> roots_;
std::vector<Alias> aliases_;
std::unordered_map<std::string, std::pair<int64_t, int64_t>> adaptable_; /* -> rows, cols */
std::unordered_map<std::string, std::string> known_; /* module -> why not adaptable */
std::unordered_map<std::string, std::vector<Piece>> pieces_;
std::set<std::string> whole_;
};
/* One adapter at a strength, for compose(). */
struct Strength {
std::string name;
std::shared_ptr<const AdapterFile> file;
double weight = 1.0;
};
/* What compose() did, for the log and the client. */
struct ComposeReport {
int64_t modules = 0; /* checkpoint modules the slot carries */
int64_t exact = 0; /* ... held exactly */
double worst_kept = 1.0; /* lowest kept energy among the truncated */
std::string worst_module;
std::vector<std::string> unplaced; /* "<adapter>: <key>: why" */
std::vector<std::string> skipped; /* "<adapter>: <tensor>: why" */
};
/* The factors of a composite, per checkpoint module: B [rows, r] and A [r, K], f32, held by the
* caller while the packer reads them. */
struct Composite {
int64_t rows = 0, K = 0, r = 0;
std::vector<float> B, A;
StTensor tA, tB;
std::vector<StTensor> tPieces; /* B's row ranges, one per piece of the module */
};
/* The sum of the adapters' deltas per checkpoint module, at most `max_rank` each. Unplaced
* modules are reported, not refused, as UIs do. RAD_E_SHAPE when a module's shape disagrees with
* the base's. */
int compose(const KeyMap& km, const std::vector<Strength>& ads, int max_rank,
std::map<std::string, Composite>* out, ComposeReport* rep, std::string* err);
/* The packer's view of a composite (scale 1: the strengths and alphas are folded into B): a
* module under its own name where a site reads it whole, and each of its row pieces under the
* piece's name. */
std::map<std::string, AdModule> as_modules(std::map<std::string, Composite>& c, const KeyMap& km);
} /* namespace lora */
} /* namespace rad */
+26 -11
View File
@@ -1,9 +1,14 @@
/* lora/config.h -- what runtime LoRA was started with (--lora, --max-loras, --max-lora-rank,
* --lora-target-modules). Read by declare (which sites and pools exist), by the adapter manager
* (what may be loaded into them) and by nothing else.
/* lora/config.h -- what runtime LoRA was started with (--lora, --lora-dir, --max-loras,
* --max-lora-rank, --lora-target-modules). Read by declare (which sites and pools exist), by the
* adapter manager (what may be loaded into them) and by nothing else.
*
* Off unless asked for: with no adapter named and no --max-loras, `enabled()` is false, declare
* appends nothing, the program has no pool and no extra op, and no step carries an adapter slot. */
* Off unless asked for: with no adapter named, no --lora-dir and no --max-loras, `enabled()` is
* false, declare appends nothing, the program has no pool and no extra op, and no step carries an
* adapter slot.
*
* A text model's slot holds one adapter; a generator's holds the combination one request asks for
* (several adapter files at their strengths, core/lora/adapter.h), so its slots are not tied to
* the number of adapters named. */
#pragma once
#include <string>
#include <utility>
@@ -12,20 +17,30 @@
namespace rad {
struct LoraConfig {
/* NAME=PATH pairs to load at startup, in the order given. */
/* NAME=PATH pairs to load at startup, in the order given: a PEFT directory, or for a
* generator one .safetensors file. */
std::vector<std::pair<std::string, std::string>> adapters;
/* Adapter slots resident at once. 0 with adapters named means "as many as were named". */
/* A generator's adapter directory: a request may name any NAME.safetensors under it. */
std::string dir;
/* Adapter slots resident at once. 0: as many as were named, and two with --lora-dir alone. */
int max_loras = 0;
/* The rank every slot is sized for; an adapter of lower rank is zero-padded into it. */
int max_rank = 16;
/* The rank every slot is sized for; an adapter of lower rank is zero-padded into it. 0: the
* default, kDefaultRank for a text model and kDefaultGenRank for a generator, whose adapter
* files run to rank 32 and are stacked. */
int max_rank = 0;
static constexpr int kDefaultRank = 16, kDefaultGenRank = 64;
int rank(bool generator) const {
return max_rank > 0 ? max_rank : generator ? kDefaultGenRank : kDefaultRank;
}
/* HF module leaf names (q_proj, gate_proj, in_proj_qkv, ...) the sites are built for, sorted
* and unique. Empty: the union of the startup adapters' target_modules. */
std::vector<std::string> targets;
bool enabled() const { return max_loras > 0 || !adapters.empty(); }
bool enabled() const { return max_loras > 0 || !adapters.empty() || !dir.empty(); }
int slots() const {
const int named = (int)adapters.size();
return max_loras > 0 ? (max_loras > named ? max_loras : named) : named;
if (max_loras > 0) return max_loras;
return named > 0 ? named : (dir.empty() ? 0 : 2);
}
};
+99 -12
View File
@@ -3,6 +3,7 @@
#include "build/rad_build.h"
#include "rad_internal.h"
#include <algorithm>
#include <cstring>
#include <map>
#include <string>
@@ -73,23 +74,36 @@ rad_buf decl_persist(Builder& b, const std::string& name, uint32_t dtype, uint32
} /* namespace */
/* A generator pass's adapter ops run over at most this many rows at a time: large enough that the
* kernels' row tiles are all busy, small enough that `t` for the largest rank is a few MiB. */
constexpr int64_t kGenChunk = 8192;
int lora_declare(Builder& b, const LoraDeclare& d) {
if (!d.cfg || !d.cfg->enabled()) return RAD_OK;
Program& P = b.program();
/* Adapters are chosen per request and applied on the token steps of a model that writes
* logits; a generator's passes and an embedding model's requests carry no adapter. */
if (P.is_pass_driven() || P.pooled_buf != RAD_NULL_HANDLE ||
P.logits_buf == RAD_NULL_HANDLE) {
RAD_ERR("lora: runtime LoRA adapters serve a model that generates text, and this one %s",
P.is_pass_driven() ? "is an image, audio or video generator"
* logits, or on every pass of a generator that names its adapter keys (rad_lora_root); an
* embedding model's requests carry no adapter. */
const bool gen = P.is_pass_driven();
if (gen ? P.lora_roots.empty()
: (P.pooled_buf != RAD_NULL_HANDLE || P.logits_buf == RAD_NULL_HANDLE)) {
RAD_ERR("lora: runtime LoRA adapters serve a model that generates text, or a generator "
"that declares how adapter files name its modules, and this one %s",
gen ? "is a generator that declares no adapter "
"key names (rad_lora_root)"
: P.pooled_buf != RAD_NULL_HANDLE ? "makes embeddings"
: "declares no logits");
return RAD_E_UNSUPPORTED;
}
if (!gen && d.targets.count("*")) {
RAD_ERR("lora: an adapter without adapter_config.json names no target modules, and a "
"text model has no default set; give them with --lora-target-modules");
return RAD_E_UNSUPPORTED;
}
const int S = d.cfg->slots();
const int max_rank = d.cfg->max_rank;
const int max_rank = d.cfg->rank(gen);
const int64_t max_tok = P.ctx.max_tok;
if (S <= 0 || max_rank <= 0 || max_tok <= 0) {
if (S <= 0 || max_rank <= 0 || (!gen && max_tok <= 0)) {
RAD_ERR("lora: %d slots of rank %d over steps of %lld tokens is not a configuration", S,
max_rank, (long long)max_tok);
return RAD_E_INVAL;
@@ -150,6 +164,26 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
}
}
/* ---- a token step's rows are its tokens; a generator pass's are each GEMM's own, issued in
* chunks of at most kGenChunk rows (Ctx::issue_lora), so `t` holds one chunk. */
int64_t rows = max_tok;
if (gen) {
rows = 0;
for (const lora::Site& x : sites)
if (x.gemm > 0 && x.gemm < P.ops.size()) rows = std::max(rows, P.ops[x.gemm].range_hi);
rows = std::min<int64_t>(rows, kGenChunk);
}
/* On the real declare, what the adapters cost: the pools are persistent buffers, so the
* arena plan (and with it what is left for weights and the KV cache) holds them. */
if (d.sites_out) {
int64_t slot_bytes = 0;
for (const LoraPool& p : P.lora_pools) slot_bytes += 2 * p.R * p.K + 2 * p.N * p.R + 4 * p.N;
RAD_INFO("lora: %zu weights carry adapters, %d slots of rank %d, %s a slot on this rank, "
"%s in all (--max-loras, --max-lora-rank)", P.lora_pools.size(), S, max_rank,
humanb(slot_bytes).c_str(), humanb(slot_bytes * S).c_str());
}
/* ---- t = A.x, one f32 plane per capacity R and lane. Persistent, not transient: the ops that
* use it run at the GEMM's position, but the buffer plan would place a transient at the
* appended ops' own position, the end of the program, and share its bytes with buffers live
@@ -160,7 +194,7 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
if (t_by_r.count(x.R)) continue;
LoraScratch sc;
sc.R = x.R;
const int64_t sh[2] = { max_tok, x.R };
const int64_t sh[2] = { rows, x.R };
for (int l = 0; l < 2; ++l) {
sc.lane[l] = decl_persist(b, fmt("lora.t.r%lld.lane%d", (long long)x.R, l), RAD_F32, 2, sh);
if (!sc.lane[l]) return RAD_E_STATE;
@@ -169,9 +203,21 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
P.lora_t.push_back(sc);
}
/* ---- a generator pass's slot operand: elements [s rows, (s + 1) rows) of an [S rows] i32
* buffer, every one s (filled when the engine starts adapters) */
P.lora_rows = 0;
P.lora_rows_n = 0;
if (gen && rows > 0) {
const int64_t sh[1] = { S * rows };
P.lora_rows = decl_persist(b, "lora.slot_rows", RAD_I32, 1, sh);
if (!P.lora_rows) return RAD_E_STATE;
P.lora_rows_n = rows;
}
/* ---- the two ops behind each targeted GEMM */
P.lora_sites.clear();
int n_refused = 0;
std::vector<char> dropped(sites.size(), 0);
for (lora::Site& x : sites) {
const uint32_t gh = x.gemm;
if (gh == 0 || gh >= P.ops.size()) return RAD_E_STATE;
@@ -186,7 +232,15 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
const int oa = opd_index(g, "a"), oas = opd_index(g, "a_scale"), oy = opd_index(g, "y");
const std::vector<rad_buf> reads = b.op_read_set(gh), writes = b.op_write_set(gh);
/* A text model's targeted GEMM that cannot carry the ops is refused; a generator's, whose
* every plain GEMM is a candidate, stays the base and its modules are reported unplaced. */
auto refuse = [&](const std::string& why) {
if (gen) {
RAD_WARN("lora: op %u '%s' over '%s' carries no adapter: %s", gh, gop.c_str(),
x.weight.c_str(), why.c_str());
dropped[(size_t)(&x - sites.data())] = 1;
return;
}
RAD_ERR("lora: op %u '%s' over '%s': %s", gh, gop.c_str(), x.weight.c_str(), why.c_str());
++n_refused;
};
@@ -223,9 +277,14 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
sp[n_sp++] = RAD_STR("dtype", rad_dtype_name(a_dt));
const rad_op hs = b.decl_op("lora_shrink", sp, n_sp, nullptr, 0);
const RadParam ep[5] = { RAD_RANGE("M", lo, hi), RAD_INT("N", x.N_r), RAD_INT("R", x.R),
RAD_INT("S", S), RAD_STR("dtype", rad_dtype_name(y_dt)) };
const rad_op he = b.decl_op("lora_expand", ep, 5, nullptr, 0);
RadParam ep[5] = { RAD_RANGE("M", lo, hi), RAD_INT("N", x.N_r), RAD_INT("R", x.R),
RAD_INT("S", S), RAD_STR("dtype", rad_dtype_name(y_dt)) };
/* A generator's passes are many rows of one adapter: its expand runs on the WMMA
* (lora_expand_mm) where a library has it. A token step keeps the exact row, whose bytes
* do not depend on the batch. */
const char* expand_op = gen && b.op_declared("lora_expand_mm") ? "lora_expand_mm"
: "lora_expand";
const rad_op he = b.decl_op(expand_op, ep, 5, nullptr, 0);
if (!hs || !he) {
refuse(fmt("no kernel resolves lora_%s for an activation of %s and an output of %s",
!hs ? "shrink" : "expand", rad_dtype_name(a_dt), rad_dtype_name(y_dt)));
@@ -233,6 +292,28 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
}
LoraIssueSite is;
/* A generator's slot packs its ranks from 0 (lora::pack_modules, compact): pairs that read
* the first half and quarter of R, so a rank-16 adapter in a slot sized 64 a module costs
* a quarter. Multiples of 16, the WMMA's step. */
if (gen) {
int64_t prev = x.R;
for (int v = 0; v < 2; ++v) {
const int64_t rv = ((x.R >> (v + 1)) + 15) / 16 * 16;
if (rv < 16 || rv >= prev) break;
RadParam vs[6];
for (int i = 0; i < n_sp; ++i) vs[i] = sp[i];
vs[2] = RAD_INT("R", rv);
ep[2] = RAD_INT("R", rv);
const rad_op vs_op = b.decl_op("lora_shrink", vs, n_sp, nullptr, 0);
const rad_op ve_op = b.decl_op(expand_op, ep, 5, nullptr, 0);
if (!vs_op || !ve_op) break;
P.ops[vs_op].anchor = (int32_t)gh;
P.ops[ve_op].anchor = (int32_t)gh;
is.shrink_v[v] = vs_op; is.expand_v[v] = ve_op; is.R_v[v] = rv;
is.n_v = (int8_t)(v + 1);
prev = rv;
}
}
is.gemm = gh; is.shrink = hs; is.expand = he;
is.opd_a = (int8_t)oa;
is.opd_a_scale = (int8_t)(coded ? oas : -1);
@@ -248,7 +329,13 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
}
if (n_refused) return RAD_E_UNSUPPORTED;
if (d.sites_out) *d.sites_out = std::move(sites);
if (gen) P.lora_rused.assign(P.lora_pools.size() * (size_t)S, 0);
if (d.sites_out) {
std::vector<lora::Site> kept;
for (size_t i = 0; i < sites.size(); ++i)
if (!dropped[i]) kept.push_back(std::move(sites[i]));
*d.sites_out = std::move(kept);
}
return RAD_OK;
}
+108 -32
View File
@@ -88,8 +88,13 @@ bool excluded_source(const std::string& src) {
return false;
}
/* A generator that declared adapter key names (rad_lora_root): its scope is those roots, every
* matrix under one of them, and none of the token model's rules below apply. */
bool gen_scope(const Program& prog) { return !prog.lora_roots.empty(); }
const char* excluded_weight(const Program& prog, const WeightInfo& w) {
if (w.decl.access == RAD_ACCESS_VOCAB) return "a vocabulary weight (embedding / lm_head)";
if (gen_scope(prog)) return w.decl.rank == 2 ? nullptr : "not a matrix";
if (w.decl.access == RAD_ACCESS_PER_REQUEST) return "an encoder tower weight (per-request access)";
if (prog.meta.n_layers > 0 && w.decl.group.layer >= prog.meta.n_layers)
return "a drafter / MTP layer (layer group at or above meta.n_layers)";
@@ -121,8 +126,23 @@ void scan_maps(const Program& prog, const std::string& declared,
struct MapIndex {
std::unordered_map<std::string, std::vector<const RadNameMap*>> by;
explicit MapIndex(const Program& prog) {
for (const RadNameMap& m : prog.name_map)
if (m.declared) by[m.declared].push_back(&m);
/* An entry repeated whole (a plugin's encoding probe maps the weight it then declares) is
* one entry. */
auto same = [](const RadNameMap& a, const RadNameMap& b) {
if (a.mode != b.mode || a.n_src != b.n_src || a.concat_dim != b.concat_dim) return false;
for (int k = 0; k < a.n_src && k < 8; ++k)
if (std::strcmp(a.src[k] ? a.src[k] : "", b.src[k] ? b.src[k] : "") != 0 ||
a.src_index[k] != b.src_index[k] || a.src_rows[k] != b.src_rows[k])
return false;
return true;
};
for (const RadNameMap& m : prog.name_map) {
if (!m.declared) continue;
std::vector<const RadNameMap*>& v = by[m.declared];
bool dup = false;
for (const RadNameMap* x : v) dup = dup || same(*x, m);
if (!dup) v.push_back(&m);
}
}
const std::vector<const RadNameMap*>* find(const std::string& d) const {
auto it = by.find(d);
@@ -130,19 +150,27 @@ struct MapIndex {
}
};
/* Is checkpoint tensor `src` an adapter target? A token model: its leaf is in the target list and
* it is in the trunk. A generator: it is under a declared root, and its leaf is in the list or the
* list is "*". */
bool source_targeted(const Program& prog, const TargetSet& targets, const std::string& src) {
std::string leaf;
if (module_of(src, &leaf).empty()) return false;
if (!gen_scope(prog)) return targets.count(leaf) && !excluded_source(src);
if (!targets.count("*") && !targets.count(leaf)) return false;
for (const LoraRoot& r : prog.lora_roots)
if (src.compare(0, r.native.size(), r.native) == 0) return true;
return false;
}
/* weight_targeted(), over the maps already found. */
bool targeted_core(const Program& prog, const WeightInfo& w,
const std::vector<const RadNameMap*>& maps, const TargetSet& targets) {
if (targets.empty() || maps.empty()) return false;
if (excluded_weight(prog, w)) return false;
for (const RadNameMap* m : maps)
for (int k = 0; k < m->n_src && k < 8; ++k) {
if (!m->src[k]) continue;
const std::string src = m->src[k];
std::string leaf;
if (module_of(src, &leaf).empty()) continue;
if (targets.count(leaf) && !excluded_source(src)) return true;
}
for (int k = 0; k < m->n_src && k < 8; ++k)
if (m->src[k] && source_targeted(prog, targets, m->src[k])) return true;
return false;
}
@@ -464,40 +492,46 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets,
if (!maps || maps->empty())
return fail(err, RAD_E_NOTFOUND, fmt("weight '%s' has no name-map entry", W.name.c_str()));
std::vector<std::string> srcs;
/* A row piece of a checkpoint tensor (RAD_MAP_ROWS) is a source of its own, named
* `<module>@<first row>+<rows>`: the adapter's B rows it takes are that range of the
* module's. */
std::vector<std::string> piece;
const bool alternatives = maps->size() == 1 && (*maps)[0]->mode == RAD_MAP_COPY &&
(*maps)[0]->n_src > 1;
for (const RadNameMap* m : *maps)
for (int k = 0; k < m->n_src && k < 8; ++k) {
if (m->src_index[k] >= 0)
const bool rows = m->mode == RAD_MAP_ROWS;
if (!rows && m->src_index[k] >= 0)
return fail(err, RAD_E_UNSUPPORTED,
fmt("weight '%s' is slice %d of the stacked checkpoint tensor %s; a "
"LoRA on a stacked (expert) tensor is not supported",
W.name.c_str(), m->src_index[k], m->src[k]));
srcs.push_back(m->src[k] ? m->src[k] : "");
piece.push_back(rows ? fmt("@%d+%lld", m->src_index[k], (long long)m->src_rows[k]) : "");
}
if (alternatives) {
/* COPY with alternatives: the first one the container holds is the weight, and which one
* that is is not recorded. Usable only when exactly one alternative is targeted. */
std::vector<std::string> hit;
for (const std::string& x : srcs) {
std::string leaf;
if (!module_of(x, &leaf).empty() && targets.count(leaf) && !excluded_source(x))
hit.push_back(x);
}
for (const std::string& x : srcs)
if (source_targeted(prog, targets, x)) hit.push_back(x);
if (hit.size() != 1)
return fail(err, RAD_E_UNSUPPORTED,
fmt("weight '%s' is one of %zu alternative checkpoint tensors and %zu of "
"them are targeted; which one the container holds is not recorded",
W.name.c_str(), srcs.size(), hit.size()));
srcs = hit;
piece.assign(srcs.size(), "");
}
int slot = 0;
for (const std::string& x : srcs) {
for (size_t si = 0; si < srcs.size(); ++si) {
const std::string& x = srcs[si];
SiteSource ss;
std::string leaf;
ss.module = module_of(x, &leaf);
if (ss.module.empty()) ss.module = x;
ss.targeted = !leaf.empty() && targets.count(leaf) && !excluded_source(x);
ss.module += piece[si];
ss.targeted = source_targeted(prog, targets, x);
if (ss.targeted) ss.slot = slot++;
s.sources.push_back(ss);
}
@@ -544,6 +578,8 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets,
/* ================================================================== predicates */
bool weight_targeted(const Program& prog, rad_weight w, const TargetSet& targets) {
if (targets.empty() || w == 0 || w >= prog.weights.size()) return false;
/* A generator's fused GEMMs are kept: its scope is the plain GEMMs (build_sites). */
if (gen_scope(prog)) return false;
const WeightInfo& wi = prog.weights[w];
if (excluded_weight(prog, wi)) return false;
std::vector<const RadNameMap*> maps;
@@ -598,7 +634,7 @@ bool op_is_site(const Program& prog, const OpInfo& op, rad_weight* b_out, std::s
int find_unsupported_uses(const Program& prog, const TargetSet& targets,
std::vector<UnsupportedUse>* out) {
if (out) out->clear();
if (targets.empty()) return 0;
if (targets.empty() || gen_scope(prog)) return 0;
const MapIndex mi(prog);
int n = 0;
for (size_t i = 1; i < prog.ops.size(); ++i) {
@@ -642,14 +678,47 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank,
if (max_rank <= 0) return fail(err, RAD_E_INVAL, fmt("max LoRA rank %d", max_rank));
if (targets.empty()) return RAD_OK;
const MapIndex mi(prog);
/* A generator's weight carries an adapter only when every op reading it is a site over it; one
* read elsewhere (a fused GEMM, a non-GEMM op) stays the base everywhere. */
std::set<std::string> other_reader;
if (gen_scope(prog))
for (size_t i = 1; i < prog.ops.size(); ++i) {
const OpInfo& op = prog.ops[i];
if (op.weights.empty() || !op_live(op)) continue;
rad_weight b = 0;
const bool site = op_is_site(prog, op, &b, nullptr);
for (rad_weight h : op.weights)
if (h && h < prog.weights.size() &&
(!site || !b || prog.weights[b].source != prog.weights[h].source))
other_reader.insert(prog.weights[h].source);
}
std::map<rad_weight, int32_t> pool_of;
std::vector<size_t> first_site;
for (size_t i = 1; i < prog.ops.size(); ++i) {
rad_weight b = 0;
if (!op_live(prog.ops[i]) || !op_is_site(prog, prog.ops[i], &b, nullptr)) continue;
if (!targeted_idx(prog, mi, b, targets)) continue;
if (other_reader.count(prog.weights[b].source)) continue;
if (gen_scope(prog)) {
/* Checkpoint tensors copied, joined, transposed or cut into row pieces carry a
* generator's adapter; a folded or derived one (weight norm, EMA) stays the base. */
bool whole = true;
if (const auto* maps = mi.find(prog.weights[b].source))
for (const RadNameMap* m : *maps)
whole = whole && (m->mode == RAD_MAP_COPY || m->mode == RAD_MAP_CONCAT ||
m->mode == RAD_MAP_TRANSPOSE || m->mode == RAD_MAP_ROWS);
if (!whole) continue;
}
Site s;
const int st = make_site(prog, mi, targets, max_rank, (uint32_t)i, b, &s, err);
if (st < 0 && gen_scope(prog)) {
/* A generator's every plain GEMM is a candidate; one whose geometry cannot be told
* stays the base, as a fused one does. */
RAD_WARN("lora: '%s' carries no adapter: %s", prog.weights[b].name.c_str(),
err ? err->c_str() : "");
if (err) err->clear();
continue;
}
if (st < 0) return st;
auto it = pool_of.find(b);
if (it == pool_of.end()) {
@@ -729,15 +798,6 @@ std::string explain_module(const Program& prog, const TargetSet& targets, const
/* ================================================================== the adapter */
namespace {
struct AdModule {
std::string name;
const StTensor* A = nullptr;
const StTensor* B = nullptr;
int64_t rank = 0;
double alpha = 0.0;
float scale = 0.0f;
};
struct Slot { int32_t pool; int32_t source; };
} /* namespace */
@@ -937,6 +997,12 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
info->leaves.insert(d == std::string::npos ? am.name : am.name.substr(d + 1));
}
return pack_modules(sites, max_rank, mods, info, packed, err);
}
int pack_modules(const std::vector<Site>& sites, int max_rank,
const std::map<std::string, AdModule>& mods, AdapterInfo* info,
std::vector<PackedSite>* packed, std::string* err, bool compact) {
/* ---- the sites, by pool: the representative of each pool and where its modules sit. */
int32_t n_pools = 0;
for (const Site& s : sites) {
@@ -955,7 +1021,9 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
}
std::unordered_map<std::string, std::vector<Slot>> where;
for (int32_t p = 0; p < n_pools; ++p) {
if (!rep[(size_t)p]) return fail(err, RAD_E_INVAL, fmt("pool %d has no site", p));
/* A pool whose only GEMM could carry no adapter ops (lora_declare drops it) holds
* nothing. */
if (!rep[(size_t)p]) continue;
const Site& s = *rep[(size_t)p];
for (size_t i = 0; i < s.sources.size(); ++i)
if (s.sources[i].targeted) where[s.sources[i].module].push_back({ p, (int32_t)i });
@@ -1001,9 +1069,10 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
/* ---- pack, pool by pool */
packed->resize((size_t)n_pools);
for (int32_t p = 0; p < n_pools; ++p) {
const Site& s = *rep[(size_t)p];
PackedSite& out = (*packed)[(size_t)p];
out.pool = p;
if (!rep[(size_t)p]) continue;
const Site& s = *rep[(size_t)p];
out.a.assign((size_t)(s.R * s.K_r), 0);
out.b.assign((size_t)(s.N_r * s.R), 0);
out.scale.assign((size_t)s.N_r, 0.0f);
@@ -1135,12 +1204,19 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
}
/* Pack. A: rows t_off.. of the module's block; B: rows y_col.., columns t_off..; scale on
* the module's rows. */
* the module's rows. Compact: the modules' ranks one after another from 0. */
std::vector<int64_t> off(n, 0);
int64_t used = 0;
for (size_t i = 0; i < n; ++i) {
off[i] = compact ? used : (int64_t)s.sources[i].slot * max_rank;
if (am[i]) used += am[i]->rank;
}
out.r_used = compact ? used : s.R;
for (size_t i = 0; i < n; ++i) {
if (!am[i]) continue;
const StTensor& A = *am[i]->A;
const int64_t r = am[i]->rank, kc = A.shape[1];
const int64_t t0 = (int64_t)s.sources[i].slot * max_rank;
const int64_t t0 = off[i];
for (int64_t j = 0; j < r; ++j)
for (int64_t k = 0; k < s.K_r; ++k)
out.a[(size_t)((t0 + j) * s.K_r + k)] = elem_bf16(A, j * kc + s.k_lo + k);
@@ -1156,7 +1232,7 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
if (yr < 0 || yr >= s.N_r)
return fail(err, RAD_E_STATE, fmt("weight '%s': a part lands outside y", s.weight.c_str()));
for (int64_t j = 0; j < r; ++j)
out.b[(size_t)(yr * s.R + sp.t_off + j)] = elem_bf16(B, row * r + j);
out.b[(size_t)(yr * s.R + off[i] + j)] = elem_bf16(B, row * r + j);
out.scale[(size_t)yr] = am[i]->scale;
}
}
+24
View File
@@ -19,12 +19,14 @@
#include "../rad_core.h"
#include <cstdint>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
namespace rad {
struct StTensor;
namespace lora {
/* HF module leaf names, ordered so every caller builds the same set. Empty targets nothing. */
@@ -82,6 +84,8 @@ struct PackedSite {
std::vector<float> scale; /* [N_r]: the module's alpha/r (alpha/sqrt(r) rsLoRA) on its rows */
int32_t pool = -1;
bool empty = true; /* no module of this adapter lands in this pool */
/* Packed compact (pack_modules): the ranks the modules take, from j = 0; R otherwise. */
int64_t r_used = 0;
};
/* What an adapter is, independent of the name it is served under. */
@@ -157,6 +161,26 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank,
int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max_rank,
AdapterInfo* info, std::vector<PackedSite>* packed, std::string* err);
/* One module's factors as the packer reads them: lora_A [rank, K] and lora_B [rows, rank] in any
* dtype a safetensors tensor carries (BF16, F16, F32), and the scale its rows run at. `name` is the
* module path the base's name map spells (without ".weight"). */
struct AdModule {
std::string name;
const StTensor* A = nullptr;
const StTensor* B = nullptr;
int64_t rank = 0;
double alpha = 0.0;
float scale = 0.0f;
};
/* load_adapter's second half, for any source of factors: `mods` (by name) packed into one
* PackedSite per pool of `sites`, in the slot layout of the pool's sites. Fills info->modules and
* info->absent. `compact`: the modules of a pool take consecutive ranks from j = 0, in source
* order, instead of a block of max_rank each, so a pass may run only the first r_used of them. */
int pack_modules(const std::vector<Site>& sites, int max_rank,
const std::map<std::string, AdModule>& mods, AdapterInfo* info,
std::vector<PackedSite>* packed, std::string* err, bool compact = false);
/* After load_adapter on every rank: refuse a module that no rank placed. With `prog`/`targets`
* (any one rank's) the message says why it is not a site (base lacks it, scope, target list, op). */
int check_placed(const std::vector<AdapterInfo>& per_rank, std::string* err,
+16 -1
View File
@@ -60,6 +60,7 @@ uint64_t SlotTable::publish(int slot, const std::string& name, const std::string
s.uid = next_uid_++;
s.used = true;
s.draining = false;
s.last_use = ++uses_;
return s.uid;
}
@@ -69,10 +70,11 @@ int SlotTable::acquire(const std::string& name, int32_t* slot, uint64_t* uid,
{
std::lock_guard<std::mutex> lk(mu_);
for (size_t i = 0; i < slots_.size() && !u; ++i) {
const Slot& x = slots_[i];
Slot& x = slots_[i];
if (x.uid == 0 || x.draining || x.name != name) continue;
u = x.uid;
*slot = (int32_t)i;
x.last_use = ++uses_;
++refs_[u];
}
}
@@ -125,6 +127,19 @@ int SlotTable::unload(const std::string& name, int* in_flight, std::string* err)
return RAD_E_NOTFOUND;
}
int SlotTable::evict_idle(std::string* evicted) {
std::lock_guard<std::mutex> lk(mu_);
Slot* best = nullptr;
for (Slot& x : slots_) {
if (x.uid == 0 || x.draining || refs_.count(x.uid)) continue;
if (!best || x.last_use < best->last_use) best = &x;
}
if (!best) return RAD_E_FULL;
if (evicted) *evicted = best->name;
free_slot(*best, " to make room");
return RAD_OK;
}
std::vector<std::string> SlotTable::names() const {
std::lock_guard<std::mutex> lk(mu_);
std::vector<std::string> out;
+6
View File
@@ -61,6 +61,10 @@ public:
* RAD_E_NOTFOUND: nothing of that name is loaded. */
int unload(const std::string& name, int* in_flight, std::string* err);
/* Free the least recently acquired loaded slot that no request holds, for a load that found
* none free; its name in *evicted. RAD_E_FULL when every loaded slot is held. */
int evict_idle(std::string* evicted);
/* The loaded adapters a request may name, in slot order: not the draining ones. */
std::vector<std::string> names() const;
/* Requests holding the adapter `name` (draining or not), 0 for none or no such adapter. */
@@ -73,6 +77,7 @@ private:
bool used = false; /* ever held an adapter, so `freed_at` means something */
bool draining = false;
uint64_t freed_at = 0; /* `epoch` when it was last freed */
uint64_t last_use = 0; /* acquire counter at its last acquire or publish */
};
void free_slot(Slot& s, const char* how); /* under mu_ */
void release(uint64_t uid); /* a hold's deleter */
@@ -82,6 +87,7 @@ private:
std::vector<Slot> slots_;
std::map<uint64_t, int> refs_; /* uid -> holds */
uint64_t next_uid_ = 1;
uint64_t uses_ = 0;
const std::atomic<uint64_t>* epoch_ = nullptr;
};
+1
View File
@@ -228,6 +228,7 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
p.bytes_per_block = 0;
p.bytes_per_state = 0;
}
p.replicated = g.replicated && p.paged() && !g.zero;
plans_.push_back(std::move(p));
}
bundling_ = compare_bundling(bundles);
+4
View File
@@ -73,6 +73,10 @@ struct KVGroupPlan {
* block count (one block table serves every rank); its costs are zero and nothing is carved.
* No op on this rank names it (issue refuses a group with no pool bound). */
bool zero = false;
/* rad_kv_group_replicated: every rank holds the same bytes, so a tier slot carries this
* group once, in a window at its front that rank 0 writes and every rank reads
* (TierExec::slot_layout). The pool is carved as for any group. */
bool replicated = false;
int64_t n_states = 0; /* LINEAR/CONV: n_seq_states * state_copies */
/* Physical slots per logical state: 1, or 2 under speculation. A verify runs 1 + n_spec
* tokens through the recurrence before acceptance is known; libr4d keeps the committed state
+3 -1
View File
@@ -96,7 +96,9 @@ class IdleTiers {
public:
struct Config {
int64_t host_cap_bytes = 0; /* 0 is off */
int64_t entry_bytes = 0; /* one entry: sum over cached groups of bytes_per_block */
/* One host slot: every cached group's bytes_per_block, under tensor parallelism every
* rank's own shard end to end and a replicated group once (TierExec::SlotLayout). */
int64_t entry_bytes = 0;
/* ---- the linear half ----
* `ckpt_bytes` is one snapshot including every rank's shard, like `entry_bytes`. The
* snapshots live in the engine's checkpoint store, `ckpt_slots` deep; reported here, not
+79 -33
View File
@@ -5,6 +5,7 @@
#include <algorithm>
#include <cstring>
#include <unordered_set>
namespace rad {
@@ -241,6 +242,22 @@ std::vector<BlockHash> PrefixCache::chain_all(const std::vector<int32_t>& tokens
return hs;
}
/* A snapshot is on the chain when its key equals the chain hash at its position. */
std::unordered_map<BlockHash, PrefixCache::Ckpt, BlockHashHash>::iterator
PrefixCache::deepest_ckpt(const std::vector<BlockHash>& hs, int64_t limit) const {
auto best = ck_by_prefix_.end();
for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) {
const Ckpt& c = it->second;
if (!c.valid || c.slot < 0 || c.pos <= 0 || c.pos > limit || c.pos % block_size_ != 0 ||
c.pos / block_size_ > (int64_t)hs.size())
continue;
if (best != ck_by_prefix_.end() && c.pos <= best->second.pos) continue;
if (hs[(size_t)(c.pos / block_size_ - 1)] != it->first) continue;
best = it;
}
return best;
}
void PrefixCache::touch(const BlockHash& h, uint64_t now_ns) const {
auto it = map_.find(h);
if (it == map_.end() || !it->second.in_lru) return;
@@ -274,23 +291,7 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
/* Back a full hit off by one block so one token remains to compute a logit from. */
if (matched * block_size_ >= (int64_t)tokens.size() && matched > 0) --matched;
/* Deepest valid snapshot at or below `limit` on this chain. Checkpoints sit on the interval or
* at a prompt's tail (Scheduler::plan_chunk), i.e. on any block boundary, so iterate the
* snapshots (a few hundred) rather than the block positions (tens of thousands); a snapshot is
* on this chain when its key equals the chain hash at its position. */
auto deepest = [&](int64_t limit) {
auto best = ck_by_prefix_.end();
for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) {
const Ckpt& c = it->second;
if (!c.valid || c.slot < 0 || c.pos <= 0 || c.pos > limit ||
c.pos % block_size_ != 0)
continue;
if (best != ck_by_prefix_.end() && c.pos <= best->second.pos) continue;
if (hs[(size_t)(c.pos / block_size_ - 1)] != it->first) continue;
best = it;
}
return best;
};
auto deepest = [&](int64_t limit) { return deepest_ckpt(hs, limit); };
/* Tokens a hit of `m` blocks lets a sequence skip: all of them, or with recurrent state only
* up to the deepest checkpoint (Scheduler::admit_one resumes there). */
auto reusable = [&](int64_t m) -> int64_t {
@@ -460,7 +461,8 @@ void PrefixCache::take_over(uint64_t session, const std::vector<BlockHash>& hs,
/* ------------------------------------------------------------------ idle session tiers */
std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm) const {
const std::vector<MMContentKey>& mm,
int64_t fit) const {
std::vector<BlockHash> out;
if (!enabled_ || !tiers_ || tokens.empty()) return out;
@@ -474,15 +476,45 @@ std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>&
* how far the maintenance pass had got; the scheduler chunks the rest of the prefill against
* that length, and greedy output is tie-level sensitive to the GEMM shapes (§19). Restoring
* the whole chain makes the hit length a function of the prompt. */
std::vector<int64_t> at; /* each entry's block on the chain */
for (int64_t b = 0; b < n_full; ++b) {
auto it = map_.find(hs[(size_t)b]);
if (it == map_.end()) break;
if (!same_tokens(it->second, tokens.data() + b * block_size_)) break;
if (tiers_->resident_off_device(hs[(size_t)b])) out.push_back(hs[(size_t)b]);
if (!tiers_->resident_off_device(hs[(size_t)b])) continue;
out.push_back(hs[(size_t)b]);
at.push_back(b);
}
if (out.empty() || (int64_t)out.size() <= fit) return out;
/* Restored up to `fit`, the hit ends at the first entry left behind. */
++stats_.restore_cuts;
int64_t keep = std::max<int64_t>(0, fit);
if (has_linear_) {
const auto best = deepest_ckpt(hs, at[(size_t)keep] * block_size_);
const int64_t upto = best == ck_by_prefix_.end() ? 0 : best->second.pos / block_size_;
keep = std::lower_bound(at.begin(), at.begin() + keep, upto) - at.begin();
}
out.resize((size_t)keep);
return out;
}
int64_t PrefixCache::restore_room() const {
if (!kv_ || groups_.empty()) return 0;
int64_t room = INT64_MAX;
for (int32_t g : groups_) room = std::min(room, kv_->total_blocks(g) - kv_->held_blocks(g));
return std::max<int64_t>(0, room);
}
int64_t PrefixCache::trim_for(const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm, int64_t n_blocks) {
if (!enabled_ || n_blocks <= 0) return 0;
const std::vector<BlockHash> hs = chain_all(tokens, mm, (int64_t)tokens.size() / block_size_);
std::unordered_set<BlockHash, BlockHashHash> spare(hs.begin(), hs.end());
for (const auto& h : held_) spare.insert(h.first);
return trim_sparing(n_blocks, &spare);
}
void PrefixCache::drop_offdevice(const BlockHash& key) {
auto it = map_.find(key);
if (it == map_.end()) return;
@@ -569,7 +601,10 @@ int64_t PrefixCache::evict_lru(int64_t n) {
return done;
}
int64_t PrefixCache::trim(int64_t n_blocks) {
int64_t PrefixCache::trim(int64_t n_blocks) { return trim_sparing(n_blocks, nullptr); }
int64_t PrefixCache::trim_sparing(int64_t n_blocks,
const std::unordered_set<BlockHash, BlockHashHash>* spare) {
/* Tiers attached but off count as no tiers: no copy will ever land, so do not wait for one. */
const bool keep = tiers_ && tiers_->host_on();
const uint64_t now = rad_mono_ns();
@@ -581,6 +616,7 @@ int64_t PrefixCache::trim(int64_t n_blocks) {
auto m = map_.find(h);
if (m == map_.end()) { it = lru_.erase(it); continue; }
Entry& e = m->second;
if (spare && spare->count(h)) { ++it; continue; }
if (shared_with_live(e)) {
/* In use: to the back, as in evict_lru. */
auto next = std::next(it);
@@ -711,9 +747,9 @@ int64_t PrefixCache::retain(uint64_t session) {
int64_t freed = 0;
for (const auto& a : all) {
if (std::binary_search(keep.begin(), keep.end(), a.first)) { kept.push_back(a.second); continue; }
/* Keep one handed out this step regardless of policy: its admission restores from the
* slot ahead of the step. */
if (handed(a.second)) { kept.push_back(a.second); continue; }
/* Keep one handed out this step or reserved and not yet committed regardless of policy:
* its admission restores from the slot ahead of the step, or the step's save lands in it. */
if (handed(a.second) || reserved(a.second)) { kept.push_back(a.second); continue; }
auto e = ck_by_prefix_.find(a.second);
if (e == ck_by_prefix_.end()) continue;
/* And one a lookup resumed from since the session's tip was written. The policy places
@@ -754,6 +790,10 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
if (existing != ck_by_prefix_.end()) {
existing->second.used = ++clock_;
existing->second.used_ns = rad_mono_ns();
/* Another session's snapshot, this step's save target: retention run by a later
* reservation in this step places its ladder from THAT session's tip and may not keep
* this position. Held until the save is committed. */
if (!reserved(prefix)) reserved_.push_back(prefix);
*slot_out = existing->second.slot;
return RAD_OK;
}
@@ -768,20 +808,20 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
for (uint64_t s : sessions) retain(s);
if (kv_->alloc_checkpoint(&slot) < 0) {
/* Evict the least recently used snapshot, where a use is its reservation or a lookup
* resuming from it, and never one handed out this step (its admission restores from
* the slot ahead of the step). A tip gets no protection beyond its recency: sessions
* are request ids, and a client that rewrites its last message leaves one tip per
* turn that no later turn reaches, while the anchor every turn resumes from is used
* each turn. */
* resuming from it, and never one handed out or reserved this step (its admission
* restores from the slot ahead of the step; the save lands in it after). A tip gets
* no protection beyond its recency: sessions are request ids, and a client that
* rewrites its last message leaves one tip per turn that no later turn reaches, while
* the anchor every turn resumes from is used each turn. */
const Ckpt* victim = nullptr;
for (const auto& kvp : ck_by_prefix_) {
if (handed(kvp.first)) continue;
if (handed(kvp.first) || reserved(kvp.first)) continue;
if (!victim || kvp.second.used < victim->used) victim = &kvp.second;
}
if (!victim) {
++stats_.ckpt_refused;
RAD_DEBUG("prefix cache: no snapshot at %lld for session %llu: every one of the "
"%lld slots was handed out this step", (long long)pos,
"%lld slots was handed out this step or awaits its save", (long long)pos,
(unsigned long long)session, (long long)ck_by_prefix_.size());
return RAD_E_FULL;
}
@@ -805,11 +845,17 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
c.used_ns = rad_mono_ns();
ck_by_prefix_.emplace(prefix, c);
ck_by_session_[session].push_back(prefix);
/* A save target until committed: a lookup's take_over may index it under another session
* before the save, where retention run by a later reservation in this step would weigh it by
* that session's ladder. */
reserved_.push_back(prefix);
*slot_out = slot;
return RAD_OK;
}
void PrefixCache::commit_checkpoint(const BlockHash& prefix) {
/* The save has landed: the slot is a snapshot like any other from here. */
reserved_.erase(std::remove(reserved_.begin(), reserved_.end(), prefix), reserved_.end());
auto it = ck_by_prefix_.find(prefix);
if (it == ck_by_prefix_.end()) return;
/* One that lost its slot since the reservation holds nothing to serve. */
@@ -915,12 +961,12 @@ int64_t PrefixCache::expire(uint64_t now_ns, uint64_t ttl_ns) {
}
}
/* ---- snapshots: skip uncommitted reservations and ones handed out this step. At most
* --checkpoint-slots of them, so walk the whole index. */
/* ---- snapshots: skip uncommitted reservations, ones handed out this step and ones a save
* is pending on. At most --checkpoint-slots of them, so walk the whole index. */
std::vector<BlockHash> gone;
for (const auto& kvp : ck_by_prefix_) {
const Ckpt& c = kvp.second;
if (!c.valid || handed(kvp.first)) continue;
if (!c.valid || handed(kvp.first) || reserved(kvp.first)) continue;
auto e = map_.find(kvp.first);
const uint64_t used = std::max(c.used_ns, e == map_.end() ? 0 : e->second.used_ns);
if (used < cutoff) gone.push_back(kvp.first);
+44 -7
View File
@@ -44,6 +44,7 @@
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace rad {
@@ -253,9 +254,24 @@ public:
/* The off-device entries this prompt's chain would hit if restored, in order, from where
* lookup stopped. The caller promotes them and looks up again; empty means the prefix ended
* on a miss or token mismatch. Separate from lookup because lookup is const and has no
* device; a promotion allocates blocks and runs a scatter between steps. */
* device; a promotion allocates blocks and runs a scatter between steps.
*
* `fit` is how many entries the pool can take. A longer chain is cut, and counted
* (Stats::restore_cuts): with recurrent state at the deepest snapshot the shorter prefix
* reaches, since the hit resumes there and blocks past it would come back for nothing;
* without, at `fit`. */
std::vector<BlockHash> restorable_from(const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm) const;
const std::vector<MMContentKey>& mm,
int64_t fit = INT64_MAX) const;
/* Entries a restore can place now: free blocks against the carve, the least over the cached
* groups. Lent blocks count, since KVManager::reserve_blocks recalls the loan for them. */
int64_t restore_room() const;
/* Room for a restore of this prompt's chain: trim(), sparing the chain itself (its blocks
* would only have to come back too) and every chain a waiting request holds (hold()), whose
* next attempt would restore it again. Nothing is lost; the reserve's trim after the next
* publish puts the pool's free quarter back. */
int64_t trim_for(const std::vector<int32_t>& tokens, const std::vector<MMContentKey>& mm,
int64_t n_blocks);
/* The tiers lost the bytes. Erases the entry without releasing blocks: an off-device entry
* owns none, and its recorded ids now belong to other sequences. Installed as
@@ -284,9 +300,10 @@ public:
void hold(uint64_t req, const std::vector<int32_t>& tokens, const std::vector<MMContentKey>& mm);
void release(uint64_t req);
/* Start of a step's admissions. Snapshots the previous step's lookups handed out have been
* read by its forward by now; until this call they keep their slots against retention,
* reserve_checkpoint's eviction and expiry. */
void begin_step() { handed_.clear(); }
* read by its forward by now, and the ones it reserved have been saved into (the engine
* issues the save before the next step is planned); until this call they keep their slots
* against retention, reserve_checkpoint's eviction and expiry. */
void begin_step() { handed_.clear(); reserved_.clear(); }
/* ---------------- expiry ----------------
*
@@ -307,8 +324,11 @@ public:
/* Reserve a snapshot slot for `session` at `pos`. When the store is full, applies the
* retention policy, then evicts the least recently used snapshot (a use is its reservation or
* a lookup resuming from it), a tip like any other. A snapshot handed out this step is never
* evicted: its admission restores from the slot ahead of the step. RAD_E_FULL when nothing
* can be given up. */
* released, by retention or eviction: its admission restores from the slot ahead of the step.
* Nor is one this call reserved and commit_checkpoint has not yet committed: the engine saves
* into the slot after the step, and a later reservation in the same step must not run
* retention over a save target (a second request reserving a snapshot a first session holds
* below its tip). RAD_E_FULL when nothing can be given up. */
int reserve_checkpoint(uint64_t session, int64_t pos, const BlockHash& prefix,
int32_t* slot_out);
/* The state for `prefix` is now in its slot; lookup() offers it only after this (Ckpt::valid). */
@@ -337,6 +357,8 @@ public:
int64_t drops = 0;
/* Entries and snapshots removed by --prefix-cache-ttl, from any tier. */
int64_t expired = 0, ckpt_expired = 0;
/* Restores from the host tier cut short because the pool could not hold the chain. */
int64_t restore_cuts = 0;
};
const Stats& stats() const { return stats_; }
@@ -372,6 +394,9 @@ private:
const std::vector<MMContentKey>& mm,
int64_t n_blocks) const;
void touch(const BlockHash& h, uint64_t now_ns) const;
/* trim(), leaving the entries in `spare` (when given) where they are. */
int64_t trim_sparing(int64_t n_blocks,
const std::unordered_set<BlockHash, BlockHashHash>* spare);
/* A live sequence also holds one of this entry's blocks, so releasing it frees nothing. */
bool shared_with_live(const Entry& e) const;
/* Whether `e` holds the block_size_ token ids at `src`, so a hash collision is a miss. */
@@ -392,6 +417,11 @@ private:
/* For the debug lines: whether `c` is its session's deepest snapshot, and seconds since a
* monotonic stamp. */
bool is_tip(const Ckpt& c) const;
/* The deepest valid snapshot on the chain `hs` at or below `limit` tokens; end() if none.
* Checkpoints sit on any block boundary (the interval or a prompt's tail), so this walks the
* snapshots, a few hundred, rather than the chain's blocks. */
std::unordered_map<BlockHash, Ckpt, BlockHashHash>::iterator
deepest_ckpt(const std::vector<BlockHash>& hs, int64_t limit) const;
static double idle_s(uint64_t used_ns);
KVManager* kv_ = nullptr;
@@ -421,6 +451,13 @@ private:
bool handed(const BlockHash& h) const {
return std::find(handed_.begin(), handed_.end(), h) != handed_.end();
}
/* Snapshots reserve_checkpoint reserved and commit_checkpoint has not committed: the step's
* save targets, kept in their slots until the commit, or until the next step begins when the
* save was skipped (its request gone). */
mutable std::vector<BlockHash> reserved_;
bool reserved(const BlockHash& h) const {
return std::find(reserved_.begin(), reserved_.end(), h) != reserved_.end();
}
mutable uint64_t clock_ = 0;
std::unique_ptr<CheckpointPolicy> policy_;
mutable Stats stats_;
+19 -6
View File
@@ -93,8 +93,13 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
/* The only measured term: the driver, loaded code objects and anything else on the card (e.g.
* a desktop compositor), so it is reported on its own line rather than folded into the
* headroom. Read after declare(), once every kernel plugin's code object is resident. */
b.already_held = std::max<int64_t>(b.capacity - freeb, 0);
* headroom. Read after declare(), once every kernel plugin's code object is resident.
*
* `held_out` is taken back out: it is the engine's own allocation that the program does not
* see (core/cvec.h's direction table), which the headroom already covers. */
int64_t held_out = 0;
for (const VramFacts& f : per_rank) held_out = std::max(held_out, f.held_out);
b.already_held = std::max<int64_t>(b.capacity - freeb - held_out, 0);
/* What is left after the fixed terms. */
b.drift = kDriverDrift;
@@ -190,21 +195,29 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
*
* The share is what the slab alone leaves off, the most a step can see: KV and arena loans only
* add residency. A layer larger than its share stages what fits and streams the rest. */
bool stage_from_experts = false;
if (layer_max > 0 && b.expert_ceiling > b.experts && cfg.placement != "all_vram" &&
cfg.placement != "layer_offload") {
const double f = (double)(b.expert_ceiling - b.experts) / (double)b.expert_ceiling;
const int64_t one = ((int64_t)std::ceil(f * (double)layer_max) + RAD_ALIGN_UNIT - 1) /
RAD_ALIGN_UNIT * RAD_ALIGN_UNIT;
if (b.lends) {
/* With a lending cache the cache pays: experts are at their floor, and the region is
* lent to the slab in small steps, as the cache would have lent it. */
if (b.kv - 2 * one >= kv_one) {
/* Expert residency above its host-pool floor pays first, so the cache keeps its
* configured coverage; otherwise the cache pays. Either way the region is lent to the
* slab in small steps. */
if (b.experts - 2 * one >= b.expert_floor) {
b.stage = 2 * one;
b.experts -= b.stage;
stage_from_experts = true;
b.weights = b.statics + b.experts;
} else if (b.kv - 2 * one >= kv_one) {
b.stage = 2 * one;
b.kv -= b.stage;
}
} else if (2 * one < b.experts) {
b.stage = 2 * one;
b.experts -= b.stage;
stage_from_experts = true;
b.weights = b.statics + b.experts;
}
}
@@ -312,7 +325,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
"non-resident experts,\n"
" at the arena's top and lent back to the "
"slab while steps are small\n", humanb(b.stage).c_str(),
b.lends ? "cache" : "experts").c_str()
stage_from_experts ? "experts" : "cache").c_str()
: "",
humanb(cfg.vram_weights_mib * kMiB).c_str(), "static + experts",
humanb(cfg.vram_kv_mib * kMiB).c_str(), "the cache's share",
+10 -3
View File
@@ -75,11 +75,17 @@ struct VramFacts {
/* Experts the pinned host pool cannot hold, plus the slab's spare slots: the expert slab's
* floor when the cache lends (expert_vram_floor, core/place/planner.h). */
int64_t expert_floor = 0;
int64_t kv_one = 0; /* the cache for one --max-model-len sequence: the least it may get */
int64_t kv_one = 0; /* all configured fixed state plus pages for one full-length context */
/* The cache lends idle blocks to the expert slab: a placement that moves units (expert_tiered
* or auto), not --deterministic, on a device with virtual memory management. A lending cache
* can be sized for what live requests could need; a non-lending one would hold it empty. */
bool lends = false;
/* A loaded control vector's direction table: device bytes the engine already holds, which are
* not part of the program or the pools and must not shrink what the plan may claim. It comes
* out of the headroom, as every deployment keeps that unclaimed. Without this, a deployment
* that merely *offers* a vector would plan its expert cache against a smaller card than one
* that does not, which is exactly the difference "off == stock" cannot allow. */
int64_t held_out = 0;
/* Integrated graphics: host memory the card must leave to the host, since device memory is
* host memory there. 0 on a discrete card. */
int64_t host_reserve = 0;
@@ -104,8 +110,9 @@ struct VramBudget {
int64_t experts = 0, kv = 0; /* the two shares, each capped at its ceiling */
int64_t unusable = 0; /* elastic neither side could take -- both were full */
/* Prefill staging region: two buffers, each one layer's share of the experts left off the
* card, appended to the top of the activation arena (core/place/stager.h). Zero when every
* expert is resident or the placement cannot move any. */
* card, funded by cache slack or expert residency above the host-pool floor, appended to the
* top of the activation arena (core/place/stager.h). Zero when every expert is resident or the
* placement cannot move any. */
int64_t stage = 0;
int64_t weights = 0; /* statics + experts: what vram_weights is set to */
std::string report; /* the block the engine prints at startup */
+21 -4
View File
@@ -22,6 +22,12 @@ double sinc(double x) {
double lanczos(double x) { return (-3.0 <= x && x < 3.0) ? sinc(x) * sinc(x / 3.0) : 0.0; }
/* PIL's BILINEAR filter: a triangle of support 1. */
double triangle(double x) {
if (x < 0.0) x = -x;
return x < 1.0 ? 1.0 - x : 0.0;
}
/* One axis: for each output index its first input index, its tap count, and `ksize` fixed-point
* coefficients. */
struct Axis {
@@ -30,11 +36,11 @@ struct Axis {
std::vector<int> kk; /* [out, ksize] */
};
Axis coeffs(int in_size, int out_size) {
Axis coeffs(int in_size, int out_size, bool bilinear) {
Axis a;
const double scale = (double)in_size / (double)out_size;
double filterscale = scale < 1.0 ? 1.0 : scale;
const double support = 3.0 * filterscale;
const double support = (bilinear ? 1.0 : 3.0) * filterscale;
a.ksize = (int)std::ceil(support) * 2 + 1;
a.bounds.assign((size_t)out_size * 2, 0);
a.kk.assign((size_t)out_size * a.ksize, 0);
@@ -50,7 +56,8 @@ Axis coeffs(int in_size, int out_size) {
xmax -= xmin;
int x = 0;
for (; x < xmax; ++x) {
const double w = lanczos((x + xmin - center + 0.5) * ss);
const double t = (x + xmin - center + 0.5) * ss;
const double w = bilinear ? triangle(t) : lanczos(t);
k[(size_t)x] = w;
ww += w;
}
@@ -80,7 +87,17 @@ inline unsigned muldiv255(unsigned a, unsigned b) {
} /* namespace */
static void resize_rgba(const FrameRGBA& src, int32_t w, int32_t h, bool bilinear, FrameRGBA* out);
void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out) {
resize_rgba(src, w, h, false, out);
}
void resize_bilinear_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out) {
resize_rgba(src, w, h, true, out);
}
static void resize_rgba(const FrameRGBA& src, int32_t w, int32_t h, bool bilinear, FrameRGBA* out) {
const int iw = src.w, ih = src.h;
/* Image.resize returns a copy at the same size. The premultiplied round trip below is not
* lossless where alpha is below 255. */
@@ -96,7 +113,7 @@ void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA*
pre[i * 4 + 3] = (uint8_t)al;
}
const bool horiz = w != iw, vert = h != ih;
const Axis ax = coeffs(iw, w), ay = coeffs(ih, h);
const Axis ax = coeffs(iw, w, bilinear), ay = coeffs(ih, h, bilinear);
/* the rows the vertical pass reads */
const int y_first = ay.bounds[0];
const int y_last = ay.bounds[(size_t)(h - 1) * 2] + ay.bounds[(size_t)(h - 1) * 2 + 1];
+2
View File
@@ -22,6 +22,8 @@ void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA*
* channels are exactly PIL's LANCZOS on the RGB image (premultiply and its inverse are the
* identity at full alpha). The video VAE's reference preprocessing resizes RGB this way. */
void resize_lanczos_rgb(const Frame& src, int32_t w, int32_t h, Frame* out);
/* The same with PIL's BILINEAR filter (a triangle of support 1, widened when shrinking). */
void resize_bilinear_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out);
/* `src` over an opaque white ground. */
void composite_white(const FrameRGBA& src, Frame* out);
+109
View File
@@ -46,6 +46,8 @@ int decode_video(const uint8_t*, size_t, SampleFn, const void*, int64_t, Video*,
std::string* why) {
return no_decoder(why);
}
int h264_roundtrip(const Frame&, int32_t, Frame*, std::string* why) { return no_decoder(why); }
bool h264_roundtrip_available() { return false; }
int decode_audio(const uint8_t*, size_t, int32_t, int64_t, std::vector<float>*,
std::string* why) {
return no_decoder(why);
@@ -677,6 +679,113 @@ int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_sample
return RAD_OK;
}
bool h264_roundtrip_available() {
return avcodec_find_encoder_by_name("libx264") && avcodec_find_decoder(AV_CODEC_ID_H264);
}
/* 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
* decoded frame's to_ndarray("rgb24"), which to_rgb reproduces. */
int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why) {
std::string w;
if (!why) why = &w;
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; }
const AVCodec* enc = avcodec_find_encoder_by_name("libx264");
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; }
AVCodecContext* ec = avcodec_alloc_context3(enc);
AVCodecContext* dc = avcodec_alloc_context3(dcd);
AVFrame* yuv = av_frame_alloc();
AVFrame* dec = av_frame_alloc();
AVPacket* pkt = av_packet_alloc();
SwsContext* sws = nullptr;
int st = RAD_OK;
auto fail = [&](const char* what, int e) {
*why = std::string(what) + (e < 0 ? " (" + averr(e) + ")" : std::string());
st = e == AVERROR(ENOMEM) ? RAD_E_NOMEM : RAD_E_INVAL;
};
bool got = false;
if (!ec || !dc || !yuv || !dec || !pkt) {
*why = "out of memory";
st = RAD_E_NOMEM;
} else {
ec->width = W;
ec->height = H;
ec->pix_fmt = AV_PIX_FMT_YUV420P;
ec->time_base = AVRational{ 1, 1 };
ec->framerate = AVRational{ 1, 1 };
/* PyAV's codec defaults: as many threads as the machine has, splitting each frame into
* that many slices, which shapes the bitstream. */
ec->thread_count = 0;
ec->thread_type = FF_THREAD_SLICE;
av_opt_set(ec->priv_data, "preset", "veryfast", 0);
av_opt_set(ec->priv_data, "crf", std::to_string(crf).c_str(), 0);
int e = avcodec_open2(ec, enc, nullptr);
if (e < 0) fail("opening libx264", e);
if (st == RAD_OK && (e = avcodec_open2(dc, dcd, nullptr)) < 0) fail("opening the H.264 decoder", e);
if (st == RAD_OK) {
yuv->format = AV_PIX_FMT_YUV420P;
yuv->width = W;
yuv->height = H;
if ((e = av_frame_get_buffer(yuv, 0)) < 0) fail("allocating a frame", e);
}
if (st == RAD_OK) {
sws = sws_getContext(W, H, AV_PIX_FMT_RGB24, W, H, AV_PIX_FMT_YUV420P, SWS_BILINEAR,
nullptr, nullptr, nullptr);
if (!sws) fail("no RGB to yuv420p conversion", 0);
}
if (st == RAD_OK) {
/* The source rows into a padded RGB frame: the scaler reads whole vectors past a tight
* row's end. */
AVFrame* rgb = av_frame_alloc();
if (!rgb) fail("out of memory", AVERROR(ENOMEM));
else {
rgb->format = AV_PIX_FMT_RGB24;
rgb->width = W;
rgb->height = H;
if ((e = av_frame_get_buffer(rgb, 0)) < 0) fail("allocating a frame", e);
else {
for (int y = 0; y < H; ++y)
std::memcpy(rgb->data[0] + (ptrdiff_t)y * rgb->linesize[0],
in.rgb.data() + (size_t)y * in.w * 3, (size_t)W * 3);
if (sws_scale(sws, rgb->data, rgb->linesize, 0, H, yuv->data, yuv->linesize) != H)
fail("colour conversion failed", 0);
}
av_frame_free(&rgb);
}
}
/* Encode the frame and flush; every packet goes straight to the decoder. */
for (int pass = 0; st == RAD_OK && pass < 2; ++pass) {
yuv->pts = 0;
if ((e = avcodec_send_frame(ec, pass == 0 ? yuv : nullptr)) < 0) { fail("encoding", e); break; }
while (st == RAD_OK && (e = avcodec_receive_packet(ec, pkt)) >= 0) {
if ((e = avcodec_send_packet(dc, pkt)) < 0) fail("decoding", e);
av_packet_unref(pkt);
}
if (st == RAD_OK && e != AVERROR(EAGAIN) && e != AVERROR_EOF) fail("encoding", e);
}
if (st == RAD_OK) avcodec_send_packet(dc, nullptr);
while (st == RAD_OK && (e = avcodec_receive_frame(dc, dec)) >= 0) {
if (!got) {
SwsContext* back = nullptr;
st = to_rgb(dec, &back, out, why);
sws_freeContext(back);
got = st == RAD_OK;
}
av_frame_unref(dec);
}
if (st == RAD_OK && !got) fail("the round trip decoded to no frame", 0);
}
sws_freeContext(sws);
av_packet_free(&pkt);
av_frame_free(&yuv);
av_frame_free(&dec);
avcodec_free_context(&ec);
avcodec_free_context(&dc);
return st;
}
#endif /* RAD_HAVE_FFMPEG */
} /* namespace mm */
+8
View File
@@ -77,5 +77,13 @@ int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* use
int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_samples,
std::vector<float>* out, std::string* why);
/* `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
* 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. */
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. */
bool h264_roundtrip_available();
} /* namespace mm */
} /* namespace rad */
+166 -1
View File
@@ -91,6 +91,65 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
return RAD_OK;
}
const char* mt = rad_meta_gets(&m, "vision_config.model_type", "");
/* GLM-5.3 states its processor only in processor_config.json's image_processor, with a token
* budget and no pixel band; the tower's geometry is the fallback, as the processor class
* defaults to it. */
if (mt && !std::strcmp(mt, "glm5_next_vision")) {
family = Family::Glm5Next;
auto geti = [&](const char* k, const char* tower, int64_t dflt) {
const std::string key = std::string("processor.image_processor.") + k;
return rad_meta_geti(&m, key.c_str(), rad_meta_geti(&m, tower, dflt));
};
patch = (int32_t)geti("patch_size", "vision_config.patch_size", 0);
temporal = (int32_t)geti("temporal_patch_size", "vision_config.temporal_patch_size", 0);
merge = (int32_t)geti("merge_size", "vision_config.spatial_merge_size", 0);
if (patch <= 0 || temporal <= 0 || merge <= 0) {
if (why) *why = "the container states no vision tower geometry (vision_config."
"patch_size, temporal_patch_size, spatial_merge_size)";
return RAD_E_NOTFOUND;
}
/* The expand factor multiplies the canvas's alignment without changing the patches; the
* checkpoints ship 1, and another one is a canvas this processor does not make. */
const int64_t expand =
rad_meta_geti(&m, "processor.image_processor.patch_expand_factor", 1);
if (expand != 1) {
if (why) *why = "processor.image_processor.patch_expand_factor is " +
std::to_string(expand) + "; this processor serves 1";
return RAD_E_UNSUPPORTED;
}
tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1);
tok_video = (int32_t)rad_meta_geti(&m, "video_token_id", -1);
tok_start = (int32_t)rad_meta_geti(&m, "image_start_token_id", -1);
tok_end = (int32_t)rad_meta_geti(&m, "image_end_token_id", -1);
if (tok_image < 0 || tok_start < 0 || tok_end < 0) {
if (why) *why = "the container states no media token ids (image_token_id, "
"image_start_token_id, image_end_token_id)";
return RAD_E_NOTFOUND;
}
min_image_tokens = (int32_t)rad_meta_geti(&m, "processor.image_processor.min_image_tokens",
16);
max_image_tokens = (int32_t)rad_meta_geti(&m, "processor.image_processor.max_image_tokens",
8000);
/* OpenAI CLIP's, the processor class's default. */
const float clip_mean[3] = { 0.48145466f, 0.4578275f, 0.40821073f };
const float clip_std[3] = { 0.26862954f, 0.26130258f, 0.27577711f };
std::copy(clip_mean, clip_mean + 3, mean);
std::copy(clip_std, clip_std + 3, stdv);
read_triple(m, "processor.image_processor.image_mean", mean);
read_triple(m, "processor.image_processor.image_std", stdv);
/* The pixel bands are QwenVL's; here they only have to be consistent for check(). */
const int64_t f2 = (int64_t)factor() * factor();
image_min_pixels = video_min_pixels = std::max<int64_t>(1, min_image_tokens) * f2;
image_max_pixels = video_max_pixels =
std::max<int64_t>(image_min_pixels, (int64_t)max_image_tokens * f2);
std::string bad;
if (check(&bad) < 0) {
if (why)
*why = "the container's GLM-5.3 processor configuration is inconsistent: " + bad;
return RAD_E_INVAL;
}
return RAD_OK;
}
if (mt && !std::strcmp(mt, "gemma4_vision")) {
family = Family::Gemma4;
patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0);
@@ -201,6 +260,9 @@ int VisionConfig::check(std::string* why) const {
if (!(max_pixels_tolerance > 0.0) || max_segment_patches <= 0)
return no("max_pixels_tolerance and max_num_patches must be positive");
}
if (family == Family::Glm5Next && (min_image_tokens < 1 || max_image_tokens < min_image_tokens))
return no("the image token band [" + std::to_string(min_image_tokens) + ", " +
std::to_string(max_image_tokens) + "] is empty");
if (family == Family::Gemma4) {
if (!soft_budget_ok(image_soft_tokens))
return no("the image soft-token budget " + std::to_string(image_soft_tokens) +
@@ -324,6 +386,51 @@ int gemma4_size(int64_t h, int64_t w, int32_t patch, int32_t pool, int64_t max_p
return RAD_OK;
}
/* Glm5NextImageProcessor's smart_resize and the size its resize() gives the picture, in Python's
* doubles. A token is `temporal` frames of factor x factor pixels, and a picture counts as
* `temporal` frames. The canvas's sides are rounded up to whole factors; under the floor the
* picture is scaled up by the area ratio and rounded up again; over the budget a binary search over
* the picture's height finds the largest canvas inside it. The picture then scales by the smaller
* side ratio, never up while it reaches the floor, truncated. */
int glm5next_size(int64_t h, int64_t w, int32_t temporal, int32_t factor, int64_t min_tok,
int64_t max_tok, int64_t* oh, int64_t* ow, int64_t* ch, int64_t* cw,
std::string* why) {
if (h <= 0 || w <= 0) { if (why) *why = "the picture has no size"; return RAD_E_INVAL; }
const int64_t per_tok = (int64_t)temporal * factor * factor;
const int64_t min_px = min_tok * per_tok, max_px = max_tok * per_tok;
if (max_px < per_tok) {
if (why) *why = "the token budget is less than one merged patch";
return RAD_E_INVAL;
}
auto align = [factor](int64_t v) { return (v + factor - 1) / factor * factor; };
int64_t ah = align(h), aw = align(w);
if (temporal * ah * aw < min_px) {
const double scale = std::sqrt((double)min_px / ((double)temporal * (double)h * (double)w));
ah = align(std::max<int64_t>(1, (int64_t)std::ceil((double)h * scale)));
aw = align(std::max<int64_t>(1, (int64_t)std::ceil((double)w * scale)));
}
if (temporal * ah * aw > max_px) {
int64_t lo = 1, hi = h, bh = factor, bw = factor;
while (lo <= hi) {
const int64_t mid = (lo + hi) / 2;
const int64_t wid = std::max<int64_t>(1, (int64_t)std::floor((double)(w * mid) /
(double)h));
const int64_t th = align(mid), tw = align(wid);
if (temporal * th * tw <= max_px) { bh = th; bw = tw; lo = mid + 1; }
else hi = mid - 1;
}
ah = bh;
aw = bw;
}
double scale = std::min((double)ah / (double)h, (double)aw / (double)w);
if (temporal * h * w >= per_tok * min_tok) scale = std::min(1.0, scale);
*oh = ah;
*ow = aw;
*ch = std::max<int64_t>(1, std::min<int64_t>(ah, (int64_t)std::floor((double)h * scale)));
*cw = std::max<int64_t>(1, std::min<int64_t>(aw, (int64_t)std::floor((double)w * scale)));
return RAD_OK;
}
/* The reference's (EmbeddingGemma2VideoProcessor.sample_frames): the stream's duration at `fps`,
* one frame each 1/fps seconds as int(i * native_fps / fps), then `max_frames` of those chosen by
* numpy's linspace truncated to integers. */
@@ -671,6 +778,15 @@ int Processor::init(const VisionConfig& cfg,
encode_text_ = std::move(encode_text);
return RAD_OK;
}
if (cfg.family == Family::Glm5Next) {
/* 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. */
const int64_t pass_tok = cfg.max_patches / ((int64_t)cfg.merge * cfg.merge);
if (pass_tok < cfg.min_image_tokens) return RAD_E_INVAL;
if (cfg_.max_image_tokens > pass_tok) cfg_.max_image_tokens = (int32_t)pass_tok;
encode_text_ = std::move(encode_text);
return RAD_OK;
}
if (cfg.family == Family::Gemma4) {
/* A budget is a patch count, and an image is one segment of one pass. */
if ((int64_t)cfg.image_soft_tokens * cfg.merge * cfg.merge > cfg.max_patches ||
@@ -805,10 +921,50 @@ int Processor::image_lfm2(const Frame& f, std::shared_ptr<Item>* out, std::strin
return RAD_OK;
}
/* GLM-5.3's image processor (transformers' Glm5NextImageProcessor, torchvision backend): the
* picture, resized only when its size changes, in the top left of a canvas of zero bytes, which
* the normalisation turns into each channel's -mean / std as it does the reference's padding. */
int Processor::image_glm5next(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const {
const VisionConfig& c = cfg_;
int64_t h = 0, w = 0, ch = 0, cw = 0;
RAD_TRY(glm5next_size(f.h, f.w, c.temporal, c.factor(), c.min_image_tokens,
c.max_image_tokens, &h, &w, &ch, &cw, why));
Frame r;
const Frame* src = &f;
if (ch != f.h || cw != f.w) {
resize_bicubic_torch(f, (int32_t)cw, (int32_t)ch, &r);
src = &r;
}
Frame canvas;
canvas.w = (int32_t)w;
canvas.h = (int32_t)h;
canvas.rgb.assign((size_t)w * h * 3, 0);
for (int64_t y = 0; y < ch; ++y)
std::memcpy(canvas.rgb.data() + (size_t)y * w * 3, src->rgb.data() + (size_t)y * cw * 3,
(size_t)cw * 3);
auto it = std::make_shared<Item>();
it->kind = Kind::Image;
it->grid_t = 1;
it->grid_h = (int32_t)(h / c.patch);
it->grid_w = (int32_t)(w / c.patch);
it->rope_1d = true;
finish_item(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;
}
std::vector<const Frame*> frames((size_t)c.temporal, &canvas);
patchify(c, frames, 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;
}
int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const {
const VisionConfig& c = cfg_;
if (c.family == Family::Gemma4) return image_gemma4(f, c.image_soft_tokens, out, why);
if (c.family == Family::Lfm2) return image_lfm2(f, out, why);
if (c.family == Family::Glm5Next) return image_glm5next(f, out, why);
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,
&h, &w, why));
@@ -901,6 +1057,10 @@ 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 {
const VisionConfig& c = cfg_;
if (c.family == Family::Gemma4) return video_gemma4(v, out, why);
if (c.family == Family::Glm5Next) {
if (why) *why = "this model's processor takes pictures, not video";
return RAD_E_UNSUPPORTED;
}
if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; }
/* Pad the frames and their indices to whole temporal groups by repeating the last; a clip
* shorter than one group becomes one group. */
@@ -982,6 +1142,11 @@ int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::strin
int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens,
std::shared_ptr<Item>* out, std::string* why, int64_t max_pixels) const {
if (image_tokens != 0) {
if (cfg_.family == Family::Glm5Next) {
if (why) *why = "this model's image token budget is the server's (--image-tokens), "
"not a request's";
return RAD_E_UNSUPPORTED;
}
if (cfg_.family != Family::Gemma4) {
if (why) *why = "this model's processor sizes an image by its pixels, not by a token "
"budget";
@@ -1153,7 +1318,7 @@ std::vector<int64_t> sample_cb(const VideoInfo& info, const void* user) {
int Processor::video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
std::string* why) const {
if (cfg_.family == Family::Lfm2) {
if (cfg_.family == Family::Lfm2 || cfg_.family == Family::Glm5Next) {
if (why) *why = "this model's processor takes pictures, not video";
return RAD_E_UNSUPPORTED;
}
+19 -2
View File
@@ -55,8 +55,16 @@ enum class Kind { Image, Video, Audio };
* is cut into tile x tile crops, min_tiles..max_tiles of them in the ratio nearest its
* own, followed by the whole picture at the budgeted size as a thumbnail. Patches
* (y, x, channel) normalised by the mean and deviation, resized with torchvision's
* fixed-point bicubic; images only, and the tokens rotate at their positions. */
enum class Family { QwenVL, Gemma4, Lfm2 };
* fixed-point bicubic; images only, and the tokens rotate at their positions.
* Glm5Next GLM-5.3's: a canvas whose sides are multiples of patch * merge and whose tokens fall
* in [min_image_tokens, max_image_tokens] (the sides rounded up, a picture under the
* floor grown, one over the budget fitted by the reference's search); the picture keeps
* its aspect ratio, is never enlarged above the floor, and is resized with torchvision's
* fixed-point bicubic only when its size changes; the rest of the canvas, right and
* bottom, is zero bytes. Patches as QwenVL's. Images only, spelled <begin_of_image>
* placeholders <end_of_image>, the tokens at their positions (the language model has no
* rotary). */
enum class Family { QwenVL, Gemma4, Lfm2, Glm5Next };
struct VisionConfig {
Family family = Family::QwenVL;
@@ -66,6 +74,8 @@ struct VisionConfig {
int32_t image_soft_tokens = 0, video_soft_tokens = 0;
int64_t image_min_pixels = 0, image_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). */
int32_t min_image_tokens = 0, max_image_tokens = 0;
double fps = 2.0;
int32_t min_frames = 4, max_frames = 768;
/* Per-frame ceiling on a video's resolution, in output rows (the reference processor's
@@ -371,6 +381,7 @@ private:
int image_gemma4(const Frame& f, int32_t soft, std::shared_ptr<Item>* out,
std::string* why) const;
int image_lfm2(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;
/* Lfm2's markers: <|img_thumbnail|>, and <|img_row_R_col_C|> at (R-1) * max_tiles + C-1. */
int32_t tok_thumbnail_ = -1;
std::vector<int32_t> tok_tiles_;
@@ -412,6 +423,12 @@ void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out);
/* ...and torchvision's on a uint8 tensor (ATen's CPU kernel), which is the same filter with the
* coefficients at the most precision 16 bits hold, chosen per axis, rather than PIL's 22. */
void resize_bicubic_torch(const Frame& in, int32_t w, int32_t h, Frame* out);
/* GLM-5.3's smart_resize: the (oh, ow) canvas, multiples of `factor`, for an h x w picture whose
* `temporal` frames take [min_tok, max_tok] tokens of temporal * factor^2 pixels each; and the
* (ch, cw) the picture is resized to inside it, top left, aspect ratio kept. */
int glm5next_size(int64_t h, int64_t w, int32_t temporal, int32_t factor, int64_t min_tok,
int64_t max_tok, int64_t* oh, int64_t* ow, int64_t* ch, int64_t* cw,
std::string* why);
/* LFM2-VL's smart_resize: (height, width) to multiples of `factor`, at least one each, pixels
* within [min_px, max_px] where the rounding left them outside. */
void lfm2_size(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max_px,
Loaded 100 of 415 files, more files were not shown because too many files have changed in this diff. Show more