Archived
radiance 2.0.0
Radiance becomes a multi-model engine: one process serves several models behind one port, loads each when a request names it, parks it in host memory or restores it from its container, and shares the cards between them (docs/MULTIMODEL.md). The configuration is one YAML file; the command line flags are gone (`radiance --config FILE`, hot reload on SIGHUP). Formats. IQ8R (rotated int8) and IQR-V4 replace FP8 and MXFP4 as whole-model formats, with an int8 KV cache (`kv-cache-dtype: i8`) in place of the fp8 one. Containers whose weights are block FP8, MXFP4, M2XFP4, NVFP4 or ParoQuant are refused at startup by the name of the first such weight. Not served until they have int8 containers: GLM-5.3-Flash, Ornith-1.5, Sage-A1.5, Nemotron-3.5-Bolt-74B, Ling-3.0-flash, drama-3 and Anima's FP8 container; Nemotron-3.5-Bolt-E4B, the Gemma 4 31B DFlash containers and MiniCPM5-2B bf16 serve without their drafter. 1.17.0 serves all of them. Speed. Chained launches for Qwen3.8-27B, Gemma 4, Gemma 3 and the small bf16 models, a new Qwen3.8-Flash-Next container (IQR-V4 experts, int8 trunk) with its decode step and prefill reworked, and a reworked adaptive draft window. Deployment. deploy/compose has two fleet files, tp1.yaml and tp2.yaml, each with its configuration beside it, in place of the per-model files. `host-pool-mib` is a model's host pool in all, split among its ranks. The dashboard is rebuilt: an hour of history kept by the server, each accelerator's memory by model, model states over time. Merged since 1.17.0: Nemotron-3.5-Bolt-74B-A9B by keptn42 (#339); GLM-5.3-Flash on four cards by AnimusNull (#397); chained launches for Flash-Next's decode step (#396) and preempted requests keeping their prefix and place (#405) by mici81; --prefill-interleave auto by Code000 (#410); eight more libr3d kernels and the w4a4 reference by RikshaDriver (#403, #407, #408); libr3d large-BAR and E4M3 decode fixes by neuromanMD (#438, #439); int4/int5 decode tiles by Kezi (#426); attention for Nanbeige 4.3 33B by everplays (#417); expert_stats_report.py by baKon (#431). Fixed: #398, #402, #419, #437 (dschmitz's patch); added the metrics of #392, and multi-model serving as asked for in #367 and #109. Plugin ABI 39: out-of-tree plugins need to be rebuilt. Thanks to @keptn42, @AnimusNull, @mici81, @Code000, @RikshaDriver, @neuromanMD, @Kezi, @everplays, @baKon and @dschmitz.
This commit is contained in:
1 parent
b4c04b6042
commit
ddcb9c69bb
696 files changed
+120770
-56596
No files matched your search
@@ -5,3 +5,5 @@ build*
|
||||
.claude
|
||||
**/*.rad
|
||||
compile_commands.json
|
||||
dashboard/node_modules
|
||||
dashboard/dist
|
||||
+10
-8
@@ -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.17.0 LANGUAGES C CXX)
|
||||
project(radiance VERSION 2.0.0 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
@@ -163,7 +163,7 @@ file(MAKE_DIRECTORY ${RAD_PLUGIN_OUT}/kernels ${RAD_PLUGIN_OUT}/architectures)
|
||||
# Recorded kernel fixtures, copied into the build's $RADIANCE_HOME (where rad-kbench looks; an
|
||||
# installed prefix has no source tree). data/kernels.rkb lets rad-kbench run with no model: it holds
|
||||
# geometries, input seeds and libref's answers reduced to a norm and a sample. Re-record with a 27B
|
||||
# container:
|
||||
# IQ8R container that carries its DFlash2 drafter:
|
||||
#
|
||||
# rad-kbench -m <model.rad> --max-cases 1 --record data/kernels.rkb
|
||||
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels.rkb)
|
||||
@@ -174,8 +174,8 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels.rkb)
|
||||
endif()
|
||||
|
||||
# A recording covers one container's geometries, and no single model declares the whole vocabulary.
|
||||
# The 27B is dense with a DFlash2 drafter and gqa 6; the 35B-A3B is routed (moe_gemm_q,
|
||||
# router_topk, moe_scatter, moe_gather, scale_rows) with an MTP head and gqa 8. Re-record with
|
||||
# The 27B is dense with a DFlash2 drafter and gqa 6; the 35B-A3B IQ8R container is routed
|
||||
# (moe_gemm_q, the fused router, moe_gather, scale_rows) with an MTP head and gqa 8. Re-record with
|
||||
#
|
||||
# rad-kbench -m <model.rad> --max-cases 1 --record data/kernels_moe.rkb
|
||||
#
|
||||
@@ -209,8 +209,8 @@ endforeach()
|
||||
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/vectors/LICENSE.qwen-community-1.0.txt
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME qwen-community.LICENSE)
|
||||
|
||||
# The downloader behind `radiance --model <owner/name>` (core/hf_model.cpp). The engine looks in
|
||||
# <bin>/../libexec/radiance/, so the build tree mirrors that layout.
|
||||
# The downloader behind a model source naming a repo, `model: <owner/name>` (core/hf_model.cpp).
|
||||
# The engine looks in <bin>/../libexec/radiance/, so the build tree mirrors that layout.
|
||||
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
|
||||
${CMAKE_BINARY_DIR}/libexec/radiance/hfget.sh COPYONLY)
|
||||
install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
|
||||
@@ -389,9 +389,11 @@ install(FILES
|
||||
install(FILES LICENSE NOTICE DESTINATION ${CMAKE_INSTALL_DOCDIR})
|
||||
install(FILES vendor/llama/LICENSE
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME llama.cpp.LICENSE)
|
||||
install(FILES vendor/nlohmann/LICENSE.MIT
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME nlohmann-json.LICENSE)
|
||||
install(FILES vendor/yyjson/LICENSE
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME yyjson.LICENSE)
|
||||
install(FILES vendor/cpp-httplib/LICENSE
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME cpp-httplib.LICENSE)
|
||||
install(FILES core/server/LICENSE.lfm
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME liquidai-d1.LICENSE)
|
||||
install(FILES dashboard/THIRD-PARTY-LICENSES.txt
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME dashboard.LICENSES)
|
||||
@@ -27,7 +27,12 @@ Written by Deadcode, with contributions from:
|
||||
a serial drafter) with mla_attn_paged, its w4a8 recipes and compose files, possessive quantifiers
|
||||
in the tokenizer's patterns, the Grafana dashboard's first screen, and Gemma 4 12B (its picture
|
||||
and audio embedders, a picture's placeholders read both ways on the sliding layers, the windowed
|
||||
attention at head_dim 512, suppress_tokens) with its compose files
|
||||
attention at head_dim 512, suppress_tokens) with its compose files, and
|
||||
NVIDIA-Nemotron-3.5-Bolt-74B-A9B (nemotronh: Mamba-2 with ssd_update and ple_conv_bias, the
|
||||
latent MoE's ungated relu^2 experts, NoPE attention with KV heads replicated over ranks, the
|
||||
paged attention at head_dim 128 and gqa 16, attention sinks) with NVIDIA's LiLiCorr drafter
|
||||
(RadBatch::anchor_rows, the candidate correlator), the C-RADIO vision tower and video tubelets,
|
||||
calibration in layer ranges, its recipes and compose files, and the kernel report's fixture
|
||||
- mechkbfan: the token embedding in the pinned host pool
|
||||
- Code000: the n-gram gather on the card and the MTP head's history-pass skip, and the MTP draft
|
||||
coupling with its cooperative verify (--draft-coupling), the W4A8 prefill's tail scale read, the
|
||||
@@ -36,7 +41,8 @@ Written by Deadcode, with contributions from:
|
||||
the rows forms of rmsnorm and rope, LFM2's 8-bit trunk with the d1-3B recipe, the file tier's
|
||||
routed reads with their own router's counts and its deposit wait, the stop-string hold-back, and
|
||||
the sampler's planes by the step's token bound, its n-gram ban beside a drafter and no candidate
|
||||
cut over a top-1 row
|
||||
cut over a top-1 row, and --prefill-interleave auto[:SHARE], sized from measured step times and
|
||||
served by default
|
||||
- baKon: three-rank tensor parallelism, serving any world size from the shipped container, the
|
||||
request log, an uneven world's per-rank KV and weights split, --rope-scaling, the model entry's
|
||||
context length, root and capabilities, /props, the three-rank two-shot all-reduce and tiered-int8
|
||||
@@ -53,7 +59,7 @@ Written by Deadcode, with contributions from:
|
||||
whole recompute and the running sequences' next blocks free and the bound on its wait
|
||||
(--preempt-wait-ms), prompt lookup alone (--spec-ngram) with each sequence's n-gram index and
|
||||
the gate that verifies a proposal only when it pays, and DeepSeek-V4.1's reply format with its
|
||||
DSML tool calls
|
||||
DSML tool calls, and expert_stats_report.py
|
||||
- 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
|
||||
@@ -97,7 +103,9 @@ Written by Deadcode, with contributions from:
|
||||
feed-forward's gated fold up to 16 rows, the three-wave verify floor bounded by the batch's
|
||||
workgroups, the split-KV row sum read with fetch-inactive, KLATE again for the head-256 gqa6
|
||||
paged prefill, the preempted-prefill gate past a KV group that holds no blocks, and the norms'
|
||||
lane sum issuing its reads eight at a time
|
||||
lane sum issuing its reads eight at a time, chained forms for every kernel of
|
||||
Qwen3.8-Flash-Next's decode step with hc_read's forms G, S and B3, and a preempted request
|
||||
publishing its prefix with an overdue one keeping its place
|
||||
- eddie168168: the rotated int8 trunk (i8a8h) and the qwen35_w8a8 plugin serving it, and the
|
||||
out-of-tree test at the tree's VOPD setting, and its norm and SiLU producers writing the int8
|
||||
linears' operands directly
|
||||
@@ -153,7 +161,8 @@ Written by Deadcode, with contributions from:
|
||||
and its gated three-tile form at 8 waves
|
||||
- RikshaDriver: libr3d, the RDNA3 (gfx11) kernel library, and its wave-matrix rewrite: the GEMMs
|
||||
retiled to 16x128 blocks, the grouped MoE GEMMs, the norms and quantisers, and the QSA and MoE
|
||||
router rows
|
||||
router rows, its MoE GEMMs at w4a8 and w4a4 with dequant_w4, row_topk_merge, ngram_ids and
|
||||
the biased and short GEMMs, and w4a4's reference implementation
|
||||
- fl0l0u: every request entry point bounded, gated and sanitised (JSON parses bounded in depth,
|
||||
errors safe on invalid UTF-8, control bytes kept off the log, the dashboard's CSP, cross-origin
|
||||
browsers refused on the loopback-only routes, method-scoped API-key exemptions), prompt ids that
|
||||
@@ -171,6 +180,15 @@ Written by Deadcode, with contributions from:
|
||||
the DMA lane's lists fenced so a stalled read pointer no longer fills its ring
|
||||
- pokesjw: the n-gram reader refilling its reads as they land, and a decode gather waiting on the
|
||||
other rank's read of a row instead of reading it again
|
||||
- AnimusNull: GLM-5.3-Flash on four cards -- its experts split by width, the small-M MXFP4 expert
|
||||
form at the TP4 slices, the indexer's take-all steps -- its E4M3 latent cache (mla_attn's fp8kv
|
||||
rows), and the DMA lane's room check over a reused fence slot
|
||||
- neuromanMD: libr3d's MXFP4 GEMM leaving VRAM exponent planes unscanned from the host, and its
|
||||
branch-free e4m3_to_f32
|
||||
- everplays: the paged attention at seven queries a KV head, head_dim 128 (Nanbeige4.3-33B)
|
||||
- Kezi: the decode tile arms of the int4 and int5 x int8 GEMM
|
||||
- dschmitz: the two-rank fused writes' host-mailbox twins taking their chained forms
|
||||
- eniga: the diagnosis of GLM-5.3-Flash's template refused for tools (jinja's unique filter)
|
||||
|
||||
This product includes software from the following projects, each under the MIT License. The
|
||||
license text is in the file named beside each.
|
||||
@@ -179,9 +197,16 @@ license text is in the file named beside each.
|
||||
vendor/llama/, and the code lifted or ported from it: core/sample/gbnf.*, the
|
||||
host samplers in core/sample/host_ref.*, the tokenisers in core/text/, and
|
||||
libquant/lq_ggml_*
|
||||
nlohmann/json Copyright (c) 2013-2025 Niels Lohmann vendor/nlohmann/LICENSE.MIT
|
||||
yyjson Copyright (c) 2020 YaoYuan vendor/yyjson/LICENSE
|
||||
cpp-httplib Copyright (c) 2017 yhirose vendor/cpp-httplib/LICENSE
|
||||
|
||||
The dashboard's page, compiled into the server from core/server/dashboard_page.h, carries
|
||||
third-party software built into it: React, Base UI and Floating UI, uPlot, shadcn/ui's components
|
||||
and helpers, Tailwind CSS's generated style and tw-animate-css (MIT), class-variance-authority
|
||||
(Apache-2.0), the Lucide icons (ISC), and the Geist and Geist Mono typefaces (SIL Open Font License
|
||||
1.1, Copyright the Geist Project Authors). dashboard/THIRD-PARTY-LICENSES.txt lists every package
|
||||
with its version and license text, as the page's build wrote it.
|
||||
|
||||
tests/data/chat/hyv3/chat_template.jinja is Tencent's Hy-Memory-30B-A3B chat template,
|
||||
copied unchanged from tencent/Hy-Memory-30B-A3B on Hugging Face.
|
||||
Copyright (C) 2026 Tencent. All rights reserved. Licensed under Apache-2.0 (LICENSE).
|
||||
|
||||
@@ -7,7 +7,7 @@ unchanged. Model architectures, kernel libraries and quantisers are `.so` plugin
|
||||
tree are built and loaded the same way a third party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)).
|
||||
|
||||
The bundled device kernels target AMD RDNA4 (`libr4d`: `gfx1200`, `gfx1201`), RDNA3 (`libr3d`:
|
||||
`gfx11xx`) and Strix Halo (`libhalo`: `gfx1151`). The serve flags
|
||||
`gfx11xx`) and Strix Halo (`libhalo`: `gfx1151`). The serve settings
|
||||
below are for two 32 GB cards (Radeon AI PRO R9700). The engine starts on any AMD GPU family;
|
||||
another card needs a kernel library for it. A machine with no GPU builds the host backend, whose
|
||||
AVX-512/AVX2 kernels (`libavx`) serve every model here: the small ones (EmbeddingGemma 2,
|
||||
@@ -18,68 +18,56 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC
|
||||
|
||||
## Models
|
||||
|
||||
| model | container | get it | compose file |
|
||||
| model | container | get it | fleet file |
|
||||
|---|---|---|---|
|
||||
| Qwen3.8-Flash-Next: 4-bit experts, int8 trunk, MTP, vision | `qwen3.8-next-flash-fp8-iq4r-moe.rad` (114 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-fp8-iq4r-moe) | `flashnext.yaml` |
|
||||
| Qwen3.8-27B FP8, DFlash2 drafter, vision | `qwen3.8-27b-fp8.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-fp8) | `qwen3.8-27b-fp8.yaml` |
|
||||
| Qwen3.8-27B MXFP4 (AMD Quark AWQ), DFlash2 drafter, vision | `qwen3.8-27b-mxfp4.rad` (19 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-mxfp4) | `qwen3.8-27b-mxfp4.yaml` |
|
||||
| Qwen3.8-27B IQR-V4, 2.5 to 8 bits a weight ([docs/IQR.md](docs/IQR.md)), DFlash2 drafter, vision | `qwen3.8-27b-iq2r-v4.rad` .. `qwen3.8-27b-iq8r-v4.rad` (10 to 28 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-iqr-v4) | `qwen3.8-27b-iqr-v4.yaml` |
|
||||
| Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` |
|
||||
| Ornith-1.5-35B-A3B FP8, MTP, vision | `ornith-1.5-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-fp8) | `ornith-1.5-35b-a3b.yaml` |
|
||||
| Ornith-1.5-35B-A3B w4a8: 4-bit experts (GPTQ), MTP, vision, fits one card | `ornith-1.5-35b-a3b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-w4a8) | `ornith-1.5-35b-a3b-w4a8.yaml` |
|
||||
| Ornith-1.5-122B FP8, MTP, vision, four cards | `ornith-1.5-122b-fp8.rad` (118 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-fp8) | `ornith-1.5-122b.yaml` |
|
||||
| Ornith-1.5-122B FP8, DFlash2 drafter, vision, four cards | `ornith-1.5-122b-fp8-dflash2.rad` (116 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-fp8-dflash2) | `ornith-1.5-122b-df2.yaml` |
|
||||
| Ornith-1.5-122B w4a8: 4-bit experts (GPTQ), MTP, vision, four cards | `ornith-1.5-122b-w4a8.rad` (65 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-w4a8) | `ornith-1.5-122b-w4a8.yaml` |
|
||||
| Ornith-1.5-122B w4a8: 4-bit experts (GPTQ), DFlash2 drafter, vision, four cards | `ornith-1.5-122b-w4a8-dflash2.rad` (64 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-w4a8-dflash2) | `ornith-1.5-122b-w4a8-df2.yaml` |
|
||||
| Sage-A1.5 FP8, MTP, vision | `sage-a1.5-fp8.rad` (35 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8) | `sage-a1.5.yaml`, `sage-a1.5-tp1.yaml` |
|
||||
| Sage-A1.5 FP8, DFlash2 drafter, vision | `sage-a1.5-fp8-df2.rad` (34 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8-df2) | `sage-a1.5-df2.yaml` |
|
||||
| MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` |
|
||||
| MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` |
|
||||
| Qwen3.8-Flash-Next: IQR-V4 experts, int8 trunk, MTP, vision | `qwen3.8-next-flash-iqr-v4.rad` (113 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-iqr-v4) | `tp1.yaml`, `tp2.yaml` |
|
||||
| Qwen3.8-27B IQ8R (rotated int8), DFlash2 drafter, vision | `qwen3.8-27b-iq8r-dflash.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-iq8r-dflash) | `tp2.yaml` |
|
||||
| Qwen3.8-27B IQR-V4, 2.5 to 8 bits a weight ([docs/IQR.md](docs/IQR.md)), DFlash2 drafter, vision | `qwen3.8-27b-iq2r-v4.rad` .. `qwen3.8-27b-iq8r-v4.rad` (10 to 28 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-iqr-v4) | `tp1.yaml` (IQ4R-L) |
|
||||
| Qwen3.6-35B-A3B IQ8R, MTP | `qwen3.6-35b-a3b-iq8r.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-iq8r) | — |
|
||||
| MiniCPM5-2B IQ8R, DSpark drafter | `minicpm5-2b-iq8r.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-iq8r) | `tp1.yaml`, `tp2.yaml` |
|
||||
| MiniCPM5-2B bf16 (served without its drafter) | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | — |
|
||||
| Spark X2.6 4B bf16: thinking and tool calls, one to four cards | `spark-x2.6-4b-bf16.rad` (8.3 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` |
|
||||
| Gemma 4 31B w5: GPTQ int5 trunk (a scale and a zero point per 128 weights), MTP, vision | `gemma4-31b-w5.rad` (23 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w5) | `gemma4-31b-w5.yaml` |
|
||||
| Gemma 4 31B 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: int8 trunk and lm_head (no calibration), MTP, vision | `gemma4-31b-i8g.rad` (33 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-i8g) | `gemma4-31b-i8g.yaml` |
|
||||
| Gemma 4 31B heretic-ara (refusals removed): int8 trunk and lm_head (no calibration), MTP, vision | `gemma4-31b-heretic-ara-i8g.rad` (33 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-i8g) | `gemma4-31b-heretic-ara-i8g.yaml` |
|
||||
| Gemma 4 31B: int4 trunk, int8 activations and lm_head, DFlash drafter, vision | `gemma4-31b-dense-w4a8-df.rad` (22 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash) | `gemma4-31b-w4a8-df.yaml` |
|
||||
| Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | `gemma4-31b-q8-df.yaml` |
|
||||
| Gemma 4 31B on four cards: int4 trunk, int8 activations and lm_head, RedHatAI's DFlash2 drafter, vision | `gemma4-31b-dense-w4a8-df2-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2) | `gemma4-31b-w4a8-df2-tp4.yaml` |
|
||||
| Gemma 4 31B on four or two cards: int4 trunk, int8 activations and lm_head, a block-16 DFlash2 drafter (15 drafts a step, verified as a tree), vision | `gemma4-31b-dense-w4a8-df2b16-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2-b16) | `gemma4-31b-w4a8-df2b16-tp4.yaml`, `gemma4-31b-w4a8-df2b16-tp2.yaml` |
|
||||
| Gemma 4 12B bf16: MTP, vision, audio | `gemma4-12b-bf16.rad` (25 GiB) | [download](https://huggingface.co/keptn/gemma4-12b-bf16) | `gemma4-12b-bf16.yaml` |
|
||||
| Gemma 4 12B int8 (i8a8): MTP, vision, audio | `gemma4-12b-i8g.rad` (14 GiB) | [download](https://huggingface.co/keptn/gemma4-12b-i8g) | `gemma4-12b-i8g.yaml` |
|
||||
| NVIDIA-Nemotron-3.5-Bolt-E4B bf16 (Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-bf16.rad` (17 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-bf16) | `nemotron-3.5-bolt-e4b-bf16.yaml` |
|
||||
| NVIDIA-Nemotron-3.5-Bolt-E4B int8 (i8a8, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-i8g.rad` (13 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-i8g) | `nemotron-3.5-bolt-e4b-i8g.yaml` |
|
||||
| NVIDIA-Nemotron-3.5-Bolt-E4B 4-bit (int4 feed-forward, GPTQ, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-a4.rad` (12 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-a4) | `nemotron-3.5-bolt-e4b-a4.yaml` |
|
||||
| Ling-3.0-flash-Sante w4a8: 4-bit experts (GPTQ), MTP, four or two cards | `ling-3.0-flash-sante-w4a8.rad` (66 GiB) | [download](https://huggingface.co/keptn/ling-3.0-flash-sante-w4a8) | `ling-3.0-flash-sante-w4a8.yaml`, `ling-3.0-flash-sante-w4a8-tp2.yaml` |
|
||||
| NVIDIA-Nemotron-3.5-Bolt-74B-A9B w4a8: 4-bit experts, FP8 trunk, NVIDIA's LiLiCorr drafter, vision, two cards | `nemotron-3.5-bolt-74b-w4a8.rad` (43 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-74b-w4a8) | `nemotron-3.5-bolt-74b-w4a8.yaml` |
|
||||
| NVIDIA-Nemotron-3.5-Bolt-74B-A9B FP8, NVIDIA's LiLiCorr drafter, vision, four cards | `nemotron-3.5-bolt-74b-fp8.rad` (73 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-74b-fp8) | `nemotron-3.5-bolt-74b-fp8.yaml` |
|
||||
| Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` |
|
||||
| Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` |
|
||||
| Krea 2 Turbo FP8: text to image, one card | `krea-2-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-fp8) | `krea-2-turbo.yaml` |
|
||||
| Krea 2 Raw FP8: the same, undistilled | `krea-2-raw-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-raw-radiance-fp8) | `krea-2-raw.yaml` |
|
||||
| FLUX.3 [klein] FP8: text to image and edits from up to ten pictures, one card | `flux-3-klein-fp8.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-fp8) | `flux-3-klein.yaml` |
|
||||
| FLUX.3 [klein] base FP8 | `flux-3-klein-base-fp8.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-base-fp8) | `flux-3-klein.yaml` |
|
||||
| LTX-2.5 distilled FP8: video with its stereo soundtrack from text or a first frame, one card | `ltx-2.5-distilled-fp8.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-distilled-fp8) | `ltx-2.5.yaml` |
|
||||
| LTX-2.5 base FP8 | `ltx-2.5-fp8.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-fp8) | `ltx-2.5.yaml` |
|
||||
| MiniMax-H3 FP8: video with its stereo soundtrack from text | `minimax-h3-fp8.rad` (60 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-fp8) | `minimax-h3.yaml` |
|
||||
| FastH3 8-Step V2 FP8: the same in eight steps | `fasth3-8-step-v2-fp8.rad` (62 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-fp8) | `fasth3.yaml` |
|
||||
| MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `minimax-music3.yaml` |
|
||||
| Unlimited-OCR bf16: document parsing with the DeepEncoder tower | `unlimited-ocr-bf16.rad` (6.2 GiB) | [download](https://huggingface.co/Aijuus/unlimited-ocr-bf16) | `unlimited-ocr-bf16.yaml` |
|
||||
| Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `breeze-tts2.yaml` |
|
||||
| Fish Audio drama-3: speech with speaker tags and inline direction, voices cloned from reference clips, whole, streamed or live; block-FP8 experts, two cards | `drama3-fp8.rad` (36 GiB) | [convert](#convert-a-checkpoint) | `drama3.yaml` |
|
||||
| Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.yaml` |
|
||||
| TranslateGemma 27B MXFP4 (GPTQ), translation; optional DFlash2 drafter | `translategemma-27b-mxfp4-gptq.rad` (17 GiB) | [convert](#convert-a-checkpoint) | `translategemma-27b.yaml` |
|
||||
| GLM-5.3-Flash: MXFP4 experts and block-FP8 attention (AMD Quark), MTP, vision, eight cards | `glm53-flash-mxfp4.rad` (172 GiB) | [convert](#convert-a-checkpoint) | `glm53-flash.yaml` |
|
||||
| Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` |
|
||||
| Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` |
|
||||
| Stable Diffusion XL bf16 and its finetunes (Illustrious, NoobAI, Pony): text to image, one card | `illustrious-xl-v2.0-bf16.rad` (6.4 GiB), from any single-file SDXL checkpoint | [convert](#convert-a-checkpoint) | `sdxl.yaml` |
|
||||
| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` |
|
||||
| nomic-embed-text-v2-moe bf16: text embeddings, one card | `nomic-embed-v2-moe-bf16.rad` (959 MB) | [convert](#convert-a-checkpoint) | - |
|
||||
| Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | — |
|
||||
| Gemma 4 31B w5: GPTQ int5 trunk (a scale and a zero point per 128 weights), MTP, vision | `gemma4-31b-w5.rad` (23 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w5) | — |
|
||||
| Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | — |
|
||||
| Gemma 4 31B: int8 trunk and lm_head (no calibration), MTP, vision | `gemma4-31b-i8g.rad` (33 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-i8g) | — |
|
||||
| Gemma 4 31B heretic-ara (refusals removed): int8 trunk and lm_head (no calibration), MTP, vision | `gemma4-31b-heretic-ara-i8g.rad` (33 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-i8g) | — |
|
||||
| Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Gemma 4 12B bf16: MTP, vision, audio | `gemma4-12b-bf16.rad` (25 GiB) | [download](https://huggingface.co/keptn/gemma4-12b-bf16) | — |
|
||||
| Gemma 4 12B int8 (i8a8): MTP, vision, audio | `gemma4-12b-i8g.rad` (14 GiB) | [download](https://huggingface.co/keptn/gemma4-12b-i8g) | — |
|
||||
| Qwen-Image 2.1 IQ8R: text to image and image edits | `qwen-image-2.1-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-iq8r) | `tp1.yaml`, `tp2.yaml` |
|
||||
| Qwen-Image 2.1 Turbo IQ8R: the same in 8 steps | `qwen-image-2.1-turbo-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-iq8r) | — |
|
||||
| Krea 2 Turbo IQ8R: text to image, one card | `krea-2-turbo-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-iq8r) | — |
|
||||
| Krea 2 Raw IQ8R: the same, undistilled | `krea-2-raw-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-raw-radiance-iq8r) | — |
|
||||
| FLUX.3 [klein] IQ8R: text to image and edits from up to ten pictures, one card | `flux-3-klein-iq8r.rad` (9.4 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-iq8r) | — |
|
||||
| FLUX.3 [klein] base IQ8R | `flux-3-klein-base-iq8r.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-base-iq8r) | — |
|
||||
| LTX-2.5 distilled IQ8R: video with its stereo soundtrack from text or a first frame, one card | `ltx-2.5-distilled-iq8r.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-distilled-iq8r) | — |
|
||||
| LTX-2.5 base IQ8R | `ltx-2.5-iq8r.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-iq8r) | — |
|
||||
| MiniMax-H3, int8 DiT: video with its stereo soundtrack from text | `minimax-h3-i8.rad` (63 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-i8) | `tp2.yaml` |
|
||||
| FastH3 8-Step V2, int8 DiT: the same in eight steps | `fasth3-8-step-v2-i8.rad` (65 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-i8) | — |
|
||||
| MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `tp1.yaml`, `tp2.yaml` |
|
||||
| Unlimited-OCR bf16: document parsing with the DeepEncoder tower | `unlimited-ocr-bf16.rad` (6.2 GiB) | [download](https://huggingface.co/Aijuus/unlimited-ocr-bf16) | — |
|
||||
| Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `tp1.yaml`, `tp2.yaml` |
|
||||
| TranslateGemma 27B, int8 trunk: translation | `translategemma-27b-i8.rad` (28 GiB) | [download](https://huggingface.co/StillDeadcode/translategemma-27b-i8) | — |
|
||||
| Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Stable Diffusion XL bf16 and its finetunes (Illustrious, NoobAI, Pony): text to image, one card | `illustrious-xl-v2.0-bf16.rad` (6.4 GiB), from any single-file SDXL checkpoint | [convert](#convert-a-checkpoint) | — |
|
||||
| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `tp1.yaml`, `tp2.yaml` |
|
||||
| nomic-embed-text-v2-moe bf16: text embeddings, one card | `nomic-embed-v2-moe-bf16.rad` (959 MB) | [convert](#convert-a-checkpoint) | — |
|
||||
| Nemotron 3.5 Embed 1B BF16: text and image embeddings, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Embed-1B-BF16) | — |
|
||||
| Nemotron 3.5 Embed 8B BF16: text and image embeddings, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16) | — |
|
||||
| Nemotron 3.5 Rerank 8B BF16: text/image document relevance, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Rerank-8B-BF16) | — |
|
||||
| Anima Aesthetic FP8: anime and illustration, text to image, one card (Base and Turbo convert the same way) | `anima-aesthetic-fp8.rad` (3.0 GiB) | [convert](#convert-a-checkpoint) | `anima.yaml` |
|
||||
| Qwen3-ASR 1.7B bf16: speech to text, `/v1/audio/transcriptions` and live over `/v1/realtime`, 30 languages, one card | the checkpoint as it ships (4.1 GiB) | [Qwen/Qwen3-ASR-1.7B-hf](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf) | — |
|
||||
| Nemotron 3.5 Rerank 8B BF16: text/image document relevance, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Rerank-8B-BF16) | `tp1.yaml`, `tp2.yaml` |
|
||||
| Qwen3-ASR 1.7B bf16: speech to text, `/v1/audio/transcriptions` and live over `/v1/realtime`, 30 languages, one card | the checkpoint as it ships (4.1 GiB) | [Qwen/Qwen3-ASR-1.7B-hf](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf) | `tp1.yaml`, `tp2.yaml` |
|
||||
|
||||
**Not served by this version.** A container whose weights are block FP8, MXFP4, M2XFP4 or
|
||||
ParoQuant, or whose experts read E4M3 activations, is refused at startup by the name of the first
|
||||
such weight. That is every FP8 and MXFP4 container of the models above, and the models that have
|
||||
no int8 container yet: Ornith-1.5 (35B-A3B and 122B), Sage-A1.5,
|
||||
NVIDIA-Nemotron-3.5-Bolt-74B-A9B, GLM-5.3-Flash, Ling-3.0-flash-Sante, Fish Audio drama-3 and
|
||||
Anima's FP8 container (Anima converted to bf16 is served). Each returns with an int8 container.
|
||||
A container with an int8 or bf16 trunk and a block-FP8 drafter (NVIDIA-Nemotron-3.5-Bolt-E4B,
|
||||
the Gemma 4 31B DFlash and DFlash2 containers, MiniCPM5-2B bf16) serves without the drafter
|
||||
under `num-speculative-tokens: 0`.
|
||||
|
||||
A container holds everything the server needs: the weights, the tokeniser, the chat template and
|
||||
any drafter. Each download link's repository has the recipe and the exact command that made the
|
||||
@@ -87,7 +75,7 @@ file. Download one into your models directory (the transfer resumes if interrupt
|
||||
|
||||
```sh
|
||||
mkdir -p /srv/models/rad && cd /srv/models/rad
|
||||
curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-fp8/resolve/main/minicpm5-2b-fp8.rad
|
||||
curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-iq8r/resolve/main/minicpm5-2b-iq8r.rad
|
||||
```
|
||||
|
||||
The Gemma 4 container is keptn42's: GPTQ calibrated in transformers, with an int8 lm_head; its
|
||||
@@ -97,38 +85,22 @@ with a scale search, bf16 lm_head); see [Convert a checkpoint](#convert-a-checkp
|
||||
that container decodes at 103 tok/s on prose and 141 on code, against 112 and 150 for keptn42's,
|
||||
and accepts 0.46 of its drafts on prose against 0.50.
|
||||
|
||||
TranslateGemma 27B is converted from Google's bf16 checkpoint in three steps: an int8 container to
|
||||
calibrate in, its Gram matrices over translation prompts, then MXFP4 with GPTQ
|
||||
(`data/recipes/translategemma-27b-*.recipe`, the steps in docs/ARCHITECTURES.md). On two R9700s it
|
||||
decodes 56 tok/s a stream (205 at four) and scores mean KL 0.042 against the bf16 model on held-out
|
||||
translations; with a DFlash2 drafter, 152 a stream. Its chat template takes structured turns
|
||||
naming the two languages and refuses the plain turn the server renders at startup, so
|
||||
`translategemma-27b.yaml` serves a plain Gemma 3 template (`deploy/compose/gemma3.jinja`) and a
|
||||
client sends on `/v1/completions` the prompt the checkpoint's template renders.
|
||||
|
||||
GLM-5.3-Flash is converted from AMD's Quark export (`amd/GLM-5.3-Flash-Quark-MXFP4`) with
|
||||
`data/recipes/glm53-mxfp4.recipe`, which keeps every weight as stored except the latent
|
||||
attention's small kv_b, decoded to bf16. At 172 GiB it takes eight R9700s (`--tp 8`), every expert
|
||||
resident, and its own MTP layer drafts. On eight R9700s it prefills 3958 tok/s at 6k tokens,
|
||||
decodes 166 tok/s on one stream and 426 over eight, and 506 under eight streams of agent turns.
|
||||
Pictures go through its own vision tower, up to 4096 tokens an image at the default encoder pass
|
||||
(`--mm-max-patches 32000` serves the checkpoint's 8000); the KV cache is bf16. Its template knows
|
||||
the reasoning efforts `low` and
|
||||
`high` and renders any other as its maximum, so `glm53-flash.yaml` maps `medium` and `xhigh`
|
||||
to `high`.
|
||||
|
||||
The ParoQuant containers keep the trunk exactly as the ParoQuant releases ship it, with the learned
|
||||
Givens rotations it was trained in. Convert int4 from `z-lab/Qwen3.8-27B-PARO`, int5 from
|
||||
`Launch80/Qwen3.8-27B-PARO-int5` and MXFP4 from `MisterSnrub/Qwen3.8-27B-PARO-MXFP4-v2`, each with
|
||||
`data/recipes/q38-27b-paro-mxfp4-df2.recipe` and the DFlash2 drafter. A ParoQuant container made
|
||||
before 1.5.0 is refused at startup; convert it again with the old one as `--reuse`, which copies
|
||||
every tensor that did not change.
|
||||
TranslateGemma 27B is converted from Google's bf16 checkpoint with
|
||||
`data/recipes/translategemma-27b-i8a8.recipe`, an int8 trunk rounded without calibration data.
|
||||
Its chat template takes structured turns
|
||||
naming the two languages and refuses the plain turn the server renders at startup, so its entry
|
||||
serves a plain Gemma 3 template, `deploy/compose/gemma3.jinja` (`override-chat-template` names it;
|
||||
in a compose file, mount it into the container), and a client sends on `/v1/completions` the prompt
|
||||
the checkpoint's template renders.
|
||||
|
||||
The Qwen-Image containers serve OpenAI's images API (`/v1/images/generations`, `/v1/images/edits`):
|
||||
pictures from a prompt, and edits of up to ten pictures with an optional mask, 2048x2048 by default.
|
||||
On two R9700s a 2048x2048 picture takes 61 s at the base model's 40 steps and 13 s with Turbo (56 and
|
||||
12 s with `--tp-wire wht6`); 1024x1024 takes 6 s and 2.6 s. Qwen-Image 2.1 is under Qwen's research
|
||||
license, which is non-commercial.
|
||||
12 s with `tp-wire: wht6`); 1024x1024 takes 6 s and 2.6 s. Qwen-Image 2.1 is under Qwen's research
|
||||
license, which is non-commercial. Krea 2 is under the Krea 2 Community License and Krea's
|
||||
acceptable use policy, FLUX.3 [klein] under the FLUX Kommunity License (non-commercial use),
|
||||
LTX-2.5 under the LTX-2.x Community License, and an SDXL finetune under its checkpoint's own
|
||||
license.
|
||||
|
||||
The MiniMax-H3 containers serve OpenAI's video jobs (`/v1/videos`): a video with its stereo
|
||||
soundtrack from a prompt, 5 to 14 s, up to 1344x768. On two R9700s a 5.17 s clip at 1344x768 takes
|
||||
@@ -159,20 +131,27 @@ without it the engine keeps kernel arguments in pinned host memory, and every di
|
||||
over the link. The image
|
||||
is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its kernels
|
||||
built for `gfx1201` (RDNA4), `gfx11-generic` (RDNA3) and `gfx1151` (Strix Halo). Pull it, clone
|
||||
this repository for its compose files, then start a model from one of them:
|
||||
this repository for its compose files, then start one of them:
|
||||
|
||||
```sh
|
||||
docker pull stilldeadcode/radiance
|
||||
git clone https://codeberg.org/StillDeadcode/radiance.git
|
||||
cp -r radiance/deploy/compose ~/radiance-compose && cd ~/radiance-compose
|
||||
cp .env.example .env # set RADIANCE_MODELS, RADIANCE_API_KEY, the GIDs
|
||||
docker compose -f minicpm5-2b.yaml up -d # or any file from the table
|
||||
docker compose -f minicpm5-2b.yaml logs -f
|
||||
docker compose -f minicpm5-2b.yaml down
|
||||
docker compose -f tp2.yaml up -d # two cards; tp1.yaml for one (RADIANCE_GPU)
|
||||
docker compose -f tp2.yaml logs -f
|
||||
docker compose -f tp2.yaml down
|
||||
```
|
||||
|
||||
Every model listens on the same port and most use both cards, so run one at a time. Running without
|
||||
compose, and the reason for each `docker run` option, is in [`docs/DOCKER.md`](docs/DOCKER.md).
|
||||
A file serves all its models from one container behind one port, and brings a model onto the cards
|
||||
when a request names it ([`docs/MULTIMODEL.md`](docs/MULTIMODEL.md)): a request's `model` is the
|
||||
entry's name (`flashnext`, `qwen3.8-27b`, `minicpm5-2b`, ...). The entries are in
|
||||
`tp1.radiance.yaml` and `tp2.radiance.yaml` beside the compose files, the server's configuration as
|
||||
it reads it. Delete the entries of the containers
|
||||
you do not have; any other model from the table is added as an entry with its keys from the table
|
||||
under [Run without Docker](#run-without-docker). The two files take the same port, so run one at a
|
||||
time. Running without compose, and the reason for each `docker run` option, is in
|
||||
[`docs/DOCKER.md`](docs/DOCKER.md).
|
||||
|
||||
To build the image yourself, for example for other cards, run `docker/build.sh -t 'gfx1200;gfx1201'`
|
||||
in the clone (it needs `docker buildx` and tests the build as it goes). Then set
|
||||
@@ -201,74 +180,141 @@ prefix gets `bin/`, `include/radiance/`, `lib/cmake/radiance/`, `libexec/radianc
|
||||
With ROCm 10.1 the build turns the compiler's VOPD pairing (dual-issue instruction pairs) off: its
|
||||
LLVM 24 pairs in an order that follows heap addresses, so two builds of the same source can differ.
|
||||
The Docker image builds its compiler with the fix and keeps the pairing, which is 1.4-3.5% faster
|
||||
on the fp8 prefill GEMMs; a compiler that has the same fix is declared with
|
||||
on prefill GEMMs; a compiler that has the same fix is declared with
|
||||
`-DRAD_HIP_VOPD_REPEATABLE=ON`. ROCm 7.2 is unaffected.
|
||||
|
||||
## Run without Docker
|
||||
|
||||
```sh
|
||||
export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an install finds its own
|
||||
build/bin/radiance --model /srv/models/rad/minicpm5-2b-fp8.rad --port 8000 <flags>
|
||||
build/bin/radiance --model StillDeadcode/minicpm5-2b-fp8 --port 8000 <flags>
|
||||
The server reads its settings from a YAML file: `server:` holds the listener, `memory:` the
|
||||
per-card VRAM budget, and `models:` one entry whose name is the model id requests use. Every key
|
||||
is named as in the [`docs/GUIDE.md`](docs/GUIDE.md) §4.11 reference; `radiance --help` prints it.
|
||||
|
||||
```yaml
|
||||
# radiance.yaml
|
||||
server:
|
||||
port: 8000
|
||||
models:
|
||||
minicpm5-2b-iq8r:
|
||||
model: /srv/models/rad/minicpm5-2b-iq8r.rad # or a Hugging Face repo id: StillDeadcode/minicpm5-2b-iq8r
|
||||
```
|
||||
|
||||
`--model` also takes a Hugging Face repo id, as vLLM does. The server fetches the repo with `curl`
|
||||
and `jq` (`scripts/hfget.sh`) into `~/.cache/radiance/hf` (`--download-dir` puts it elsewhere),
|
||||
```sh
|
||||
export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an install finds its own
|
||||
build/bin/radiance --config radiance.yaml --check # validate the file, serve nothing
|
||||
build/bin/radiance --config radiance.yaml
|
||||
```
|
||||
|
||||
`model` also takes a Hugging Face repo id, as vLLM does. The server fetches the repo with `curl`
|
||||
and `jq` (`scripts/hfget.sh`) into `~/.cache/radiance/hf` (`server.download-dir` puts it elsewhere),
|
||||
serves the container it holds, and checks it for changes at every start; a start that cannot reach
|
||||
the hub serves the copy it has. The Docker image carries both tools; in a container,
|
||||
`--download-dir` must name a writable mount, since the compose files mount `/models` read-only.
|
||||
`server.download-dir` must name a writable mount, since the compose files mount `/models` read-only.
|
||||
|
||||
These rows match the compose files, minus Flash-Next's `--prefix-cache-mib`; the three- and
|
||||
four-rank rows have no compose file. The other models' flags are in their compose files.
|
||||
The server takes no other command-line options. A command line written for an earlier release
|
||||
(`radiance --model ... --tp 2`) is refused with the same settings printed as YAML, and
|
||||
`rad-yaml FLAGS...` prints that file without starting anything:
|
||||
`rad-yaml --model x.rad --tp 2 > radiance.yaml`. [`docs/MULTIMODEL.md`](docs/MULTIMODEL.md) §4
|
||||
describes the file's levels.
|
||||
|
||||
| model | flags |
|
||||
Each row holds the keys a model is served with in a file of its own (the Flash-Next rows leave out
|
||||
`prefix-cache-mib`). They go under the model's entry, except `gpu-headroom-mib`, which goes under
|
||||
`memory:` and in a file of several models holds for all of them. `tp1.radiance.yaml` and
|
||||
`tp2.radiance.yaml` carry their models' entries as set for sharing the cards; a model added to either takes its row from
|
||||
here.
|
||||
|
||||
| model | keys |
|
||||
|---|---|
|
||||
| Qwen3.8-Flash-Next | `--tp 2 --tp-wire wht6 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
|
||||
| Qwen3.8-Flash-Next, four ranks | `--tp 4 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
|
||||
| Qwen3.8-Flash-Next, three ranks (the shipped container as it is, [`docs/TP3.md`](docs/TP3.md)) | `--tp 3 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 8192 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
|
||||
| Qwen3.8-27B FP8 and MXFP4, Qwen3.6-35B-A3B | `--tp 2 --max-num-seqs 32 --max-model-len 200000 --kv-cache-dtype fp8` |
|
||||
| Qwen3.8-27B bf16 | `--tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8` |
|
||||
| MiniCPM5-2B FP8 and bf16 | `--tp 2 --max-num-seqs 32 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512` |
|
||||
| Qwen3.8-Flash-Next bf16 | `--tp 2 --max-model-len 32768 --placement expert_tiered --weights-disk-tier --host-pool-mib 12288 --gpu-headroom-mib 768 --deterministic --max-num-seqs 32 --max-num-batched-tokens 32768 --num-speculative-tokens 0` |
|
||||
| Qwen-Image 2.1 and 2.1 Turbo | `--tp 2 --tp-wire wht6` |
|
||||
| MiniMax-H3 and FastH3 | `--tp 2 --vision-tower-placement ram` |
|
||||
| MiniMax-Music3 | `--tp 2` |
|
||||
| Breeze-TTS-2 | `--tp 1` |
|
||||
| Fish Audio drama-3 | `--tp 2` |
|
||||
| Qwen3.8-Flash-Next | `tp: 2, tp-wire: wht6, max-num-seqs: 8, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 24576, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048` |
|
||||
| Qwen3.8-Flash-Next, one card | `tp: 1, max-num-seqs: 4, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 43000, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 4096, checkpoint-interval: 4096` |
|
||||
| Qwen3.8-Flash-Next, four ranks | `tp: 4, max-num-seqs: 8, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 49152, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048` |
|
||||
| Qwen3.8-Flash-Next, three ranks (the shipped container as it is, [`docs/TP3.md`](docs/TP3.md)) | `tp: 3, max-num-seqs: 8, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 24576, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048` |
|
||||
| Qwen3.8-27B IQ8R and IQR-V4, Qwen3.6-35B-A3B | `tp: 2, max-num-seqs: 32, max-model-len: 200000, kv-cache-dtype: i8` |
|
||||
| Qwen3.8-27B bf16 | `tp: 2, max-num-seqs: 8, max-model-len: 200000, kv-cache-dtype: i8` |
|
||||
| MiniCPM5-2B IQ8R and bf16 | `tp: 2, max-num-seqs: 32, max-model-len: 131072, kv-cache-dtype: i8, gpu-headroom-mib: 160, max-num-batched-tokens: 512` |
|
||||
| Qwen3.8-Flash-Next bf16 | `tp: 2, max-model-len: 32768, placement: expert_tiered, weights-disk-tier: true, host-pool-mib: 24576, gpu-headroom-mib: 768, deterministic: true, max-num-seqs: 32, max-num-batched-tokens: 32768, num-speculative-tokens: 0` |
|
||||
| Qwen-Image 2.1 and 2.1 Turbo | `tp: 2, tp-wire: wht6` |
|
||||
| MiniMax-H3 and FastH3 | `tp: 2, vision-tower-placement: ram` |
|
||||
| MiniMax-Music3 | `tp: 2`, or `tp: 1` (20.5 GiB of weights on the card) |
|
||||
| Breeze-TTS-2 | `tp: 1` |
|
||||
| Gemma 4 31B (GPTQ int4) | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64` |
|
||||
| Gemma 4 31B w5, heretic-ara int4, int8 and heretic-ara int8 | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: i8, vision-tower-placement: ram, num-speculative-tokens: 3, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64` |
|
||||
| Gemma 4 31B Q8 | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: i8, num-speculative-tokens: 0, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64` |
|
||||
| Gemma 4 12B bf16 | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: bf16, num-speculative-tokens: 3, max-num-batched-tokens: 2048, mm-max-patches: 1120, temp: 1.0, top-p: 0.95, top-k: 64, chat-template-kwargs: {"enable_thinking":false}` |
|
||||
| Gemma 4 12B int8 | `tp: 1, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: bf16, num-speculative-tokens: 3, max-num-batched-tokens: 2048, mm-max-patches: 1120, temp: 1.0, top-p: 0.95, top-k: 64, chat-template-kwargs: {"enable_thinking":false}` |
|
||||
| NVIDIA-Nemotron-3.5-Bolt-E4B bf16, int8 and 4-bit, without the drafter | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: bf16, num-speculative-tokens: 0, mm-max-patches: 2520, vision-tower-placement: ram, temp: 1.0, top-p: 0.95, top-k: 64, chat-template-kwargs: {"enable_thinking":false}`; `tp: 1` on one card |
|
||||
| TranslateGemma 27B | `tp: 2, max-num-seqs: 8, max-model-len: 16384, kv-cache-dtype: i8`, and `override-chat-template` naming `deploy/compose/gemma3.jinja` |
|
||||
| Unlimited-OCR | `tp: 1, max-num-seqs: 8, max-model-len: 32768, kv-cache-dtype: i8, gpu-headroom-mib: 96`, and `override-chat-template` naming `deploy/chat-templates/unlimited-ocr-parser.jinja` (`/chat-templates/unlimited-ocr-parser.jinja` in the compose files' container) |
|
||||
| Krea 2 Turbo and Raw, FLUX.3 [klein] and its base, Stable Diffusion XL | `tp: 1` |
|
||||
| LTX-2.5 distilled and base | `tp: 1, vision-tower-placement: ram` |
|
||||
| EmbeddingGemma 2 | `tp: 1, max-num-seqs: 64, max-num-batched-tokens: 8192` |
|
||||
| Qwen3-ASR 1.7B | `tp: 1, max-num-seqs: 16` |
|
||||
|
||||
Every model here runs at up to 32 sequences a step. The Flash-Next rows (except the bf16 reference)
|
||||
and the 27B in bf16 keep 8: on a hybrid model each sequence holds its own recurrent state, and 32 of
|
||||
them take that memory from the attention cache and, on Flash-Next, from the expert slab. See
|
||||
The 27B in IQ8R and IQR-V4, the 35B-A3B, MiniCPM5 and the Flash-Next bf16 reference run at up to
|
||||
32 sequences a step. The other Flash-Next rows and the 27B in bf16 keep 8, the one-card Flash-Next
|
||||
row 4: on a hybrid model each sequence holds its own recurrent state, and 32 of them take that
|
||||
memory from the attention cache and, on Flash-Next, from the expert slab. See
|
||||
[`docs/GUIDE.md`](docs/GUIDE.md) §4.4.
|
||||
|
||||
At `--tp 4`, decode and verify steps carry the exact all-reduce in the gated residual's write, with
|
||||
On one card a Flash-Next prefill step copies every pooled expert across the link once, so a
|
||||
4096-token step shares that copy among twice the tokens of a 2048-token one (26K-token prompts:
|
||||
2545 against 1413 tok/s); the checkpoint interval matches the step because a prefill chunk never
|
||||
crosses a checkpoint. At 4 sequences that row's cache holds 301K tokens. The Flash-Next bf16 row
|
||||
is a reference to calibrate and compare against, a step taking tens of seconds whatever its size;
|
||||
its 32K of context keeps QSA's score plane for a 32K-token step at 1 GiB.
|
||||
|
||||
At `tp: 4`, decode and verify steps carry the exact all-reduce in the gated residual's write, with
|
||||
the MoE gather in front of it; a prefill chunk runs the unfused chain. That chain's exact
|
||||
all-reduce is one-shot up to 1 MiB a message and two-shot above, which sends half the bytes on a
|
||||
prefill chunk; both produce the same bits. The four-rank row runs exact. At three and four ranks
|
||||
`--tp-wire wht6` selects a different lossy wire, tiered int8 over the two-shot, above
|
||||
`--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6` stops at startup
|
||||
`tp-wire: wht6` selects a different lossy wire, tiered int8 over the two-shot, above
|
||||
`tp-wire-min-kb`. Eight ranks have no lossy wire, so `tp: 8` with `tp-wire: wht6` stops at startup
|
||||
naming the all-reduce.
|
||||
|
||||
Four ranks is a capacity configuration: its per-step rate against `--tp 2` on the same cards has
|
||||
not been measured, and its tiering flags are the two-rank recipe carried over. As at two ranks, each
|
||||
Four ranks is a capacity configuration: its per-step rate against `tp: 2` on the same cards has
|
||||
not been measured, and its tiering keys are the two-rank recipe carried over. As at two ranks, each
|
||||
rank owns a slice of every expert's width: each parity's 128-column blocks are cut contiguously over
|
||||
the ranks and the odd block alternates with the parity, so every rank's share is whole blocks and
|
||||
every block has one owner. The resident expert bytes per rank are smaller, so the elastic window
|
||||
has a different shape: read the boot log's `elastic` line and re-derive `--host-pool-mib` before
|
||||
has a different shape: read the boot log's `elastic` line and re-derive `host-pool-mib` before
|
||||
trusting it.
|
||||
|
||||
`--host-pool-mib` is pinned on every card, so the four-rank row pins 4 × 12 GiB = 48 GiB of RAM
|
||||
that nothing else can use and the kernel cannot swap out. The amdgpu driver caps what all processes
|
||||
`host-pool-mib` is what a model pins for its weights in all, each rank an equal share: the
|
||||
four-rank row pins 48 GiB of RAM (12 GiB a rank) that nothing else can use and the kernel cannot
|
||||
swap out. The amdgpu driver caps what all processes
|
||||
together pin at the machine's RAM less 1/64 and 1.5 GiB; the pool is locked user memory, which
|
||||
`ttm.pages_limit` does not count. A 64 GiB machine serves `flashnext-tp1.yaml` with 49 GiB pinned
|
||||
([`docs/GUIDE.md`](docs/GUIDE.md) §7).
|
||||
`ttm.pages_limit` does not count. A 64 GiB machine serves the one-card Flash-Next row alone, with
|
||||
`prefix-cache-mib: 4096`, at about 49 GiB pinned ([`docs/GUIDE.md`](docs/GUIDE.md) §7). In
|
||||
`tp1.yaml` its entry carries `prefix-cache-mib: 1024` so its host pins fit such a host beside the
|
||||
8 GiB the fleet keeps free; there it is unloaded when another model loads, and on a 61 GB host it
|
||||
answered its next request after 17 to 19 s, loaded from its container again.
|
||||
|
||||
Add `--api-key KEY` to require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). `--debug-graph`
|
||||
The Gemma 4 rows sample as the checkpoint's `generation_config` states, and a request switches
|
||||
thinking (`chat_template_kwargs`). `vision-tower-placement: ram` keeps the vision tower in host
|
||||
memory, so its VRAM goes to the KV cache. The 31B takes its full 262,144-token context at
|
||||
`max-model-len: 262144, max-num-seqs: 2`. The 12B keeps a bf16 cache because an 8-bit one costs it
|
||||
more than it saves; on Bolt-E4B an E4M3 cache cost 9x the KL and the int8 cache is unmeasured. The
|
||||
Bolt-E4B row serves without speculation because the published containers' drafters are block FP8.
|
||||
|
||||
EmbeddingGemma 2 takes an input in one step, so its `max-num-batched-tokens` is the longest input
|
||||
as well as the batch. A live Qwen3-ASR session holds one sequence, so its `max-num-seqs` is the
|
||||
most sessions served at once. On one card LTX-2.5's adapter slots fit at `max-lora-rank: 16,
|
||||
max-loras: 1` (433 MiB).
|
||||
|
||||
In a file of several models, Qwen-Image's grant counts two sequences of `max-model-len` tokens of
|
||||
cache, which at the model's own 33600 tokens is 55.8 GiB on one card and 32.6 GiB a card on two,
|
||||
more than the cards. `tp1.yaml` sets `max-model-len: 8192` (it needs 29.7 GiB; pictures up to
|
||||
about 1.9 megapixels, 1024x1024 being 4096 tokens) and `tp2.yaml` `20480` (25.4 GiB a card; the
|
||||
default 2048x2048 is 16384 tokens). Alone in a file it loads at its own length, its cache taking
|
||||
what the cards have left. It sizes its buffers itself and warns that it does not take
|
||||
`image-gen-max-pixels` or `image-gen-max-refs`.
|
||||
|
||||
Add `server.api-key: KEY` (or `server.api-key-env: VAR`, which reads it from the environment) to
|
||||
require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). `debug-graph: true` on the model
|
||||
prints every op and the kernel it resolved to, then exits without serving. A chat request:
|
||||
|
||||
```sh
|
||||
curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' \
|
||||
-d '{"model":"m","messages":[{"role":"user","content":"hi"}],"max_tokens":50}'
|
||||
-d '{"model":"minicpm5-2b-iq8r","messages":[{"role":"user","content":"hi"}],"max_tokens":50}'
|
||||
```
|
||||
|
||||
An image model answers OpenAI's images API instead, with base64 pictures:
|
||||
@@ -305,9 +351,6 @@ build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-dense-q
|
||||
--recipe data/recipes/gemma4-31b-dense-bf16-q8-df.recipe \
|
||||
--set quantization_config.quant_method=compressed-tensors \
|
||||
--draft-model /srv/models/hf/z-lab/gemma-4-31B-it-DFlash
|
||||
build/bin/rad-convert /srv/models/hf/z-lab/Qwen3.8-27B-PARO -o qwen3.8-27b-paro-int4.rad \
|
||||
--recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe \
|
||||
--draft-model /srv/models/hf/z-lab/Qwen3.8-27B-DFlash2
|
||||
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
|
||||
@@ -319,16 +362,15 @@ build/bin/rad-convert /srv/models/hf/OnomaAIResearch/Illustrious-XL-v2.0/Illustr
|
||||
|
||||
With Docker, use `docker run --rm -v /srv/models:/models --entrypoint rad-convert stilldeadcode/radiance ...`.
|
||||
In the image the recipes are in `/opt/radiance/share/radiance/recipes/`. A checkpoint served at its
|
||||
own precision needs no container: `radiance --model /srv/models/hf/Qwen/Qwen3.8-27B-FP8`. A release
|
||||
someone else quantised is read as it ships when the engine serves its form (block-scaled FP8,
|
||||
Quark's MXFP4), written at its own numbers when the kernels read them in another spelling (an int4
|
||||
W4A16 release, compressed-tensors' AWQ and GPTQ or AutoRound's, on the 4-bit GEMMs with
|
||||
`data/recipes/q38-27b-w4a16.recipe`), and converted from its exact dequantisation when no kernel
|
||||
reads it: NVFP4 (compressed-tensors' and NVIDIA ModelOpt's) to the MXFP4 kernels, an AutoRound
|
||||
Flash-Next's int4 block projections to int8. [docs/GUIDE.md](docs/GUIDE.md) names the recipes of record
|
||||
own precision needs no container: its directory is the entry's `model`
|
||||
(`model: /srv/models/hf/Qwen/Qwen3.8-27B`). A release someone else quantised to an integer grid is
|
||||
written at its own numbers where the kernels read them (an int4 W4A16 release, compressed-tensors'
|
||||
AWQ and GPTQ or AutoRound's, on the 4-bit GEMMs with `data/recipes/q38-27b-w4a16.recipe`). Block
|
||||
FP8, MXFP4, NVFP4 and ParoQuant releases are not served: convert the model's bf16 checkpoint with
|
||||
an int8 recipe. [docs/GUIDE.md](docs/GUIDE.md) names the recipes of record
|
||||
with their `rad-convert` commands.
|
||||
|
||||
Spark X2.6 runs BF16 at `--tp 1`, `2`, `3` or `4` -- and `8`, the worlds libr4d has an exact
|
||||
Spark X2.6 runs BF16 at `tp: 1`, `2`, `3` or `4` -- and `8`, the worlds libr4d has an exact
|
||||
all-reduce for -- without a drafter or quantisation recipe. Its checkpoint's chat template enables
|
||||
thinking by default; replies return reasoning in `reasoning_content`. Set
|
||||
`chat_template_kwargs.enable_thinking` to `false` for a non-thinking request. Tool calls use the
|
||||
|
||||
+14
-4
@@ -19,7 +19,7 @@ extern "C" {
|
||||
* version is refused at load with both versions printed. Each also exports the layout's fingerprint
|
||||
* (rad_abi_layout.h), so two layouts given one number are refused as well. A new optional export
|
||||
* (e.g. rad_plugin_reference) is not a change of shape: a plugin without it gets the default. */
|
||||
#define RAD_ABI_VERSION 37u
|
||||
#define RAD_ABI_VERSION 39u
|
||||
|
||||
/* ================================================================== plugin identity */
|
||||
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
|
||||
@@ -62,8 +62,8 @@ typedef struct RadArgs {
|
||||
int world_size;
|
||||
/* ABI 35: host-side maximum KV length represented by this exact launch operand (a seqused
|
||||
* span or a supported one-sequence prefill boundary), or -1 when it cannot be proven. In a
|
||||
* decode, verify or draft pass of an architecture with no rad_arch_pass_key it is instead the
|
||||
* step's context bound plus its longest query, which the recorded pass's key holds. Plugins
|
||||
* decode, verify or draft pass it is instead the step's context bound plus its longest query,
|
||||
* which the recorded pass's key holds. Plugins
|
||||
* must not infer it from a device pointer or synchronously read device memory to get it. */
|
||||
int32_t kv_used_max_h;
|
||||
/* The current rank's WGP count (HIP multiProcessorCount on RDNA); lets split launchers use
|
||||
@@ -162,7 +162,8 @@ typedef int (*RadLayoutFn)(const RadParam* p, int n_p, int operand, const RadEnc
|
||||
|
||||
/* Write the stored form `layout` described into `dst`, `dst_bytes` long, from the planes, which
|
||||
* now carry their bytes. Pure host code, run by the loader on a pool behind the container read,
|
||||
* so it has to keep pace with the disk. */
|
||||
* so it has to keep pace with the disk. The planes are read only: the loader may hand them
|
||||
* straight out of its read buffer, which the copies for other ranks read at the same time. */
|
||||
typedef int (*RadRelayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const RadTensor* planes, int n_planes, void* dst,
|
||||
int64_t dst_bytes);
|
||||
@@ -515,6 +516,15 @@ const RadKernelInfo* rad_kernel_at(int i);
|
||||
typedef int (*RadPluginOpenFn) (void);
|
||||
typedef void (*RadPluginCloseFn)(void);
|
||||
|
||||
/* Optional, symbol `rad_plugin_freed`. The core has freed the device memory [base, base + bytes)
|
||||
* and nothing launched against it runs any more. A kernel library that keeps state keyed by an
|
||||
* operand's address (a counter block per output buffer, made at the first launch and replayed by
|
||||
* recorded passes) drops what it keeps for addresses inside the range. A process serving several
|
||||
* models frees an engine's memory when it unloads the model, so state kept past that would pile
|
||||
* up with every load. Called from the freeing thread, any number of times, possibly for ranges the
|
||||
* plugin never saw. */
|
||||
typedef void (*RadPluginFreedFn)(const void* base, int64_t bytes);
|
||||
|
||||
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means every launch reads and writes
|
||||
* only its operands and the scratch it was handed (no allocation it keeps, no counter kept between
|
||||
* launches), so two launches may run at once on one device when their operands and scratch do not
|
||||
|
||||
@@ -17,7 +17,7 @@ ABI_FIELD(RadArchProbe, gen_patches)
|
||||
ABI_FIELD(RadArchProbe, gen_audio)
|
||||
ABI_FIELD(RadArchProbe, gen_ctx)
|
||||
ABI_FIELD(RadArchProbe, gen_video)
|
||||
ABI_FIELD(RadArchProbe, kv_quant_ok)
|
||||
ABI_FIELD(RadArchProbe, kv_fp8_ok)
|
||||
ABI_FIELD(RadArchProbe, chain_pays)
|
||||
ABI_FIELD(RadArchProbe, kv_stream_ok)
|
||||
ABI_FIELD(RadArchProbe, control_vector_ok)
|
||||
@@ -130,8 +130,6 @@ ABI_FIELD(RadBuildCtx, max_enc_patches)
|
||||
ABI_FIELD(RadBuildCtx, max_out_rows)
|
||||
ABI_FIELD(RadBuildCtx, max_audio_frames)
|
||||
ABI_FIELD(RadBuildCtx, max_mixed_tok)
|
||||
ABI_FIELD(RadBuildCtx, kv_quant)
|
||||
ABI_FIELD(RadBuildCtx, attn_prefill_fp8)
|
||||
ABI_FIELD(RadBuildCtx, kv_resident_blocks)
|
||||
ABI_FIELD(RadBuildCtx, kv_stream_ok)
|
||||
ABI_FIELD(RadBuildCtx, cvec)
|
||||
@@ -147,6 +145,7 @@ ABI_FIELD(RadBuildCtx, calib_tokens)
|
||||
ABI_FIELD(RadBuildCtx, gen_max_pixels)
|
||||
ABI_FIELD(RadBuildCtx, gen_max_refs)
|
||||
ABI_FIELD(RadBuildCtx, expert_file_tier)
|
||||
ABI_FIELD(RadBuildCtx, slot_base)
|
||||
ABI_STRUCT(RadAudioGenBatch)
|
||||
ABI_FIELD(RadAudioGenBatch, n_lane)
|
||||
ABI_FIELD(RadAudioGenBatch, lane)
|
||||
|
||||
+76
-61
@@ -56,35 +56,27 @@ double rad_meta_getf(const RadModelMeta* m, const char* key, double dflt);
|
||||
const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* dflt);
|
||||
|
||||
/* ================================================================== build context */
|
||||
/* RadBuildCtx::kv_quant. A layout groups each head's dims by 32 with an f16 scale per group, the
|
||||
* group's absmax over the largest code. A token's row in a head, at head_dim HD (a multiple of 32):
|
||||
/* A paged cache group's dtype says how a token's row in a head is laid out, at head_dim HD:
|
||||
*
|
||||
* RAD_KVQ_V4 (fp8_v4), 25 * HD / 16 bytes:
|
||||
* [0, HD) K, E4M3 as the fp8 cache stores it
|
||||
* [HD, 3HD/2) V's int4 codes, dim d in the nibble at bit 4 * (d % 2) of byte d / 2
|
||||
* [3HD/2, 25HD/16) V's scales (absmax / 7)
|
||||
* RAD_KVQ_K6V4 (k6_v4), 22 * HD / 16 bytes:
|
||||
* [0, HD/2) K's low four bits, as V's codes above
|
||||
* [HD/2, 3HD/4) K's high two bits, a 4-byte word per 16 dims whose byte j holds dims 2j
|
||||
* and 2j+1 in bits 0-3 and dims 8+2j and 9+2j in bits 4-7
|
||||
* [3HD/4, 5HD/4) V's int4 codes
|
||||
* [5HD/4, 21HD/16) K's scales (absmax / 31)
|
||||
* [21HD/16, 22HD/16) V's scales (absmax / 7)
|
||||
*
|
||||
* Codes are two's complement (int4 -7..7, int6 -31..31). The group is declared at RAD_F8E4M3 with
|
||||
* head_dim the row's bytes / 2 so the core sizes pages from it; only the layout's kernels read
|
||||
* it. */
|
||||
enum {
|
||||
RAD_KVQ_NONE = 0,
|
||||
RAD_KVQ_V4 = 1,
|
||||
RAD_KVQ_K6V4 = 2
|
||||
};
|
||||
* RAD_BF16, 4 * HD bytes: K then V, as the model computes them.
|
||||
* RAD_I8, 2 * HD + 4 bytes: K and V as int8 codes with one f16 scale each per (token, head):
|
||||
* [0, HD) K's int8 codes (two's complement, -127..127)
|
||||
* [HD, 2HD) V's int8 codes
|
||||
* [2HD, 2HD + 2) K's scale (the head's absmax / 127)
|
||||
* [2HD + 2, 2HD + 4) V's scale (absmax / 127)
|
||||
* The plugin declares HD; the core adds the scales' bytes (rad_kv_row_elems). */
|
||||
|
||||
/* The products of the prefill attention a deployment accepts in e4m3 (RadBuildCtx::
|
||||
* attn_prefill_fp8, `attn_paged`'s `prefill_fp8`): bits, so both is 3. */
|
||||
/* Elements of a token's row in one head of a paged group declared at `dtype` and `head_dim`: K
|
||||
* then V, and under the int8 cache the two f16 scales after them. */
|
||||
static inline int64_t rad_kv_row_elems(uint32_t dtype, int64_t head_dim) {
|
||||
return 2 * head_dim + (dtype == RAD_I8 ? 4 : 0);
|
||||
}
|
||||
|
||||
/* RadArchProbe::chain_pays. */
|
||||
enum {
|
||||
RAD_ATTN_FP8_QK = 1, /* Q.K^T, the query rounded to e4m3 after the softmax scale */
|
||||
RAD_ATTN_FP8_PV = 2 /* P.V, the probabilities rounded to e4m3 */
|
||||
RAD_CHAIN_NONE = 0,
|
||||
RAD_CHAIN_SPEC = 1, /* with a drafter decoding speculatively */
|
||||
RAD_CHAIN_ALWAYS = 2 /* with or without one */
|
||||
};
|
||||
|
||||
typedef struct RadBuildCtx {
|
||||
@@ -111,17 +103,16 @@ typedef struct RadBuildCtx {
|
||||
int64_t tp_wire_min_bytes;
|
||||
|
||||
|
||||
/* The KV cache dtype, a deployment choice rather than a property of the checkpoint: fp8
|
||||
* weights may want a bf16 cache and vice versa.
|
||||
/* The KV cache dtype, a deployment choice rather than a property of the checkpoint.
|
||||
*
|
||||
* RAD_DT_INVALID (the zero-initialised default) means the plugin's default, bf16 for every
|
||||
* architecture in this tree. RAD_F8E4M3 is the only other implemented value: the fp8kv
|
||||
* attention family is band-gated on it, and the store side writes E4M3 with per-(sequence,
|
||||
* head) descales. `kv_quant` below narrows the trunk's attention cache further.
|
||||
* architecture in this tree. RAD_I8 is the other value every paged attention serves, the
|
||||
* int8 cache above: the attention kernels band on it and the store writes each token's codes
|
||||
* and scales. RAD_F8E4M3 reaches only a plugin whose probe sets RadArchProbe::kv_fp8_ok.
|
||||
*
|
||||
* An ABI field rather than an environment variable because it changes what the model
|
||||
* computes, so it must have one visible answer: --kv-cache-dtype. */
|
||||
int kv_dtype; /* RAD_DT_INVALID = the plugin's default (bf16); or RAD_F8E4M3 */
|
||||
int kv_dtype; /* RAD_DT_INVALID = the plugin's default (bf16); RAD_I8; RAD_F8E4M3 */
|
||||
int is_draft; /* this builder scope is a drafter (spec §10) */
|
||||
const char* scope; /* "", "draft", "vision", "audio" -- prefixes declared names */
|
||||
|
||||
@@ -172,25 +163,6 @@ typedef struct RadBuildCtx {
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int64_t max_mixed_tok;
|
||||
|
||||
/* A narrower layout of the trunk's attention cache under kv_dtype RAD_F8E4M3, from
|
||||
* --kv-cache-dtype fp8_v4 or k6_v4: a RAD_KVQ_* (below). The engine sets it only for a plugin
|
||||
* whose probe has the layout's bit in RadArchProbe::kv_quant_ok and refuses the flag
|
||||
* otherwise, so no plugin sees it that would store plain E4M3 instead. A drafter's cache stays
|
||||
* E4M3.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int kv_quant;
|
||||
|
||||
/* ---- appended in ABI 26 (fp8 prefill attention) */
|
||||
/* RAD_ATTN_FP8_* bits from --attn-prefill-fp8: the attention products the deployment accepts
|
||||
* in e4m3 rather than exactly. 0 (the zero-initialised default) is exact. A plugin passes a
|
||||
* nonzero value on as `attn_paged`'s `prefill_fp8` (docs/OPS.md) and omits the parameter at
|
||||
* 0, so an exact declare is unchanged. The engine refuses to start when no resolved kernel
|
||||
* takes it, so a plugin that ignores the field is refused rather than silently exact.
|
||||
*
|
||||
* Zero-defaulted and in the padding after kv_quant, so no other field moves. */
|
||||
int attn_prefill_fp8;
|
||||
|
||||
/* ---- appended in ABI 30 (KV streaming) */
|
||||
/* --kv-resident in tokens, 0 when nothing streams: the ring a streamed group carves is this in
|
||||
* whole blocks, raised to the engine's floors and clamped to the context. A plugin states it as
|
||||
@@ -301,8 +273,24 @@ typedef struct RadBuildCtx {
|
||||
* drive has to be stored whole, so a plugin that can lay its routed experts out either way
|
||||
* keeps them whole for this; 0 leaves it free to split them across the ranks by width. */
|
||||
int expert_file_tier;
|
||||
|
||||
/* ---- appended in ABI 38 (several engines in one process) */
|
||||
/* The first of this engine's slots. Each engine in the process holds a contiguous block of
|
||||
* slots, one per rank, so an instance's slot, `slot_base + rank` (rad_build_slot), is unique
|
||||
* among the ranks of every engine alive, where `rank` is unique only within one engine. A
|
||||
* plugin keeps per-instance state (handles, geometry, its step's view of the model) indexed by
|
||||
* the slot, and reads it back in step() with rad_slot(). Zero, the default, makes the slot the
|
||||
* rank: one engine in a process, or a test driving a plugin alone. Two engines may serve the
|
||||
* same plugin at once only when it says so (rad_arch_multi_instance). */
|
||||
int slot_base;
|
||||
} RadBuildCtx;
|
||||
|
||||
/* The most instances (engine ranks) one process holds at once; every slot is below it. */
|
||||
#define RAD_MAX_SLOTS 32
|
||||
|
||||
/* The declaring instance's slot (see RadBuildCtx::slot_base). */
|
||||
static inline int rad_build_slot(const RadBuildCtx* c) { return c->slot_base + c->rank; }
|
||||
|
||||
/* ================================================================== control vectors */
|
||||
/* A direction per layer, in the shape llama.cpp's `--cvec-mode project` applies it:
|
||||
*
|
||||
@@ -834,6 +822,23 @@ int rad_drafter_shared_kv(RadBuilder* b, int pos_offset);
|
||||
* the drafter's passes (the KL mode drafts nothing, so trees do not apply there). */
|
||||
int rad_drafter_tree(RadBuilder* b, rad_buf parents);
|
||||
|
||||
/* The model's routing counts live in `table`: an i32 RAD_BUF_PERSIST device buffer of at least
|
||||
* [layers, n_expert], one row per layer that reports (rad_route_report's `layer`, so a head past
|
||||
* the trunk counts) and n_expert the model's expert count. Each layer's router writes its counts
|
||||
* into its own row and the report names that row as RadRouting::expert_count; the core takes it
|
||||
* in place and copies the pass's rows to the host once, at the end of the pass. Without a table
|
||||
* the core keeps the rows itself and a report costs one copy dispatch per routed layer on the
|
||||
* compute stream, since a plugin cannot bind the core's rows as operands of a recorded pass. A
|
||||
* report naming any other buffer is still copied, into the layer's row of the table.
|
||||
*
|
||||
* A row per layer also means a consumer that reads a layer's counts later in stream order (the
|
||||
* file stager, at the layer's first expert op) reads that layer's, which one buffer shared by
|
||||
* every layer does not guarantee once a later layer's router has run.
|
||||
*
|
||||
* Called at most once. The row count is checked when a context binds, where the reporting layers
|
||||
* are known. Additive export; RAD_ABI_VERSION does not move. */
|
||||
int rad_route_table(RadBuilder* b, rad_buf table);
|
||||
|
||||
/* Whether this engine's launches chain (RadKernelChainFn, abi/rad_abi.h): the core's decision, on
|
||||
* the AQL backend only, which keeps a completion counter per queue, where the model's plugin
|
||||
* measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes
|
||||
@@ -1593,6 +1598,13 @@ const char* rad_arch_quant(void);
|
||||
* move. */
|
||||
int rad_arch_serves_imports(void);
|
||||
|
||||
/* Nonzero when every piece of per-instance state the plugin keeps is indexed by
|
||||
* rad_build_slot() / rad_slot(), so several engines in one process may run it at once
|
||||
* (docs/MULTIMODEL.md §3.3). Optional: absent or zero, the core runs the plugin for one engine at
|
||||
* a time and refuses a second engine on it by name. arch/common/rad_arch.h writes it with
|
||||
* RAD_ARCH_MULTI_INSTANCE(). */
|
||||
int rad_arch_multi_instance(void);
|
||||
|
||||
/* What the plugin can say before it declares anything. Optional: a plugin that does not export
|
||||
* it answers zero to everything, each field's default.
|
||||
*
|
||||
@@ -1652,17 +1664,18 @@ typedef struct RadArchProbe {
|
||||
* `gen_rows` (its largest pass: a step's packed sequence at the largest size and length). It
|
||||
* keeps no KV. */
|
||||
int32_t gen_video;
|
||||
/* The RadBuildCtx::kv_quant layouts the plugin serves for this model, bit 1 << RAD_KVQ_*:
|
||||
* libr4d has their rows for its attention geometry. A layout whose bit is clear is refused at
|
||||
* startup with the plugin named. */
|
||||
int32_t kv_quant_ok;
|
||||
/* Nonzero when the plugin serves an E4M3 cache for this model (--kv-cache-dtype fp8,
|
||||
* RadBuildCtx::kv_dtype RAD_F8E4M3): GLM-5.3's latent attention. The engine refuses the flag
|
||||
* for a plugin that leaves it zero, naming the int8 cache every paged attention serves. */
|
||||
int32_t kv_fp8_ok;
|
||||
|
||||
/* ---- appended in ABI 26 (chained launches, control vectors) */
|
||||
/* Nonzero when this plugin measured its speculative step faster with chained launches
|
||||
* (RadKernelChainFn: a dependent kernel waits in its own prologue rather than behind the
|
||||
* queue's barrier bit). With a drafter decoding speculatively on the AQL backend, the core
|
||||
* then takes them. Zero keeps them off: plain decode measured slower chained, and a plugin
|
||||
* that never measured them asks for nothing. */
|
||||
/* How this plugin measured chained launches (RadKernelChainFn: a dependent kernel waits in its
|
||||
* own prologue rather than behind the queue's barrier bit), a RAD_CHAIN_*. SPEC: its
|
||||
* speculative step is faster with them, and the core takes them on the AQL backend while a
|
||||
* drafter decodes speculatively. ALWAYS: its plain decode is faster too, and the core takes
|
||||
* them with or without a drafter. Zero keeps them off: some models' plain decode measured
|
||||
* slower chained, and a plugin that never measured them asks for nothing. */
|
||||
int32_t chain_pays;
|
||||
/* ---- appended in ABI 30 (KV streaming) */
|
||||
/* Nonzero when the architecture can stream a KV group between host memory and a VRAM ring: its
|
||||
@@ -1949,7 +1962,9 @@ void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch);
|
||||
/* Optional. Return a stable fingerprint of actual dispatch geometry whose grid depends on live
|
||||
* per-group seqused values. `kv_used_max_h[g]` is the host maximum for batch->kv[g], and
|
||||
* rad_ctx_wgp_count(c) supplies the device's WGP count. Return 0 when exact geometry is unknown;
|
||||
* that pass runs live and is not recorded. */
|
||||
* that pass runs live and is not recorded. Only prefill and mixed launches read the live maximum:
|
||||
* in a decode, verify or draft pass every launch reads the step's keyed context bound
|
||||
* (RadArgs::kv_used_max_h), so such a pass needs no geometry here and returns nonzero. */
|
||||
uint64_t rad_arch_pass_key(struct RadCtx* c, const struct RadBatch* batch,
|
||||
const int32_t* kv_used_max_h);
|
||||
|
||||
|
||||
@@ -936,6 +936,9 @@ int rad_kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGrou
|
||||
int layer);
|
||||
int rad_kv_stage_next(RadCtx* c, rad_kvgroup group, int layer);
|
||||
int rad_rank(RadCtx* c);
|
||||
/* The instance's slot, rad_build_slot() of the declare that built it: what a plugin indexes its
|
||||
* per-instance state by. */
|
||||
int rad_slot(RadCtx* c);
|
||||
int rad_world_size(RadCtx* c);
|
||||
/* Workgroups the current rank's card can run concurrently (HIP multiProcessorCount on RDNA;
|
||||
* 32 on the host backend or when the backend has no positive count). */
|
||||
|
||||
@@ -184,7 +184,7 @@ struct Model {
|
||||
std::string mul, add;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype,
|
||||
std::initializer_list<int64_t> shape, int access, int group) {
|
||||
@@ -978,8 +978,9 @@ static int find_prefix(RadBuilder* b, Model& m, const char** marker) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta, ctx));
|
||||
@@ -1335,7 +1336,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->gen_b) {
|
||||
rad_step_fail(c, "anima is an image generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1361,6 +1362,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(anima)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(anima, "anima", "", "0.1.0",
|
||||
"Anima (Base, Aesthetic, Turbo): Qwen3-0.6B through the LLM adapter, Cosmos-Predict2's "
|
||||
"2B diffusion transformer and the Qwen-Image VAE; bf16 or block-fp8 linears")
|
||||
|
||||
@@ -324,7 +324,7 @@ struct Model {
|
||||
Layer draft{};
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) {
|
||||
return rad_meta_geti(m, key, fallback);
|
||||
@@ -511,13 +511,14 @@ static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc) {
|
||||
/* ============================== declare ============================== */
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS)
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
const int world = ctx->world_size ? ctx->world_size : 1;
|
||||
/* A sizing declare writes scratch: the step reads g_model, filled by the real declare at the
|
||||
* real max_tok (RadBuildCtx::shape_probe). */
|
||||
static thread_local Model probe_model;
|
||||
Model& m = ctx->shape_probe ? probe_model : g_model[ctx->rank];
|
||||
Model& m = ctx->shape_probe ? probe_model : g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
auto& g = m.g;
|
||||
@@ -831,7 +832,7 @@ static void draft_pass(RadCtx* c, Model& m, const RadBatch* batch) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
const int64_t T = batch->n_tok, E = m.g.n_embd;
|
||||
if (batch->enc) {
|
||||
rad_step_fail(c, "bailing_hybrid serves text");
|
||||
@@ -880,6 +881,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(bailing_hybrid)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(bailing_hybrid, "bailinghybrid", "", "0.1.0",
|
||||
"Ling-3.0 (bailing_hybrid): KDA and dense latent attention, group-routed experts")
|
||||
#endif
|
||||
@@ -225,7 +225,7 @@ struct Model {
|
||||
rad_buf b_vout = 0, b_audio = 0;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* ================================================================== declare helpers */
|
||||
static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, rad_buf x,
|
||||
@@ -1185,8 +1185,9 @@ static int check_format(const RadModelMeta* meta) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -1475,7 +1476,7 @@ static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->agen_b) {
|
||||
rad_step_fail(c, "breeze is an audio generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1521,6 +1522,8 @@ RAD_ARCH_PROBE(breeze)
|
||||
extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap) {
|
||||
return breeze::text_prepare(field, in, out, cap);
|
||||
}
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(breeze, "breeze", "", "0.1.0",
|
||||
"Breeze-TTS-2: a T5Gemma 2 text encoder over a Qwen3 backbone with a 16-codebook "
|
||||
"depth decoder and the Qwen3-TTS 12 Hz codec; 24 kHz mono speech")
|
||||
|
||||
@@ -21,11 +21,12 @@ namespace clef_bf16 {
|
||||
using namespace rad::arch;
|
||||
|
||||
/* One head per rank beside the trunk's own per-rank state (qwen35_bf16::g_model). */
|
||||
static ClefHead g_head[MAX_RANKS];
|
||||
static ClefHead g_head[MAX_SLOTS];
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (!ClefHead::present(meta)) {
|
||||
std::fprintf(stderr, "radiance: clef_bf16 serves a container converted with "
|
||||
"--set decision.type=clef and the head added (--add "
|
||||
@@ -36,13 +37,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* The trunk's declare does not take part in sizing declares (no probe), so its state and the
|
||||
* head's are the real ones. The head goes after the vision tower: its buffers join the same
|
||||
* arena, and it reads the final norm's rows, the lm_head and the trunk's cache block size. */
|
||||
qwen35_bf16::Model& m = qwen35_bf16::g_model[ctx->rank];
|
||||
qwen35_bf16::Model& m = qwen35_bf16::g_model[rad_build_slot(ctx)];
|
||||
/* The lm_head's row would be sampled once and discarded: with this fill declared, the trunk
|
||||
* skips the lm_head on a step every sampled row of which carries a request's words
|
||||
* (plugin_words_cover_rows) and leaves zero rows instead. */
|
||||
m.op_logits_fill = clef_logits_fill(b, m.nm, m.g, m.b_logits);
|
||||
if (!m.op_logits_fill) return RAD_E_INVAL;
|
||||
ClefHead& h = g_head[ctx->rank];
|
||||
ClefHead& h = g_head[rad_build_slot(ctx)];
|
||||
h = ClefHead{};
|
||||
return h.declare(b, meta, ctx, m.nm, m.g, m.b_h, m.b_logits, m.w_lm_head, m.kv_full,
|
||||
(int)m.g.n_layer + 256);
|
||||
@@ -52,8 +53,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
qwen35_bf16::step(c, batch);
|
||||
/* An encoder pass runs the tower alone and leaves no rows for the head. */
|
||||
if (batch->enc) return;
|
||||
qwen35_bf16::Model& m = qwen35_bf16::g_model[rad_rank(c)];
|
||||
ClefHead& h = g_head[rad_rank(c)];
|
||||
qwen35_bf16::Model& m = qwen35_bf16::g_model[rad_slot(c)];
|
||||
ClefHead& h = g_head[rad_slot(c)];
|
||||
/* The final norm's rows are still in `h` after the trunk's step; the logits row of each
|
||||
* sampled sequence has been written, and the head adds its values beside it. */
|
||||
h.step_tokens(c, batch, m.b_h);
|
||||
@@ -62,6 +63,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
|
||||
} /* namespace clef_bf16 */
|
||||
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(clef_bf16, "clef", "", "0.1.0",
|
||||
"Cloudflare's clef / clef-flash (9B, 27B): the Qwen3.5 trunk of qwen35_bf16, bf16, "
|
||||
"with the joint schema head on the card for /v1/systemone")
|
||||
@@ -21,11 +21,12 @@ namespace clef_fp8 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
static ClefHead g_head[MAX_RANKS];
|
||||
static ClefHead g_head[MAX_SLOTS];
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (!ClefHead::present(meta)) {
|
||||
std::fprintf(stderr, "radiance: clef_fp8 serves a container converted with "
|
||||
"--set decision.type=clef and the head added (--add "
|
||||
@@ -33,13 +34,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(qwen35_clef_fp8::declare(b, meta, ctx));
|
||||
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[ctx->rank];
|
||||
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[rad_build_slot(ctx)];
|
||||
/* The lm_head's row would be sampled once and discarded: with this fill declared, the trunk
|
||||
* skips the lm_head on a step every sampled row of which carries a request's words
|
||||
* (plugin_words_cover_rows) and leaves zero rows instead. */
|
||||
m.op_logits_fill = clef_logits_fill(b, m.nm, m.g, m.b_logits);
|
||||
if (!m.op_logits_fill) return RAD_E_INVAL;
|
||||
ClefHead& h = g_head[ctx->rank];
|
||||
ClefHead& h = g_head[rad_build_slot(ctx)];
|
||||
h = ClefHead{};
|
||||
return h.declare(b, meta, ctx, m.nm, m.g, m.a_h.x, m.b_logits, m.w_lm_head, m.kv_full,
|
||||
(int)m.g.n_layer + 256);
|
||||
@@ -49,8 +50,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
qwen35_clef_fp8::step(c, batch);
|
||||
/* An encoder pass leaves no rows for the head, and a drafter's pass is not a trunk step. */
|
||||
if (batch->enc || batch->draft_pass != 0) return;
|
||||
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[rad_rank(c)];
|
||||
ClefHead& h = g_head[rad_rank(c)];
|
||||
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[rad_slot(c)];
|
||||
ClefHead& h = g_head[rad_slot(c)];
|
||||
/* The final norm's rows are in `a_h.x` after either of the trunk's step paths. */
|
||||
h.step_tokens(c, batch, m.a_h.x);
|
||||
if (batch->n_out > 0) h.step_heads(c, batch, m.b_logits, m.w_lm_head);
|
||||
@@ -59,6 +60,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
} /* namespace clef_fp8 */
|
||||
|
||||
RAD_ARCH_PROBE(qwen35_clef_fp8)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(clef_fp8, "clef", "fp8_e4m3", "0.1.0",
|
||||
"Cloudflare's clef / clef-flash (9B, 27B): the Qwen3.5 trunk of qwen35_fp8, "
|
||||
"block-scaled fp8, with the joint schema head on the card for /v1/systemone")
|
||||
+22
-21
@@ -37,9 +37,12 @@ namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* One thread per tensor-parallel rank in one process (spec §1), and declare runs once per rank,
|
||||
* so declared handles are per-rank state; a single global would let rank 1 overwrite rank 0.
|
||||
* libr4d all-reduces over 2/4/8 ranks, hence eight. */
|
||||
enum { MAX_RANKS = 8 };
|
||||
* so declared handles are per-instance state; a single global would let rank 1 overwrite rank 0.
|
||||
* libr4d all-reduces over 2/4/8 ranks, hence eight ranks. Several engines may run in the process
|
||||
* (docs/MULTIMODEL.md), each with its own ranks, so state is indexed by the instance's slot
|
||||
* (rad_build_slot at declare, rad_slot in step), unique across all of them, never by the rank two
|
||||
* engines share. */
|
||||
enum { MAX_RANKS = 8, MAX_SLOTS = RAD_MAX_SLOTS };
|
||||
|
||||
/* ================================================================== a debug residual probe
|
||||
*
|
||||
@@ -220,13 +223,14 @@ inline bool calib_write(RadCtx* c, rad_buf b, int64_t k, long long rows, const c
|
||||
return calib_write_host(h.data(), k, rows, what, domain, rad_rank(c));
|
||||
}
|
||||
|
||||
/* A pinned host buffer of at least `bytes`, one per rank, held for the process lifetime, so a tap
|
||||
* that copies a scratch back every pass runs at link speed. Null (and logged) on failure. */
|
||||
/* A pinned host buffer of at least `bytes`, one per instance (slot), held for the process
|
||||
* lifetime, so a tap that copies a scratch back every pass runs at link speed. Null (and logged)
|
||||
* on failure. */
|
||||
inline float* calib_staging(RadCtx* c, int64_t bytes) {
|
||||
static std::mutex mu;
|
||||
static std::map<int, std::pair<void*, int64_t>> per_rank;
|
||||
static std::map<int, std::pair<void*, int64_t>> per_slot;
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
std::pair<void*, int64_t>& s = per_rank[rad_rank(c)];
|
||||
std::pair<void*, int64_t>& s = per_slot[rad_slot(c)];
|
||||
if (s.second >= bytes) return (float*)s.first;
|
||||
if (s.first) rad_dev_free(s.first, RAD_MEM_HOST_PINNED);
|
||||
s.first = rad_dev_alloc(bytes, RAD_MEM_HOST_PINNED);
|
||||
@@ -733,9 +737,6 @@ struct Geom {
|
||||
/* Messages below this many bytes use the exact all-reduce even with a lossy wire. Passed as
|
||||
* `all_reduce`'s `min_bytes`; 0 leaves the default to the kernel plugin. */
|
||||
int64_t wire_min_bytes = 0;
|
||||
/* RAD_ATTN_FP8_* bits: the attention products accepted in e4m3 (RadBuildCtx describes it).
|
||||
* decl_attn passes it on as `attn_paged`'s `prefill_fp8`. */
|
||||
int attn_prefill_fp8 = 0;
|
||||
float eps = 1e-6f;
|
||||
/* GemmaRMSNorm's `1 +`. Qwen3.5, Qwen3-Next and Gemma normalise with `x_hat * (1 + w)` and
|
||||
* store `w` near 0.1, so reading it as a plain gain shrinks every normed activation 5-10x. An
|
||||
@@ -771,6 +772,12 @@ struct Geom {
|
||||
* setting because producers and consumers must agree; the plugin reads it off a trunk weight's
|
||||
* encoding and every linear checks its own against it. */
|
||||
bool w_bf16 = false;
|
||||
/* The linears are rotated int8 (rad_fp8.h's linear_is_w8h: IQ8R, or the 128-group form) with
|
||||
* one activation scale per `w_i8_group` columns, for a plugin whose producers are declared away
|
||||
* from its probe: each then declares an int8 code pair (ActFP8::declare_pair). Model-wide as
|
||||
* w_bf16 is. */
|
||||
bool w_i8h = false;
|
||||
int64_t w_i8_group = 128;
|
||||
|
||||
int64_t q_dim() const { return n_head * head_dim; }
|
||||
int64_t kv_dim() const { return n_head_kv * head_dim; }
|
||||
@@ -1007,7 +1014,6 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
g.world = c->world_size ? c->world_size : 1;
|
||||
g.wire_exact= c->tp_wire_lossy ? 0 : 1;
|
||||
g.wire_min_bytes = c->tp_wire_min_bytes;
|
||||
g.attn_prefill_fp8 = c->attn_prefill_fp8;
|
||||
g.eps = m->rms_eps;
|
||||
g.theta = m->rope_theta;
|
||||
g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */
|
||||
@@ -1324,16 +1330,6 @@ inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name,
|
||||
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
|
||||
}
|
||||
|
||||
/* An `attn_paged` op with the deployment's `prefill_fp8` appended (docs/OPS.md). At 0 the
|
||||
* parameters are passed unchanged, so op identities and tune keys do not change. */
|
||||
inline rad_op decl_attn(RadBuilder* b, const Geom& g, const char* name,
|
||||
const RadParam* params, int n, const rad_weight* weights, int nw) {
|
||||
if (g.attn_prefill_fp8 == 0) return rad_decl_op(b, name, params, n, weights, nw);
|
||||
std::vector<RadParam> p(params, params + n);
|
||||
p.push_back(RAD_INT("prefill_fp8", g.attn_prefill_fp8));
|
||||
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
|
||||
}
|
||||
|
||||
/* Reads a model's rotary scaling into `g.rope_scale` and `g.yarn`. Every architecture calls it
|
||||
* after geom_from, for the target ("") and for a drafter with its own config ("draft."). Only the
|
||||
* free-form keys are read; RadModelMeta::rope_scale is not, since a factor without its type would
|
||||
@@ -1638,6 +1634,11 @@ inline int drafter_kv_group(RadBuilder* b, Names& nm, const RadBuildCtx* ctx, Ge
|
||||
#define RAD_ARCH_SERVES_IMPORTS(V) \
|
||||
extern "C" int rad_arch_serves_imports(void) { return V; }
|
||||
|
||||
/* RAD_ARCH_MULTI_INSTANCE() states that the plugin keeps all per-instance state by slot, so several
|
||||
* engines in one process may run it at once (rad_builder.h, rad_arch_multi_instance). */
|
||||
#define RAD_ARCH_MULTI_INSTANCE() \
|
||||
extern "C" int rad_arch_multi_instance(void) { return 1; }
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
|
||||
@@ -139,7 +139,7 @@ inline int AttnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
|
||||
/* attn_paged before kv_store: block_size is RAD_DERIVED, read off the resolved attention
|
||||
* kernel and back into kv_store with rad_kv_block_size() (rad_block_attn_gated.h says why). */
|
||||
op_attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
op_attn = rw(b, rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
|
||||
@@ -137,7 +137,7 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
|
||||
/* Declared before kv_store, which reads back the resolved `block_size` (rad_block_attn_gated.h
|
||||
* explains declare vs issue order). */
|
||||
op_attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
op_attn = rw(b, rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
|
||||
@@ -195,7 +195,7 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
|
||||
*
|
||||
* The ranged parameter is q_len, not M: 1 at decode, up to n_spec+1 at a verify, thousands in
|
||||
* a prefill chunk, with a libr4d kernel per band. `scale` defaults to 1/sqrt(head_dim). */
|
||||
op_attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
op_attn = rw(b, rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0),
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
* state); the gate pass quantises the out-projection's input.
|
||||
* - Per-head norms, rope, kv_store and attn_paged stay bf16.
|
||||
* - The KV cache dtype is `g.kv_dtype`, not `g.dtype`: it is a deployment choice that selects
|
||||
* libr4d's fp8kv attention family. The attention op and kv_store both take it, so they agree.
|
||||
* the attention family's cache rows. The attention op and kv_store both take it, so they agree.
|
||||
* - Optional fused prologue, QSA sparse attention and an attention-zero mode (see declare).
|
||||
*
|
||||
* The q|gate projection is [2*n_head*head_dim, n_embd] = [12288, 5120] at 27B, scale plane
|
||||
@@ -26,14 +26,6 @@
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* Whether the streamed store has a row for this cache layout: libr4d's are E4M3 and bf16 only. A
|
||||
* packed cache (fp8_v4, k6_v4) must not declare it, since a weightless op with no row is a hole
|
||||
* that refuses startup even with --kv-resident off; kvstream_configure then names the layout. */
|
||||
inline bool kv_store_streamed_dtype(const char* kv_dtype) {
|
||||
return kv_dtype && (std::strcmp(kv_dtype, "fp8_e4m3") == 0 ||
|
||||
std::strcmp(kv_dtype, "bf16") == 0);
|
||||
}
|
||||
|
||||
struct AttnGatedFP8 {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
@@ -115,6 +107,10 @@ struct AttnGatedFP8 {
|
||||
/* The input was normed and quantised by the caller; this block declares no norm. */
|
||||
bool ext_in = false;
|
||||
LinearFP8 qg{}, kp{}, vp{}, o{};
|
||||
/* Set by the architecture after declare: a `prefetch` of the out projection's leading bytes
|
||||
* (decl_prefetch, rad_arch.h), issued behind the q, k and v projections on decode steps
|
||||
* (prefetch_beside). 0 where none is declared. */
|
||||
rad_op op_pf_o = 0;
|
||||
NormQuantFP8 nq_h{};
|
||||
|
||||
rad_op op_fused = 0; /* qk_norm_rope_gate, if it resolves */
|
||||
@@ -125,7 +121,7 @@ struct AttnGatedFP8 {
|
||||
int64_t fused_rows = 0; /* widest T the fused ops take */
|
||||
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
|
||||
rad_op op_attn = 0, op_kv_store = 0, op_gq = 0;
|
||||
rad_op op_attn_gq = 0; /* attn_paged + gate_quant_fp8 */
|
||||
rad_op op_attn_gq = 0; /* attn_paged + gate_quant_fp8 or gate_had_quant_i8g */
|
||||
/* kv_store_streamed: the host mirror always, the ring slot when `res` says the block is resident
|
||||
* (docs/OPS.md). Zero when no row serves it; a streamed group then fails the step. */
|
||||
rad_op op_kv_stream = 0;
|
||||
@@ -334,7 +330,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
|
||||
/* Declared before kv_store, which reads back the resolved `block_size`
|
||||
* (rad_block_attn_gated.h). */
|
||||
op_attn = decl_attn(b, g, "attn_paged",
|
||||
op_attn = rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0),
|
||||
@@ -374,8 +370,8 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
|
||||
/* The streamed store: kv_store's operands and parameters plus the residency map and the layer's
|
||||
* mirror row, which the batch carries (store_cache). `block_size` does not bind the group;
|
||||
* `attn_paged` already has. Only for a layout with a row (kv_store_streamed_dtype). */
|
||||
if (kv_store_streamed_dtype(g.kv_dtype) && rad_op_declared(b, "kv_store_streamed"))
|
||||
* `attn_paged` already has. */
|
||||
if (rad_op_declared(b, "kv_store_streamed"))
|
||||
op_kv_stream = rw(b, RAD_OP(b, "kv_store_streamed",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("head_dim", g.head_dim),
|
||||
@@ -388,7 +384,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
/* The fused prologue with the cache store folded in: a k head's block already holds its
|
||||
* token's rotated k, so it also writes k and v into the cache, byte-identical to kv_store.
|
||||
* Declared here because the cache block size is read back from the attention op above.
|
||||
* Resolves for E4M3 and bf16 caches. */
|
||||
* Resolves for either cache. */
|
||||
if (op_fused && rad_op_declared(b, "qk_norm_rope_gate_kv_store"))
|
||||
op_fused_kv = rw(b, RAD_OP(b, "qk_norm_rope_gate_kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows),
|
||||
@@ -402,9 +398,8 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
{w.qg, w.k, w.cos_sin, w.v}, {w.q, w.k});
|
||||
|
||||
/* The fold for a streamed group: also writes the mirror and consults the residency map, whose
|
||||
* operands are added at issue. Gated on the same layouts. */
|
||||
if (op_fused && kv_store_streamed_dtype(g.kv_dtype) &&
|
||||
rad_op_declared(b, "qk_norm_rope_gate_kv_store_streamed"))
|
||||
* operands are added at issue. */
|
||||
if (op_fused && rad_op_declared(b, "qk_norm_rope_gate_kv_store_streamed"))
|
||||
op_fused_stream = rw(b, RAD_OP(b, "qk_norm_rope_gate_kv_store_streamed",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows),
|
||||
RAD_INT("head_dim", g.head_dim), RAD_INT("n_head", g.n_head),
|
||||
@@ -455,7 +450,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
if (rad_op_declared(b, gq))
|
||||
op_gq = rw(b, RAD_OP(b, gq,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_INT("n", g.head_dim), RAD_INT("group", w.attn.cg()),
|
||||
RAD_STR("dtype", g.dtype), RAD_STR("act", "sigmoid")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qg, w.attn.x}, {w.attn.cq(), w.attn.cs(), w.attn.x});
|
||||
@@ -471,10 +466,12 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
* row is one (token, head) at q_len 1, and the merge already holds the head_dim values the gate
|
||||
* and quantiser read, so one op merges, gates, rounds and quantises (byte-identical to the
|
||||
* pair). Declared only with a selection: the dense path also uses the prefill kernel, which
|
||||
* has no merge. */
|
||||
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 && !w.attn.q8_rot &&
|
||||
rad_op_declared(b, "attn_paged_gate_quant")) {
|
||||
op_attn_gq = RAD_OP(b, "attn_paged_gate_quant",
|
||||
* has no merge. Rotated int8 codes (ActFP8::q8_rot) take attn_paged_gate_had_quant, the merge
|
||||
* with gate_had_quant_i8g's quantiser. */
|
||||
const char* attn_gq = w.attn.q8_rot ? "attn_paged_gate_had_quant" : "attn_paged_gate_quant";
|
||||
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 && w.attn.cg() == RAD_FP8_BLOCK &&
|
||||
rad_op_declared(b, attn_gq)) {
|
||||
op_attn_gq = RAD_OP(b, attn_gq,
|
||||
RAD_PARAMS(RAD_INT("q_len", 1), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
@@ -619,7 +616,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
RAD_ISSUE_N(c, op_gq, n * g.n_head,
|
||||
bcol_at(w.qg, r0, qgw, hd, hd, n), brow_slice(w.attn.x, r0, n, qw),
|
||||
brow_slice(w.attn.cq(), r0, n, qw),
|
||||
brow_slice(w.attn.cs(), r0, n, fp8_blocks(qw)),
|
||||
brow_slice(w.attn.cs(), r0, n, qw / w.attn.cg()),
|
||||
brow_slice(w.attn.x, r0, n, qw));
|
||||
o.step(c, w.attn, w.h.x, T, r0, n);
|
||||
if (p == 0) pieces->hand(r0, n);
|
||||
@@ -639,6 +636,8 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
qg.step(c, w.h, w.qg, T);
|
||||
kp.step(c, w.h, w.k, T);
|
||||
vp.step(c, w.h, w.v, T);
|
||||
/* The out projection's weight, read beside the prologue and the attention (op_pf_o). */
|
||||
prefetch_beside(c, op_pf_o, o.w, T);
|
||||
|
||||
/* Fused or unfused prologue. The fused kernel takes the whole [q|gate] projection and splits it
|
||||
* itself, and rotates k in place like the unfused ops. It reads one rotary component per
|
||||
@@ -743,7 +742,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
brow_slice(w.attn.x, off, rows, qw),
|
||||
bcol_at(w.qg, off, g.n_head * 2 * hd, hd, hd, rows),
|
||||
brow_slice(w.attn.cq(), off, rows, qw),
|
||||
brow_slice(w.attn.cs(), off, rows, fp8_blocks(qw)));
|
||||
brow_slice(w.attn.cs(), off, rows, qw / w.attn.cg()));
|
||||
}
|
||||
o.step(c, w.attn, w.h.x, T, p0, pn);
|
||||
if (p0 + pn < T) pieces->hand(p0, pn);
|
||||
@@ -767,7 +766,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
brow_slice(w.attn.x, off, rows, qw),
|
||||
bcol_at(w.qg, off, g.n_head * 2 * hd, hd, hd, rows),
|
||||
brow_slice(w.attn.cq(), off, rows, qw),
|
||||
brow_slice(w.attn.cs(), off, rows, fp8_blocks(qw)));
|
||||
brow_slice(w.attn.cs(), off, rows, qw / w.attn.cg()));
|
||||
}
|
||||
} else if (sparse) {
|
||||
const int64_t chunk = qsa_rows();
|
||||
|
||||
@@ -161,6 +161,14 @@ struct Dflash2 {
|
||||
* acceptance, sum min(P, Q). */
|
||||
double q_temp = 1.0;
|
||||
int64_t short_rows = 0;
|
||||
/* The drafter's linears are served at i8a8h (DenseFP8::w8h: IQ8R, or a rotated int8 or
|
||||
* narrower form at group 128), learned by the plugin from `probe_i8` before it declares the
|
||||
* activation pairs: they are then int8 codes with one f32 scale per (row, act_g8), written
|
||||
* by had_quant_act_i8g. Every linear must agree. `fc_mapped`: probe_i8 made
|
||||
* `dflash.fc.weight`'s name map. */
|
||||
bool act_i8 = false;
|
||||
int64_t act_g8 = RAD_FP8_BLOCK;
|
||||
bool fc_mapped = false;
|
||||
/* LiLiCorr's backbone (the LILICORR section above): sinks, and the head left to the
|
||||
* plugin. sel_rank and sel_topk are then unused. */
|
||||
int lili = 0;
|
||||
@@ -198,7 +206,9 @@ struct Dflash2 {
|
||||
rad_buf gate_up = 0;/* [qrows, 2 * n_ff] */
|
||||
rad_buf ffn = 0; /* [qrows, n_ff] */
|
||||
/* FP8 codes and scales of the activations the linears read, written by `quant_act_fp8`
|
||||
* and read only by the `gemm_nt_q` linears. One pair per activation, not per linear: q, k
|
||||
* and read only by the `gemm_nt_q` linears (int8 codes with a scale per Config::act_g8,
|
||||
* written by `had_quant_act_i8g`, when the drafter's linears are rotated int8:
|
||||
* Config::act_i8). One pair per activation, not per linear: q, k
|
||||
* and v all read h2. h2 is still quantised twice a layer, because the convolution
|
||||
* rewrites it between the attention and feed-forward halves. */
|
||||
rad_buf srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] e4m3 | [.., /128] f32 */
|
||||
@@ -342,6 +352,18 @@ struct Dflash2 {
|
||||
* the drafter's own block is longer (rad_drafter_short_block). */
|
||||
static constexpr int64_t kShortBlock = 4;
|
||||
|
||||
/* Whether the container's drafter is served at i8a8h and at which scale group, from its `fc`,
|
||||
* whose name map this makes (set Config::fc_mapped). Asked before the activation pairs are
|
||||
* declared, since it decides their dtype and scale grid. */
|
||||
static int probe_i8(RadBuilder* b, Names& nm, const char* ck, bool* i8, int64_t* g8) {
|
||||
const char* fwn = nm.f("dflash.fc.weight");
|
||||
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
RadEncoding fe{};
|
||||
*i8 = weight_enc(b, fwn, &fe) && linear_is_w8h(fe);
|
||||
*g8 = *i8 ? linear_w8h_group(fe) : (int64_t)RAD_FP8_BLOCK;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
|
||||
rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix,
|
||||
const char* ck_lm, const Wire& wire);
|
||||
@@ -381,11 +403,18 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
srows = g.max_seqs * cfg.steps();
|
||||
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
|
||||
|
||||
/* The linears read the activation pairs the plugin declared: int8 ones take rotated int8
|
||||
* weights (cfg.act_i8), E4M3 ones block fp8 or MXFP4. */
|
||||
w_fc.w8h_ok = cfg.act_i8;
|
||||
for (int i = 0; i < MAX_LAYERS; ++i)
|
||||
w_q[i].w8h_ok = w_k[i].w8h_ok = w_v[i].w8h_ok = w_o[i].w8h_ok = w_gu[i].w8h_ok =
|
||||
w_dn[i].w8h_ok = cfg.act_i8;
|
||||
|
||||
/* ---------------------------------------------------------------- model-scope weights */
|
||||
{
|
||||
const int64_t K = cfg.n_taps * g.n_embd;
|
||||
const char* fwn = nm.f("dflash.fc.weight");
|
||||
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
if (!cfg.fc_mapped) RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
/* Split only block fp8 (an MXFP4 GEMM's K split is its own), into equal shares of whole
|
||||
* 16-byte words (the gather's unit). */
|
||||
RadEncoding fe{};
|
||||
@@ -602,9 +631,29 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* Nothing is row-sliced: the fp8a8 pair covers every M, and libr4d's bf16 GEMM row (used by
|
||||
* the conv coefficient projections and the selector's hidden projection, K = n_embd) is
|
||||
* C_LE("M", 65536). */
|
||||
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
/* A rotated int8 drafter (cfg.act_i8): the same five quantisers as had_quant_act_i8g at its
|
||||
* scale group, and no fp8a8 fold. Its linears read one activation pair, so they are all
|
||||
* i8a8h forms at one group or none is. */
|
||||
const char* const qop = cfg.act_i8 ? "had_quant_act_i8g" : "quant_act_fp8";
|
||||
const int64_t qgr = cfg.act_i8 ? cfg.act_g8 : (int64_t)RAD_FP8_BLOCK;
|
||||
{
|
||||
auto fits = [&](const DenseFP8& d) {
|
||||
return d.w8h == cfg.act_i8 && (!d.w8h || d.g8 == cfg.act_g8);
|
||||
};
|
||||
bool same = fits(w_fc);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l)
|
||||
same = same && fits(w_q[l]) && fits(w_k[l]) && fits(w_v[l]) && fits(w_o[l]) &&
|
||||
fits(w_gu[l]) && fits(w_dn[l]);
|
||||
if (!same) {
|
||||
fprintf(stderr, "radiance: the drafter's linears are not all rotated int8 at one scale "
|
||||
"group or all block fp8 / MXFP4; they read one activation pair, so the "
|
||||
"recipe must give them one format\n");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
}
|
||||
op_qsrc = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.srcq, w.srcs});
|
||||
if (fc_rows) {
|
||||
@@ -634,9 +683,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_WEIGHTS(w_hnorm)),
|
||||
{w.c}, {w.c});
|
||||
/* One quantise for all layers: every layer's k and v read the same `c`. */
|
||||
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qc = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.c}, {w.cq, w.cs});
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
@@ -700,19 +749,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
{w.x}, {w.x});
|
||||
/* The query pass's quantisers, issued per layer: h2 twice (the convolution rewrites it between
|
||||
* the halves), attn and ffn once each. */
|
||||
op_qh2 = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qh2 = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h2}, {w.h2q, w.h2s});
|
||||
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qat = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn}, {w.atq, w.ats});
|
||||
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qff = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ffn}, {w.ffq, w.ffs});
|
||||
|
||||
@@ -759,7 +808,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h2q, w.h2s}, {w.gate_up});
|
||||
/* The fold saves two launches and the bf16 round trip of the [T, n_ff] product; it is an
|
||||
* fp8a8 tile, so an MXFP4 or M2XFP4 gate_up takes the pair. */
|
||||
if (!w_gu[i].mx && !w_gu[i].m2x)
|
||||
if (!w_gu[i].mx && !w_gu[i].m2x && !w_gu[i].w8h)
|
||||
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
|
||||
{w.h2q, w.h2s}, {w.ffq, w.ffs}, &gated_rows);
|
||||
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
|
||||
@@ -832,12 +881,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
/* Only for a shape a library serves: an op declared for one that resolves to no device
|
||||
* kernel is a hole that refuses startup (Program::device_holes), whether or not it is
|
||||
* issued, so the block asks within libr4d's span for the fold (head_dim 256 to 512 in
|
||||
* steps of 256, bf16 rows, an fp8 or bf16 cache). Qwen3.8's DFlash2 drafter (head_dim
|
||||
* 128) keeps the chain. */
|
||||
* steps of 256, bf16 rows, either cache). Qwen3.8's DFlash2 drafter (head_dim 128) keeps
|
||||
* the chain. */
|
||||
const bool fold_shape = g.head_dim >= 256 && g.head_dim <= 512 && g.head_dim % 256 == 0 &&
|
||||
!std::strcmp(g.dtype, "bf16") &&
|
||||
(!std::strcmp(g.kv_dtype, "fp8_e4m3") ||
|
||||
!std::strcmp(g.kv_dtype, "bf16"));
|
||||
!std::strcmp(g.dtype, "bf16");
|
||||
if (fold_shape && g.yarn.factor == 0.0f &&
|
||||
rad_op_declared(b, "qkv_norm_rope_kv_store")) {
|
||||
const int64_t bsz = rad_kv_block_size(b, kv);
|
||||
|
||||
@@ -93,12 +93,15 @@
|
||||
*
|
||||
* ============================== PRECISION ==============================
|
||||
*
|
||||
* E4M3 + a bf16 [N/128][K/128] plane fc, q/k/v/o, gate_up, down -- every linear
|
||||
* what the recipe made them fc, q/k/v/o, gate_up, down -- every linear
|
||||
* bf16, no plane every norm, and both Markov codebooks
|
||||
*
|
||||
* The checkpoint is dense bf16; the linears are rad_fp8.h's DenseFP8 over weights the recipe
|
||||
* quantises, because the drafter is read whole every decode step (324M parameters: 648 MB at
|
||||
* bf16, 324 MB at fp8). This can only change acceptance.
|
||||
* bf16, 324 MB at eight bits). DenseFP8 reads block fp8 or MXFP4 against E4M3 activations, or a
|
||||
* rotated int8 form (IQ8R and the narrower grids under the same rotation) against int8 ones
|
||||
* (Config::act_i8); one format for all of them, since they share the activation pairs. This can
|
||||
* only change acceptance.
|
||||
*
|
||||
* The codebooks are bf16 and replicated: they are gathered by global token id from a merged
|
||||
* candidate set. 66.8 MiB each; only K rows are read per position, so the cost is residency.
|
||||
@@ -135,6 +138,14 @@ struct Dspark {
|
||||
int64_t top_k = 0; /* candidates the Markov walk re-ranks */
|
||||
int64_t window = 0; /* sliding attention width, 0 for none */
|
||||
int causal = 0;
|
||||
/* The drafter's linears are served at i8a8h (DenseFP8::w8h: IQ8R, or a rotated int8 or
|
||||
* narrower form at group 128), learned by the plugin from `probe_i8` before it declares the
|
||||
* activation pairs: they are then int8 codes with one f32 scale per (row, act_g8), written
|
||||
* by had_quant_act_i8g and the rotating norm. Every linear must agree. `fc_mapped`:
|
||||
* probe_i8 made `dspark.fc.weight`'s name map. */
|
||||
bool act_i8 = false;
|
||||
int64_t act_g8 = RAD_FP8_BLOCK;
|
||||
bool fc_mapped = false;
|
||||
/* Every row predicts, so `block`, not `block - 1` (see ROW ALIGNMENT). */
|
||||
int64_t steps() const { return block; }
|
||||
};
|
||||
@@ -149,7 +160,10 @@ struct Dspark {
|
||||
* rows_pitch). */
|
||||
rad_buf ck = 0; /* [max_tok, kv_dim] one layer's K, reused across layers */
|
||||
rad_buf cv = 0; /* [max_tok, kv_dim] one layer's V, reused across layers */
|
||||
rad_buf srcq = 0, srcs = 0; /* fp8 codes and scales: e4m3 | f32 [.., /128] */
|
||||
/* The codes and scales the linears read: e4m3 | f32 [.., /128], or with Config::act_i8
|
||||
* i8 | f32 [.., /act_g8]. The same holds for the three ActFP8 pairs below, whose `q` and
|
||||
* `s` are then the int8 pair. */
|
||||
rad_buf srcq = 0, srcs = 0;
|
||||
rad_buf cq = 0, cs = 0;
|
||||
|
||||
/* ---- the query pass, `block` rows per sequence */
|
||||
@@ -235,6 +249,18 @@ struct Dspark {
|
||||
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
|
||||
rad_op op_sel = 0;
|
||||
|
||||
/* Whether the container's drafter is served at i8a8h and at which scale group, from its `fc`,
|
||||
* whose name map this makes (set Config::fc_mapped). Asked before the activation pairs are
|
||||
* declared, since it decides their dtype and scale grid. */
|
||||
static int probe_i8(RadBuilder* b, Names& nm, const char* ck, bool* i8, int64_t* g8) {
|
||||
const char* fwn = nm.f("dspark.fc.weight");
|
||||
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
RadEncoding fe{};
|
||||
*i8 = weight_enc(b, fwn, &fe) && linear_is_w8h(fe);
|
||||
*g8 = *i8 ? linear_w8h_group(fe) : (int64_t)RAD_FP8_BLOCK;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
|
||||
rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix,
|
||||
const char* ck_lm, const char* ck_lm_alt, const Wire& wire);
|
||||
@@ -274,10 +300,17 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
srows = g.max_seqs * cfg.steps();
|
||||
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
|
||||
|
||||
/* The linears read the activation pairs the plugin declared: int8 ones take rotated int8
|
||||
* weights (cfg.act_i8), E4M3 ones block fp8 or MXFP4. */
|
||||
w_fc.w8h_ok = cfg.act_i8;
|
||||
for (int i = 0; i < MAX_LAYERS; ++i)
|
||||
w_q[i].w8h_ok = w_k[i].w8h_ok = w_v[i].w8h_ok = w_o[i].w8h_ok = w_gu[i].w8h_ok =
|
||||
w_dn[i].w8h_ok = cfg.act_i8;
|
||||
|
||||
/* ---------------------------------------------------------------- model-scope weights */
|
||||
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dspark.fc"), g.n_embd, cfg.n_taps * g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
|
||||
{ nm.ckpt("%s.fc.weight", ck) }));
|
||||
{ nm.ckpt("%s.fc.weight", ck) }, {}, cfg.fc_mapped));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.hidden_norm.weight"),
|
||||
nm.ckpt("%s.hidden_norm.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
|
||||
@@ -379,19 +412,34 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass
|
||||
*
|
||||
* Every linear is `fp8a8`, fed by a `quant_act_fp8`. There is no `fp8a16` band: that kernel is
|
||||
* M <= 1, and neither pass runs at one row. */
|
||||
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
* Every linear is a DenseFP8 GEMM over the pair its quantiser writes: `quant_act_fp8` codes
|
||||
* for block fp8 or MXFP4, had_quant_act_i8g's at the weights' scale group for a rotated int8
|
||||
* drafter (cfg.act_i8). The linears read one activation pair, so they are all i8a8h forms at
|
||||
* one group or none is. There is no `fp8a16` band: that kernel is M <= 1, and neither pass
|
||||
* runs at one row. */
|
||||
const char* const qop = cfg.act_i8 ? "had_quant_act_i8g" : "quant_act_fp8";
|
||||
const int64_t qgr = cfg.act_i8 ? cfg.act_g8 : (int64_t)RAD_FP8_BLOCK;
|
||||
{
|
||||
auto fits = [&](const DenseFP8& d) {
|
||||
return d.w8h == cfg.act_i8 && (!d.w8h || d.g8 == cfg.act_g8);
|
||||
};
|
||||
bool same = fits(w_fc);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l)
|
||||
same = same && fits(w_q[l]) && fits(w_k[l]) && fits(w_v[l]) && fits(w_o[l]) &&
|
||||
fits(w_gu[l]) && fits(w_dn[l]);
|
||||
if (!same) {
|
||||
fprintf(stderr, "radiance: the drafter's linears are not all rotated int8 at one scale "
|
||||
"group or all block fp8 / MXFP4; they read one activation pair, so the "
|
||||
"recipe must give them one format\n");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
}
|
||||
op_qsrc = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.srcq, w.srcs});
|
||||
op_cfc = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_fc.w, w_fc.s)),
|
||||
{w.srcq, w.srcs}, {w.c});
|
||||
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
|
||||
/* In place, like the per-head q/k norms below: a row's scale is computed before the row is
|
||||
* written. */
|
||||
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
@@ -401,27 +449,17 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
RAD_WEIGHTS(w_hnorm)),
|
||||
{w.c}, {w.c});
|
||||
/* One quantise for all layers: every layer's k and v read the same `c`. */
|
||||
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qc = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.c}, {w.cq, w.cs});
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
/* One op per weight: an op's declared weight list gives each weight its prefetch interval
|
||||
* and residency class. */
|
||||
op_ck[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.cq, w.cs}, {w.cv});
|
||||
op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv});
|
||||
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
@@ -468,7 +506,8 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
{w.x}, {w.x});
|
||||
|
||||
/* Norm, residual add and quantise are one op, `rmsnorm_quant_fp8` (what rad_fp8.h's
|
||||
* NormQuantFP8 wraps). Layer 0 has no delta to fold, each later norm folds the previous
|
||||
* NormQuantFP8 wraps), or its rotating int8 twin `rmsnorm_had_quant_i8g` for a rotated int8
|
||||
* drafter, which takes the same operands. Layer 0 has no delta to fold, each later norm folds the previous
|
||||
* block's delta, and op_outnorm folds the last into the final norm, so there is no `add` op.
|
||||
* The final norm's fp8 output is unused (the head runs its own i8 quantiser), a few KiB of
|
||||
* waste that saves a launch: libr4d has no plain `rmsnorm_add` row.
|
||||
@@ -478,9 +517,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
* stream as `x` and no residual. `residual` is INOUT, so it is in both the read and write sets;
|
||||
* otherwise the planner could reorder a reader in front of it. */
|
||||
auto decl_norm = [&](rad_weight gain, bool fold) -> rad_op {
|
||||
rad_op h = RAD_OP(b, "rmsnorm_quant_fp8",
|
||||
rad_op h = RAD_OP(b, cfg.act_i8 ? "rmsnorm_had_quant_i8g" : "rmsnorm_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_F64("eps", g.eps), RAD_INT("group", qgr),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
|
||||
RAD_WEIGHTS(gain));
|
||||
if (!h) return 0;
|
||||
@@ -490,9 +529,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
rad_op_writes(b, h, wr, fold ? 4 : 3);
|
||||
return h;
|
||||
};
|
||||
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qat = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn.x}, {w.attn.q, w.attn.s});
|
||||
if (!op_qat) return RAD_E_INVAL;
|
||||
@@ -508,24 +547,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
const int i = (int)l;
|
||||
op_anorm[i] = decl_norm(w_anorm[i], i != 0);
|
||||
if (!op_anorm[i]) return RAD_E_INVAL;
|
||||
op_qp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", qd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_q[i].w, w_q[i].s)),
|
||||
{w.h.q, w.h.s}, {w.q});
|
||||
op_kp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.h.q, w.h.s}, {w.k});
|
||||
op_vp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.h.q, w.h.s}, {w.v});
|
||||
op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.h.q, w.h.s}, {w.q});
|
||||
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.h.q, w.h.s}, {w.k});
|
||||
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.h.q, w.h.s}, {w.v});
|
||||
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
@@ -538,28 +562,15 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.k}, {w.k});
|
||||
op_op[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", qd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_o[i].w, w_o[i].s)),
|
||||
{w.attn.q, w.attn.s}, {w.h.x});
|
||||
op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.attn.q, w.attn.s}, {w.h.x});
|
||||
op_fnorm[i] = decl_norm(w_fnorm[i], true);
|
||||
if (!op_fnorm[i]) return RAD_E_INVAL;
|
||||
op_gu[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
|
||||
{w.h.q, w.h.s}, {w.gate_up});
|
||||
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
|
||||
{w.h.q, w.h.s}, {w.ffn.q, w.ffn.s}, &gated_rows);
|
||||
op_dn[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", g.n_ff), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_dn[i].w, w_dn[i].s)),
|
||||
{w.ffn.q, w.ffn.s}, {w.h.x});
|
||||
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h.q, w.h.s}, {w.gate_up});
|
||||
/* The fold is an fp8a8 tile, so any other gate_up takes the pair. */
|
||||
if (!w_gu[i].mx && !w_gu[i].m2x && !w_gu[i].w8h)
|
||||
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
|
||||
{w.h.q, w.h.s}, {w.ffn.q, w.ffn.s}, &gated_rows);
|
||||
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffn.q, w.ffn.s}, {w.h.x});
|
||||
}
|
||||
|
||||
op_qrope = rw(b, decl_rotary(b, g, "rope",
|
||||
@@ -588,9 +599,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gate_up}, {w.ffn.x});
|
||||
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
op_qff = rw(b, RAD_OP(b, qop,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ffn.x}, {w.ffn.q, w.ffn.s});
|
||||
/* One collective, issued after both the out and the down projection (same shape, same buffer).
|
||||
@@ -687,16 +698,16 @@ inline void Dspark::context(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
|
||||
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
|
||||
brows(w.c, T), RAD_NONE, RAD_NONE);
|
||||
brows(w.c, T), RAD_NONE, w_fc.bref());
|
||||
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
|
||||
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref());
|
||||
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref());
|
||||
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv,
|
||||
brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T));
|
||||
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
|
||||
@@ -735,11 +746,11 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
|
||||
* quantises; at layer 0 it norms the embedding. */
|
||||
issue_norm(op_anorm[i], i != 0, w_anorm[i], T);
|
||||
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref());
|
||||
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
|
||||
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
|
||||
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
|
||||
RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T));
|
||||
@@ -757,7 +768,7 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
|
||||
brows(w.attn.x, T));
|
||||
RAD_ISSUE_N(c, op_qat, T, brows(w.attn.x, T), brows(w.attn.q, T), brows(w.attn.s, T));
|
||||
RAD_ISSUE_N(c, op_op[i], T, brows(w.attn.q, T), brows(w.attn.s, T),
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h.x, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h.x, T), RAD_NONE, w_o[i].bref());
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
|
||||
/* ---- the feed-forward, behind the same fused norm-add-quantise */
|
||||
@@ -769,12 +780,12 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
|
||||
RAD_NONE);
|
||||
w_gu[i].bref());
|
||||
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn.x, T));
|
||||
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn.x, T), brows(w.ffn.q, T), brows(w.ffn.s, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffn.q, T), brows(w.ffn.s, T),
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h.x, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h.x, T), RAD_NONE, w_dn[i].bref());
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
}
|
||||
|
||||
|
||||
@@ -126,10 +126,12 @@ struct GdnFP8 {
|
||||
* convolution in the recurrent update's prologue. The pair is declared either way; cr_rows is
|
||||
* the widest decode window the fold serves. */
|
||||
rad_op op_cr = 0;
|
||||
/* Whether op_cr writes the out projection's codes; otherwise q_o follows it. */
|
||||
bool cr_codes = false;
|
||||
int64_t cr_rows = 0;
|
||||
/* Set by the architecture after declare: a `prefetch` of the out-projection's leading bytes
|
||||
* (decl_prefetch, rad_arch.h), issued on the second lane beside the decode recurrent update on
|
||||
* steps of up to pf_out_rows rows and pf_out_seqs sequences. 0 where none is declared. */
|
||||
* (decl_prefetch, rad_arch.h), issued beside the decode recurrent update on steps of up to
|
||||
* pf_out_rows rows and pf_out_seqs sequences. 0 where none is declared. */
|
||||
rad_op op_pf_out = 0;
|
||||
int64_t pf_out_rows = 0, pf_out_seqs = 0;
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
@@ -339,17 +341,25 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
* tokens per sequence. Optional (no RAD_ARCH_TRY): without it the pair runs. */
|
||||
{
|
||||
const int64_t hi = g.max_tok < 8 ? g.max_tok : 8;
|
||||
op_cr = rw(b, RAD_OP(b, w.o.q8_rot ? "gdn_conv_recurrent_update_had" : "gdn_conv_recurrent_update",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v),
|
||||
RAD_INT("conv_width", cfg.conv_width),
|
||||
RAD_INT("n_head_v", cfg.n_head_v), RAD_F64("scale", q_scale),
|
||||
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act),
|
||||
RAD_STR("state_form",
|
||||
g.max_spec > 0 ? "anchor" : "per_candidate")),
|
||||
RAD_WEIGHTS(w_conv, w_a_log, w_dt_bias, w_out_norm)),
|
||||
/* The fold's rotated epilogue writes one scale per (row, 128), or per 256 for an IQ8R
|
||||
* trunk's codes (ActFP8::g8; `group`, stated to that form alone: last, and cut off
|
||||
* otherwise), where this rank's value heads pair up. */
|
||||
const bool cr_wide = w.o.q8_rot && w.o.g8 == RAD_I8_GROUP_WIDE && cfg.n_head_v % 2 == 0;
|
||||
cr_codes = w.o.cq() && (!w.o.q8_rot || w.o.g8 == RAD_FP8_BLOCK || cr_wide);
|
||||
const RadParam cp[] = { RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v),
|
||||
RAD_INT("conv_width", cfg.conv_width),
|
||||
RAD_INT("n_head_v", cfg.n_head_v), RAD_F64("scale", q_scale),
|
||||
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act),
|
||||
RAD_STR("state_form", g.max_spec > 0 ? "anchor" : "per_candidate"),
|
||||
RAD_INT("group", RAD_I8_GROUP_WIDE) };
|
||||
const rad_weight cw[] = { w_conv, w_a_log, w_dt_bias, w_out_norm };
|
||||
op_cr = rw(b, rad_decl_op(b, w.o.q8_rot && cr_codes ? "gdn_conv_recurrent_update_had"
|
||||
: "gdn_conv_recurrent_update",
|
||||
cp, (int)(sizeof cp / sizeof *cp) - (cr_wide && cr_codes ? 0 : 1),
|
||||
cw, 4),
|
||||
{w.in.x, w.ab}, {w.o.x});
|
||||
if (op_cr && w.o.cq()) {
|
||||
if (op_cr && cr_codes) {
|
||||
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
|
||||
RAD_ARCH_TRY(rad_op_writes(b, op_cr, oq, 2));
|
||||
}
|
||||
@@ -455,8 +465,12 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
/* At decode and verify sizes the a|b projection is nearly all launch cost and reads only the
|
||||
* norm's output, as the in-projection does, so it runs beside it on lane 1 and is joined before
|
||||
* the convolution reads `ab`. A prefill chunk keeps one lane, where the two would share
|
||||
* bandwidth. */
|
||||
if (ab_lane && T <= 64 && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) {
|
||||
* bandwidth. Where launches chain it stays on lane 0: its chained form starts beside the
|
||||
* in-projection without the two lane joins, each of which holds a launch back until the host
|
||||
* has seen the other lane finish (Qwen3.8-27B on two cards: the projection started 55 us late
|
||||
* and the update behind it another 20 to 40 us). */
|
||||
if (ab_lane && !rad_chain_on() && T <= 64 && rad_lane_join(c, 0, 1) == RAD_OK &&
|
||||
rad_lane(c, 1) == RAD_OK) {
|
||||
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
|
||||
rad_lane(c, 0);
|
||||
in.step(c, w.h, w.in.x, T);
|
||||
@@ -490,11 +504,17 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
|
||||
/* The recurrent update at decode heights runs one workgroup per (sequence, head) and leaves the
|
||||
* card's memory mostly idle, so the out-projection's weight is read into the on-die cache
|
||||
* beside it, on the second lane behind a join from lane 0 (as prefetch_beside). */
|
||||
* beside it: in front of the update on lane 0 where launches chain (the read's chained form
|
||||
* holds nothing behind it), else on the second lane behind a join from lane 0 (as
|
||||
* prefetch_beside). */
|
||||
if (op_pf_out && D > 0 && D <= pf_out_seqs && P == 0 && T <= pf_out_rows) {
|
||||
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK)
|
||||
if (prefetch_lane0()) {
|
||||
RAD_ISSUE(c, op_pf_out, RAD_W(out.w));
|
||||
rad_lane(c, 0);
|
||||
} else {
|
||||
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK)
|
||||
RAD_ISSUE(c, op_pf_out, RAD_W(out.w));
|
||||
rad_lane(c, 0);
|
||||
}
|
||||
}
|
||||
if (D > 0 && op_cr && qd <= cr_rows) {
|
||||
RAD_ISSUE_N(c, op_cr, qd,
|
||||
@@ -505,8 +525,9 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
|
||||
praw(batch->cu_seqlens, RAD_I32, D + 1),
|
||||
bcol(w.in.x, conv_dim, v_dim, DT), RAD_W(w_out_norm), brows(w.o.x, DT),
|
||||
w.o.cq() ? brows(w.o.cq(), DT) : RAD_NONE,
|
||||
w.o.cq() ? brows(w.o.cs(), DT) : RAD_NONE);
|
||||
cr_codes ? brows(w.o.cq(), DT) : RAD_NONE,
|
||||
cr_codes ? brows(w.o.cs(), DT) : RAD_NONE);
|
||||
if (w.o.cq() && !cr_codes) q_o.step(c, T, 0, DT);
|
||||
} else if (D > 0) {
|
||||
RAD_ISSUE_N(c, op_conv_update, qd,
|
||||
bcol(w.in.x, 0, conv_dim, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer),
|
||||
|
||||
+39
-11
@@ -77,12 +77,13 @@ struct HyperConn {
|
||||
* skips its own on every step takes_ar() accepts. The block's partial sum is the write's
|
||||
* input buffer, so this saves a launch. */
|
||||
int reduce = 0;
|
||||
/* Whether the read also emits Hadamard-rotated fp8 codes of the block input, for a
|
||||
* consumer whose weight carries the rotation (MoeFP8's rotated expert plane). Produced in
|
||||
* the plain codes' finisher, so requires `quant`; the consumer declares no quantiser. */
|
||||
/* Whether the read also emits Hadamard-rotated codes of the block input, for a consumer
|
||||
* whose weight carries the rotation (MoeFP8's rotated expert plane). Produced in the
|
||||
* plain codes' finisher, so requires `quant`; the consumer declares no quantiser. */
|
||||
int rotate = 0;
|
||||
/* Whether the plain codes are int8 (q8/s8) rather than E4M3 (q/s), for int8 trunk linears
|
||||
* (LinearFP8::i8). The rotated codes stay E4M3, the routed experts' operand. */
|
||||
* (LinearFP8::i8). The rotated codes take the same dtype (had_quant_act_i8g's beside int8,
|
||||
* had_quant_act_fp8's beside E4M3), so `Wire::rq` is declared to match. */
|
||||
int codes_i8 = 0;
|
||||
/* The most rows one read is declared for, 0 for max_tok; a wider step reads in pieces
|
||||
* (read_pieces). The read's scratch is sized for its band (some 22 KiB a row at
|
||||
@@ -115,6 +116,11 @@ struct HyperConn {
|
||||
* `mix`), read from their encoding at declare. */
|
||||
bool mix_e4m3 = false;
|
||||
rad_op op_read = 0, op_write = 0;
|
||||
/* The block input's own int8 pair is the rotated one (ActFP8::q8_rot, a trunk stored rotated):
|
||||
* the read writes its rotated codes there and its plain ones into `pq` / `ps`, a pair of this
|
||||
* connection's that nothing reads. */
|
||||
bool xrot = false;
|
||||
rad_buf pq = 0, ps = 0;
|
||||
/* The write with the all-reduce folded in; 0 when not requested or not served.
|
||||
* `op_ar_write6` is the same on the rotated 6-bit wire, declared only when a lossy payload is
|
||||
* accepted and issued on the steps ar_wire_is_exact rejects (every trunk all-reduce at a
|
||||
@@ -193,6 +199,17 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c.quant && (c.codes_i8 ? (!w.x.q8 || !w.x.s8) : (!w.x.q || !w.x.s))) return RAD_E_INVAL;
|
||||
/* A trunk whose int8 linears are stored rotated reads the rotated codes alone: `x`'s int8 pair
|
||||
* is then that pair (ActFP8::q8_rot), and every reader of the block input -- the trunk's
|
||||
* projections and the rotated experts -- takes it. The read derives the rotated codes in its
|
||||
* plain codes' finisher, so the plain ones still have somewhere to go: a pair of this
|
||||
* connection's own that nothing reads. */
|
||||
xrot = c.quant && c.codes_i8 && w.x.q8_rot;
|
||||
if (xrot && c.rotate) {
|
||||
fprintf(stderr, "radiance: %s: the block input's own codes are the rotated ones "
|
||||
"(ActFP8::q8_rot), so there is no second rotated pair to ask for\n", name);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c.rotate && (!c.quant || !w.rq || !w.rs)) {
|
||||
fprintf(stderr, "radiance: %s: the rotated codes need the plain ones (quant) and the "
|
||||
"rq/rs pair on the wire\n", name);
|
||||
@@ -248,8 +265,16 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
rad_buf wr[6] = { w.x.x, 0, 0, 0, 0, 0 };
|
||||
int n_wr = 1;
|
||||
if (c.inject) wr[n_wr++] = w.inj;
|
||||
if (c.quant) { wr[n_wr++] = c.codes_i8 ? w.x.q8 : w.x.q; wr[n_wr++] = c.codes_i8 ? w.x.s8 : w.x.s; }
|
||||
if (c.rotate) { wr[n_wr++] = w.rq; wr[n_wr++] = w.rs; }
|
||||
if (xrot) {
|
||||
pq = decl_b(b, nm.f("%s.plain.q8", name), RAD_I8, { g.max_tok, g.n_embd });
|
||||
ps = decl_b(b, nm.f("%s.plain.s8", name), RAD_F32, { g.max_tok, fp8_blocks(g.n_embd) });
|
||||
if (!pq || !ps || w.x.g8 != RAD_FP8_BLOCK) return RAD_E_INVAL;
|
||||
wr[n_wr++] = pq; wr[n_wr++] = ps;
|
||||
wr[n_wr++] = w.x.q8; wr[n_wr++] = w.x.s8;
|
||||
} else {
|
||||
if (c.quant) { wr[n_wr++] = c.codes_i8 ? w.x.q8 : w.x.q; wr[n_wr++] = c.codes_i8 ? w.x.s8 : w.x.s; }
|
||||
if (c.rotate) { wr[n_wr++] = w.rq; wr[n_wr++] = w.rs; }
|
||||
}
|
||||
|
||||
op_read = RAD_OP(b, "hc_read",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.read_rows > 0 && c.read_rows < g.max_tok
|
||||
@@ -259,7 +284,7 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype),
|
||||
RAD_F64("wadd", g.wadd), RAD_INT("inject", c.inject ? 1 : 0),
|
||||
RAD_INT("group", c.quant ? RAD_FP8_BLOCK : 0),
|
||||
RAD_INT("rotate", c.rotate ? 1 : 0),
|
||||
RAD_INT("rotate", (c.rotate || xrot) ? 1 : 0),
|
||||
RAD_STR("mix", mix_e4m3 ? "e4m3" : "bf16")),
|
||||
wts, n_wts);
|
||||
if (!op_read) return RAD_E_INVAL;
|
||||
@@ -358,11 +383,14 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
|
||||
c.inject ? RAD_W(w_inj) : RAD_NONE,
|
||||
brow_slice(w.x.x, r0, rows, g.n_embd),
|
||||
c.inject ? brow_slice(w.inj, r0, rows, c.hc) : RAD_NONE,
|
||||
c.quant ? brow_slice(c.codes_i8 ? w.x.q8 : w.x.q, r0, rows, g.n_embd) : RAD_NONE,
|
||||
c.quant ? brow_slice(c.codes_i8 ? w.x.s8 : w.x.s, r0, rows,
|
||||
c.quant ? brow_slice(xrot ? pq : c.codes_i8 ? w.x.q8 : w.x.q, r0, rows,
|
||||
g.n_embd) : RAD_NONE,
|
||||
c.quant ? brow_slice(xrot ? ps : c.codes_i8 ? w.x.s8 : w.x.s, r0, rows,
|
||||
fp8_blocks(g.n_embd)) : RAD_NONE,
|
||||
c.rotate ? brow_slice(w.rq, r0, rows, g.n_embd) : RAD_NONE,
|
||||
c.rotate ? brow_slice(w.rs, r0, rows, fp8_blocks(g.n_embd)) : RAD_NONE);
|
||||
(c.rotate || xrot) ? brow_slice(xrot ? w.x.q8 : w.rq, r0, rows, g.n_embd)
|
||||
: RAD_NONE,
|
||||
(c.rotate || xrot) ? brow_slice(xrot ? w.x.s8 : w.rs, r0, rows,
|
||||
fp8_blocks(g.n_embd)) : RAD_NONE);
|
||||
}
|
||||
|
||||
/* ================================================================== the control-vector projection
|
||||
|
||||
+287
-128
@@ -259,6 +259,16 @@ struct MoeFP8 {
|
||||
* layer's; the 64-group codebook forms may differ by layer and projection, and declare()
|
||||
* resolves each layer's (MoeFP8::fmt). */
|
||||
int expert_w5 = 0;
|
||||
/* Int8 experts (`i8*bf16[1x128]/fwht128`): codes -127..127 with a bf16 scale per (row, 128
|
||||
* of K), each 128 of K rotated as `expert_rot` describes, read against int8 activations
|
||||
* (dtype `i8a8h`). The eight-bit expert of an int8 model, where block fp8 is that of an
|
||||
* E4M3 one. Set with `expert_rot`. */
|
||||
int expert_i8 = 0;
|
||||
/* Experts as IQR weights: the rotated computed trellis (libquant's tcq_code=mad) under one
|
||||
* f32 scale a row, two to six bits a code, each expert decoded where the grouped GEMM
|
||||
* reads it against the rotated int8 activations (dtype `i8a8h`, libr4d's moe_gemm_iqr).
|
||||
* Set with `expert_rot`. */
|
||||
int expert_iqr = 0;
|
||||
/* Plain bf16 experts (no quantising recipe). Both GEMMs are `moe_gemm` over one table of
|
||||
* whole experts with `silu_mul` between, and the shared arm follows the trunk
|
||||
* (Geom::w_bf16). Not sliced by parity: each expert is served whole on its rank, which
|
||||
@@ -302,6 +312,11 @@ struct MoeFP8 {
|
||||
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 */
|
||||
/* Above 0, `ecnt` is the model's routing table (rad_route_table), [layers, ecnt_pitch],
|
||||
* and this block's counts are its row `layer`: the report then costs no copy and every
|
||||
* layer keeps its own counts. 0: `ecnt` is one row, which the layers sharing the wire
|
||||
* overwrite in turn. */
|
||||
int64_t ecnt_pitch = 0;
|
||||
/* 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
|
||||
@@ -364,6 +379,14 @@ struct MoeFP8 {
|
||||
|
||||
NormQuantFP8 nq_h{};
|
||||
GateQuantFP8 gq_exp{}, gq_sh{};
|
||||
/* The shared arm's gate_up and its quantiser as one launch (decl_gated_fold_iqr), and the rows
|
||||
* it serves; 0 where the pair runs. */
|
||||
rad_op op_sh_gated = 0;
|
||||
int64_t sh_gated_rows = 0;
|
||||
/* Whether the routed gate_up is a trellis weight (moe_gemm_iqr), and the routed rows from
|
||||
* which the shared arm's first stage then runs beside the router instead (pass()). */
|
||||
bool gu_trellis = false;
|
||||
static constexpr int64_t kSharedFirstRows = 100;
|
||||
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
|
||||
@@ -392,6 +415,16 @@ struct MoeFP8 {
|
||||
* no quantiser for it. Set before declare. */
|
||||
bool hr_in = false;
|
||||
rad_op op_gu = 0, op_dn = 0, op_gather = 0;
|
||||
/* The routed arm's activations are int8: rotated codes with an f32 scale per (row, group),
|
||||
* which the grouped GEMMs meet with the iu8 WMMA (the `a8i8` and `i8a8h` dtypes). The
|
||||
* architecture asks for it by feeding `Wire::eff` int8 (ActFP8::q8_fed with q8_rot); int8
|
||||
* experts take nothing else, and the rotated four-bit forms take either. Resolved by
|
||||
* declare(). */
|
||||
bool a8 = false;
|
||||
/* The codes gate_up reads and the K one of their scales covers: `h`'s own pair where the
|
||||
* trunk feeds rotated int8 (at its group, 128 or IQ8R's 256), else `hr`'s. */
|
||||
rad_buf gin_q = 0, gin_s = 0;
|
||||
int64_t gin_g = RAD_FP8_BLOCK;
|
||||
/* Protected experts: local experts a quantised layer keeps bf16, the few whose output dwarfs
|
||||
* the rest (docs/MOE-W4.md). The scatter sorts them last (`protect`, `prot_list`), the
|
||||
* quantised GEMMs serve the other `n_reg`, and a bf16 grouped GEMM pair serves these over the
|
||||
@@ -413,9 +446,13 @@ struct MoeFP8 {
|
||||
* number mod 4 (`moe_gemm_q_mod4`, Config::ff_lo4). */
|
||||
int ncls = 2;
|
||||
/* This layer's gate_up and down formats (format_of's numbers), resolved by declare(): the
|
||||
* probed layer's, except that among the codebook forms at E4M3 scales (w4nl64a8h, w4nl32a8h,
|
||||
* w5nl64a8h) each projection of each layer takes its own experts'. */
|
||||
* probed layer's, except that among the forms reading one input (declare()'s `family`: the
|
||||
* codebook forms at E4M3 scales, or under an int8 routed arm every form with an int8 row) each
|
||||
* projection of each layer takes its own experts'. */
|
||||
int fmt[2] = { 0, 0 };
|
||||
/* The encoding of the layer's first quantised expert, per projection: a trellis's code width
|
||||
* is the views' dtype. */
|
||||
RadEncoding fenc[2]{};
|
||||
std::vector<rad_weight> w_pgu, w_pdn;
|
||||
rad_buf b_pgu = 0;
|
||||
ActFP8 pff{};
|
||||
@@ -469,11 +506,18 @@ 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, 8 OCP MXFP4, 9 block fp8 at f32 scales; RAD_E_DTYPE otherwise. */
|
||||
* five-bit form per 64, 8 OCP MXFP4, 9 block fp8 at f32 scales, 10 rotated int8, 11 the rotated
|
||||
* computed trellis under one f32 scale a row (an IQR weight an expert); 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[10] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
|
||||
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h", "mxfp4a8", "fp8a8f32" };
|
||||
/* format_of's numbers as the grouped GEMMs' dtype strings against an E4M3 activation, and
|
||||
* against an int8 one (null: the format has no such row). Int8 experts read int8 only. */
|
||||
static constexpr const char* kServed[12] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
|
||||
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h", "mxfp4a8",
|
||||
"fp8a8f32", nullptr, nullptr };
|
||||
static constexpr const char* kServed8[12] = { nullptr, nullptr, "w4a8i8h", nullptr, nullptr,
|
||||
"w4nl64a8i8h", "w4nl32a8i8h", nullptr, nullptr,
|
||||
nullptr, "i8a8h", "i8a8h" };
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
const Wire& wire, const Src& src, bool fold = false, bool add_out = true,
|
||||
@@ -505,6 +549,10 @@ 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;
|
||||
/* The computed trellis under one f32 scale a row, rotated (IQR-V4's feed-forward form). */
|
||||
if (rad_enc_is(&e, "trellis"))
|
||||
return std::strcmp(e.transform, "fwht128") == 0 && linear_w8h_mad(e) &&
|
||||
linear_w8h_rowf(e) ? 11 : RAD_E_DTYPE;
|
||||
if (!rad_enc_is(&e, "affine")) return RAD_E_DTYPE;
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
/* The codebook at E4M3 scales per 64 or 32 of K under one fixed f32 (w4nl64a8h, w4nl32a8h),
|
||||
@@ -544,6 +592,9 @@ inline int MoeFP8::format_of(const RadEncoding& e) {
|
||||
if (!e.transform[0]) return 1;
|
||||
if (std::strcmp(e.transform, "fwht128") == 0) return 2;
|
||||
}
|
||||
if (e.plane[0].dtype == RAD_I8 && sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK &&
|
||||
std::strcmp(e.transform, "fwht128") == 0)
|
||||
return 10;
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
|
||||
@@ -616,7 +667,8 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
|
||||
cfg->probed_count = ge - g0 + 1;
|
||||
RadEncoding e{};
|
||||
f = 0;
|
||||
if (weight_enc(b, guw, &e) && (f = format_of(e)) < 0) {
|
||||
const bool known = weight_enc(b, guw, &e);
|
||||
if (known && (f = format_of(e)) < 0) {
|
||||
char en[256];
|
||||
rad_enc_format(&e, en, sizeof en);
|
||||
fprintf(stderr, "radiance: '%s' is %s, and the routed experts are served as block fp8 "
|
||||
@@ -624,14 +676,19 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
|
||||
"/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, or OCP MXFP4 "
|
||||
"(fp4_e2m1*e8m0[1x32]). "
|
||||
"Convert it with a recipe that makes one of them.\n", guw, en);
|
||||
"(fp4_e2m1*e8m0[1x32]), or rotated int8 (i8*bf16[1x128]/fwht128), or "
|
||||
"the rotated computed trellis under one f32 scale a row. Convert it "
|
||||
"with a recipe that makes one of them.\n", guw, en);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (known && (f == 0 || f == 8 || f == 9))
|
||||
return linear_refuse_retired(guw, f == 8 ? "MXFP4" : "block fp8");
|
||||
if (f != 3) break;
|
||||
}
|
||||
cfg->expert_w4 = (f == 1 || f == 2 || f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0;
|
||||
cfg->expert_rot = (f == 2 || f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0;
|
||||
cfg->expert_rot = (f == 2 || f == 4 || f == 5 || f == 6 || f == 7 || f == 10 || f == 11) ? 1 : 0;
|
||||
cfg->expert_i8 = f == 10 ? 1 : 0;
|
||||
cfg->expert_iqr = f == 11 ? 1 : 0;
|
||||
cfg->expert_nl = (f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0;
|
||||
cfg->expert_g64 = (f == 5 || f == 7) ? 2 : f == 6 ? 4 : 0;
|
||||
cfg->expert_w5 = f == 7 ? 1 : 0;
|
||||
@@ -693,7 +750,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
* refused, since the fused all-reduce lives inside the norm. See rad_block_attn_gated_fp8.h. */
|
||||
ext_in = (src.norm == nullptr);
|
||||
if (ext_in) {
|
||||
if (!w.h.x || (!g.w_bf16 && (!w.h.q || !w.h.s)) || ar_in != kArNone) return RAD_E_INVAL;
|
||||
if (!w.h.x || (!g.w_bf16 && (!w.h.cq() || !w.h.cs())) || ar_in != kArNone)
|
||||
return RAD_E_INVAL;
|
||||
} else {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_norm.weight", l), src.norm));
|
||||
w_norm = decl_w(b, nm.f("blk.%d.ffn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
@@ -714,9 +772,12 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
RAD_ARCH_TRY(moe_map_expert(b, nm, src, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, ge),
|
||||
nm.f("blk.%d.ffn_down_exps.%lld.weight", l, ge), ge, !probed));
|
||||
}
|
||||
/* The routed arm's activations (see `a8`), known before the layer's formats are resolved:
|
||||
* which forms may share a model depends on the codes they read. */
|
||||
a8 = w.eff.q8_fed && !c.expert_bf16;
|
||||
prot.clear();
|
||||
{
|
||||
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
|
||||
const int want = c.expert_iqr ? 11 : c.expert_i8 ? 10 : 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]) {
|
||||
@@ -728,36 +789,50 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
if (weight_enc(b, nmv[i], &enc[i])) fe[i] = format_of(enc[i]);
|
||||
}
|
||||
};
|
||||
/* The codebook forms at E4M3 scales differ only in the GEMM's dtype (same rotated input,
|
||||
* scale views, fixed second level, accumulators), so each layer and projection may use any
|
||||
* of them. The layer's first non-bf16 expert decides both; every other must match. Outside
|
||||
* that family a layer uses the probed layer's form. */
|
||||
auto family = [](int f) { return f == 5 || f == 6 || f == 7; };
|
||||
/* The forms that read one input may differ by layer and projection: against E4M3 codes the
|
||||
* codebook forms at E4M3 scales (same rotated input, scale views, fixed second level,
|
||||
* accumulators; only the GEMM's dtype differs), and against the rotated int8 pair every
|
||||
* form with a row for it (four-bit, the codebook at a 64 or 32 of K, int8), whose views
|
||||
* efmt_of states per projection. The layer's first non-bf16 expert decides both
|
||||
* projections; every other must match. Outside its family a layer uses the probed
|
||||
* layer's form. */
|
||||
const bool a8f = a8;
|
||||
auto family = [a8f](int f) {
|
||||
return a8f ? (f == 2 || f == 5 || f == 6 || f == 10 || f == 11)
|
||||
: (f == 5 || f == 6 || f == 7);
|
||||
};
|
||||
fmt[0] = fmt[1] = want;
|
||||
if (family(want))
|
||||
for (int64_t e = 0; e < ne; ++e) {
|
||||
RadEncoding enc[2]{};
|
||||
int fe[2];
|
||||
const char* nmv[2];
|
||||
fmt_of(e, enc, fe, nmv);
|
||||
if (fe[0] == 3 && fe[1] == 3) continue;
|
||||
for (int i = 0; i < 2; ++i)
|
||||
if (family(fe[i])) fmt[i] = fe[i];
|
||||
break;
|
||||
fenc[0] = fenc[1] = RadEncoding{};
|
||||
for (int64_t e = 0; e < ne; ++e) {
|
||||
RadEncoding enc[2]{};
|
||||
int fe[2];
|
||||
const char* nmv[2];
|
||||
fmt_of(e, enc, fe, nmv);
|
||||
if (fe[0] == 3 && fe[1] == 3) continue;
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
if (family(want) && family(fe[i])) fmt[i] = fe[i];
|
||||
fenc[i] = enc[i];
|
||||
}
|
||||
break;
|
||||
}
|
||||
for (int64_t e = 0; e < ne; ++e) {
|
||||
RadEncoding enc[2]{};
|
||||
int fe[2];
|
||||
const char* names[2];
|
||||
fmt_of(e, enc, fe, names);
|
||||
if (fe[0] == fmt[0] && fe[1] == fmt[1]) continue;
|
||||
/* A trellis layer is one code width a projection: the views are declared at it. */
|
||||
const bool same = fe[0] == fmt[0] && fe[1] == fmt[1] &&
|
||||
(fmt[0] != 11 || enc[0].plane[0].dtype == fenc[0].plane[0].dtype) &&
|
||||
(fmt[1] != 11 || enc[1].plane[0].dtype == fenc[1].plane[0].dtype);
|
||||
if (same) continue;
|
||||
if (want != 3 && fe[0] == 3 && fe[1] == 3) { prot.push_back(e); continue; }
|
||||
const int i = fe[0] != fmt[0] ? 0 : 1;
|
||||
char en[256];
|
||||
rad_enc_format(&enc[i], en, sizeof en);
|
||||
fprintf(stderr, "radiance: '%s' is %s, and this layer's experts are served as %s -- one "
|
||||
"table of experts takes one encoding, and only a whole expert kept "
|
||||
"plain bf16 is served beside it.\n", names[i], en, kServed[fmt[i]]);
|
||||
"plain bf16 is served beside it.\n", names[i], en,
|
||||
kServed[fmt[i]] ? kServed[fmt[i]] : kServed8[fmt[i]]);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
}
|
||||
@@ -950,14 +1025,32 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
(long long)wq[q], (long long)g.n_embd, RAD_FP8_BLOCK, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* 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 == 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;
|
||||
/* A format's views: the codes view's dtype and planes (a codebook's table is selected with its
|
||||
* codes so the relayout sees it), and the scale view's -- 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; f32 per 128x128 tile (format 9) or E8M0 per (row, 32
|
||||
* of K) for MXFP4. `sgk` is the K one declared scale column covers: a view of two planes 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. */
|
||||
struct EFmt { uint32_t cdt; const char* cplanes; uint32_t sdt; int64_t sgk; const char* splanes; };
|
||||
auto efmt_of = [](int f, const RadEncoding& fe) -> EFmt {
|
||||
switch (f) {
|
||||
/* An IQR weight: the codes at their stored width with the code's planes, and the row and
|
||||
* block scales as one view at the weight's extents (LinearFP8's views of the same form). */
|
||||
case 11: return { fe.plane[0].dtype, "codes,trellis,trellis.mad", RAD_F32, 1,
|
||||
"scale,scale.col" };
|
||||
case 10: return { RAD_I8, "codes", RAD_BF16, RAD_FP8_BLOCK, "scale" };
|
||||
case 9: return { RAD_F8E4M3, "codes", RAD_F32, RAD_FP8_BLOCK, "scale" };
|
||||
case 8: return { RAD_FP4E2M1, "codes", RAD_E8M0, RAD_MX_GROUP, "scale" };
|
||||
case 7: return { RAD_U5, "codes,table", RAD_F8E4M3, 1, "scale,scale.1" };
|
||||
case 5: case 6: return { RAD_U4, "codes,table", RAD_F8E4M3, 1, "scale,scale.1" };
|
||||
case 4: return { RAD_U4, "codes,table", RAD_BF16, RAD_FP8_BLOCK, "scale" };
|
||||
case 1: case 2: return { RAD_I4, "codes", RAD_BF16, RAD_FP8_BLOCK, "scale" };
|
||||
default: return { RAD_F8E4M3, "codes", RAD_BF16, RAD_FP8_BLOCK, "scale" };
|
||||
}
|
||||
};
|
||||
const uint32_t edt[2] = { edt_of(fmt[0]), edt_of(fmt[1]) };
|
||||
const char* const ecodes = c.expert_nl ? "codes,table" : "codes";
|
||||
const EFmt ef[2] = { efmt_of(fmt[0], fenc[0]), efmt_of(fmt[1], fenc[1]) };
|
||||
/* Under expert parallelism each owned expert is whole, so its weights are not sharded;
|
||||
* RAD_SHARD_ROW would make the loader slice it again (and refuse). */
|
||||
const bool ep = c.n_expert != c.n_expert_all;
|
||||
@@ -972,33 +1065,47 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
*
|
||||
* Rotation exists only for the 4-bit plane (the fp8 layout hook has no rotated form), and the
|
||||
* codebook only with rotation; other combinations are refused. */
|
||||
if ((c.expert_rot && !c.expert_w4) || (c.expert_nl && !c.expert_rot)) {
|
||||
fprintf(stderr, "radiance: rotated experts (expert_rot) require the 4-bit expert format, "
|
||||
"and a codebook (expert_nl) the rotated one; there is no rotated E4M3 "
|
||||
"expert plane and no unrotated codebook\n");
|
||||
if ((c.expert_rot && !c.expert_w4 && !c.expert_i8 && !c.expert_iqr) ||
|
||||
(c.expert_nl && !c.expert_rot) || ((c.expert_i8 || c.expert_iqr) && !c.expert_rot)) {
|
||||
fprintf(stderr, "radiance: rotated experts (expert_rot) require the 4-bit or the int8 "
|
||||
"expert format, and a codebook (expert_nl) or int8 experts the rotated "
|
||||
"one; there is no rotated E4M3 expert plane, no unrotated codebook and no "
|
||||
"unrotated int8 expert\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* ---- The routed arm's activations (see `a8`). */
|
||||
if ((c.expert_i8 || c.expert_iqr || fmt[0] >= 10 || fmt[1] >= 10) && !a8) {
|
||||
fprintf(stderr, "radiance: layer %d's experts read int8 activations (int8, or an IQR weight); the "
|
||||
"architecture declared the routed arm's codes E4M3\n", l);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (a8) {
|
||||
const bool pair = w.eff.q8 && w.eff.s8 && w.eff.q8_rot && w.eff.g8 == RAD_FP8_BLOCK;
|
||||
if (!pair || !c.expert_rot || !kServed8[fmt[0]] || !kServed8[fmt[1]] || c.calib ||
|
||||
c.swiglu_limit > 0) {
|
||||
fprintf(stderr, "radiance: layer %d: int8 activations meet rotated experts (int8, "
|
||||
"four-bit, or the codebook at E4M3 scales a 64 or 32 of K) through "
|
||||
"rotated codes at one scale a 128 of K, unclamped, outside "
|
||||
"calibration; these are %s / %s%s\n", l,
|
||||
kServed[fmt[0]] ? kServed[fmt[0]] : kServed8[fmt[0]],
|
||||
kServed[fmt[1]] ? kServed[fmt[1]] : kServed8[fmt[1]],
|
||||
pair ? "" : ", and the gated product's int8 pair is not that");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
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 : (int)gu;
|
||||
/* 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;
|
||||
const bool rowscale = c.expert_w4 || c.expert_mx || c.expert_i8 || c.expert_iqr;
|
||||
const int64_t sdiv = rowscale ? 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; 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_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";
|
||||
gu_trellis = fmt[0] == 11;
|
||||
const char* const edtype[2] = { a8 ? kServed8[fmt[0]] : kServed[fmt[0]],
|
||||
a8 ? kServed8[fmt[1]] : kServed[fmt[1]] };
|
||||
/* 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. */
|
||||
auto span = [&](rad_weight h, int q, int64_t unit) -> int {
|
||||
@@ -1064,7 +1171,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_weight& h = w_gu[(size_t)s];
|
||||
h = decl_view(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
nullptr, ecodes, edt[0], {gu * wq[q], g.n_embd},
|
||||
nullptr, ef[0].cplanes, ef[0].cdt, {gu * wq[q], g.n_embd},
|
||||
RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0),
|
||||
parts, n_parts);
|
||||
if (!h) return RAD_E_INVAL;
|
||||
@@ -1079,9 +1186,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
(long long)(c.expert_base + e)),
|
||||
nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
escale, sdt,
|
||||
{(c.expert_w4 || c.expert_mx) ? gu * wq[q] : fp8_blocks(gu * wq[q]),
|
||||
(c.expert_w4 || c.expert_mx) ? g.n_embd / sgk : fp8_blocks(g.n_embd)},
|
||||
ef[0].splanes, ef[0].sdt,
|
||||
{rowscale ? gu * wq[q] : fp8_blocks(gu * wq[q]),
|
||||
rowscale ? g.n_embd / ef[0].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;
|
||||
@@ -1093,7 +1200,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_weight& h = w_dn[(size_t)s];
|
||||
h = decl_view(b, nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
nullptr, ecodes, edt[1], {g.n_embd, wq[q]},
|
||||
nullptr, ef[1].cplanes, ef[1].cdt, {g.n_embd, wq[q]},
|
||||
RAD_ACCESS_CONDITIONAL, sh_col, grp_expert_slot(l, (int)s, 1));
|
||||
if (!h) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(span(h, q, 1));
|
||||
@@ -1106,11 +1213,11 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
(long long)(c.expert_base + e)),
|
||||
nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
escale, sdt,
|
||||
{(c.expert_w4 || c.expert_mx) ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / sgk},
|
||||
ef[1].splanes, ef[1].sdt,
|
||||
{rowscale ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / ef[1].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));
|
||||
RAD_ARCH_TRY(span(h, q, ef[1].sgk));
|
||||
}
|
||||
|
||||
/* ---- the two grouped GEMMs. `M` is a pass's token count, not the sorted row count: kernels
|
||||
@@ -1125,19 +1232,32 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
/* The routed arm's rotated copy of the input. Not in place: the shared expert also reads
|
||||
* `w.h.q` with an unrotated weight (see Config::expert_rot). Declared just before its one
|
||||
* consumer so graph and issue order agree. */
|
||||
if (rot) {
|
||||
if (!w.hr.q || !w.hr.s) {
|
||||
fprintf(stderr, "radiance: rotated experts need the `hr` (q, scale) pair on the wire; "
|
||||
"the architecture declares the buffers\n");
|
||||
gin_q = w.h.q;
|
||||
gin_s = w.h.s;
|
||||
gin_g = RAD_FP8_BLOCK;
|
||||
if (a8 && w.h.q8_fed && w.h.q8_rot) {
|
||||
/* The trunk's own rotated int8 codes, at its group: no second quantiser. */
|
||||
gin_q = w.h.q8;
|
||||
gin_s = w.h.s8;
|
||||
gin_g = w.h.g8;
|
||||
} else if (rot) {
|
||||
if (a8 ? !(w.hr.q8 && w.hr.s8 && w.hr.q8_fed && w.hr.q8_rot) : !(w.hr.q && w.hr.s)) {
|
||||
fprintf(stderr, "radiance: rotated experts need the `hr` (q, scale) pair on the wire%s; "
|
||||
"the architecture declares the buffers\n",
|
||||
a8 ? ", int8 and fed" : "");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
gin_q = w.hr.cq();
|
||||
gin_s = w.hr.cs();
|
||||
gin_g = w.hr.cg();
|
||||
if (!hr_in)
|
||||
op_hq = rw(b, RAD_OP(b, "had_quant_act_fp8",
|
||||
op_hq = rw(b, RAD_OP(b, a8 ? "had_quant_act_i8g" : "had_quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", gin_g), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.hr.q, w.hr.s});
|
||||
{w.h.x}, {gin_q, gin_s});
|
||||
}
|
||||
if (!gin_q || !gin_s || g.n_embd % gin_g) return RAD_E_INVAL;
|
||||
/* A table op's weights in operand order: even experts' codes and scales, then odd experts'
|
||||
* (`w`, `w_scale`, `w_odd`, `w_odd_scale`), or at four classes classes 0 to 3. */
|
||||
auto tables = [&](const std::vector<rad_weight>& wc, const std::vector<rad_weight>& ws) {
|
||||
@@ -1154,55 +1274,60 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
* and the zeros past the width are never read by that class's down projection. */
|
||||
{
|
||||
const std::vector<rad_weight> tab = tables(w_gu, w_gus);
|
||||
/* `a_group` is stated to the int8 rows alone: last, and cut off otherwise, so an E4M3
|
||||
* graph is the one it was. */
|
||||
const RadParam p4[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
|
||||
RAD_INT("N_1", gu * wq[1]), RAD_INT("K_1", g.n_embd),
|
||||
RAD_INT("N_2", gu * wq[2]), RAD_INT("K_2", g.n_embd),
|
||||
RAD_INT("N_3", gu * wq[3]), RAD_INT("K_3", g.n_embd),
|
||||
RAD_INT("parts", gu), RAD_INT("a_group", gin_g) };
|
||||
const RadParam p2[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
|
||||
RAD_INT("N_odd", gu * wq[1]), RAD_INT("K_odd", g.n_embd),
|
||||
RAD_INT("parts", gu), RAD_INT("a_group", gin_g) };
|
||||
const int cut = a8 ? 0 : 1;
|
||||
rad_op h = ncls == 4
|
||||
? rad_decl_op(b, "moe_gemm_q_mod4",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
|
||||
RAD_INT("N_1", gu * wq[1]), RAD_INT("K_1", g.n_embd),
|
||||
RAD_INT("N_2", gu * wq[2]), RAD_INT("K_2", g.n_embd),
|
||||
RAD_INT("N_3", gu * wq[3]), RAD_INT("K_3", g.n_embd),
|
||||
RAD_INT("parts", gu)),
|
||||
tab.data(), (int)tab.size())
|
||||
: rad_decl_op(b, "moe_gemm_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
|
||||
RAD_INT("N_odd", gu * wq[1]), RAD_INT("K_odd", g.n_embd),
|
||||
RAD_INT("parts", gu)),
|
||||
tab.data(), (int)tab.size());
|
||||
op_gu = rw(b, h, {rot ? w.hr.q : w.h.q, rot ? w.hr.s : w.h.s, w.sorted, w.eoff}, {w.egu});
|
||||
? rad_decl_op(b, "moe_gemm_q_mod4", p4, (int)(sizeof p4 / sizeof *p4) - cut,
|
||||
tab.data(), (int)tab.size())
|
||||
: rad_decl_op(b, "moe_gemm_q", p2, (int)(sizeof p2 / sizeof *p2) - cut,
|
||||
tab.data(), (int)tab.size());
|
||||
op_gu = rw(b, h, {gin_q, gin_s, w.sorted, w.eoff}, {w.egu});
|
||||
}
|
||||
/* 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;
|
||||
/* Fed int8, `eff` names the rotating int8 quantiser itself (ActFP8::q8_rot). */
|
||||
RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, w.eff, c.n_ff_exp, gact, c.rows * c.top_k,
|
||||
false, rot, c.swiglu_limit, c.swiglu_step != 0));
|
||||
false, rot && !a8, c.swiglu_limit, c.swiglu_step != 0));
|
||||
{
|
||||
const std::vector<rad_weight> tab = tables(w_dn, w_dns);
|
||||
const RadParam p4[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
|
||||
RAD_INT("N_1", g.n_embd), RAD_INT("K_1", wq[1]),
|
||||
RAD_INT("N_2", g.n_embd), RAD_INT("K_2", wq[2]),
|
||||
RAD_INT("N_3", g.n_embd), RAD_INT("K_3", wq[3]),
|
||||
RAD_INT("parts", 1), RAD_INT("a_group", RAD_FP8_BLOCK) };
|
||||
const RadParam p2[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
|
||||
RAD_INT("N_odd", g.n_embd), RAD_INT("K_odd", wq[1]),
|
||||
RAD_INT("parts", 1), RAD_INT("a_group", RAD_FP8_BLOCK) };
|
||||
const int cut = a8 ? 0 : 1;
|
||||
rad_op h = ncls == 4
|
||||
? rad_decl_op(b, "moe_gemm_q_mod4",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
|
||||
RAD_INT("N_1", g.n_embd), RAD_INT("K_1", wq[1]),
|
||||
RAD_INT("N_2", g.n_embd), RAD_INT("K_2", wq[2]),
|
||||
RAD_INT("N_3", g.n_embd), RAD_INT("K_3", wq[3]),
|
||||
RAD_INT("parts", 1)),
|
||||
tab.data(), (int)tab.size())
|
||||
: rad_decl_op(b, "moe_gemm_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
|
||||
RAD_INT("N_odd", g.n_embd), RAD_INT("K_odd", wq[1]),
|
||||
RAD_INT("parts", 1)),
|
||||
tab.data(), (int)tab.size());
|
||||
op_dn = rw(b, h, {w.eff.q, w.eff.s, w.sorted, w.eoff}, {w.edn});
|
||||
? rad_decl_op(b, "moe_gemm_q_mod4", p4, (int)(sizeof p4 / sizeof *p4) - cut,
|
||||
tab.data(), (int)tab.size())
|
||||
: rad_decl_op(b, "moe_gemm_q", p2, (int)(sizeof p2 / sizeof *p2) - cut,
|
||||
tab.data(), (int)tab.size());
|
||||
op_dn = rw(b, h, {w.eff.cq(), w.eff.cs(), w.sorted, w.eoff}, {w.edn});
|
||||
}
|
||||
/* ---- The protected experts' own GEMM pair. Their weights belong to the layer group, not to
|
||||
* expert slots: each container expert unit has a fixed size and these are four times larger, so
|
||||
@@ -1339,7 +1464,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
|
||||
RAD_NOWEIGHTS),
|
||||
{rot ? w.hr.q : w.h.q, rot ? w.hr.s : w.h.s, b_gram_gu}, {b_gram_gu});
|
||||
{gin_q, gin_s, b_gram_gu}, {b_gram_gu});
|
||||
/* The down tap's M is the sorted height `rows * top_k` (one row per (token, slot)).
|
||||
* gate_up's is the token height: every token goes to exactly top_k experts, so the gathered
|
||||
* distribution is the token distribution scaled by top_k, and H is used only up to scale. */
|
||||
@@ -1412,7 +1537,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
const char* shared_up = src.shared_mlp_up
|
||||
? src.shared_mlp_up
|
||||
: nm.ckpt("%s.up_proj.weight", src.shared);
|
||||
RAD_ARCH_TRY(sh_down.probe(b, nm, g, down_base, { shared_down }));
|
||||
/* An architecture that sized the gate's code pair from this weight has probed it. */
|
||||
if (!sh_down.mapped) RAD_ARCH_TRY(sh_down.probe(b, nm, g, down_base, { shared_down }));
|
||||
/* The code pair the gate writes, E4M3 or int8 (ActFP8::q8_fed); an int8 down projection
|
||||
* that quantises for itself also writes the int8 pair on this lane. */
|
||||
if (w.sff.cq()) {
|
||||
@@ -1441,6 +1567,17 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
RAD_ARCH_TRY(gq_sh.declare(b, g, w.sgu, w.sff, c.n_ff_shared, "silu", c.rows,
|
||||
sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8), false,
|
||||
sh_limit, c.swiglu_step != 0));
|
||||
/* An IQR gate_up between the rotated int8 trunk's fed pairs folds SwiGLU and the rotating
|
||||
* quantiser into its epilogue, to 16 rows: one launch a layer less than the pair, which
|
||||
* stays declared for longer steps, other encodings and a clamped product. */
|
||||
if (sh_limit <= 0 && sh_gate_up.iqr && w.h.q8_fed && w.h.q8_rot && w.sff.q8_fed &&
|
||||
w.sff.q8_rot)
|
||||
op_sh_gated = decl_gated_fold_iqr(
|
||||
b, c.rows, sh_gate_up.N, sh_gate_up.K, sh_gate_up.w, sh_gate_up.ws,
|
||||
{ w.h.q8, w.h.s8 },
|
||||
gq_sh.want_x ? std::initializer_list<rad_buf>{ w.sff.q8, w.sff.s8, w.sff.x }
|
||||
: std::initializer_list<rad_buf>{ w.sff.q8, w.sff.s8 },
|
||||
&sh_gated_rows);
|
||||
RAD_ARCH_TRY(sh_down.declare(b, nm, g, down_base,
|
||||
g.n_embd, c.n_ff_shared, RAD_SHARD_COL, grp_layer(l),
|
||||
{ shared_down },
|
||||
@@ -1641,7 +1778,14 @@ inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows,
|
||||
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);
|
||||
if (op_sh_gated && rows <= sh_gated_rows)
|
||||
RAD_ISSUE_N(c_, op_sh_gated, rows, brow_slice(w.h.cq(), r0, rows, g.n_embd),
|
||||
brow_slice(w.h.cs(), r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(sh_gate_up.w),
|
||||
RAD_W(sh_gate_up.ws), brow_slice(w.sff.cq(), r0, rows, c.n_ff_shared),
|
||||
brow_slice(w.sff.cs(), r0, rows, c.n_ff_shared / RAD_FP8_BLOCK),
|
||||
gq_sh.want_x ? brow_slice(w.sff.x, r0, rows, c.n_ff_shared) : RAD_NONE);
|
||||
else
|
||||
sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows);
|
||||
}
|
||||
|
||||
/* One pass of at most `c.rows` tokens. Every op is per row (norm and quantiser within a row,
|
||||
@@ -1660,9 +1804,10 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
|
||||
/* The shared arm is interleaved with the routed arm on the same queue. It reads the same
|
||||
* input and writes nothing the routed arm touches before the gather, so each of its stages
|
||||
* (gate + gate_up, quantiser, down) is issued right behind the matching routed stage. A
|
||||
* recorded pass leaves each such pair unordered (Ctx::haz_mark), so they overlap without a
|
||||
* second queue's fork/join cost. The arm's buffers are excluded from sharing (see declare), so
|
||||
* (gate + gate_up, quantiser, down) is issued right behind the matching routed stage (its
|
||||
* first stage behind the router instead where `sh_first` below says so). A recorded pass
|
||||
* leaves each such pair unordered (Ctx::haz_mark), so they overlap without a second queue's
|
||||
* fork/join cost. The arm's buffers are excluded from sharing (see declare), so
|
||||
* issuing them ahead of their declared position is safe. */
|
||||
|
||||
/* The routed arm. */
|
||||
@@ -1675,8 +1820,11 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
* the histogram the kernel writes there never lands, and a consumer reading the reported
|
||||
* counts -- the file stager, at the layer's trigger -- sees zeros and skips every expert's
|
||||
* weights. The declared buffer is stable across record and replay, and route_report hands
|
||||
* the same buffer on, so the stager's stream-ordered read sees this pass's counts. */
|
||||
const RadOperand ecnt = brows(w.ecnt, ne);
|
||||
* the same buffer on, so the stager's stream-ordered read sees this pass's counts. With a
|
||||
* routing table (Wire::ecnt_pitch) the buffer is the core's rows too, and this is the
|
||||
* layer's. */
|
||||
const RadOperand ecnt = w.ecnt_pitch > 0 ? brow_slice(w.ecnt, layer, 1, w.ecnt_pitch)
|
||||
: brows(w.ecnt, ne);
|
||||
/* 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;
|
||||
@@ -1726,13 +1874,22 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
const bool rot = c.expert_rot != 0;
|
||||
if (op_hq)
|
||||
RAD_ISSUE_N(c_, op_hq, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
|
||||
brow_slice(w.hr.q, r0, rows, g.n_embd),
|
||||
brow_slice(w.hr.s, r0, rows, g.n_embd / RAD_FP8_BLOCK));
|
||||
brow_slice(gin_q, r0, rows, g.n_embd),
|
||||
brow_slice(gin_s, r0, rows, g.n_embd / gin_g));
|
||||
|
||||
/* The grouped GEMMs. Each table is the first handle of its run and its length; runs are
|
||||
* contiguous (see declare), so `w_gu[q] + i` is expert 2 * i + q, or 4 * i + q at four
|
||||
* classes, where class q holds ceil((n_reg - q) / 4). */
|
||||
const int64_t n4[4] = { (n_reg + 3) / 4, (n_reg + 2) / 4, (n_reg + 1) / 4, n_reg / 4 };
|
||||
/* Behind a trellis gate_up from kSharedFirstRows routed rows, the shared arm's first stage is
|
||||
* issued here, so it overlaps the router and the routed gate_up runs alone: that GEMM is
|
||||
* compute-bound at such heights, and with the arm beside it the pair ends later than the two
|
||||
* in turn. Flash-Next's 16- and 32-row verify passes on two R9700: 22.1 -> 21.9 ms and
|
||||
* 31.6 -> 30.95 ms. Below, the arm fits inside the routed GEMM's time and stays beside it. */
|
||||
const bool sh_first = shared && gu_trellis && rows * k >= kSharedFirstRows;
|
||||
if (sh_first)
|
||||
shared_up(c_, T, r0, rows,
|
||||
(rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate));
|
||||
/* Apply the previous layer's prefetch prediction: substitute the copied experts into the
|
||||
* tables. */
|
||||
(void)rad_expert_prefetch_step(c_, layer);
|
||||
@@ -1742,8 +1899,8 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
brows(w.egu, rows * k));
|
||||
else if (ncls == 4)
|
||||
RAD_ISSUE_N(c_, op_gu, rows,
|
||||
brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd),
|
||||
brow_slice(rot ? w.hr.s : w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK),
|
||||
brow_slice(gin_q, r0, rows, g.n_embd),
|
||||
brow_slice(gin_s, r0, rows, g.n_embd / gin_g),
|
||||
RAD_WTAB(w_gu[0], n4[0]), RAD_WTAB(w_gus[0], n4[0]),
|
||||
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
|
||||
RAD_WTAB(w_gu[1], n4[1]), RAD_WTAB(w_gus[1], n4[1]),
|
||||
@@ -1752,22 +1909,23 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
brows(w.egu, rows * k));
|
||||
else
|
||||
RAD_ISSUE_N(c_, op_gu, rows,
|
||||
brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd),
|
||||
brow_slice(rot ? w.hr.s : w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK),
|
||||
brow_slice(gin_q, r0, rows, g.n_embd),
|
||||
brow_slice(gin_s, r0, rows, g.n_embd / gin_g),
|
||||
RAD_WTAB(w_gu[0], n_reg / 2), RAD_WTAB(w_gus[0], n_reg / 2),
|
||||
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) || (sfused && sigmoid_scatter_gate));
|
||||
if (shared && !sh_first)
|
||||
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 (shared && !(op_sh_gated && rows <= sh_gated_rows)) gq_sh.step(c_, w.sgu, T, r0, rows);
|
||||
if (c.expert_bf16)
|
||||
RAD_ISSUE_N(c_, op_dn, rows, brows(w.eff.x, rows * k), RAD_WTAB(w_dn[0], ne),
|
||||
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), brows(w.edn, rows * k));
|
||||
else if (ncls == 4)
|
||||
RAD_ISSUE_N(c_, op_dn, rows,
|
||||
brows(w.eff.q, rows * k), brows(w.eff.s, rows * k),
|
||||
brows(w.eff.cq(), rows * k), brows(w.eff.cs(), rows * k),
|
||||
RAD_WTAB(w_dn[0], n4[0]), RAD_WTAB(w_dns[0], n4[0]),
|
||||
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
|
||||
RAD_WTAB(w_dn[1], n4[1]), RAD_WTAB(w_dns[1], n4[1]),
|
||||
@@ -1776,7 +1934,7 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
brows(w.edn, rows * k));
|
||||
else
|
||||
RAD_ISSUE_N(c_, op_dn, rows,
|
||||
brows(w.eff.q, rows * k), brows(w.eff.s, rows * k),
|
||||
brows(w.eff.cq(), rows * k), brows(w.eff.cs(), rows * k),
|
||||
RAD_WTAB(w_dn[0], n_reg / 2), RAD_WTAB(w_dns[0], n_reg / 2),
|
||||
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
|
||||
RAD_WTAB(w_dn[1], n_reg / 2), RAD_WTAB(w_dns[1], n_reg / 2),
|
||||
@@ -1946,12 +2104,13 @@ inline void MoeFP8::route_report(RadCtx* c_) const {
|
||||
* destination row, the copy here is skipped, and the row stays zero -- which the file stager
|
||||
* read as "no expert routed" and skipped every layer's weights (NaN logits, empty text).
|
||||
* Copying w.ecnt into the row (the pointers now differ) also feeds the heat engine real
|
||||
* histograms instead of the zeros it saw before. */
|
||||
* histograms instead of the zeros it saw before. With a routing table (Wire::ecnt_pitch) the
|
||||
* router did write the core's row, as a declared operand, and the report copies nothing. */
|
||||
moe_debug_weights(c_, layer, c.top_k, w.ids, w.ew, c.sigmoid_router != 0);
|
||||
RadRouting r{};
|
||||
r.expert_ids = (const int32_t*)rad_buf_ptr(c_, w.ids);
|
||||
r.expert_w = nullptr;
|
||||
r.expert_count = (const int32_t*)rad_buf_ptr(c_, w.ecnt);
|
||||
r.expert_count = (const int32_t*)rad_buf_ptr(c_, w.ecnt) + (int64_t)layer * w.ecnt_pitch;
|
||||
r.sorted_tok = (const int32_t*)rad_buf_ptr(c_, w.sorted);
|
||||
r.expert_offset = (const int32_t*)rad_buf_ptr(c_, w.eoff);
|
||||
r.top_k = c.top_k;
|
||||
|
||||
@@ -282,7 +282,11 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
/* The connection's read also writes the rotated expert input, as on the trunk. */
|
||||
HyperConn::Config mcfg = hc;
|
||||
HyperConn::Wire mwire{w.hw, w.x, w.inj};
|
||||
if (src.mlp.cfg.expert_rot) { mcfg.rotate = 1; mwire.rq = w.mlp.hr.q; mwire.rs = w.mlp.hr.s; }
|
||||
if (src.mlp.cfg.expert_rot && !w.x.q8_rot) {
|
||||
mcfg.rotate = 1;
|
||||
mwire.rq = w.mlp.hr.cq();
|
||||
mwire.rs = w.mlp.hr.cs();
|
||||
}
|
||||
RAD_ARCH_TRY(hc_mlp.declare(b, nm, g, nm.f("mtp.ffn_hc"), mcfg, mwire, src.hc_mlp));
|
||||
mlp.ar_out_take = hc_mlp.ar_take();
|
||||
mlp.hr_in = mcfg.rotate != 0;
|
||||
|
||||
+129
-22
@@ -98,12 +98,24 @@ struct PleLayer {
|
||||
rad_weight w_table = 0, w_scale = 0, w_mult = 0, w_vsz = 0, w_off = 0;
|
||||
/* The table is plain bf16 as shipped (no scale weight) rather than E4M3. */
|
||||
bool table_bf16 = false;
|
||||
rad_weight w_key = 0, w_value = 0, w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
|
||||
rad_weight w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
|
||||
/* The two projections of the gathered embedding, each in the encoding its container stores:
|
||||
* plain bf16 as the checkpoint ships them, or rotated int8 (or a narrower rotated form), which
|
||||
* halves the bytes a pass waits for once the rows are on the card. `a_embd` is their input and
|
||||
* `a_fed` the same planes for the second projection, whose codes the first one's quantiser
|
||||
* wrote. */
|
||||
LinearFP8 key{}, value{};
|
||||
ActFP8 a_embd{}, a_fed{};
|
||||
|
||||
rad_kvgroup kv_tok = 0, kv_conv = 0;
|
||||
rad_buf b_ids = 0, b_emb = 0, b_embd = 0, b_k = 0, b_v = 0, b_gv = 0, b_gvn = 0, b_out = 0;
|
||||
rad_op op_ids = 0, op_gather = 0, op_embd = 0, op_key = 0, op_value = 0;
|
||||
rad_op op_ids = 0, op_gather = 0, op_embd = 0;
|
||||
rad_op op_gate = 0, op_conv = 0, op_add = 0;
|
||||
/* The draft passes' hint (hint_ids, hint_fetch), where a drafter and `ngram_hint` exist: the
|
||||
* per-slot tails the hash continues from, the hinted ids (host domain, as `ple_ids`) and the
|
||||
* rows fetched for them, which nothing reads. */
|
||||
rad_buf b_tail = 0, b_hint_ids = 0, b_hint_emb = 0;
|
||||
rad_op op_hint_hist = 0, op_hint_round = 0, op_hint_gather = 0;
|
||||
|
||||
int64_t hn() const { return c.hc * g.n_embd; }
|
||||
/* The read-ahead queue's depth in steps: batch.cpp's k_ahead_chunks steps of the following
|
||||
@@ -123,6 +135,14 @@ struct PleLayer {
|
||||
/* The hash, issued at the top of the step; the rest at the layer (see ids()). */
|
||||
void ids(RadCtx* c_, const RadBatch* batch) const;
|
||||
void step(RadCtx* c_, const RadBatch* batch) const;
|
||||
/* On a draft head's pass: the ids of each sequence's newest token, first in the pass, and
|
||||
* the fetch of their rows, last in it (see hint_ids()). */
|
||||
void hint_ids(RadCtx* c_, const RadBatch* batch) const;
|
||||
void hint_fetch(RadCtx* c_, const RadBatch* batch) const;
|
||||
bool hints(const RadBatch* batch) const {
|
||||
return op_hint_gather != 0 &&
|
||||
(batch->draft_pass > 1 || (batch->draft_pass < 0 && batch->n_draft_out > 0));
|
||||
}
|
||||
};
|
||||
|
||||
inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg,
|
||||
@@ -178,7 +198,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
/* E4M3 with one scale for all 320 million rows (Qwen3.8-Flash-Next-FP8's choice; E4M3 has its
|
||||
* own exponent, a row's dynamic range is 2.3x, and the scale sits on a three-octave plateau).
|
||||
* One stored weight, `fp8_e4m3*bf16[*x*]`: codes plus a one-element scale plane, made by the
|
||||
* recipe (data/recipes/qwen4exp-w4.recipe) or read as that release ships it (its shards under
|
||||
* recipe (data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe) or read as that release ships it (its shards under
|
||||
* one `weight_scale`); the gather takes them as two operands. The name map
|
||||
* joins the shards along rows and is declared first, since the encoding is looked up through
|
||||
* it. RAD_ACCESS_VOCAB: it is a vocabulary table, just not the token one. */
|
||||
@@ -212,13 +232,12 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
/* ---- the projections and the three gains ------------------------------------------------ */
|
||||
/* bf16: the FP8 checkpoint's `modules_to_not_convert` names both projections. */
|
||||
/* bf16 as shipped (the FP8 checkpoint's `modules_to_not_convert` names both projections); a
|
||||
* recipe may store them rotated int8. The name maps come first: the encodings, looked up
|
||||
* through them, say whether the input needs its int8 pair. They are declared below, with the
|
||||
* buffers they read and write. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_key.weight", layer), src.key_proj));
|
||||
w_key = decl_w(b, nm.f("blk.%d.ple_key.weight", layer), RAD_BF16, {HN, c.embed_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_value.weight", layer), src.value_proj));
|
||||
w_value = decl_w(b, nm.f("blk.%d.ple_value.weight", layer), RAD_BF16,
|
||||
{g.n_embd, c.embed_dim}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_norm_key.weight", layer), src.norm_key));
|
||||
w_nk = decl_w(b, nm.f("blk.%d.ple_norm_key.weight", layer), RAD_F32, {HN},
|
||||
@@ -236,7 +255,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
w_conv = decl_w(b, nm.f("blk.%d.ple_conv.weight", layer), RAD_BF16, {HN, c.conv_width},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
if (!w_table || (!table_bf16 && !w_scale) || !w_mult || !w_vsz || !w_off || !w_key || !w_value ||
|
||||
if (!w_table || (!table_bf16 && !w_scale) || !w_mult || !w_vsz || !w_off ||
|
||||
!w_nk || !w_nq || !w_nc || !w_conv) return RAD_E_INVAL;
|
||||
|
||||
/* ---- the two rolling windows ------------------------------------------------------------ */
|
||||
@@ -337,22 +356,83 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
{b_ids}, {b_emb});
|
||||
}
|
||||
|
||||
/* ---- the draft passes' hint. A verify step's rows are the token the last verify chose and
|
||||
* the drafter's proposals, each known a draft pass or more before the verify hashes it,
|
||||
* except the last. Each draft pass hashes its sequences' newest token (`ngram_hint`) and
|
||||
* gathers those rows through the same row source, which for a table on a drive reads them
|
||||
* into its row cache; the verify step's gather then waits for the last proposal's rows
|
||||
* only. All three ops or none: without a drafter, or where no library hashes the hint,
|
||||
* nothing is declared and the verify step reads every row itself, as before. */
|
||||
if (g.max_spec > 0 && rad_op_declared(b, "ngram_hint")) {
|
||||
const int64_t ctx = c.ngram - 1;
|
||||
b_tail = decl_b(b, nm.f("ple_hint_tail"), RAD_I32, {g.max_seqs, 2 * ctx}, RAD_BUF_PERSIST);
|
||||
RadBufDecl hi{};
|
||||
hi.dtype = RAD_I32; hi.rank = 2;
|
||||
hi.shape[0] = g.max_seqs; hi.shape[1] = c.heads;
|
||||
hi.kind = RAD_BUF_PERSIST; hi.domain = RAD_DOMAIN_HOST;
|
||||
b_hint_ids = rad_decl_buffer(b, nm.f("ple_hint_ids"), &hi);
|
||||
/* PERSIST although nothing reads it: a transient's bytes are shared by declared op
|
||||
* order, and the fetch runs on the host while the draft pass's other buffers are live. */
|
||||
RadBufDecl he{};
|
||||
he.dtype = g.act_dtype; he.rank = 2;
|
||||
he.shape[0] = g.max_seqs; he.shape[1] = c.embed_dim;
|
||||
he.kind = RAD_BUF_PERSIST; he.domain = RAD_DOMAIN_HOST;
|
||||
b_hint_emb = rad_decl_buffer(b, nm.f("ple_hint_emb"), &he);
|
||||
if (!b_tail || !b_hint_ids || !b_hint_emb) return RAD_E_INVAL;
|
||||
for (const int hist : { 1, 0 })
|
||||
(hist ? op_hint_hist : op_hint_round) =
|
||||
rw(b, RAD_OP(b, "ngram_hint",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("heads", c.heads),
|
||||
RAD_INT("ngram", c.ngram), RAD_INT("eos", c.eos),
|
||||
RAD_INT("hist", hist)),
|
||||
RAD_WEIGHTS(w_mult, w_vsz, w_off)),
|
||||
{b_tail}, {b_tail, b_hint_ids});
|
||||
const rad_weight wt[2] = { w_table, w_scale };
|
||||
op_hint_gather = rw(b, RAD_OP(b, "embed_lookup_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs * c.heads),
|
||||
RAD_INT("n_embd", HD), RAD_INT("n_vocab", c.rows),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
wt, table_bf16 ? 1 : 2),
|
||||
{b_hint_ids}, {b_hint_emb});
|
||||
if (!op_hint_hist || !op_hint_round || !op_hint_gather)
|
||||
op_hint_hist = op_hint_round = op_hint_gather = 0;
|
||||
}
|
||||
|
||||
op_embd = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.embed_dim),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_emb}, {b_embd});
|
||||
|
||||
op_key = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", HN),
|
||||
RAD_INT("K", c.embed_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_key)),
|
||||
{b_embd}, {b_k});
|
||||
op_value = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", c.embed_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_value)),
|
||||
{b_embd}, {b_v});
|
||||
/* The projections. An int8 one reads the embedding's int8 codes at its own scale group; the
|
||||
* first such quantises the bf16 plane and a second reads those codes, so two int8 projections
|
||||
* must agree in rotation and group (LinearFP8 refuses the pair otherwise). */
|
||||
{
|
||||
const char* kb = nm.f("blk.%d.ple_key", layer);
|
||||
const char* vb = nm.f("blk.%d.ple_value", layer);
|
||||
RadEncoding ke{}, ve{};
|
||||
const bool kk = weight_enc(b, nm.f("%s.weight", kb), &ke);
|
||||
const bool vk = weight_enc(b, nm.f("%s.weight", vb), &ve);
|
||||
const bool k8 = !g.w_bf16 && kk && (linear_is_w8(ke) || linear_is_w8h(ke));
|
||||
const bool v8 = !g.w_bf16 && vk && (linear_is_w8(ve) || linear_is_w8h(ve));
|
||||
a_embd.x = b_embd;
|
||||
if (k8 || v8)
|
||||
RAD_ARCH_TRY(a_embd.declare_qs(b, nm, g, "ple_emb_dev", c.embed_dim, 0, true, false,
|
||||
linear_w8h_group(k8 ? ke : ve)));
|
||||
a_fed = a_embd;
|
||||
if (k8 && v8) {
|
||||
a_fed.q8_fed = true;
|
||||
a_fed.q8_rot = linear_is_w8h(ke);
|
||||
}
|
||||
key.mapped = value.mapped = true;
|
||||
/* Anything but an int8 form is the plain bf16 GEMM, in a quantised model too. */
|
||||
Geom gb = g;
|
||||
gb.w_bf16 = true;
|
||||
RAD_ARCH_TRY(key.declare(b, nm, k8 ? g : gb, kb, HN, c.embed_dim, RAD_SHARD_NONE,
|
||||
grp_model(), { src.key_proj }, a_embd, b_k));
|
||||
RAD_ARCH_TRY(value.declare(b, nm, v8 ? g : gb, vb, g.n_embd, c.embed_dim, RAD_SHARD_NONE,
|
||||
grp_model(), { src.value_proj }, a_fed, b_v));
|
||||
}
|
||||
|
||||
/* `q` is the incoming stream, un-normed; the op applies all three norms because the third is
|
||||
* over bytes it writes. */
|
||||
@@ -378,7 +458,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h, b_out}, {w.h});
|
||||
|
||||
if (!op_ids || !op_gather || !op_embd || !op_key || !op_value || !op_gate || !op_conv ||
|
||||
if (!op_ids || !op_gather || !op_embd || !key.op || !value.op || !op_gate || !op_conv ||
|
||||
!op_add)
|
||||
return RAD_E_INVAL;
|
||||
return RAD_OK;
|
||||
@@ -433,6 +513,33 @@ inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
|
||||
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
|
||||
}
|
||||
|
||||
/* The hint of a draft head's pass. The history pass ends at the token the verify chose and each
|
||||
* later round reads the proposal before it (RadBatch::draft_pass), so the pass's newest token per
|
||||
* sequence is one the next verify step runs. hint_ids() hashes it first in the pass, so the ids
|
||||
* are in host memory as the pass starts; hint_fetch() goes last, where the host has issued the
|
||||
* whole pass and only waits for that one kernel, and the rows it reads arrive while the card
|
||||
* drafts. A history pass that drafts nothing gets neither. */
|
||||
inline void PleLayer::hint_ids(RadCtx* c_, const RadBatch* batch) const {
|
||||
if (!hints(batch)) return;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const RadKVGroupBatch* tk = kv_batch(batch, kv_tok);
|
||||
const int32_t* tk_idx = tk ? tk->state_index : nullptr;
|
||||
RAD_ISSUE_N(c_, batch->draft_pass < 0 ? op_hint_hist : op_hint_round, S,
|
||||
praw(batch->token_ids, RAD_I32, T), praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
RAD_W(w_mult), RAD_W(w_vsz), RAD_W(w_off),
|
||||
tk_idx ? praw(tk_idx, RAD_I32, S) : RAD_NONE,
|
||||
RAD_B(b_tail), brows(b_hint_ids, S));
|
||||
}
|
||||
|
||||
inline void PleLayer::hint_fetch(RadCtx* c_, const RadBatch* batch) const {
|
||||
if (!hints(batch)) return;
|
||||
const int64_t S = batch->n_seq;
|
||||
RAD_ISSUE_N(c_, op_hint_gather, S * c.heads,
|
||||
brows(b_hint_ids, S), RAD_W(w_table), table_bf16 ? RAD_NONE : RAD_W(w_scale),
|
||||
brows(b_hint_emb, S), RAD_NONE);
|
||||
}
|
||||
|
||||
inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t S = batch->n_seq;
|
||||
@@ -454,8 +561,8 @@ inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
|
||||
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
|
||||
|
||||
RAD_ISSUE_N(c_, op_embd, T, brows(b_emb, T), brows(b_embd, T));
|
||||
RAD_ISSUE_N(c_, op_key, T, brows(b_embd, T), RAD_W(w_key), brows(b_k, T));
|
||||
RAD_ISSUE_N(c_, op_value, T, brows(b_embd, T), RAD_W(w_value), brows(b_v, T));
|
||||
key.step(c_, a_embd, b_k, T, 0, T);
|
||||
value.step(c_, a_fed, b_v, T, 0, T);
|
||||
|
||||
RAD_ISSUE_N(c_, op_gate, T,
|
||||
brows(b_k, T), brows(w.h, T), brows(b_v, T),
|
||||
|
||||
+193
-34
@@ -48,6 +48,9 @@ namespace arch {
|
||||
/* The scale block in both dimensions, fixed by the checkpoint (`weight_block_size`). libr4d
|
||||
* compiles it in and its rows carry C_EQ("group", 128), so other widths resolve to no kernel. */
|
||||
enum { RAD_FP8_BLOCK = 128 };
|
||||
/* IQ8R's scale group: an int8 weight rotated 128 wide with one bf16 scale per row per 256 of K,
|
||||
* met by an int8 activation with one f32 scale per (token, 256). */
|
||||
enum { RAD_I8_GROUP_WIDE = 256 };
|
||||
|
||||
/* Rows of the scale plane for an N-row weight, and columns for a K-wide one. */
|
||||
inline int64_t fp8_blocks(int64_t n) { return (n + RAD_FP8_BLOCK - 1) / RAD_FP8_BLOCK; }
|
||||
@@ -63,6 +66,9 @@ struct ActFP8 {
|
||||
* by the linear's own quant_act_i8g from `x`, or by the producer when `q8_fed`. */
|
||||
rad_buf q8 = 0;
|
||||
rad_buf s8 = 0;
|
||||
/* The int8 pair's scale group: RAD_FP8_BLOCK, or RAD_I8_GROUP_WIDE for an IQ8R trunk, whose
|
||||
* producers and quantisers write one scale per (row, 256). s8 has ceil(n / g8) columns. */
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
/* The producer writes q8/s8 instead of the E4M3 pair (a connection read with
|
||||
* HyperConn::Config::codes_i8, a gated quantiser, the attention gate or delta-net output
|
||||
* epilogue), so an int8 linear reading it declares no quantiser. Set by the model when it
|
||||
@@ -76,6 +82,8 @@ struct ActFP8 {
|
||||
/* The code pair the producer writes: int8 when the model fed it, E4M3 otherwise. */
|
||||
rad_buf cq() const { return q8_fed ? q8 : q; }
|
||||
rad_buf cs() const { return q8_fed ? s8 : s; }
|
||||
/* The scale group of cs(). */
|
||||
int64_t cg() const { return q8_fed ? g8 : (int64_t)RAD_FP8_BLOCK; }
|
||||
|
||||
/* Declares the codes: the E4M3 pair with `fp8_pair`, the int8 pair with `i8` (an int8 model's
|
||||
* activations need no E4M3 plane taking arena); `x` is set by the caller.
|
||||
@@ -84,7 +92,9 @@ struct ActFP8 {
|
||||
* (a MoE expert plane is `rows * top_k`, an encoder tower's its patch count); too small a value
|
||||
* overruns the arena (core/runtime/issue.cpp refuses such an issue). */
|
||||
int declare_qs(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t n,
|
||||
int64_t rows = 0, bool i8 = false, bool fp8_pair = true) {
|
||||
int64_t rows = 0, bool i8 = false, bool fp8_pair = true,
|
||||
int64_t i8_group = RAD_FP8_BLOCK) {
|
||||
g8 = i8_group;
|
||||
/* bf16 linears read only `x` (Geom::w_bf16), so declare no codes; an unused plane would
|
||||
* still take arena space. */
|
||||
if (g.w_bf16) { q = s = q8 = s8 = 0; return RAD_OK; }
|
||||
@@ -96,11 +106,30 @@ struct ActFP8 {
|
||||
}
|
||||
if (i8) {
|
||||
q8 = decl_b(b, nm.f("%s.q8", name), RAD_I8, { m, n });
|
||||
s8 = decl_b(b, nm.f("%s.s8", name), RAD_F32, { m, fp8_blocks(n) });
|
||||
s8 = decl_b(b, nm.f("%s.s8", name), RAD_F32, { m, (n + g8 - 1) / g8 });
|
||||
if (!q8 || !s8) return RAD_E_INVAL;
|
||||
}
|
||||
return (fp8_pair || i8) ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* The code pair of a model that learned from a probe whether its linears are rotated int8
|
||||
* (`i8`, at `i8_group` columns a scale): declare_qs's E4M3 pair for a block-fp8 model, and for
|
||||
* an int8 one int8 codes. Those are written by the producer's own rotating quantiser `fed_op`
|
||||
* (had_quant_act_i8g, or gated_had_quant_i8g behind a gated product) where the kernels serve
|
||||
* it, and the linears reading them declare none; where they do not (the CPU kernels) the
|
||||
* producer keeps its E4M3 pair and each linear quantises its own input from the bf16 plane.
|
||||
* `x` is set by the caller. */
|
||||
int declare_pair(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t n,
|
||||
int64_t rows, bool i8, int64_t i8_group, const char* fed_op) {
|
||||
if (i8 && (i8_group <= 0 || n % i8_group)) {
|
||||
fprintf(stderr, "radiance: the int8 linears keep one scale a %lld of K, which does not "
|
||||
"divide this rank's %lld-wide '%s'\n",
|
||||
(long long)i8_group, (long long)n, name);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (i8 && rad_op_declared(b, fed_op)) q8_fed = q8_rot = true;
|
||||
return declare_qs(b, nm, g, name, n, rows, i8, !q8_fed, i8 ? i8_group : RAD_FP8_BLOCK);
|
||||
}
|
||||
};
|
||||
|
||||
/* The fused attention prologue's row band, shared by the block issuing it, the rope table fill,
|
||||
@@ -145,7 +174,7 @@ inline int QuantFP8::declare(RadBuilder* b, const Geom& g, const ActFP8& act, in
|
||||
* are rotated (ActFP8::q8_rot). */
|
||||
op = rw(b, RAD_OP(b, a.q8_fed ? (a.q8_rot ? "had_quant_act_i8g" : "quant_act_i8g") : "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("group", a.cg()), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a.x }, { a.cq(), a.cs() });
|
||||
return RAD_OK;
|
||||
@@ -155,7 +184,7 @@ inline void QuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const
|
||||
if (!op) return;
|
||||
if (rows <= 0) rows = T - r0;
|
||||
RAD_ISSUE(c, op, brow_slice(a.x, r0, rows, n), brow_slice(a.cq(), r0, rows, n),
|
||||
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
|
||||
brow_slice(a.cs(), r0, rows, n / a.cg()));
|
||||
}
|
||||
|
||||
/* ================================== the quantiser folded into the op that produces the row
|
||||
@@ -427,7 +456,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
|
||||
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),
|
||||
RAD_INT("group", a.cg()), RAD_STR("dtype", g.dtype),
|
||||
RAD_F64("wadd", g.wadd)),
|
||||
RAD_WEIGHTS(w));
|
||||
if (!op) return RAD_E_INVAL;
|
||||
@@ -450,7 +479,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
|
||||
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),
|
||||
RAD_INT("group", a.cg()),
|
||||
RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
|
||||
RAD_WEIGHTS(w));
|
||||
@@ -465,7 +494,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
|
||||
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),
|
||||
RAD_INT("group", a.cg()),
|
||||
RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd),
|
||||
RAD_INT("wire", 6)),
|
||||
@@ -497,7 +526,7 @@ inline void NormQuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) c
|
||||
RAD_ISSUE_N(c, pick(rows), rows, brow_slice(src, r0, rows, n),
|
||||
res ? brow_slice(res, r0, rows, n) : RAD_NONE, RAD_W(w),
|
||||
brow_slice(hi8 ? a.q8 : a.q, r0, rows, n),
|
||||
brow_slice(hi8 ? a.s8 : a.s, r0, rows, n / RAD_FP8_BLOCK),
|
||||
brow_slice(hi8 ? a.s8 : a.s, r0, rows, n / (hi8 ? a.g8 : (int64_t)RAD_FP8_BLOCK)),
|
||||
brow_slice(a.x, r0, rows, n));
|
||||
}
|
||||
|
||||
@@ -619,7 +648,7 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
|
||||
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_INT("group", a.cg()), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a.x }, { a.cq(), a.cs() });
|
||||
if (!op_quant) return RAD_E_INVAL;
|
||||
@@ -651,7 +680,7 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
|
||||
if (!rot || rad_op_declared(b, "gated_had_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_INT("group", a.cg()), RAD_STR("dtype", g.dtype),
|
||||
RAD_STR("act", act_name)),
|
||||
RAD_NOWEIGHTS);
|
||||
/* The rotated op's chain, which writes the bf16 plane whether or not a consumer asked. */
|
||||
@@ -690,7 +719,7 @@ inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_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),
|
||||
brow_slice(a.cs(), r0, rows, n / a.cg()),
|
||||
want_x ? brow_slice(a.x, r0, rows, n) : RAD_NONE);
|
||||
return;
|
||||
}
|
||||
@@ -700,7 +729,7 @@ inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0
|
||||
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));
|
||||
brow_slice(a.cs(), r0, rows, n / a.cg()));
|
||||
return;
|
||||
}
|
||||
if (bf16 || op_q) {
|
||||
@@ -708,12 +737,12 @@ inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0
|
||||
if (op_q)
|
||||
RAD_ISSUE_N(c, op_q, rows, brow_slice(a.x, r0, rows, n),
|
||||
brow_slice(a.cq(), r0, rows, n),
|
||||
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
|
||||
brow_slice(a.cs(), r0, rows, n / a.cg()));
|
||||
return;
|
||||
}
|
||||
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),
|
||||
brow_slice(a.cs(), r0, rows, n / a.cg()),
|
||||
want_x ? brow_slice(a.x, r0, rows, n) : RAD_NONE);
|
||||
}
|
||||
|
||||
@@ -813,6 +842,9 @@ struct LinearFP8 {
|
||||
/* probe() found an int8 weight; lets a model learn its trunk's format from one linear before
|
||||
* declaring activation buffers (ActFP8::declare_qs's `i8`). */
|
||||
bool probed_i8 = false;
|
||||
/* With probed_i8: the weight's scale group along K (linear_w8h_group), which the model's int8
|
||||
* activation pairs must share (ActFP8::g8). */
|
||||
int64_t probed_g8 = RAD_FP8_BLOCK;
|
||||
/* Whether this linear's block-fp8 GEMM takes the short-prompt split rule
|
||||
* (`gemm_nt_q_short`, narrow_ksplit's `short_unsplit`): at N <= 512, K <= 5120 and 41..64 rows
|
||||
* the split's per-slice floors dominate, so the row runs unsplit. Opt-in, so every other
|
||||
@@ -965,7 +997,26 @@ inline bool linear_w8h_scale2(const RadEncoding& e) {
|
||||
s2->kind == RAD_PLANE_TILED && (s2->dtype == RAD_F32 || s2->dtype == RAD_BF16) &&
|
||||
(s2->block[0] == 0 || s2->block[0] == 1) && s2->block[1] == 0;
|
||||
}
|
||||
/* IQ8R: int8 codes rotated 128 wide with a u8 scale per [1 x 256] under one bf16 scale a row
|
||||
* (libquant `codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128`), served as the
|
||||
* I8 form at twice the scale group. */
|
||||
inline bool linear_is_iq8r(const RadEncoding& e) {
|
||||
if (!rad_enc_is(&e, "affine") || e.n_planes != 3 ||
|
||||
std::strncmp(e.transform, "fwht128", RAD_ENC_STR) != 0)
|
||||
return false;
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
const RadEncPlane* s2 = rad_enc_plane(&e, "scale.1");
|
||||
return e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 && sc && sc->dtype == RAD_U8 &&
|
||||
sc->kind == RAD_PLANE_TILED && sc->block[0] == 1 && sc->block[1] == RAD_I8_GROUP_WIDE &&
|
||||
s2 && s2->dtype == RAD_BF16 && s2->kind == RAD_PLANE_TILED && s2->block[0] == 1 &&
|
||||
s2->block[1] == 0;
|
||||
}
|
||||
/* The scale group along K of a weight served at i8a8 / i8a8h. */
|
||||
inline int64_t linear_w8h_group(const RadEncoding& e) {
|
||||
return linear_is_iq8r(e) ? (int64_t)RAD_I8_GROUP_WIDE : (int64_t)RAD_FP8_BLOCK;
|
||||
}
|
||||
inline W8hForm linear_w8h_form(const RadEncoding& e) {
|
||||
if (linear_is_iq8r(e)) return W8hForm::I8;
|
||||
const bool trellis = rad_enc_is(&e, "trellis");
|
||||
if ((!rad_enc_is(&e, "affine") && !trellis) ||
|
||||
std::strncmp(e.transform, "fwht128", RAD_ENC_STR) != 0)
|
||||
@@ -1088,6 +1139,32 @@ inline bool linear_is_paro_m2xfp4(const RadEncoding& e) {
|
||||
mt->block[1] == RAD_MX_GROUP;
|
||||
}
|
||||
|
||||
/* The weight formats rad-convert reads and the engine does not serve: block fp8 (E4M3
|
||||
* codes under a scale per 128 x 128), OCP MXFP4, M2XFP4 and the ParoQuant-rotated forms of the
|
||||
* last two. The format's name, or nullptr for one that is served. */
|
||||
inline const char* linear_retired(const RadEncoding& e) {
|
||||
if (linear_is_paro_m2xfp4(e)) return "ParoQuant M2XFP4";
|
||||
if (linear_is_paro_mxfp4(e)) return "ParoQuant MXFP4";
|
||||
if (linear_is_givens(e)) return "ParoQuant";
|
||||
if (linear_is_m2xfp4(e)) return "M2XFP4";
|
||||
if (linear_is_mxfp4(e)) return "MXFP4";
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
if (rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] &&
|
||||
e.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)
|
||||
return "block fp8";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* The refusal of a weight stored in one of them, by name, with what serves the model instead. */
|
||||
inline int linear_refuse_retired(const char* weight, const char* format) {
|
||||
fprintf(stderr, "radiance: '%s' is stored as %s, which this build does not serve. Convert "
|
||||
"the checkpoint again with an int8 recipe (the IQ8R ones in data/recipes); if "
|
||||
"the weight belongs to the container's drafter, `num-speculative-tokens: 0` "
|
||||
"serves the model without it\n", weight, format);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* A 4-bit weight with a zero point and no transform: u4 codes, an f16 scale and a u4 or u8 zero
|
||||
* point per 128 of K (libquant `codes=u4 zero=u4 group=128 scale=f16`, or rad-convert's import rule
|
||||
* over an int4 release). At decode w4a16_asym narrows the BF16 input to F16 on load; larger
|
||||
@@ -1122,6 +1199,7 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char*
|
||||
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) || linear_is_w8h(enc) || linear_is_wnh(enc));
|
||||
probed_g8 = known ? linear_w8h_group(enc) : (int64_t)RAD_FP8_BLOCK;
|
||||
/* 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) ||
|
||||
@@ -1244,6 +1322,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
const bool known = weight_enc(b, sw, &enc);
|
||||
const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
|
||||
enc.plane[0].dtype == RAD_BF16;
|
||||
if (known && !plain)
|
||||
if (const char* gone = linear_retired(enc)) return linear_refuse_retired(sw, gone);
|
||||
|
||||
/* ---- bf16 weight, `gemm_nt` over `a.x`: every linear of a bf16 model, or one a quantised
|
||||
* container keeps at checkpoint precision (e.g. the QSA indexer's projection, whose top-k is a
|
||||
@@ -1317,10 +1397,18 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
"int8)\n", wn, a.q8_fed ? "" : " or the bf16 plane it quantises");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
/* The scale group: 128, or 256 for IQ8R, which the input's int8 pair must share. */
|
||||
const int64_t wg = linear_w8h_group(enc);
|
||||
if (wg != a.g8) {
|
||||
fprintf(stderr, "radiance: '%s' has a scale per %lld columns and its input's int8 codes "
|
||||
"one per %lld; a trunk mixes IQ8R and 128-group int8 weights\n",
|
||||
wn, (long long)wg, (long long)a.g8);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (N % 16 || K % wg) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an int8 weight takes rows in "
|
||||
"16s and K in whole %d-column scale groups\n",
|
||||
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
|
||||
"16s and K in whole %lld-column scale groups\n",
|
||||
base, (long long)N, (long long)K, (long long)wg);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RowParts rp;
|
||||
@@ -1344,42 +1432,42 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
rp.w, rp.n);
|
||||
/* A view of two planes is declared at the weight's logical extents and sliced in its
|
||||
* columns, the stored planes left to the layout hook. */
|
||||
const bool two = linear_w8h_scale2(enc) || linear_w8h_rowf(enc);
|
||||
const bool iq8r = linear_is_iq8r(enc);
|
||||
const bool two = linear_w8h_scale2(enc) || linear_w8h_rowf(enc) || iq8r;
|
||||
ws = asym ? decl_view(b, sn, wn, "scale,zero", RAD_F16, { N, K }, access, shard, grp,
|
||||
rp.w, rp.n)
|
||||
: linear_w8h_rowf(enc) ? decl_view(b, sn, wn, "scale,scale.col", RAD_F32, { N, K },
|
||||
access, shard, grp, rp.w, rp.n)
|
||||
: two ? decl_view(b, sn, wn, "scale,scale.1", RAD_F8E4M3, { N, K }, access, shard,
|
||||
grp, rp.w, rp.n)
|
||||
: decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, access,
|
||||
: two ? decl_view(b, sn, wn, "scale,scale.1", iq8r ? RAD_U8 : RAD_F8E4M3, { N, K },
|
||||
access, shard, grp, rp.w, rp.n)
|
||||
: decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / wg }, access,
|
||||
shard, grp, rp.w, rp.n);
|
||||
if (!w || !ws) return RAD_E_INVAL;
|
||||
if (span_hi > 0) {
|
||||
/* The (scale, zero) and (scale, scale.1) views are at the logical extents, sliced as
|
||||
* the codes are. */
|
||||
const bool col = shard == RAD_SHARD_COL && !asym && !two;
|
||||
if (col && (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) {
|
||||
if (col && (span_lo % wg || span_hi % wg)) {
|
||||
fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
|
||||
"%d-column scale group\n", base, (long long)span_lo,
|
||||
(long long)span_hi, RAD_FP8_BLOCK);
|
||||
"%lld-column scale group\n", base, (long long)span_lo,
|
||||
(long long)span_hi, (long long)wg);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi));
|
||||
if ((asym || two) && shard == RAD_SHARD_COL &&
|
||||
(span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) {
|
||||
if ((asym || two) && shard == RAD_SHARD_COL && (span_lo % wg || span_hi % wg)) {
|
||||
fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
|
||||
"%d-column scale group\n", base, (long long)span_lo,
|
||||
(long long)span_hi, RAD_FP8_BLOCK);
|
||||
"%lld-column scale group\n", base, (long long)span_lo,
|
||||
(long long)span_hi, (long long)wg);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, col ? span_lo / RAD_FP8_BLOCK : span_lo,
|
||||
col ? span_hi / RAD_FP8_BLOCK : span_hi));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, col ? span_lo / wg : span_lo,
|
||||
col ? span_hi / wg : span_hi));
|
||||
}
|
||||
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
|
||||
if (!a.q8_fed)
|
||||
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_INT("group", wg), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a.x }, { a.q8, a.s8 });
|
||||
const char* qdt = asym ? (enc.plane[0].dtype == RAD_U5 ? "w5a8i8" : "w4a8i8_asym")
|
||||
@@ -1394,7 +1482,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
{ a.q8, a.s8 }, { y })
|
||||
: 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", qdt)),
|
||||
RAD_INT("group", wg), RAD_STR("dtype", qdt)),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ a.q8, a.s8 }, { y });
|
||||
return (op_q || a.q8_fed) && op ? RAD_OK : RAD_E_INVAL;
|
||||
@@ -1712,9 +1800,9 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
if (i8) {
|
||||
if (op_q)
|
||||
RAD_ISSUE_N(c, op_q, rows, brow_slice(a.x, r0, rows, K), brow_slice(a.q8, r0, rows, K),
|
||||
brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK));
|
||||
brow_slice(a.s8, r0, rows, K / a.g8));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.q8, r0, rows, K),
|
||||
brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK),
|
||||
brow_slice(a.s8, r0, rows, K / a.g8),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
@@ -1788,6 +1876,17 @@ struct DenseFP8 {
|
||||
bool mx = false;
|
||||
/* Or M2XFP4 (libquant `m2xfp4`): the MXFP4 views, the meta plane riding the weight operand. */
|
||||
bool m2x = false;
|
||||
/* Or a weight served at i8a8h (linear_w8h_form): IQ8R, the rotated int8 grid at 128, or a
|
||||
* narrower form on it (signed codes, a zero point, a codebook, a trellis), its views as
|
||||
* LinearFP8 declares them. It reads an INT8 activation pair with one scale per (row, `g8`) under
|
||||
* the same rotation (had_quant_act_i8g at that group); the block declares that pair where it
|
||||
* would the E4M3 one. `w_rb`: a trellis on a grid of several rows a scale says how many. */
|
||||
bool w8h = false;
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
int64_t w_rb = 0;
|
||||
/* Set before declare by a block that declares the int8 activation pair such a weight reads;
|
||||
* any other block's activations are E4M3, so declare refuses the weight there. */
|
||||
bool w8h_ok = 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). */
|
||||
@@ -1842,6 +1941,19 @@ struct DenseFP8 {
|
||||
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,
|
||||
int64_t split_n = 0) const {
|
||||
if (w8h && w_rb > 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", g8), RAD_STR("dtype", "i8a8h"),
|
||||
RAD_INT("w_rb", w_rb)),
|
||||
RAD_WEIGHTS(w, s)),
|
||||
reads, writes);
|
||||
if (w8h)
|
||||
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", g8), RAD_STR("dtype", "i8a8h")),
|
||||
RAD_WEIGHTS(w, s)),
|
||||
reads, writes);
|
||||
if (mx || m2x)
|
||||
return rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
@@ -1883,6 +1995,53 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
|
||||
const bool known = weight_enc(b, wn, &enc);
|
||||
mx = known && linear_is_mxfp4(enc);
|
||||
m2x = known && linear_is_m2xfp4(enc);
|
||||
/* Plain MXFP4 is still read here: the published IQR-V4 containers carry their DFlash2
|
||||
* drafter in it. */
|
||||
if (known && !mx)
|
||||
if (const char* gone = linear_retired(enc)) return linear_refuse_retired(wn, gone);
|
||||
const W8hForm form = known ? linear_w8h_form(enc) : W8hForm::None;
|
||||
w8h = form != W8hForm::None;
|
||||
if (w8h && !w8h_ok) {
|
||||
fprintf(stderr, "radiance: '%s' is a rotated int8 weight, which reads an int8 "
|
||||
"activation; this block quantises its activations to E4M3 and takes "
|
||||
"block fp8 or MXFP4 weights\n", base);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (w8h) {
|
||||
g8 = linear_w8h_group(enc);
|
||||
if (N % 16 || K % g8) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; a rotated int8 weight takes "
|
||||
"rows in 16s and K in whole %lld-column scale groups\n",
|
||||
base, (long long)N, (long long)K, (long long)g8);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RowParts rp;
|
||||
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "int8 tiles"));
|
||||
/* The views LinearFP8's i8a8h branch declares: a narrower form's codes take the plane
|
||||
* that decodes them, and a scale of two planes is one view at the weight's logical
|
||||
* extents, which the kernel's layout combines. */
|
||||
const RadEncPlane* tpl = rad_enc_plane(&enc, "trellis");
|
||||
w_rb = form == W8hForm::Trellis && tpl && tpl->block[1] > 1 ? tpl->block[1] : 0;
|
||||
const char* cv = form == W8hForm::Zero ? "codes,zero"
|
||||
: form == W8hForm::Table ? "codes,table"
|
||||
: form == W8hForm::Grid ? "codes,grid"
|
||||
: form == W8hForm::Trellis ? (linear_w8h_mad(enc) ? "codes,trellis,trellis.mad"
|
||||
: "codes,trellis")
|
||||
: "codes";
|
||||
const char* sn = nm.f("%s.scale", base);
|
||||
const bool iq8r = linear_is_iq8r(enc);
|
||||
w = decl_view(b, wn, nullptr, cv, enc.plane[0].dtype, { N, K }, access, shard, grp,
|
||||
rp.w, rp.n);
|
||||
s = linear_w8h_rowf(enc)
|
||||
? decl_view(b, sn, wn, "scale,scale.col", RAD_F32, { N, K }, access, shard, grp,
|
||||
rp.w, rp.n)
|
||||
: (linear_w8h_scale2(enc) || iq8r)
|
||||
? decl_view(b, sn, wn, "scale,scale.1", iq8r ? RAD_U8 : RAD_F8E4M3, { N, K },
|
||||
access, shard, grp, rp.w, rp.n)
|
||||
: decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / g8 }, access, shard, grp,
|
||||
rp.w, rp.n);
|
||||
return w && s ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
if (mx || m2x) {
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an %s weight takes rows "
|
||||
|
||||
@@ -86,7 +86,7 @@ struct Model {
|
||||
Gemma4Audio aud;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* The layer schedule, read rather than derived: layer_types states which layers attend to the
|
||||
* whole input, and an assumed pattern would silently be wrong for a sibling checkpoint that
|
||||
@@ -123,7 +123,8 @@ static int read_schedule(const RadModelMeta* meta, int64_t n_layer, std::vector<
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
/* A 270M encoder fits easily on one card; tensor parallelism would only add an all-reduce per
|
||||
* layer, so it is not offered. */
|
||||
if (ctx->world_size > 1) {
|
||||
@@ -132,7 +133,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
@@ -417,7 +418,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd;
|
||||
if (batch->enc) {
|
||||
@@ -480,6 +481,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
} /* namespace embgemma2 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(embgemma2, "embeddinggemma2", "", "0.1.0",
|
||||
"EmbeddingGemma 2: a bidirectional Gemma encoder with per-layer embeddings, "
|
||||
"mean-pooled to one vector an input; bf16")
|
||||
|
||||
@@ -322,7 +322,7 @@ struct Model {
|
||||
* row's label). */
|
||||
constexpr int64_t kPcW = kMaxPrompt + 1;
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* ================================================================== declare helpers */
|
||||
static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, double wadd,
|
||||
@@ -1701,8 +1701,9 @@ static int declare_encoder(RadBuilder* b, Model& m) {
|
||||
/* ================================================================== declare */
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -2184,7 +2185,7 @@ static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->agen_b) {
|
||||
rad_step_fail(c, "fishomni is an audio generator and runs generator passes only");
|
||||
return;
|
||||
@@ -2352,6 +2353,8 @@ RAD_ARCH_PROBE(fishomni)
|
||||
extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap) {
|
||||
return fishomni::text_prepare(field, in, out, cap);
|
||||
}
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(fishomni, "fishomni", "bsgemm-moe", "0.1.0",
|
||||
"Fish Audio drama-3: the Qwen3.5-35B-A3B backbone (block-scaled fp8 experts), a "
|
||||
"13-layer codebook tower over its full-attention cache, and Fish S2's modified "
|
||||
|
||||
+54
-20
@@ -39,7 +39,11 @@
|
||||
*
|
||||
* Every linear of the language model and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16
|
||||
* throughout when the first joint block's projection is plain; the embedders, the timestep MLPs,
|
||||
* the modulations, the output layer and the VAE stay bf16.
|
||||
* the modulations, the output layer and the VAE stay bf16. That projection also says whether the
|
||||
* linears are rotated int8 (IQ8R): the activations they read then carry int8 codes in place of the
|
||||
* E4M3 pair, which a block's modulated norm writes in its own pass where a library serves the
|
||||
* rotating twin (rms_mod_had_quant_i8g) and the rotating quantiser behind the plain norm
|
||||
* elsewhere.
|
||||
*
|
||||
* ============================== TENSOR PARALLEL ==============================
|
||||
*
|
||||
@@ -113,6 +117,9 @@ struct Block {
|
||||
LinearFP8 qkv{}, o{}, ff_in{}, ff_out{};
|
||||
GateQuantFP8 gq{};
|
||||
QuantFP8 q_attn{};
|
||||
/* The normed rows' quantiser for a rotated int8 model whose norm is the unquantised one
|
||||
* (Model::norm_i8 false). */
|
||||
QuantFP8 q_n{};
|
||||
rad_op op_n = 0, op_qkr = 0, op_attn = 0, op_sum = 0, op_ar = 0;
|
||||
};
|
||||
|
||||
@@ -172,6 +179,14 @@ struct Model {
|
||||
ActFP8 a_hm{}, a_attn{}, a_ffn{};
|
||||
std::vector<Block> mode[3], single;
|
||||
LinearFP8 qkv0{};
|
||||
/* The linears of both networks are rotated int8 (IQ8R, or the 128-group int8 before it), read
|
||||
* off qkv0's probe: the activations then carry int8 code pairs with one scale per (token, `g8`
|
||||
* columns) in place of the E4M3 pair. */
|
||||
bool i8 = false;
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
/* A block's modulated norm writes those int8 codes in its own pass (rms_mod_had_quant_i8g),
|
||||
* where a library serves it. */
|
||||
bool norm_i8 = false;
|
||||
rad_weight w_pout = 0;
|
||||
|
||||
/* ---- per-image state and conditioning store (PERSIST) */
|
||||
@@ -184,7 +199,7 @@ struct Model {
|
||||
rad_buf b_dl = 0, b_decin = 0, b_cu4 = 0, b_img = 0;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
static std::vector<double> meta_list(const RadModelMeta* m, const char* key) {
|
||||
std::vector<double> v;
|
||||
@@ -276,14 +291,16 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, E });
|
||||
m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, E });
|
||||
RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", E, T));
|
||||
RAD_ARCH_TRY(m.a_th.declare_pair(b, nm, g, "te.h", E, T, m.i8, m.g8, "had_quant_act_i8g"));
|
||||
m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim });
|
||||
m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim });
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim, T));
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_pair(b, nm, g, "te.attn", q_dim, T, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, E });
|
||||
m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff, T));
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_pair(b, nm, g, "te.ffn", g.n_ff, T, m.i8, m.g8,
|
||||
"gated_had_quant_i8g"));
|
||||
m.b_taps = decl_b(b, nm.f("te.taps"), RAD_BF16, { T, kNTaps * E });
|
||||
m.b_tidx = decl_b(b, nm.f("te.rows"), RAD_I32, { T });
|
||||
|
||||
@@ -530,11 +547,16 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
|
||||
B.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), nm.ckpt("%s.attn.norm_k.weight", pre), RAD_F32,
|
||||
{ hd }, RAD_ACCESS_PER_TOKEN, grp);
|
||||
if (!B.w_qn || !B.w_kn) return RAD_E_INVAL;
|
||||
const bool q = !g.w_bf16;
|
||||
/* The norm with the quantiser in it: E4M3 for block-fp8 linears, the rotating int8 twin for
|
||||
* rotated int8 ones where a library serves it. bf16 linears read its bf16 rows, and rotated
|
||||
* int8 ones without the twin quantise those with the rotating quantiser (q_n). */
|
||||
m.norm_i8 = m.i8 && m.a_hm.q8_fed && rad_op_declared(b, "rms_mod_had_quant_i8g") != 0;
|
||||
const bool q = (!g.w_bf16 && !m.i8) || m.norm_i8;
|
||||
auto norm = [&](bool gt) {
|
||||
rad_op op = q ? RAD_OP(b, "rms_mod_quant_fp8",
|
||||
rad_op op = q ? RAD_OP(b, m.norm_i8 ? "rms_mod_had_quant_i8g" : "rms_mod_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", D),
|
||||
RAD_F64("eps", eps), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_F64("eps", eps),
|
||||
RAD_INT("group", m.norm_i8 ? m.g8 : RAD_FP8_BLOCK),
|
||||
RAD_INT("gated", gt ? 1 : 0), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("norm", "layer")),
|
||||
RAD_NOWEIGHTS)
|
||||
@@ -546,7 +568,7 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
|
||||
if (!op) return op;
|
||||
/* The residual, the modulation table and, gated, the branch sum. */
|
||||
rad_buf rd[4] = { m.b_xc, m.b_h, mod, m.b_sum };
|
||||
rad_buf wq[3] = { m.a_hm.q, m.a_hm.s, m.b_h };
|
||||
rad_buf wq[3] = { m.a_hm.cq(), m.a_hm.cs(), m.b_h };
|
||||
rad_buf wb[2] = { m.a_hm.x, m.b_h };
|
||||
rad_op_reads(b, op, rd, gt ? 4 : 3);
|
||||
if (q) rad_op_writes(b, op, wq, 3);
|
||||
@@ -554,6 +576,7 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
|
||||
return op;
|
||||
};
|
||||
B.op_n = norm(gated);
|
||||
if (m.i8 && m.a_hm.q8_fed && !m.norm_i8) RAD_ARCH_TRY(B.q_n.declare(b, g, m.a_hm, D));
|
||||
RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), 3 * qd, D, RAD_SHARD_ROW,
|
||||
grp_layer(grp),
|
||||
{ nm.ckpt("%s.attn.to_q.weight", pre),
|
||||
@@ -728,14 +751,16 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
/* ---- the blocks' buffers */
|
||||
const int64_t qd = g.q_dim();
|
||||
m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D });
|
||||
RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D));
|
||||
RAD_ARCH_TRY(m.a_hm.declare_pair(b, nm, g, "dit.hm", D, 0, m.i8, m.g8, "had_quant_act_i8g"));
|
||||
m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, 3 * qd });
|
||||
m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd });
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_pair(b, nm, g, "dit.attn", qd, 0, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_o = decl_b(b, nm.f("dit.o"), RAD_BF16, { T, D });
|
||||
m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_pair(b, nm, g, "dit.ffn", g.n_ff, 0, m.i8, m.g8,
|
||||
"gated_had_quant_i8g"));
|
||||
m.b_f = decl_b(b, nm.f("dit.f"), RAD_BF16, { T, D });
|
||||
m.b_sum = decl_b(b, nm.f("dit.sum"), RAD_BF16, { T, D });
|
||||
|
||||
@@ -895,8 +920,9 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -941,9 +967,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"transformer.single_transformer_blocks.0.attn.to_k.weight",
|
||||
"transformer.single_transformer_blocks.0.attn.to_v.weight" }));
|
||||
RadEncoding e{};
|
||||
const bool plain = weight_enc(b, nm.f("dit.single.0.attn_qkv.weight"), &e) &&
|
||||
rad_enc_is(&e, "plain");
|
||||
const bool known = weight_enc(b, nm.f("dit.single.0.attn_qkv.weight"), &e);
|
||||
const bool plain = known && rad_enc_is(&e, "plain");
|
||||
gd.w_bf16 = m.gt.w_bf16 = plain;
|
||||
/* Or rotated int8 (IQ8R): the activations then carry int8 codes at the weights' scale
|
||||
* group in place of the E4M3 pair (ActFP8::declare_pair). */
|
||||
m.i8 = known && (linear_is_w8h(e) || linear_is_wnh(e));
|
||||
if (m.i8) m.g8 = linear_w8h_group(e);
|
||||
}
|
||||
|
||||
const int64_t lane_rows = m.lanes * m.max_img;
|
||||
@@ -1030,7 +1060,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"+ %zu joint blocks (%lld heads a rank, ff %lld), %s linears",
|
||||
m.gt.rank, m.gt.world, m.flow_map ? " (flow map)" : " base", kTaps[kNTaps - 1],
|
||||
(long long)m.gt.n_layer, m.mode[0].size(), m.single.size(), (long long)gd.n_head,
|
||||
(long long)gd.n_ff, gd.w_bf16 ? "bf16" : "block-fp8");
|
||||
(long long)gd.n_ff, gd.w_bf16 ? "bf16" : m.i8 ? "rotated int8" : "block-fp8");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1125,17 +1155,19 @@ static void step_blocks(RadCtx* c, const Model& m, const std::vector<Block>& sta
|
||||
const RadOperand& s, const RadOperand& gt, const RadOperand& pos) {
|
||||
const Geom& g = m.gd;
|
||||
const int64_t D = g.n_embd, qd = g.q_dim(), nD = D / RAD_FP8_BLOCK;
|
||||
const bool q8 = !g.w_bf16;
|
||||
const bool q8 = (!g.w_bf16 && !m.i8) || m.norm_i8;
|
||||
const RadOperand xv = brow_slice(x, r0, R, D);
|
||||
for (size_t i = 0; i < stack.size(); ++i) {
|
||||
const Block& B = stack[i];
|
||||
const bool gated = i > 0;
|
||||
if (q8)
|
||||
RAD_ISSUE_N(c, B.op_n, R, gated ? brows(m.b_sum, R) : RAD_NONE, gated ? gt : RAD_NONE,
|
||||
s, RAD_NONE, mcu, xv, brows(m.a_hm.q, R), brows(m.a_hm.s, R), RAD_NONE);
|
||||
s, RAD_NONE, mcu, xv, brows(m.a_hm.cq(), R), brows(m.a_hm.cs(), R),
|
||||
RAD_NONE);
|
||||
else
|
||||
RAD_ISSUE_N(c, B.op_n, R, gated ? brows(m.b_sum, R) : RAD_NONE, gated ? gt : RAD_NONE,
|
||||
s, RAD_NONE, mcu, xv, brows(m.a_hm.x, R));
|
||||
B.q_n.step(c, R);
|
||||
B.qkv.step(c, m.a_hm, m.b_qkv, R);
|
||||
RAD_ISSUE_N(c, B.op_qkr, R, brows(m.b_qkv, R), pos, RAD_W(B.w_qn), RAD_W(B.w_kn));
|
||||
RAD_ISSUE_N(c, B.op_attn, R, bcol(m.b_qkv, 0, qd, R), bcol(m.b_qkv, qd, qd, R),
|
||||
@@ -1254,7 +1286,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->gen_b) {
|
||||
rad_step_fail(c, "flux3 is an image generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1283,6 +1315,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
/* One more level of expansion so `#NS` sees the expanded namespace. */
|
||||
#define FLUX3_PROBE_X(NS) RAD_ARCH_PROBE(NS)
|
||||
#define FLUX3_PLUGIN_X(NS, ...) RAD_ARCH_PLUGIN(NS, __VA_ARGS__)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
FLUX3_PROBE_X(FLUX3_NS)
|
||||
FLUX3_PLUGIN_X(FLUX3_NS, FLUX3_ID, "", "0.1.0",
|
||||
"FLUX.3 [klein] and its base: Qwen3-VL-4B's stacked layers, a 5.6B three-mode "
|
||||
|
||||
+30
-15
@@ -85,7 +85,8 @@ struct ClassGeom {
|
||||
* - `mx`: OCP-MXFP4 (e2m1 codes, an E8M0 exponent per [1 x 32]), gemm_nt_q at mxfp4a8 over
|
||||
* quant_act_fp8's E4M3 codes, an f32 scale per (row, 128); the exponent plane is passed twice,
|
||||
* as b_scale and as b_ref (arch/common/rad_fp8.h LinearFP8 says why).
|
||||
* Neither has a fused norm/quantiser here, so the junctions stay off for them. */
|
||||
* The i8g grid takes the `_i8g` twins of the fused junction and of the GELU quantiser, as
|
||||
* gemma4_bf16's does; MXFP4 has its own junction (G3JunctionFP8). */
|
||||
struct G3Linear {
|
||||
rad_weight w = 0, ws = 0, wref = 0;
|
||||
rad_op op = 0, op_q = 0;
|
||||
@@ -192,6 +193,7 @@ inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
|
||||
i8g = known && linear_is_w8(enc);
|
||||
mx = known && linear_is_mxfp4(enc);
|
||||
if (mx) return linear_refuse_retired(wn, "MXFP4");
|
||||
/* Asymmetric int4 (libquant `codes=u4 zero=u8 group=128 scale=f16`), unrotated: gemm_nt_q at
|
||||
* w4a8i8_asym over the same per-(row, 128) int8 activation as i8g. LinearFP8 serves this grid
|
||||
* only under ParoQuant's rotation, which a tensor-parallel shard cannot cut; unrotated it shards
|
||||
@@ -698,8 +700,9 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gu}, {w.ffn});
|
||||
// Not under calibration: the tap reads the bf16 activation this fusion never writes.
|
||||
if (ln_down.quant && !ln_down.shared_in && !calib_dir() && rad_op_declared(b, "gelu_mul_quant_i8"))
|
||||
op_gq = rw(b, RAD_OP(b, "gelu_mul_quant_i8",
|
||||
const char* gq = ln_down.quant ? "gelu_mul_quant_i8" : ln_down.i8g ? "gelu_mul_quant_i8g" : nullptr;
|
||||
if (gq && !ln_down.shared_in && !calib_dir() && rad_op_declared(b, gq))
|
||||
op_gq = rw(b, RAD_OP(b, gq,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gu}, {ln_down.q8, ln_down.s8});
|
||||
@@ -782,7 +785,8 @@ void Gemma3Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai
|
||||
RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
/* ---- one residual junction as one op (libr4d `rmsnorm_quant_i8`): [post-norm of the branch,
|
||||
/* ---- one residual junction as one op (libr4d `rmsnorm_quant_i8`, on quant_act_i8g's grid
|
||||
* `rmsnorm_quant_i8g`): [post-norm of the branch,
|
||||
* the add into the stream,] the next block's norm and its int8 quantiser. gemma4_bf16's
|
||||
* G4Junction without the layer scalar. */
|
||||
struct G3Junction {
|
||||
@@ -794,25 +798,27 @@ struct G3Junction {
|
||||
int declare(RadBuilder* b, const Geom& g, rad_buf x_, rad_buf res_, rad_weight w_,
|
||||
rad_weight wp_, const G3Linear& into) {
|
||||
x = x_; res = res_; w = w_; wp = wp_; q8 = into.q8; s8 = into.s8;
|
||||
if (!into.quant || into.shared_in || !q8 || !s8 || !w || (wp && !res))
|
||||
if (!(into.quant || into.i8g) || into.shared_in || !q8 || !s8 || !w || (wp && !res))
|
||||
return RAD_E_INVAL;
|
||||
const char* rq = into.i8g ? "rmsnorm_quant_i8g" : "rmsnorm_quant_i8";
|
||||
const char* arq = into.i8g ? "ar_rmsnorm_quant_i8g" : "ar_rmsnorm_quant_i8";
|
||||
const RadParam p[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype),
|
||||
RAD_F64("wadd", g.wadd) };
|
||||
const rad_weight ws[2] = { w, wp };
|
||||
const int nw = wp ? 2 : 1;
|
||||
if (rad_op_declared(b, "rmsnorm_quant_i8"))
|
||||
op = rad_decl_op(b, "rmsnorm_quant_i8", p, (int)(sizeof p / sizeof p[0]), ws, nw);
|
||||
if (rad_op_declared(b, rq))
|
||||
op = rad_decl_op(b, rq, p, (int)(sizeof p / sizeof p[0]), ws, nw);
|
||||
if (!op) return RAD_OK;
|
||||
const rad_buf rd[2] = { x, res };
|
||||
const rad_buf wr[3] = { q8, s8, res };
|
||||
rad_op_reads (b, op, rd, res ? 2 : 1);
|
||||
rad_op_writes(b, op, wr, res ? 3 : 2);
|
||||
if (res && g.world == 2 && rad_op_declared(b, "ar_rmsnorm_quant_i8")) {
|
||||
if (res && g.world == 2 && rad_op_declared(b, arq)) {
|
||||
const RadParam pa[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd) };
|
||||
op_ar = rad_decl_op(b, "ar_rmsnorm_quant_i8", pa, (int)(sizeof pa / sizeof pa[0]), ws, nw);
|
||||
op_ar = rad_decl_op(b, arq, pa, (int)(sizeof pa / sizeof pa[0]), ws, nw);
|
||||
if (op_ar) {
|
||||
const rad_buf wa[4] = { x, q8, s8, res };
|
||||
rad_op_reads (b, op_ar, rd, 2);
|
||||
@@ -1002,7 +1008,7 @@ struct Model {
|
||||
bool pipe_serial_noted = false;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* The narrowest step the pipelined prefill takes, and its first piece: half the step rounded up
|
||||
* to 64 rows (qwen35_fp8 says why). */
|
||||
@@ -1149,9 +1155,10 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
if (m.pipe_tbl) rad_dev_free(m.pipe_tbl, RAD_MEM_HOST_PINNED);
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
@@ -1322,8 +1329,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (g.n_layer > 0 && !calib_dir()) {
|
||||
bool ok = true;
|
||||
for (const Layer& lay : m.layers)
|
||||
ok = ok && lay.attn.ln_q.quant && lay.attn.ln_k.shared_in && lay.attn.ln_v.shared_in &&
|
||||
lay.mlp.ln_gu.quant;
|
||||
ok = ok && (lay.attn.ln_q.quant || lay.attn.ln_q.i8g) && lay.attn.ln_k.shared_in &&
|
||||
lay.attn.ln_v.shared_in && (lay.mlp.ln_gu.quant || lay.mlp.ln_gu.i8g);
|
||||
if (ok) {
|
||||
RAD_ARCH_TRY(m.j0.declare(b, g, m.b_x, 0, m.layers[0].attn.w_norm, 0, m.layers[0].attn.ln_q));
|
||||
ok = m.j0.op != 0;
|
||||
@@ -1665,7 +1672,7 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
if (batch->enc) {
|
||||
rad_step_fail(c, "gemma3 serves text only");
|
||||
return;
|
||||
@@ -1800,11 +1807,19 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
out->draft_depth = bs > 1 ? (int)(bs - 1) : 7;
|
||||
out->draft_depth_fixed = 1; /* as qwen35_fp8: the trained block */
|
||||
}
|
||||
/* Chained launches pay with a drafter and without one: the decode kernels of the int8 trunk
|
||||
* have chained forms (libr4d's rad_kernel_chain), and the weight reads beside the reductions
|
||||
* then stay on lane 0 instead of a second queue. TranslateGemma 27B int8 on two R9700, ms a
|
||||
* decode step unchained / chained: 31.9 / 24.1 at one sequence, 32.2 / 24.8 at four (with
|
||||
* the junctions unfused, 40.9 / 26.4 and 41.2 / 27.0). */
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(gemma3)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(gemma3, "gemma3", "", "0.1.0",
|
||||
"Gemma 3 dense text trunk (TranslateGemma), bf16 or w4a8 at convert: sliding-window "
|
||||
"and linearly-scaled global attention over a (1 + w) RMSNorm stream with GELU "
|
||||
|
||||
+141
-81
@@ -1,6 +1,6 @@
|
||||
/* gemma4 -- Gemma 4 text decoders (26B-A4B MoE, and the dense members of the family): a bf16
|
||||
* trunk, routed experts bf16 or block fp8 (see FP8 EXPERTS), and the DFlash block-diffusion
|
||||
* drafter.
|
||||
* trunk, routed experts bf16, block fp8 or rotated int8 (see FP8 EXPERTS), and the DFlash
|
||||
* block-diffusion drafter.
|
||||
*
|
||||
* ============================== THE SHAPE (gemma-4-26B-A4B-it) ==============================
|
||||
*
|
||||
@@ -77,7 +77,17 @@
|
||||
* blocks, which 704 is not. It stays bf16 -- unless the checkpoint is padded to 768
|
||||
* first, outside the engine: zero rows of gate and up give gelu(0) * 0 = 0 in the
|
||||
* padded columns, which meet zero columns of down, so the function is unchanged, and
|
||||
* then both projections are fp8 (data/recipes/gemma4-26b-a4b-df-pad768.recipe).
|
||||
* then both projections are fp8.
|
||||
*
|
||||
* Rotated int8 experts (`rtn codes=i8 group=128 scale=bf16 transform=fwht128`) take the same
|
||||
* tables and the same widths through `moe_gemm_q` at i8a8h, over int8 codes of the experts' input
|
||||
* that the attention join's fused route writes (`norm_add_norm_route_i8g`), or the rotating norm
|
||||
* (`rmsnorm_had_quant_i8g`) where that is not served. A model's quantised experts are all one or
|
||||
* all the other.
|
||||
*
|
||||
* The cache is bf16 or int8 with an f16 scale of K and of V per token and head
|
||||
* (--kv-cache-dtype i8, libr4d's windowed kernels' int8 rows and kv_store_i8), the drafter's
|
||||
* with it.
|
||||
*
|
||||
* ============================== NOT DECLARED ==============================
|
||||
*
|
||||
@@ -157,7 +167,9 @@ struct Layer {
|
||||
* w_egus/w_edns, so each parity is one run (see declare). */
|
||||
rad_weight w_rscale = 0, w_router = 0, w_escale = 0, w_enorm = 0, w_fpost2 = 0;
|
||||
std::vector<rad_weight> w_egu, w_edn, w_egus, w_edns;
|
||||
bool gu_fp8 = false, dn_fp8 = false;
|
||||
/* A projection's experts are quantised (block fp8 or rotated int8: the table GEMM over a code
|
||||
* pair), else plain bf16. */
|
||||
bool gu_q = false, dn_q = false;
|
||||
rad_op op_rnorm = 0, op_router = 0, op_topk = 0, op_escale = 0, op_emul = 0, op_enorm = 0;
|
||||
rad_op op_scatter = 0, op_egu = 0, op_eact = 0, op_eq = 0, op_edn = 0, op_gather = 0;
|
||||
/* libr4d's fused forms of the router, its top-k and the sort, where they resolve: the pair
|
||||
@@ -177,8 +189,9 @@ struct Layer {
|
||||
* then declared and issued instead. */
|
||||
rad_op op_join_a = 0, op_join_f = 0;
|
||||
/* op_join_r: op_join_a writing the routed arm's two inputs as well -- the router's norm into
|
||||
* b_rn and the experts' fp8 codes into b_hq / b_hqs (norm_add_norm_route) -- where the
|
||||
* layer's gate_up is block fp8. op_rnorm and op_enorm are then declared and not issued. */
|
||||
* b_rn and the experts' codes into b_hq / b_hqs (norm_add_norm_route's E4M3, or
|
||||
* norm_add_norm_route_i8g's rotated int8) -- where the layer's gate_up is quantised. op_rnorm
|
||||
* and op_enorm are then declared and not issued. */
|
||||
rad_op op_join_r = 0;
|
||||
/* op_join_f also writes the next norm (the following layer's input norm, or the final norm
|
||||
* after the last layer) into `h`, with that norm's gain `w_next`; the replaced norm is then
|
||||
@@ -220,7 +233,10 @@ struct Model {
|
||||
/* the experts' E4M3 inputs, declared only where some layer's projection is fp8: gate_up's
|
||||
* (the normed block input, a row a token) and down's (the gated product, a row a slot) */
|
||||
rad_buf b_hq = 0, b_hqs = 0, b_eq = 0, b_eqs = 0;
|
||||
int n_gu_fp8 = 0, n_dn_fp8 = 0; /* layers whose projection is fp8 */
|
||||
int n_gu_q = 0, n_dn_q = 0; /* layers whose projection is quantised */
|
||||
/* The quantised experts are rotated int8 against int8 activations (EXP_I8), every layer's:
|
||||
* the code pairs are one buffer each for the whole model. */
|
||||
bool exp_i8 = false, exp_seen = false;
|
||||
rad_buf b_hout = 0, b_logits = 0;
|
||||
|
||||
rad_weight w_tok = 0, w_onorm = 0;
|
||||
@@ -245,7 +261,7 @@ struct Model {
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* ============================================================== geometry */
|
||||
|
||||
@@ -331,7 +347,7 @@ static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
* plan, rad_weight_encoding), which picks the GEMM: plain bf16 is `moe_gemm`, block fp8 (fp8_e4m3
|
||||
* codes, a bf16 scale per 128x128 block) is `moe_gemm_q` at fp8a8. Anything else is refused by
|
||||
* name. A builder with no model behind it answers nothing, and the declared dtype bf16 is read. */
|
||||
enum { EXP_BF16 = 0, EXP_FP8 = 1 };
|
||||
enum { EXP_BF16 = 0, EXP_FP8 = 1, EXP_I8 = 2 };
|
||||
static int expert_format(RadBuilder* b, const char* wn, int* fmt) {
|
||||
RadEncoding e{};
|
||||
*fmt = EXP_BF16;
|
||||
@@ -341,11 +357,22 @@ static int expert_format(RadBuilder* b, const char* wn, int* fmt) {
|
||||
*fmt = EXP_FP8;
|
||||
return RAD_OK;
|
||||
}
|
||||
/* Rotated int8: codes with a bf16 scale per (row, 128 of K), each 128 of K rotated by the
|
||||
* Hadamard (libquant's `codes=i8 group=128 scale=bf16 transform=fwht128`). */
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
if (rad_enc_is(&e, "affine") && e.n_planes == 2 && e.plane[0].dtype == RAD_I8 && sc &&
|
||||
sc->dtype == RAD_BF16 && sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK &&
|
||||
std::strcmp(e.transform, "fwht128") == 0) {
|
||||
*fmt = EXP_I8;
|
||||
return RAD_OK;
|
||||
}
|
||||
char en[256];
|
||||
rad_enc_format(&e, en, sizeof en);
|
||||
fprintf(stderr, "radiance: gemma4: '%s' is %s; the routed experts are served plain bf16 or "
|
||||
"block fp8 (fp8_e4m3*bf16[128x128]). Convert with no rule for them, or with "
|
||||
"`rtn codes=fp8_e4m3 block=128x128 scale=bf16`.\n", wn, en);
|
||||
fprintf(stderr, "radiance: gemma4: '%s' is %s; the routed experts are served plain bf16, "
|
||||
"block fp8 (fp8_e4m3*bf16[128x128]) or rotated int8 "
|
||||
"(i8*bf16[1x128]/fwht128). Convert with no rule for them, or with `rtn "
|
||||
"codes=fp8_e4m3 block=128x128 scale=bf16` or `rtn codes=i8 group=128 "
|
||||
"scale=bf16 transform=fwht128 clamp=sym rule=search`.\n", wn, en);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
|
||||
@@ -360,11 +387,11 @@ static int layer_expert_format(RadBuilder* b, Names& nm, int64_t l, int64_t base
|
||||
RAD_ARCH_TRY(expert_format(b, wn, &f));
|
||||
if (e == 0) { *fmt = f; continue; }
|
||||
if (f != *fmt) {
|
||||
static const char* const kName[3] = { "bf16", "block fp8", "rotated int8" };
|
||||
fprintf(stderr, "radiance: gemma4: '%s' is %s and expert %lld of the same layer is %s; "
|
||||
"one layer's %s experts take one encoding (a recipe rule for them "
|
||||
"matches all of a layer's or none)\n", wn,
|
||||
f == EXP_FP8 ? "block fp8" : "bf16", (long long)base,
|
||||
*fmt == EXP_FP8 ? "block fp8" : "bf16", what);
|
||||
"matches all of a layer's or none)\n", wn, kName[f], (long long)base,
|
||||
kName[*fmt], what);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
}
|
||||
@@ -375,7 +402,8 @@ static int layer_expert_format(RadBuilder* b, Names& nm, int64_t l, int64_t base
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (ctx->is_draft) {
|
||||
fprintf(stderr, "radiance: gemma4: this plugin has no draft scope\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -388,7 +416,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
Names& nm = m.nm;
|
||||
@@ -587,26 +615,40 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
int fgu = EXP_BF16, fdn = EXP_BF16;
|
||||
RAD_ARCH_TRY(layer_expert_format(b, nm, l, m.expert_base, NL, "gate_up", &fgu));
|
||||
RAD_ARCH_TRY(layer_expert_format(b, nm, l, m.expert_base, NL, "down", &fdn));
|
||||
y.gu_fp8 = fgu == EXP_FP8;
|
||||
y.dn_fp8 = fdn == EXP_FP8;
|
||||
y.gu_q = fgu != EXP_BF16;
|
||||
y.dn_q = fdn != EXP_BF16;
|
||||
/* One quantised format for the model: the experts' code pairs are shared buffers. */
|
||||
for (const int f : { fgu, fdn }) {
|
||||
if (f == EXP_BF16) continue;
|
||||
const bool i8 = f == EXP_I8;
|
||||
if (m.exp_seen && i8 != m.exp_i8) {
|
||||
fprintf(stderr, "radiance: gemma4: layer %lld's experts are %s and an earlier "
|
||||
"projection's %s; a model's quantised experts are all block "
|
||||
"fp8 or all rotated int8\n", ll,
|
||||
i8 ? "rotated int8" : "block fp8", i8 ? "block fp8" : "rotated int8");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
m.exp_seen = true;
|
||||
m.exp_i8 = i8;
|
||||
}
|
||||
/* moe_gemm_q's geometry, refused here by name rather than as a kernel miss. It takes
|
||||
* experts as two tables by parity, so a rank must hold an even count. */
|
||||
if ((y.gu_fp8 || y.dn_fp8) && NL % 2) {
|
||||
fprintf(stderr, "radiance: gemma4: block fp8 experts come in pairs on a rank (the "
|
||||
"fp8 grouped GEMM takes them as two tables by parity); this rank "
|
||||
if ((y.gu_q || y.dn_q) && NL % 2) {
|
||||
fprintf(stderr, "radiance: gemma4: quantised experts come in pairs on a rank (the "
|
||||
"grouped GEMM takes them as two tables by parity); this rank "
|
||||
"holds %lld\n", (long long)NL);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (y.gu_fp8 && ((2 * m.n_ffe) % 64 || E % RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: gemma4: layer %lld's gate_up experts are block fp8 at "
|
||||
"%lld x %lld; the fp8 grouped GEMM takes N in 64s and K in whole "
|
||||
if (y.gu_q && ((2 * m.n_ffe) % 64 || E % RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: gemma4: layer %lld's gate_up experts are quantised at "
|
||||
"%lld x %lld; the grouped GEMM takes N in 64s and K in whole "
|
||||
"%d-column blocks\n", ll, (long long)(2 * m.n_ffe), (long long)E,
|
||||
RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (y.dn_fp8 && (E % 64 || m.n_ffe % RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: gemma4: layer %lld's down experts are block fp8, and "
|
||||
"the experts are %lld wide: the fp8 grouped GEMM reads K in whole "
|
||||
if (y.dn_q && (E % 64 || m.n_ffe % RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: gemma4: layer %lld's down experts are quantised, and "
|
||||
"the experts are %lld wide: the grouped GEMM reads K in whole "
|
||||
"%d-column scale blocks. Keep `ffn_down_exps` bf16 (no recipe "
|
||||
"rule for it), or pad the experts to a multiple of %d (zero rows "
|
||||
"of gate and up, zero columns of down) and convert the padded "
|
||||
@@ -614,8 +656,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
(long long)m.n_ffe, RAD_FP8_BLOCK, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
m.n_gu_fp8 += y.gu_fp8;
|
||||
m.n_dn_fp8 += y.dn_fp8;
|
||||
m.n_gu_q += y.gu_q;
|
||||
m.n_dn_q += y.dn_q;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -640,10 +682,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.b_ids = decl_b(b, nm.f("moe_ids"), RAD_I32, {T, K});
|
||||
m.b_ew = decl_b(b, nm.f("moe_w"), RAD_BF16, {T, K});
|
||||
m.b_es = decl_b(b, nm.f("moe_es"), RAD_BF16, {T, K});
|
||||
if (m.n_gu_fp8 < m.n_layer)
|
||||
if (m.n_gu_q < m.n_layer)
|
||||
m.b_hx = decl_b(b, nm.f("moe_h"), RAD_BF16, {T, E});
|
||||
if (m.n_gu_fp8 > 0) {
|
||||
m.b_hq = decl_b(b, nm.f("moe_hq"), RAD_F8E4M3, {T, E});
|
||||
if (m.n_gu_q > 0) {
|
||||
m.b_hq = decl_b(b, nm.f("moe_hq"), m.exp_i8 ? RAD_I8 : RAD_F8E4M3, {T, E});
|
||||
m.b_hqs = decl_b(b, nm.f("moe_hqs"), RAD_F32, {T, fp8_blocks(E)});
|
||||
}
|
||||
m.b_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {P * K});
|
||||
@@ -651,8 +693,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.b_ecnt = decl_b(b, nm.f("moe_ecnt"), RAD_I32, {m.n_local});
|
||||
m.b_egu = decl_b(b, nm.f("moe_egu"), RAD_BF16, {P * K, 2 * m.n_ffe});
|
||||
m.b_eact = decl_b(b, nm.f("moe_eact"), RAD_BF16, {P * K, m.n_ffe});
|
||||
if (m.n_dn_fp8 > 0) {
|
||||
m.b_eq = decl_b(b, nm.f("moe_eq"), RAD_F8E4M3, {P * K, m.n_ffe});
|
||||
if (m.n_dn_q > 0) {
|
||||
m.b_eq = decl_b(b, nm.f("moe_eq"), m.exp_i8 ? RAD_I8 : RAD_F8E4M3, {P * K, m.n_ffe});
|
||||
m.b_eqs = decl_b(b, nm.f("moe_eqs"), RAD_F32, {P * K, fp8_blocks(m.n_ffe)});
|
||||
}
|
||||
m.b_edn = decl_b(b, nm.f("moe_edn"), RAD_BF16, {P * K, E});
|
||||
@@ -769,7 +811,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* (libr4d/r4d_norm_join_bf16.hip); on a card they differ from libr4d's chain only in reduction
|
||||
* order. libref deliberately has no row for them, so the chain path stays tested. */
|
||||
const bool has_join_a = rad_op_declared(b, "norm_add_norm") != 0;
|
||||
const bool has_join_r = rad_op_declared(b, "norm_add_norm_route") != 0;
|
||||
const char* const join_r = m.exp_i8 ? "norm_add_norm_route_i8g" : "norm_add_norm_route";
|
||||
const bool has_join_r = rad_op_declared(b, join_r) != 0;
|
||||
const bool has_join_f = rad_op_declared(b, "join_add_scale") != 0;
|
||||
const bool has_escale = rad_op_declared(b, "expert_scale") != 0;
|
||||
const bool has_qrow = rad_op_declared(b, "attn_paged_qrow") != 0;
|
||||
@@ -924,12 +967,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
y.w_rscale = decl_w(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), RAD_F32, {E}, A, N, gl);
|
||||
}
|
||||
|
||||
/* The attention join. On a layer whose gate_up is block fp8 it also writes the routed
|
||||
/* The attention join. On a layer whose gate_up is quantised it also writes the routed
|
||||
* arm's two inputs: the router's norm (rmsnorm with mult hidden^-0.5) and the experts'
|
||||
* E4M3 codes (as rmsnorm_quant_fp8), saving two launches and two reads of x per layer.
|
||||
* Otherwise norm_add_norm, else the chain. */
|
||||
if (has_join_r && m.moe && y.gu_fp8)
|
||||
y.op_join_r = rw(b, RAD_OP(b, "norm_add_norm_route",
|
||||
* codes (as rmsnorm_quant_fp8, or for rotated int8 experts rmsnorm_had_quant_i8g),
|
||||
* saving two launches and two reads of x per layer. Otherwise norm_add_norm, else the
|
||||
* chain. */
|
||||
if (has_join_r && m.moe && y.gu_q)
|
||||
y.op_join_r = rw(b, RAD_OP(b, join_r,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_F64("eps", eps), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("mult", 1.0 / std::sqrt((double)E)),
|
||||
@@ -972,10 +1016,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* The experts: this rank's run of whole experts (name maps and encodings were settled
|
||||
* before the buffers). Each projection's handles are declared in its GEMM's table
|
||||
* order, since a table is a run of consecutively declared handles: bf16 is one run in
|
||||
* expert order; block fp8 is the even local experts' codes, then the odd ones', then
|
||||
* the scale views in the same two runs (`moe_gemm_q` takes two tables by parity). Codes
|
||||
* expert order; block fp8 or int8 is the even local experts' codes, then the odd ones',
|
||||
* then the scale views in the same two runs (`moe_gemm_q` takes two tables by parity;
|
||||
* an int8 expert's scale is per row, block fp8's per 128 rows). Codes
|
||||
* and scale plane are two views of one stored weight and one movement unit (slot 0
|
||||
* gate_up, 1 down). */
|
||||
const uint32_t cdt = m.exp_i8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3;
|
||||
auto experts = [&](bool fp8, const char* what, int slot, int64_t rows, int64_t cols,
|
||||
std::vector<rad_weight>& wc, std::vector<rad_weight>& ws) {
|
||||
wc.assign((size_t)NL, 0);
|
||||
@@ -1001,18 +1047,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rad_weight& h = (pass ? ws : wc)[(size_t)(par * half + i)];
|
||||
h = pass ? decl_view(b, nm.f("blk.%lld.ffn_%s_exps.%lld.scale", ll, what, ge),
|
||||
wn, "scale", RAD_BF16,
|
||||
{fp8_blocks(rows), fp8_blocks(cols)},
|
||||
{m.exp_i8 ? rows : fp8_blocks(rows),
|
||||
fp8_blocks(cols)},
|
||||
RAD_ACCESS_CONDITIONAL, N,
|
||||
grp_expert_slot(li, (int)e, slot))
|
||||
: decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, {rows, cols},
|
||||
: decl_view(b, wn, nullptr, "codes", cdt, {rows, cols},
|
||||
RAD_ACCESS_CONDITIONAL, N,
|
||||
grp_expert_slot(li, (int)e, slot));
|
||||
if (!h) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
};
|
||||
RAD_ARCH_TRY(experts(y.gu_fp8, "gate_up", 0, 2 * m.n_ffe, E, y.w_egu, y.w_egus));
|
||||
RAD_ARCH_TRY(experts(y.dn_fp8, "down", 1, E, m.n_ffe, y.w_edn, y.w_edns));
|
||||
RAD_ARCH_TRY(experts(y.gu_q, "gate_up", 0, 2 * m.n_ffe, E, y.w_egu, y.w_egus));
|
||||
RAD_ARCH_TRY(experts(y.dn_q, "down", 1, E, m.n_ffe, y.w_edn, y.w_edns));
|
||||
/* An fp8 projection's op takes its weights in its table operands' order: even codes,
|
||||
* even scales, odd codes, odd scales. */
|
||||
auto tables = [&](const std::vector<rad_weight>& wc, const std::vector<rad_weight>& ws) {
|
||||
@@ -1051,11 +1098,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
{m.b_ids}, {m.b_es});
|
||||
y.op_emul = binop("mul", P, K, m.b_ew, m.b_es, m.b_ew);
|
||||
}
|
||||
/* The experts' input, pre_feedforward_layernorm_2 of the stream. For an fp8 gate_up it
|
||||
* is normed and quantised in one pass (`rmsnorm_quant_fp8`) with no bf16 copy, since
|
||||
* the fp8 GEMM reads only codes and scales. */
|
||||
if (y.gu_fp8) {
|
||||
y.op_enorm = RAD_OP(b, "rmsnorm_quant_fp8",
|
||||
/* The experts' input, pre_feedforward_layernorm_2 of the stream. For a quantised
|
||||
* gate_up it is normed and quantised in one pass (`rmsnorm_quant_fp8`, or for int8
|
||||
* experts the rotating `rmsnorm_had_quant_i8g`) with no bf16 copy, since the table
|
||||
* GEMM reads only codes and scales. */
|
||||
if (y.gu_q) {
|
||||
y.op_enorm = RAD_OP(b, m.exp_i8 ? "rmsnorm_had_quant_i8g" : "rmsnorm_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", E),
|
||||
RAD_F64("eps", eps), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("wadd", 0.0)),
|
||||
@@ -1108,13 +1156,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* The two grouped GEMMs use different a_order: gate_up reads the block input, one row
|
||||
* per token, gathered through sorted_tok; down reads gate_up's product, already one row
|
||||
* per (token, slot) in scatter order (rad_block_moe_fp8.h). */
|
||||
if (y.gu_fp8) {
|
||||
if (y.gu_q) {
|
||||
const std::vector<rad_weight> tab = tables(y.w_egu, y.w_egus);
|
||||
y.op_egu = rw(b, rad_decl_op(b, "moe_gemm_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", 2 * m.n_ffe),
|
||||
RAD_INT("K", E), RAD_INT("n_expert", NL),
|
||||
RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"), RAD_STR("dtype", "fp8a8")),
|
||||
/* `a_group` is stated to the int8 rows alone, last and cut off otherwise. */
|
||||
const RadParam ps[] = { RAD_RANGE("M", 1, P), RAD_INT("N", 2 * m.n_ffe),
|
||||
RAD_INT("K", E), RAD_INT("n_expert", NL),
|
||||
RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"),
|
||||
RAD_STR("dtype", m.exp_i8 ? "i8a8h" : "fp8a8"),
|
||||
RAD_INT("a_group", RAD_FP8_BLOCK) };
|
||||
y.op_egu = rw(b, rad_decl_op(b, "moe_gemm_q", ps,
|
||||
(int)(sizeof ps / sizeof *ps) - (m.exp_i8 ? 0 : 1),
|
||||
tab.data(), (int)tab.size()),
|
||||
{m.b_hq, m.b_hqs, m.b_sorted, m.b_eoff}, {m.b_egu});
|
||||
} else {
|
||||
@@ -1129,19 +1181,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* gelu_tanh(gate) * up over the two column halves. An fp8 down then quantises the
|
||||
* product on its own launch: libr4d's fused gated quantiser is compiled for silu. */
|
||||
y.op_eact = act_mul(P * K, m.n_ffe, m.b_egu, m.b_eact);
|
||||
if (y.dn_fp8) {
|
||||
y.op_eq = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
if (y.dn_q) {
|
||||
y.op_eq = rw(b, RAD_OP(b, m.exp_i8 ? "had_quant_act_i8g" : "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P * K), RAD_INT("n", m.n_ffe),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_eact}, {m.b_eq, m.b_eqs});
|
||||
const std::vector<rad_weight> tab = tables(y.w_edn, y.w_edns);
|
||||
y.op_edn = rw(b, rad_decl_op(b, "moe_gemm_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", E),
|
||||
RAD_INT("K", m.n_ffe), RAD_INT("n_expert", NL),
|
||||
RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "sorted"), RAD_STR("dtype", "fp8a8")),
|
||||
const RadParam ps[] = { RAD_RANGE("M", 1, P), RAD_INT("N", E),
|
||||
RAD_INT("K", m.n_ffe), RAD_INT("n_expert", NL),
|
||||
RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "sorted"),
|
||||
RAD_STR("dtype", m.exp_i8 ? "i8a8h" : "fp8a8"),
|
||||
RAD_INT("a_group", RAD_FP8_BLOCK) };
|
||||
y.op_edn = rw(b, rad_decl_op(b, "moe_gemm_q", ps,
|
||||
(int)(sizeof ps / sizeof *ps) - (m.exp_i8 ? 0 : 1),
|
||||
tab.data(), (int)tab.size()),
|
||||
{m.b_eq, m.b_eqs, m.b_sorted, m.b_eoff}, {m.b_edn});
|
||||
} else {
|
||||
@@ -1165,7 +1220,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rad_op_reads(b, y.op_gather, rd, 3);
|
||||
rad_op_writes(b, y.op_gather, wr, 1);
|
||||
}
|
||||
if (!y.op_enorm || !y.op_egu || !y.op_edn || (y.dn_fp8 && !y.op_eq)) return RAD_E_INVAL;
|
||||
if (!y.op_enorm || !y.op_egu || !y.op_edn || (y.dn_q && !y.op_eq)) return RAD_E_INVAL;
|
||||
if (W > 1) y.op_ar_f = allreduce(2 * T * E, m.b_ff2);
|
||||
if (has_join_f)
|
||||
{
|
||||
@@ -1309,24 +1364,27 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rad_note(b, "sandwich joins: %d of %lld fused (norm_add_norm / join_add_scale)%s",
|
||||
n_joins, (long long)(m.moe ? 2 * m.n_layer : m.n_layer),
|
||||
n_joins == 0 ? " -- not served, the rmsnorm / add / mul_weight chain" : "");
|
||||
if (m.moe && m.n_gu_fp8 > 0)
|
||||
rad_note(b, "routed inputs: %d of %d fp8 layers take the router's norm and the experts' "
|
||||
"codes from the attention join (norm_add_norm_route)%s",
|
||||
n_route, m.n_gu_fp8,
|
||||
n_route ? "" : " -- the rmsnorm and rmsnorm_quant_fp8 launches instead");
|
||||
if (m.moe && m.n_gu_q > 0)
|
||||
rad_note(b, "routed inputs: %d of %d quantised layers take the router's norm and the "
|
||||
"experts' codes from the attention join (%s)%s",
|
||||
n_route, m.n_gu_q, join_r,
|
||||
n_route ? "" : m.exp_i8 ? " -- the rmsnorm and rmsnorm_had_quant_i8g launches instead"
|
||||
: " -- the rmsnorm and rmsnorm_quant_fp8 launches instead");
|
||||
if (m.ks.nh > 0)
|
||||
rad_note(b, "sliding attention: q %s", m.qrow == 1
|
||||
? "read in the fused qkv row (attn_paged_qrow)"
|
||||
: "lifted into a dense block for attn_paged (attn_paged_qrow not served)");
|
||||
if (m.moe) {
|
||||
auto how = [&](int n_fp8) {
|
||||
return n_fp8 == m.n_layer ? "block fp8" : n_fp8 == 0 ? "bf16" : "mixed";
|
||||
return n_fp8 == 0 ? "bf16" : n_fp8 < m.n_layer ? "mixed"
|
||||
: m.exp_i8 ? "rotated int8" : "block fp8";
|
||||
};
|
||||
rad_note(b, "routed arm: %lld local experts from %lld of %lld, top %lld, %lld wide; "
|
||||
"gate_up %s (%d of %lld layers fp8), down %s (%d fp8); passes of %lld tokens",
|
||||
"gate_up %s (%d of %lld layers quantised), down %s (%d quantised); passes of "
|
||||
"%lld tokens",
|
||||
(long long)m.n_local, (long long)m.expert_base, (long long)m.n_expert,
|
||||
(long long)m.top_k, (long long)m.n_ffe, how(m.n_gu_fp8), m.n_gu_fp8,
|
||||
(long long)m.n_layer, how(m.n_dn_fp8), m.n_dn_fp8, (long long)m.moe_rows);
|
||||
(long long)m.top_k, (long long)m.n_ffe, how(m.n_gu_q), m.n_gu_q,
|
||||
(long long)m.n_layer, how(m.n_dn_q), m.n_dn_q, (long long)m.moe_rows);
|
||||
if (W > 1)
|
||||
rad_note(b, "prefill overlap: %s", m.overlap
|
||||
? "a chunk of two routed passes or more runs as two slices, each slice's "
|
||||
@@ -1394,11 +1452,11 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t
|
||||
}
|
||||
/* rmsnorm_quant_fp8's operands: x, residual (absent), w, q, scale, out_bf16 (absent);
|
||||
* issued only where the attention join did not already write the codes. */
|
||||
if (y.gu_fp8 && !y.op_join_r)
|
||||
if (y.gu_q && !y.op_join_r)
|
||||
RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_NONE, RAD_W(y.w_enorm),
|
||||
brow_slice(m.b_hq, r0, n, E), brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK),
|
||||
RAD_NONE);
|
||||
else if (!y.gu_fp8)
|
||||
else if (!y.gu_q)
|
||||
RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_enorm),
|
||||
brow_slice(m.b_hx, r0, n, E));
|
||||
if (!rfused && !pair)
|
||||
@@ -1407,7 +1465,7 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t
|
||||
/* An fp8 projection's tables: the first handle of each parity's run and its length --
|
||||
* even codes, even scales, odd codes, odd scales (declare). */
|
||||
const int64_t H = NL / 2;
|
||||
if (y.gu_fp8)
|
||||
if (y.gu_q)
|
||||
RAD_ISSUE_N(c, y.op_egu, n, brow_slice(m.b_hq, r0, n, E),
|
||||
brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK),
|
||||
RAD_WTAB(y.w_egu[0], H), RAD_WTAB(y.w_egus[0], H),
|
||||
@@ -1419,7 +1477,7 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t
|
||||
brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), brows(m.b_egu, n * K));
|
||||
RAD_ISSUE_N(c, y.op_eact, n * K, bcol(m.b_egu, 0, m.n_ffe, n * K),
|
||||
bcol(m.b_egu, m.n_ffe, m.n_ffe, n * K), brows(m.b_eact, n * K));
|
||||
if (y.dn_fp8) {
|
||||
if (y.dn_q) {
|
||||
RAD_ISSUE_N(c, y.op_eq, n * K, brows(m.b_eact, n * K), brows(m.b_eq, n * K),
|
||||
brows(m.b_eqs, n * K));
|
||||
RAD_ISSUE_N(c, y.op_edn, n, brows(m.b_eq, n * K), brows(m.b_eqs, n * K),
|
||||
@@ -1737,7 +1795,7 @@ static void calib_count(RadCtx* c, Model& m, int64_t T) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (batch->draft_pass != 0) {
|
||||
if (!m.have_df) {
|
||||
rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the "
|
||||
@@ -1763,7 +1821,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const int64_t cut = split_at(m, T);
|
||||
if (cut > 0) trunk_overlap(c, m, batch, cut);
|
||||
else trunk(c, m, batch);
|
||||
if (m.calib && m.tap_live) calib_count(c, g_model[rad_rank(c)], T);
|
||||
if (m.calib && m.tap_live) calib_count(c, g_model[rad_slot(c)], T);
|
||||
|
||||
if (m.op_onorm) RAD_ISSUE(c, m.op_onorm, brows(m.b_x, T), RAD_W(m.w_onorm), brows(m.b_h, T));
|
||||
if (batch->n_out > 0) {
|
||||
@@ -1796,6 +1854,8 @@ static const RadChatFormat* chat_format(const RadModelMeta*) { return gemma4_cha
|
||||
} /* namespace gemma4 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(gemma4, "gemma4", "", "0.1.0",
|
||||
"Gemma 4 text decoders (26B-A4B MoE, dense 31B), bf16: sliding and full attention "
|
||||
"with proportional rope and K = V, a dense and a routed feed-forward side by side, "
|
||||
|
||||
@@ -2013,7 +2013,7 @@ struct Model {
|
||||
bool slice_attn = false;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* A DFlash2 drafter's config key, from vLLM's speculators layout (the speculator's keys at the
|
||||
* top of `draft.`) or z-lab's (under `draft.dflash_config.`), whichever the checkpoint has. */
|
||||
@@ -2162,17 +2162,31 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, 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.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3, {dg.max_tok, dc.n_taps * dg.n_embd});
|
||||
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32,
|
||||
{dg.max_tok, fp8_blocks(dc.n_taps * 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.h2q = decl_b(b, nm.f("df_h2q"), RAD_F8E4M3, {qr, dg.n_embd});
|
||||
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, fp8_blocks(dg.n_embd)});
|
||||
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.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)});
|
||||
/* The codes the drafter's linears read: int8 with one f32 scale per (row, group) for linears
|
||||
* stored rotated int8 (the -df2 recipe's), which the drafter's `fc` tells; E4M3 with a scale
|
||||
* per 128 for an MXFP4 drafter (rad_fp8.h's DenseFP8). */
|
||||
RAD_ARCH_TRY(Dflash2::probe_i8(b, nm, "draft", &dc.act_i8, &dc.act_g8));
|
||||
dc.fc_mapped = true;
|
||||
const uint32_t dqt = dc.act_i8 ? RAD_I8 : RAD_F8E4M3;
|
||||
const int64_t dqg = dc.act_i8 ? dc.act_g8 : (int64_t)RAD_FP8_BLOCK;
|
||||
if (dc.act_i8 && ((dc.n_taps * dg.n_embd) % dqg || dg.n_embd % dqg || qd % dqg ||
|
||||
dg.n_ff % dqg)) {
|
||||
fprintf(stderr, "radiance: a rotated int8 drafter takes widths in whole %lld-column scale "
|
||||
"groups; this one is n_embd %lld, q %lld, n_ff %lld\n", (long long)dqg,
|
||||
(long long)dg.n_embd, (long long)qd, (long long)dg.n_ff);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto dqs = [&](int64_t n) { return (n + dqg - 1) / dqg; };
|
||||
dw.srcq = decl_b(b, nm.f("df_srcq"), dqt, {dg.max_tok, dc.n_taps * dg.n_embd});
|
||||
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, dqs(dc.n_taps * dg.n_embd)});
|
||||
dw.cq = decl_b(b, nm.f("df_cq"), dqt, {dg.max_tok, dg.n_embd});
|
||||
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, dqs(dg.n_embd)});
|
||||
dw.h2q = decl_b(b, nm.f("df_h2q"), dqt, {qr, dg.n_embd});
|
||||
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, dqs(dg.n_embd)});
|
||||
dw.atq = decl_b(b, nm.f("df_atq"), dqt, {qr, qd});
|
||||
dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, dqs(qd)});
|
||||
dw.ffq = decl_b(b, nm.f("df_ffq"), dqt, {qr, dg.n_ff});
|
||||
dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, dqs(dg.n_ff)});
|
||||
dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd});
|
||||
dw.hp = decl_b(b, nm.f("df_hp"), dg.act_dtype, {sr, dc.sel_rank});
|
||||
dw.dq = decl_b(b, nm.f("df_dq"), RAD_I8, {sr, dg.n_embd});
|
||||
@@ -2261,9 +2275,10 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
@@ -3155,7 +3170,7 @@ static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int6
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
|
||||
/* An encoder pass runs only its encoder. */
|
||||
if (batch->enc) {
|
||||
@@ -3301,6 +3316,14 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
* DFlash2 one too (rad_block_dflash2.h). */
|
||||
(void)gemma4::dflash_probe(meta, out);
|
||||
(void)gemma4::dflash2_probe(meta, out);
|
||||
/* Chained launches pay on the dense trunk under any drafter and without one: its decode
|
||||
* kernels have chained forms (libr4d's rad_kernel_chain), the two-rank junctions among them,
|
||||
* and the weight reads beside the reductions then stay on lane 0 instead of a second queue.
|
||||
* Gemma 4 31B on two R9700, ms a decode step unchained / chained: grouped int8 35.81 / 27.60
|
||||
* without a drafter and 42.14 / 31.23 with the assistant head (44.93 / 34.17 at four
|
||||
* sequences); w4a8 26.14 / 15.78 and 32.30 / 20.36 (35.93 / 25.01). The 12B with its head:
|
||||
* bf16 38.65 / 28.84, grouped int8 24.35 / 14.74. */
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
/* The tower's pooling window, so a pass size the core picks itself is whole windows. */
|
||||
if (Gemma4Vision::present(meta)) {
|
||||
const int64_t k = rad_meta_geti(meta, "vision_config.pooling_kernel_size", 0);
|
||||
@@ -3314,6 +3337,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
}
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0",
|
||||
"Gemma 4 dense (text, images, E2B/E4B/12B audio), w4a8 or w8a8 from its bf16 or its CT-INT4 (QAT) "
|
||||
"release: sliding-window and proportional-RoPE global attention over a plain "
|
||||
|
||||
@@ -79,7 +79,7 @@ struct Model {
|
||||
GlmVision vit{};
|
||||
MediaRows mrows{};
|
||||
};
|
||||
static std::unique_ptr<Model> models[MAX_RANKS];
|
||||
static std::unique_ptr<Model> models[MAX_SLOTS];
|
||||
static thread_local std::unique_ptr<Model> probe_model;
|
||||
|
||||
/* Whether every routed expert is MXFP4, asked before any buffer is sized and of the same experts on
|
||||
@@ -473,7 +473,8 @@ static int geometry(Geom& g, const RadModelMeta* meta, const RadBuildCtx* ctx, i
|
||||
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)
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
const int world = ctx->world_size ? ctx->world_size : 1;
|
||||
if (!GlmTp::world_ok(world)) {
|
||||
@@ -514,7 +515,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rad_dtype_name(ctx->kv_dtype));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank];
|
||||
auto& slot = ctx->shape_probe ? probe_model : models[rad_build_slot(ctx)];
|
||||
slot = std::make_unique<Model>();
|
||||
auto& m = *slot;
|
||||
auto& g = m.g;
|
||||
@@ -625,7 +626,7 @@ static void draft_pass(RadCtx* c, Model& m, const RadBatch* batch) {
|
||||
m.mtp.step_head(c, batch);
|
||||
}
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
auto& m = *models[rad_rank(c)];
|
||||
auto& m = *models[rad_slot(c)];
|
||||
const int64_t T = batch->n_tok;
|
||||
// An encoder pass runs only the vision tower (RadBatch::enc).
|
||||
if (batch->enc) {
|
||||
@@ -675,11 +676,15 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
}
|
||||
out->shape_probe_ok = 1;
|
||||
out->tp_attn_rows_ok = 1;
|
||||
/* --kv-cache-dtype fp8: the latent attention cache as E4M3 (declare, kv_groups). */
|
||||
out->kv_fp8_ok = 1;
|
||||
return RAD_OK;
|
||||
}
|
||||
} // namespace glm5next
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(glm5next)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(glm5next, "glm5next", "", "0.1.0",
|
||||
"GLM-5.3-Flash mixed MXFP4/FP8, mHC/KDA/MLA and native serial MTP")
|
||||
#endif
|
||||
@@ -180,7 +180,8 @@ struct Model {
|
||||
b_qlogit = 0, b_field = 0;
|
||||
};
|
||||
|
||||
static Model g_model;
|
||||
/* One per engine instance in the process, by slot (rad_builder.h, rad_build_slot). */
|
||||
static Model g_model[RAD_MAX_SLOTS];
|
||||
|
||||
/* ================================================================== declare helpers */
|
||||
static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype,
|
||||
@@ -890,7 +891,9 @@ static int declare_query(RadBuilder* b, Model& m) {
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
Model& m = g_model;
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || rad_build_slot(ctx) >= RAD_MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -1197,7 +1200,7 @@ static void step_query(RadCtx* c, const RadShapeGenBatch* S, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model;
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const RadShapeGenBatch* S = batch->sgen_b;
|
||||
if (!batch->gen || !S) {
|
||||
rad_step_fail(c, "hunyuan3d2 is a shape generator and runs generator passes only");
|
||||
@@ -1225,6 +1228,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
} /* namespace hunyuan3d2 */
|
||||
|
||||
RAD_ARCH_PROBE(hunyuan3d2)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(hunyuan3d2, "hunyuan3d2", "", "0.1.0",
|
||||
"Hunyuan3D-2's shape model: DINOv2-giant over the picture, a flow-matching DiT of "
|
||||
"16 double and 32 single blocks over 3072 latents, and the shape VAE's geometry "
|
||||
|
||||
@@ -38,7 +38,6 @@ struct AttnQKFP8 {
|
||||
const char* q_norm = nullptr;
|
||||
const char* k_norm = nullptr;
|
||||
const char* o = nullptr;
|
||||
double k_scale = 1.0, v_scale = 1.0; /* static FP8-cache descales; 1 for BF16 cache */
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
@@ -48,11 +47,9 @@ struct AttnQKFP8 {
|
||||
|
||||
rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0;
|
||||
LinearFP8 q{}, k{}, v{}, o{};
|
||||
rad_buf k_descale = 0, v_descale = 0;
|
||||
NormQuantFP8 nq_h{};
|
||||
QuantFP8 q_attn{};
|
||||
rad_op op_q_norm = 0, op_k_norm = 0;
|
||||
rad_op op_k_descale = 0, op_v_descale = 0;
|
||||
rad_op op_rope_q = 0, op_rope_k = 0, op_attn = 0, op_kv_store = 0;
|
||||
rad_op op_qkr_store = 0; /* Q/K norms, NeoX rotary and BF16 cache store, decode band */
|
||||
int64_t qkr_rows = 0;
|
||||
@@ -78,14 +75,6 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
(long long)g.n_head_kv_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const bool fp8_cache = std::strcmp(g.kv_dtype, "fp8_e4m3") == 0;
|
||||
if (fp8_cache && (!std::isfinite(src.k_scale) || src.k_scale <= 0.0 ||
|
||||
!std::isfinite(src.v_scale) || src.v_scale <= 0.0)) {
|
||||
fprintf(stderr, "radiance: HYV3 layer %d needs positive finite static K/V descales for "
|
||||
"its FP8 KV cache\n", l);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), src.q_norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), src.k_norm));
|
||||
@@ -122,23 +111,7 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim, "neox"),
|
||||
{w.k}, {w.k});
|
||||
|
||||
if (fp8_cache) {
|
||||
k_descale = decl_b(b, nm.f("blk.%d.attn_k_descale", l), RAD_F32,
|
||||
{g.max_seqs, g.n_head_kv});
|
||||
v_descale = decl_b(b, nm.f("blk.%d.attn_v_descale", l), RAD_F32,
|
||||
{g.max_seqs, g.n_head_kv});
|
||||
op_k_descale = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", g.n_head_kv),
|
||||
RAD_STR("dtype", "f32"), RAD_F64("value", src.k_scale)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {k_descale});
|
||||
op_v_descale = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", g.n_head_kv),
|
||||
RAD_STR("dtype", "f32"), RAD_F64("value", src.v_scale)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {v_descale});
|
||||
}
|
||||
const rad_op attn = decl_attn(b, g, "attn_paged",
|
||||
const rad_op attn = rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
@@ -146,19 +119,17 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
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);
|
||||
op_attn = fp8_cache ? rw(b, attn, {w.q, k_descale, v_descale}, {w.attn.x})
|
||||
: rw(b, attn, {w.q}, {w.attn.x});
|
||||
op_attn = rw(b, attn, {w.q}, {w.attn.x});
|
||||
op_kv_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype),
|
||||
RAD_F64("k_scale", src.k_scale), RAD_F64("v_scale", src.v_scale)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
|
||||
/* The standalone chain stays available for prefill, scaled/multicomponent rotary, FP8 KV,
|
||||
* and libraries without the fold. A 128-channel BF16 decode prologue is otherwise five tiny
|
||||
/* The standalone chain stays available for prefill, scaled/multicomponent rotary, the int8
|
||||
* cache and libraries without the fold. A 128-channel BF16 decode prologue is otherwise five tiny
|
||||
* launches; the fused kernel preserves the BF16 norm rounding before the rotary. */
|
||||
if (g.head_dim == 128 && !std::strcmp(g.dtype, "bf16") &&
|
||||
!std::strcmp(g.kv_dtype, "bf16") &&
|
||||
@@ -195,9 +166,7 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h.x}, {w.x});
|
||||
return op_attn && op_kv_store && (!add_out || op_add) &&
|
||||
(!fp8_cache || (k_descale && v_descale && op_k_descale && op_v_descale))
|
||||
? RAD_OK : RAD_E_INVAL;
|
||||
return op_attn && op_kv_store && (!add_out || op_add) ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
inline void AttnQKFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
@@ -223,21 +192,10 @@ inline void AttnQKFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_ISSUE(c, op_kv_store, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
|
||||
kv_cache(kv, layer));
|
||||
}
|
||||
if (op_k_descale) {
|
||||
RAD_ISSUE_N(c, op_k_descale, batch->n_seq, brows(k_descale, batch->n_seq));
|
||||
RAD_ISSUE_N(c, op_v_descale, batch->n_seq, brows(v_descale, batch->n_seq));
|
||||
}
|
||||
if (k_descale && v_descale)
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq), brows(k_descale, batch->n_seq),
|
||||
brows(v_descale, batch->n_seq),
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn.x, T));
|
||||
else
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn.x, T));
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn.x, T));
|
||||
q_attn.step(c, T);
|
||||
o.step(c, w.attn, w.h.x, T);
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
|
||||
@@ -56,7 +56,7 @@ struct Model {
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model models[MAX_RANKS];
|
||||
static Model models[MAX_SLOTS];
|
||||
|
||||
static int check_format(const RadModelMeta* meta) {
|
||||
const char* q = meta && meta->quant ? meta->quant : "";
|
||||
@@ -153,8 +153,10 @@ static void block_slice_128(int64_t width, int world, int rank, int64_t* lo, int
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = models[ctx->rank];
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = models[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
int status = check_format(meta);
|
||||
@@ -173,19 +175,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
status = check_model_config(meta, g, m);
|
||||
if (status < 0) return status;
|
||||
#if HYV3_FP8_SOURCE
|
||||
if ((ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16 &&
|
||||
ctx->kv_dtype != RAD_F8E4M3) || ctx->kv_quant != RAD_KVQ_NONE) {
|
||||
fprintf(stderr, "radiance: HYV3 FP8 supports BF16 or plain E4M3 KV cache, not this layout\n");
|
||||
if (ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_I8) {
|
||||
fprintf(stderr, "radiance: HYV3 serves a bf16 or an int8 KV cache, not %s\n",
|
||||
rad_dtype_name(ctx->kv_dtype));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
#else
|
||||
if ((ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16) ||
|
||||
ctx->kv_quant != RAD_KVQ_NONE) {
|
||||
fprintf(stderr, "radiance: HYV3 BF16 supports a BF16 KV cache only\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
#endif
|
||||
status = yarn_from(g, meta, "", g.head_dim);
|
||||
if (status < 0) return status;
|
||||
|
||||
@@ -340,21 +334,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
as.q_norm = nm.ckpt("%s.self_attn.q_norm.weight", pre);
|
||||
as.k_norm = nm.ckpt("%s.self_attn.k_norm.weight", pre);
|
||||
as.o = nm.ckpt("%s.self_attn.o_proj.weight", pre);
|
||||
#endif
|
||||
#if HYV3_FP8_SOURCE
|
||||
if (kd.dtype == RAD_F8E4M3) {
|
||||
const std::string sk = "hyv3.kv_cache." + std::to_string(l) + ".k_scale";
|
||||
const std::string sv = "hyv3.kv_cache." + std::to_string(l) + ".v_scale";
|
||||
as.k_scale = meta_text_getf(meta, sk.c_str(), NAN);
|
||||
as.v_scale = meta_text_getf(meta, sv.c_str(), NAN);
|
||||
if (!std::isfinite(as.k_scale) || as.k_scale <= 0.0 ||
|
||||
!std::isfinite(as.v_scale) || as.v_scale <= 0.0) {
|
||||
fprintf(stderr, "radiance: hyv3_fp8: FP8 KV cache needs positive finite scales "
|
||||
"for layer %lld (metadata keys %s and %s)\n",
|
||||
(long long)l, sk.c_str(), sv.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full));
|
||||
// Each norm folds its predecessor's residual add. The first attention reads the
|
||||
@@ -462,7 +441,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = models[rad_rank(c)];
|
||||
Model& m = models[rad_slot(c)];
|
||||
RAD_ISSUE(c, m.embed,
|
||||
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.token),
|
||||
brows(m.x, batch->n_tok));
|
||||
@@ -529,6 +508,8 @@ extern "C" const RadChatFormat* rad_arch_chat_format(const RadModelMeta*) {
|
||||
return &kHyv3ChatFormat;
|
||||
}
|
||||
extern "C" const char* rad_arch_id(void) { return "hyv3"; }
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
extern "C" const char* rad_arch_quant(void) { return HYV3_QUANT; }
|
||||
extern "C" int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* c) {
|
||||
return HYV3_NS::declare(b, m, c);
|
||||
|
||||
+115
-41
@@ -33,10 +33,15 @@
|
||||
*
|
||||
* ============================== WHAT IS QUANTISED ==============================
|
||||
*
|
||||
* One plugin serves bf16 and block-fp8 containers: every linear of the language model, of the
|
||||
* text fusion and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16 throughout when the first
|
||||
* DiT projection is plain. txt_in, img_in, the timestep MLP and modulation, the final layer and
|
||||
* the VAE stay bf16.
|
||||
* One plugin serves bf16, block-fp8 and rotated int8 (IQ8R) containers: every linear of the
|
||||
* language model, of the text fusion and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16
|
||||
* throughout when the first DiT projection is plain. That projection also says whether the
|
||||
* linears are rotated int8: the activations they read then carry int8 codes in place of the E4M3
|
||||
* pair, written by the rotating twins of the fused ops where a library serves them
|
||||
* (rms_mod_had_quant_i8g for a modulated norm, gate_had_quant_i8g for an attention's output
|
||||
* gate); elsewhere the norm, or the sigmoid and multiply pair, is followed by the rotating
|
||||
* quantiser. txt_in, img_in, the timestep MLP and modulation, the final layer and the VAE stay
|
||||
* bf16.
|
||||
*
|
||||
* ============================== TENSOR PARALLEL ==============================
|
||||
*
|
||||
@@ -132,6 +137,9 @@ struct DitLayer {
|
||||
rad_op op_tab = 0; /* the shared modulation plus this block's table, into its columns */
|
||||
LinearFP8 qkv{}, gate{}, o{}, gate_up{}, down{};
|
||||
QuantFP8 q_attn{};
|
||||
/* The two modulated norms' quantisers for a rotated int8 model whose norms are the
|
||||
* unquantised form (Model::norm_i8 false). */
|
||||
QuantFP8 q_n1{}, q_n2{};
|
||||
GateQuantFP8 gq{};
|
||||
rad_op op_n1 = 0, op_n2 = 0, op_qkr = 0, op_attn = 0, op_gq = 0, op_sig = 0;
|
||||
rad_op op_ar1 = 0, op_ar2 = 0;
|
||||
@@ -189,6 +197,15 @@ struct Model {
|
||||
ActFP8 a_hm{}, a_attn{}, a_ffn{};
|
||||
std::vector<DitLayer> dit;
|
||||
LinearFP8 qkv0{};
|
||||
/* The linears of every network are rotated int8 (IQ8R, or the 128-group int8 before it), read
|
||||
* off qkv0's probe: the activations then carry int8 code pairs with one scale per (token, `g8`
|
||||
* columns) in place of the E4M3 pair. */
|
||||
bool i8 = false;
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
/* Where a library serves the rotating twins, a DiT block's modulated norms write those int8
|
||||
* codes in their own pass (rms_mod_had_quant_i8g: norm_i8) and an attention's output gate
|
||||
* writes the out projection's (gate_had_quant_i8g: gate_i8, and fgate_i8 for the fusion blocks'). */
|
||||
bool norm_i8 = false, gate_i8 = false, fgate_i8 = false;
|
||||
rad_weight w_fn = 0, w_pout = 0, b_pout = 0;
|
||||
rad_op op_fn = 0, op_pout = 0, op_euler = 0;
|
||||
rad_buf b_fz = 0, b_v = 0;
|
||||
@@ -205,7 +222,7 @@ struct Model {
|
||||
std::string inv_std, mean, ones, zeros;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* A space-separated list off the container (rad-convert flattens arrays that way). */
|
||||
static std::vector<double> meta_list(const RadModelMeta* m, const char* key) {
|
||||
@@ -281,14 +298,27 @@ static rad_op zc_norm(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_we
|
||||
}
|
||||
|
||||
/* The attention's sigmoid output gate: `gate_quant_fp8` (gate, multiply and the out projection's
|
||||
* quantiser in one pass) over fp8 linears, or `sigmoid` then `mul` over bf16 ones and wherever no
|
||||
* loaded library declares the fused op (the out projection's quantiser then runs on its own).
|
||||
* Rows are (token, head) pairs of `head_dim` columns. Returns the gate op; `sig` is the pair's
|
||||
* sigmoid, written into `g` itself. */
|
||||
* quantiser in one pass) over fp8 linears, rows (token, head) pairs of `head_dim` columns; over
|
||||
* rotated int8 ones (`pair`) its rotating twin `gate_had_quant_i8g`, a token a row, since one
|
||||
* scale covers the codes' group across heads (`fused_i8` says so); or `sigmoid` then `mul` over
|
||||
* bf16 ones and wherever no loaded library declares the fused op (the out projection's quantiser
|
||||
* then runs on its own). Returns the gate op; `sig` is the pair's sigmoid, written into `g`
|
||||
* itself. */
|
||||
static rad_op out_gate(RadBuilder* b, const Geom& g, int64_t rows, int64_t width, rad_buf gate,
|
||||
const ActFP8& attn, rad_op* sig) {
|
||||
const ActFP8& attn, rad_op* sig, bool pair, bool* fused_i8) {
|
||||
const int64_t hd = g.head_dim;
|
||||
if (g.w_bf16 || !rad_op_declared(b, "gate_quant_fp8")) {
|
||||
*fused_i8 = false;
|
||||
if (pair && !g.w_bf16 && attn.q8_fed && attn.q8_rot && rad_op_declared(b, "gate_had_quant_i8g")) {
|
||||
*sig = 0;
|
||||
*fused_i8 = true;
|
||||
return rw(b, RAD_OP(b, "gate_had_quant_i8g",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
|
||||
RAD_INT("group", attn.cg()), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("act", "sigmoid")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ gate, attn.x }, { attn.cq(), attn.cs(), attn.x });
|
||||
}
|
||||
if (g.w_bf16 || pair || !rad_op_declared(b, "gate_quant_fp8")) {
|
||||
*sig = rw(b, RAD_OP(b, "sigmoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
@@ -369,14 +399,17 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, g.n_embd });
|
||||
m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, g.n_embd });
|
||||
RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", g.n_embd, T));
|
||||
RAD_ARCH_TRY(m.a_th.declare_pair(b, nm, g, "te.h", g.n_embd, T, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim });
|
||||
m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim });
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim, T));
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_pair(b, nm, g, "te.attn", q_dim, T, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, g.n_embd });
|
||||
m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff, T));
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_pair(b, nm, g, "te.ffn", g.n_ff, T, m.i8, m.g8,
|
||||
"gated_had_quant_i8g"));
|
||||
m.b_taps = decl_b(b, nm.f("te.taps"), RAD_BF16, { (int64_t)kTeRows * kNTaps, g.n_embd });
|
||||
m.b_tidx = decl_b(b, nm.f("te.tap_idx"), RAD_I32, { T });
|
||||
|
||||
@@ -579,7 +612,7 @@ static int declare_fuse_block(RadBuilder* b, Model& m, FuseBlock& F, const char*
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)hd))),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_fqkv }, { m.a_fattn.x });
|
||||
F.op_gq = out_gate(b, g, rows, qd, m.b_fg, m.a_fattn, &F.op_sig);
|
||||
F.op_gq = out_gate(b, g, rows, qd, m.b_fg, m.a_fattn, &F.op_sig, m.i8, &m.fgate_i8);
|
||||
if (F.op_sig) RAD_ARCH_TRY(F.q_attn.declare(b, g, m.a_fattn, qd));
|
||||
RAD_ARCH_TRY(F.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_COL,
|
||||
grp_layer(grp), { nm.ckpt("%s.attn.to_out.0.weight", pre) },
|
||||
@@ -610,15 +643,35 @@ static int declare_fusion(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
const int64_t D = g.n_embd, qd = g.q_dim();
|
||||
const int64_t RL = (int64_t)kCondRows * kNTaps; /* the layer-wise blocks' rows */
|
||||
m.a_fh.x = decl_b(b, nm.f("fuse.h"), RAD_BF16, { RL, D });
|
||||
RAD_ARCH_TRY(m.a_fh.declare_qs(b, nm, g, "fuse.h", D, RL));
|
||||
RAD_ARCH_TRY(m.a_fh.declare_pair(b, nm, g, "fuse.h", D, RL, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_fqkv = decl_b(b, nm.f("fuse.qkv"), RAD_BF16, { RL, 3 * qd });
|
||||
m.b_fg = decl_b(b, nm.f("fuse.gate"), RAD_BF16, { RL, qd });
|
||||
m.a_fattn.x = decl_b(b, nm.f("fuse.attn"), RAD_BF16, { RL, qd });
|
||||
RAD_ARCH_TRY(m.a_fattn.declare_qs(b, nm, g, "fuse.attn", qd, RL));
|
||||
RAD_ARCH_TRY(m.a_fattn.declare_pair(b, nm, g, "fuse.attn", qd, RL, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_fo = decl_b(b, nm.f("fuse.o"), RAD_BF16, { RL, D });
|
||||
m.b_fgu = decl_b(b, nm.f("fuse.gate_up"), RAD_BF16, { RL, 2 * g.n_ff });
|
||||
m.a_fffn.x = decl_b(b, nm.f("fuse.ffn"), RAD_BF16, { RL, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_fffn.declare_qs(b, nm, g, "fuse.ffn", g.n_ff, RL));
|
||||
/* The feed-forward product's scale group is its reader's, the first block's down projection,
|
||||
* which a recipe may keep narrower than the other linears: the fusion's 6912-wide product is
|
||||
* 3456 a rank at two, which whole 128s tile and whole 256s do not (krea-2-iq8r.recipe). The
|
||||
* probe maps the weight through the block's own LinearFP8, which then does not map it again;
|
||||
* the resizes here keep the blocks the loops below declare. */
|
||||
const int nlw = (int)rad_meta_geti(meta, "transformer.num_layerwise_text_blocks", 2);
|
||||
const int nrf = (int)rad_meta_geti(meta, "transformer.num_refiner_text_blocks", 2);
|
||||
m.lw.resize((size_t)nlw);
|
||||
m.rf.resize((size_t)nrf);
|
||||
int64_t ffn_g8 = m.g8;
|
||||
if (m.i8 && nlw + nrf > 0) {
|
||||
LinearFP8& d0 = nlw > 0 ? m.lw[0].down : m.rf[0].down;
|
||||
RAD_ARCH_TRY(d0.probe(b, nm, g, nm.f("fuse.0.ffn_down"),
|
||||
{ nm.ckpt("transformer.text_fusion.%s.0.ff.down.weight",
|
||||
nlw > 0 ? "layerwise_blocks" : "refiner_blocks") }));
|
||||
ffn_g8 = d0.probed_g8;
|
||||
}
|
||||
RAD_ARCH_TRY(m.a_fffn.declare_pair(b, nm, g, "fuse.ffn", g.n_ff, RL, m.i8, ffn_g8,
|
||||
"gated_had_quant_i8g"));
|
||||
m.b_fcu = decl_b(b, nm.f("fuse.cu"), RAD_I32, { kCondRows + 1 });
|
||||
m.b_ft = decl_b(b, nm.f("fuse.out"), RAD_BF16, { kCondRows, D });
|
||||
|
||||
@@ -628,10 +681,6 @@ static int declare_fusion(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_INT("step", kNTaps)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { m.b_fcu });
|
||||
const int nlw = (int)rad_meta_geti(meta, "transformer.num_layerwise_text_blocks", 2);
|
||||
const int nrf = (int)rad_meta_geti(meta, "transformer.num_refiner_text_blocks", 2);
|
||||
m.lw.resize((size_t)nlw);
|
||||
m.rf.resize((size_t)nrf);
|
||||
for (int i = 0; i < nlw; ++i) {
|
||||
RAD_ARCH_TRY(declare_fuse_block(b, m, m.lw[(size_t)i],
|
||||
nm.f("transformer.text_fusion.layerwise_blocks.%d", i),
|
||||
@@ -645,7 +694,7 @@ static int declare_fusion(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
* served bf16 as diffusers runs them: a recipe casts them. */
|
||||
if (weight_codes_dtype(b, "fuse.mix.weight", RAD_BF16) != RAD_BF16) {
|
||||
fprintf(stderr, "radiance: krea2: 'fuse.mix.weight' is stored %s; convert with "
|
||||
"data/recipes/krea-2-bf16.recipe or krea-2-fp8.recipe, which cast the "
|
||||
"data/recipes/krea-2-bf16.recipe or krea-2-iq8r.recipe, which cast the "
|
||||
"release's f32 tensors\n",
|
||||
rad_dtype_name(weight_codes_dtype(b, "fuse.mix.weight", RAD_BF16)));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -789,15 +838,18 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
|
||||
/* ---- the blocks */
|
||||
m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D });
|
||||
RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D));
|
||||
RAD_ARCH_TRY(m.a_hm.declare_pair(b, nm, g, "dit.hm", D, 0, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, qd + 2 * kvd });
|
||||
m.b_g = decl_b(b, nm.f("dit.gate"), RAD_BF16, { T, qd });
|
||||
m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd });
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_pair(b, nm, g, "dit.attn", qd, 0, m.i8, m.g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_ao = decl_b(b, nm.f("dit.ao"), RAD_BF16, { T, D });
|
||||
m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_pair(b, nm, g, "dit.ffn", g.n_ff, 0, m.i8, m.g8,
|
||||
"gated_had_quant_i8g"));
|
||||
|
||||
const std::vector<double> ax = meta_list(meta, "transformer.axes_dims_rope");
|
||||
const int64_t a0 = ax.size() == 3 ? (int64_t)ax[0] : 32, a1 = ax.size() == 3 ? (int64_t)ax[1] : 48,
|
||||
@@ -811,12 +863,15 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
const double theta = rad_meta_getf(meta, "transformer.rope_theta", 1000.0);
|
||||
|
||||
/* The modulated norm, gated by the branch before it when `gated`, into the next linear's
|
||||
* input (codes for fp8, the bf16 plane for bf16). */
|
||||
* input: codes for fp8 and, where the rotating twin is served, for rotated int8; the bf16
|
||||
* plane for bf16 and for rotated int8 without the twin, whose codes the rotating quantiser
|
||||
* then takes from it (DitLayer::q_n1 / q_n2). */
|
||||
m.norm_i8 = m.i8 && m.a_hm.q8_fed && rad_op_declared(b, "rms_mod_had_quant_i8g") != 0;
|
||||
auto mod_norm = [&](rad_weight w, bool gated) {
|
||||
const bool q = !g.w_bf16;
|
||||
rad_op op = q ? RAD_OP(b, "rms_mod_quant_fp8",
|
||||
const bool q = (!g.w_bf16 && !m.i8) || m.norm_i8;
|
||||
rad_op op = q ? RAD_OP(b, m.norm_i8 ? "rms_mod_had_quant_i8g" : "rms_mod_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_INT("group", m.norm_i8 ? m.g8 : RAD_FP8_BLOCK),
|
||||
RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("wadd", 1.0), RAD_INT("norm_once", 1)),
|
||||
RAD_WEIGHTS(w))
|
||||
@@ -827,7 +882,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_WEIGHTS(w));
|
||||
if (!op) return op;
|
||||
rad_buf rd[3] = { m.b_mods, m.b_h, m.b_ao };
|
||||
rad_buf wq[3] = { m.a_hm.q, m.a_hm.s, m.b_h };
|
||||
rad_buf wq[3] = { m.a_hm.cq(), m.a_hm.cs(), m.b_h };
|
||||
rad_buf wb[2] = { m.a_hm.x, m.b_h };
|
||||
rad_op_reads(b, op, rd, gated ? 3 : 2);
|
||||
if (q) rad_op_writes(b, op, wq, 3);
|
||||
@@ -866,6 +921,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
if (!B.w_tab || !B.op_tab) return RAD_E_INVAL;
|
||||
}
|
||||
B.op_n1 = mod_norm(B.w_n1, l > 0);
|
||||
if (m.i8 && m.a_hm.q8_fed && !m.norm_i8) RAD_ARCH_TRY(B.q_n1.declare(b, g, m.a_hm, D));
|
||||
if (l == 0) B.qkv = m.qkv0;
|
||||
RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), qd + 2 * kvd, D,
|
||||
RAD_SHARD_ROW, grp_layer(grp),
|
||||
@@ -893,13 +949,14 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)hd))),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_qkv }, { m.a_attn.x });
|
||||
B.op_gq = out_gate(b, g, T, qd, m.b_g, m.a_attn, &B.op_sig);
|
||||
B.op_gq = out_gate(b, g, T, qd, m.b_g, m.a_attn, &B.op_sig, m.i8, &m.gate_i8);
|
||||
if (B.op_sig) RAD_ARCH_TRY(B.q_attn.declare(b, g, m.a_attn, qd));
|
||||
RAD_ARCH_TRY(B.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_COL,
|
||||
grp_layer(grp), { nm.ckpt("%s.attn.to_out.0.weight", pre) },
|
||||
m.a_attn, m.b_ao));
|
||||
B.op_ar1 = all_reduce(b, g, m.b_ao, T);
|
||||
B.op_n2 = mod_norm(B.w_n2, true);
|
||||
if (m.i8 && m.a_hm.q8_fed && !m.norm_i8) RAD_ARCH_TRY(B.q_n2.declare(b, g, m.a_hm, D));
|
||||
RAD_ARCH_TRY(B.gate_up.declare(b, nm, g, nm.f("%s.ffn_gate_up", dn), 2 * g.n_ff, D,
|
||||
RAD_SHARD_ROW, grp_layer(grp),
|
||||
{ nm.ckpt("%s.ff.gate.weight", pre),
|
||||
@@ -1090,8 +1147,9 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -1150,9 +1208,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"transformer.transformer_blocks.0.attn.to_k.weight",
|
||||
"transformer.transformer_blocks.0.attn.to_v.weight" }));
|
||||
RadEncoding e{};
|
||||
const bool plain = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e) &&
|
||||
rad_enc_is(&e, "plain");
|
||||
const bool known = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e);
|
||||
const bool plain = known && rad_enc_is(&e, "plain");
|
||||
gd.w_bf16 = gf.w_bf16 = m.gt.w_bf16 = plain;
|
||||
/* Or rotated int8 (IQ8R): the activations then carry int8 codes at the weights' scale
|
||||
* group in place of the E4M3 pair (ActFP8::declare_pair). */
|
||||
m.i8 = known && (linear_is_w8h(e) || linear_is_wnh(e));
|
||||
if (m.i8) m.g8 = linear_w8h_group(e);
|
||||
}
|
||||
|
||||
/* ---- the per-image state, the conditioning store, and in issue order the language model,
|
||||
@@ -1220,7 +1282,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.gt.rank, m.gt.world, m.turbo ? " Turbo" : "", kTaps[kNTaps - 1],
|
||||
(long long)m.gt.n_layer, m.lw.size(), m.rf.size(), (long long)gd.n_layer,
|
||||
(long long)gd.n_head, (long long)gd.n_head_kv, (long long)gd.n_ff,
|
||||
gd.w_bf16 ? "bf16" : "block-fp8");
|
||||
gd.w_bf16 ? "bf16" : m.i8 ? "rotated int8" : "block-fp8");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1284,6 +1346,9 @@ static void step_fuse(RadCtx* c, const Model& m, const FuseBlock& F, int64_t r0,
|
||||
RAD_ISSUE_N(c, F.op_sig, R, brows(m.b_fg, R), brows(m.b_fg, R));
|
||||
RAD_ISSUE_N(c, F.op_gq, R, brows(m.a_fattn.x, R), brows(m.b_fg, R), brows(m.a_fattn.x, R));
|
||||
F.q_attn.step(c, R);
|
||||
} else if (m.fgate_i8) {
|
||||
RAD_ISSUE_N(c, F.op_gq, R, brows(m.b_fg, R), brows(m.a_fattn.x, R),
|
||||
brows(m.a_fattn.cq(), R), brows(m.a_fattn.cs(), R), brows(m.a_fattn.x, R));
|
||||
} else {
|
||||
const int64_t rh = R * (qd / hd), nb = hd / RAD_FP8_BLOCK;
|
||||
RAD_ISSUE_N(c, F.op_gq, rh, RAD_P_T2(rad_buf_ptr(c, m.b_fg), RAD_BF16, rh, hd),
|
||||
@@ -1368,7 +1433,7 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const RadOperand pos = praw2(G->rope_f, RAD_F32, 4, N);
|
||||
auto mod = [&](int64_t l, int k, int width) { return bcol_at(m.b_mods, 0, W, (6 * l + k) * D,
|
||||
width * D, S); };
|
||||
const bool q8 = !g.w_bf16;
|
||||
const bool q8 = (!g.w_bf16 && !m.i8) || m.norm_i8;
|
||||
for (int64_t l = 0; l < L; ++l) {
|
||||
const DitLayer& B = m.dit[(size_t)l];
|
||||
/* The block's modulation: the shared projection plus its own table, into its columns. */
|
||||
@@ -1377,11 +1442,13 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
if (q8)
|
||||
RAD_ISSUE_N(c, B.op_n1, N, l > 0 ? brows(m.b_ao, N) : RAD_NONE,
|
||||
l > 0 ? mod(l - 1, 5, 1) : RAD_NONE, mod(l, 0, 2), RAD_W(B.w_n1), cu,
|
||||
brows(m.b_h, N), brows(m.a_hm.q, N), brows(m.a_hm.s, N), RAD_NONE);
|
||||
brows(m.b_h, N), brows(m.a_hm.cq(), N), brows(m.a_hm.cs(), N),
|
||||
RAD_NONE);
|
||||
else
|
||||
RAD_ISSUE_N(c, B.op_n1, N, l > 0 ? brows(m.b_ao, N) : RAD_NONE,
|
||||
l > 0 ? mod(l - 1, 5, 1) : RAD_NONE, mod(l, 0, 2), RAD_W(B.w_n1), cu,
|
||||
brows(m.b_h, N), brows(m.a_hm.x, N));
|
||||
B.q_n1.step(c, N);
|
||||
B.qkv.step(c, m.a_hm, m.b_qkv, N);
|
||||
B.gate.step(c, m.a_hm, m.b_g, N);
|
||||
RAD_ISSUE_N(c, B.op_qkr, N, brows(m.b_qkv, N), pos, RAD_W(B.w_qn), RAD_W(B.w_kn));
|
||||
@@ -1391,6 +1458,9 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
RAD_ISSUE_N(c, B.op_sig, N, brows(m.b_g, N), brows(m.b_g, N));
|
||||
RAD_ISSUE_N(c, B.op_gq, N, brows(m.a_attn.x, N), brows(m.b_g, N), brows(m.a_attn.x, N));
|
||||
B.q_attn.step(c, N);
|
||||
} else if (m.gate_i8) {
|
||||
RAD_ISSUE_N(c, B.op_gq, N, brows(m.b_g, N), brows(m.a_attn.x, N),
|
||||
brows(m.a_attn.cq(), N), brows(m.a_attn.cs(), N), brows(m.a_attn.x, N));
|
||||
} else {
|
||||
const int64_t rh = N * (qd / hd), nb = hd / RAD_FP8_BLOCK;
|
||||
RAD_ISSUE_N(c, B.op_gq, rh, RAD_P_T2(rad_buf_ptr(c, m.b_g), RAD_BF16, rh, hd),
|
||||
@@ -1403,10 +1473,12 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
if (B.op_ar1) RAD_ISSUE_N(c, B.op_ar1, N * D, brows(m.b_ao, N), RAD_NONE);
|
||||
if (q8)
|
||||
RAD_ISSUE_N(c, B.op_n2, N, brows(m.b_ao, N), mod(l, 2, 1), mod(l, 3, 2), RAD_W(B.w_n2),
|
||||
cu, brows(m.b_h, N), brows(m.a_hm.q, N), brows(m.a_hm.s, N), RAD_NONE);
|
||||
cu, brows(m.b_h, N), brows(m.a_hm.cq(), N), brows(m.a_hm.cs(), N),
|
||||
RAD_NONE);
|
||||
else
|
||||
RAD_ISSUE_N(c, B.op_n2, N, brows(m.b_ao, N), mod(l, 2, 1), mod(l, 3, 2), RAD_W(B.w_n2),
|
||||
cu, brows(m.b_h, N), brows(m.a_hm.x, N));
|
||||
B.q_n2.step(c, N);
|
||||
B.gate_up.step(c, m.a_hm, m.b_gu, N);
|
||||
B.gq.step(c, m.b_gu, N);
|
||||
B.down.step(c, m.a_ffn, m.b_ao, N);
|
||||
@@ -1467,7 +1539,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->gen_b) {
|
||||
rad_step_fail(c, "krea2 is an image generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1493,6 +1565,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(krea2)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(krea2, "krea2", "", "0.1.0",
|
||||
"Krea 2 / Krea 2 Turbo: Qwen3-VL-4B taps through a text-fusion transformer, a 12.9B "
|
||||
"single-stream diffusion transformer over the joint text and image, and Wan 2.1's "
|
||||
|
||||
+7
-4
@@ -74,7 +74,7 @@ struct Model {
|
||||
std::vector<HeadLayer> head;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
@@ -115,7 +115,8 @@ static int sliding_layers(const RadModelMeta* meta, int64_t n_layer, std::vector
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (ctx->world_size > 1) {
|
||||
fprintf(stderr, "radiance: laya runs on one card (--tp 1); the largest checkpoint is "
|
||||
"0.4B parameters\n");
|
||||
@@ -124,7 +125,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RadArchProbe pr{};
|
||||
RAD_ARCH_TRY(probe(meta, &pr));
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
@@ -409,7 +410,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd, F = m.F;
|
||||
const int64_t P = RAD_LAYA_POOLED;
|
||||
@@ -523,6 +524,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
|
||||
} /* namespace laya */
|
||||
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(laya, "laya", "", "0.1.0",
|
||||
"Convai Innovations' Laya (laya, laya-typed-decisions, laya-multilingual): a "
|
||||
"ModernBERT encoder and a decision head scoring each option at its [MASK], one "
|
||||
|
||||
@@ -28,8 +28,9 @@
|
||||
* block E4M3 (`codes=fp8_e4m3 block=128x128 scale=bf16`) is `gemm_nt_q` at fp8a8 over the
|
||||
* activation quantised per 128 columns (one quant_act_fp8 per activation, shared by the linears
|
||||
* that read it); int8 (`codes=i8 group=128 scale=bf16`) is `gemm_nt_q` at i8a8, each linear
|
||||
* quantising its input. The trunk's format is read off layer 0's down projection and every linear
|
||||
* must match it. The convolution, the norms and attention stay bf16; the lm_head is read at its
|
||||
* quantising its input, and IQ8R (rotated int8 with a scale per 256 of K,
|
||||
* data/recipes/d1-3b-iq8r.recipe) the same at i8a8h with the activation pairs at the weights'
|
||||
* group. The trunk's format is read off layer 0's first linear and every linear must match it. The convolution, the norms and attention stay bf16; the lm_head is read at its
|
||||
* stored codes (bf16, or E4M3 / int8 where a recipe made it so; logits_gemm_fp8 / _i8). At d1-3B
|
||||
* the linears are 5.8 of the 6.3 GB a token reads, so 8-bit codes nearly halve decode and short
|
||||
* prefill, both bound by that read.
|
||||
@@ -106,6 +107,8 @@ struct Model {
|
||||
/* The trunk's format, read off layer 0's first linear. `fused`: the fp8 trunk's fused
|
||||
* producers (see the head of the file). */
|
||||
bool q_fp8 = false, q_i8 = false, fused = false;
|
||||
/* An int8 trunk's scale group along K, which its activation pairs share (ActFP8::g8). */
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
|
||||
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
|
||||
rad_op op_embed = 0, op_gather = 0, op_final_norm = 0, op_logits = 0;
|
||||
@@ -118,7 +121,7 @@ struct Model {
|
||||
MediaRows mrows{};
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* A text_config key first, then the top level: a VL checkpoint nests the text model's settings
|
||||
* and a text checkpoint does not. */
|
||||
@@ -166,7 +169,9 @@ static int read_schedule(const RadModelMeta* m, int64_t n_layer, std::vector<Lay
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (ctx->world_size > 1) {
|
||||
fprintf(stderr, "radiance: lfm2_bf16 serves one rank; run it with --tp 1\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -178,7 +183,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
Names& nm = m.nm;
|
||||
@@ -290,14 +295,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
enc.plane[0].dtype == RAD_BF16);
|
||||
g.w_bf16 = plain;
|
||||
m.q_i8 = !plain && L0.in.probed_i8;
|
||||
if (m.q_i8) m.g8 = L0.in.probed_g8;
|
||||
m.q_fp8 = !plain && !m.q_i8;
|
||||
m.fused = m.q_fp8;
|
||||
}
|
||||
if (m.q_i8 && (g.n_embd % m.g8 || g.q_dim() % m.g8 || g.n_ff % m.g8)) {
|
||||
fprintf(stderr, "radiance: lfm2: the int8 trunk keeps one scale a %lld of K, which does not "
|
||||
"divide this model's widths (hidden %lld, attention %lld, feed-forward "
|
||||
"%lld)\n",
|
||||
(long long)m.g8, (long long)g.n_embd, (long long)g.q_dim(), (long long)g.n_ff);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.a_h.x = m.b_h; m.a_attn.x = m.b_attn; m.a_conv.x = m.b_conv_out; m.a_ffn.x = m.b_ffn;
|
||||
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.q_i8));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", g.q_dim(), 0, m.q_i8));
|
||||
RAD_ARCH_TRY(m.a_conv.declare_qs(b, nm, g, "conv_out", g.n_embd, 0, m.q_i8));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.q_i8));
|
||||
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.q_i8, true, m.g8));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", g.q_dim(), 0, m.q_i8, true, m.g8));
|
||||
RAD_ARCH_TRY(m.a_conv.declare_qs(b, nm, g, "conv_out", g.n_embd, 0, m.q_i8, true, m.g8));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.q_i8, true, m.g8));
|
||||
/* An E4M3 activation is quantised once by the model and read by every linear on it; an int8
|
||||
* linear quantises its own input (LinearFP8::op_q), and a bf16 one reads the bf16 plane. */
|
||||
auto quant = [&](QuantFP8& q, const ActFP8& a, int64_t n) {
|
||||
@@ -471,7 +484,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
ms.up = nm.ckpt(ffn_fmt, pre, l, "w3.weight");
|
||||
ms.down = nm.ckpt(ffn_fmt, pre, l, "w2.weight");
|
||||
const bool last = l + 1 == (int)m.layers.size();
|
||||
/* The whole prompt in the fold: gemm_nt_q_gated_wide serves every M, so a prefill
|
||||
/* The whole prompt in the fold (`wide_fold`): its row serves every M, so a prefill
|
||||
* chunk does not fall back to the pair past 64 rows. */
|
||||
RAD_ARCH_TRY(L.mlp8.declare(b, nm, g, l, mw, ms, /*fold=*/true, /*add_out=*/last,
|
||||
0, false, 0, /*wide_fold=*/true));
|
||||
@@ -572,7 +585,7 @@ static void conv_step(const Model& m, const Layer& L, RadCtx* c, const RadBatch*
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
if (batch->draft_pass || batch->spec_parent ||
|
||||
(!m.media && (batch->enc || batch->n_mm_rows > 0))) {
|
||||
@@ -663,9 +676,23 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Chained launches pay on the plain-bf16 trunk: its GEMMs, norms and elementwise kernels have
|
||||
* chained forms (libr4d's rad_kernel_chain); the head norms, the rotary and the convolution keep
|
||||
* their plain rows, with which the long GEMMs between them run faster. The 3B text model on one
|
||||
* R9700, ms a decode step unchained / chained: 12.14 / 11.31 at one sequence and 12.54 / 11.60 at
|
||||
* four. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace lfm2_bf16 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PROBE(lfm2_bf16)
|
||||
RAD_ARCH_PLUGIN(lfm2_bf16, "lfm2", "", "0.2.0",
|
||||
"LiquidAI LFM2 / LFM2-VL, bf16, or with block-fp8 or int8 linears from a recipe: "
|
||||
"short gated convolutions and GQA attention in the checkpoint's own schedule, one "
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/* llama_dense_fp8 -- arch/llama_fp8 over a bf16 checkpoint quantised by rad-convert.
|
||||
*
|
||||
* For MiniCPM5-2B, which OpenBMB publishes only in bf16. The recipe
|
||||
* data/recipes/minicpm5-2b-dspark.recipe takes one amax per 128x128 block with scale = amax/448
|
||||
* rounded to bf16, so the container matches what a checkpoint shipped in fp8 would hold and every
|
||||
* kernel, layout and placement decision downstream is the same.
|
||||
* data/recipes/minicpm5-2b-iq8r.recipe stores every linear as rotated int8 with a scale per
|
||||
* (row, 256 of K); data/recipes/minicpm5-2b-bf16-dspark.recipe keeps the model's own linears bf16
|
||||
* and quantises only the merged drafter.
|
||||
*
|
||||
* A separate .so because the selection key is the (architecture, quantisation) pair (spec §2.4),
|
||||
* and a dense checkpoint's descriptor is empty. Everything else is arch/llama_fp8/llama_fp8.cpp;
|
||||
|
||||
+112
-28
@@ -14,10 +14,10 @@
|
||||
*
|
||||
* llama_fp8 quant "fp8_e4m3" the checkpoint holds E4M3 codes and a `weight_scale_inv`
|
||||
* plane per linear, as the engine reads them.
|
||||
* llama_dense_fp8 quant "" the checkpoint is dense bf16, and a recipe quantises each
|
||||
* linear to those two planes at convert time
|
||||
* (data/recipes/minicpm5-2b-dspark.recipe: amax per 128x128
|
||||
* block, scale = amax/448 rounded to bf16).
|
||||
* llama_dense_fp8 quant "" the checkpoint is dense bf16, and a recipe quantises its
|
||||
* linears at convert time
|
||||
* (data/recipes/minicpm5-2b-iq8r.recipe: rotated int8, a
|
||||
* scale per (row, 256 of K)) or leaves them bf16.
|
||||
*
|
||||
* MiniCPM5-2B needs the second, since it is published only in bf16. Both builds declare the same
|
||||
* weights and ops, so nothing downstream can tell which one ran.
|
||||
@@ -28,8 +28,17 @@
|
||||
* BF16, no plane every norm and the embedding
|
||||
*
|
||||
* The lm_head is declared at whatever the model holds: bf16 as llama checkpoints ship it, or block
|
||||
* fp8 where a recipe quantised it (the widest GEMM at half the bytes), and the logits kernel for
|
||||
* that encoding is selected. Both vocabulary edges are row-sharded with the vocabulary.
|
||||
* fp8 or int8 where a recipe quantised it (the widest GEMM at half the bytes), and the logits
|
||||
* kernel for that encoding is selected. Both vocabulary edges are row-sharded with the vocabulary.
|
||||
*
|
||||
* ============================== AN INT8 TRUNK ==============================
|
||||
*
|
||||
* The dense build also serves a recipe that makes the linears rotated int8 (IQ8R:
|
||||
* data/recipes/minicpm5-2b-iq8r.recipe). Each is a LinearFP8, which reads what the container holds,
|
||||
* and declare() learns the format from the first layer's q|k|v before it declares the activations:
|
||||
* they then carry int8 codes with one scale per (token, scale group) in place of the E4M3 pair,
|
||||
* written by the norms, the gated product and the attention output's quantiser. The DSpark
|
||||
* drafter's linears follow their own encodings the same way (rad_block_dspark.h).
|
||||
*/
|
||||
#ifndef LLAMA_DENSE_SRC
|
||||
#define LLAMA_DENSE_SRC 0
|
||||
@@ -67,6 +76,12 @@ struct Model {
|
||||
|
||||
rad_kvgroup kv_full = 0;
|
||||
|
||||
/* The trunk's linears are rotated int8 (IQ8R, or the 128-group int8 before it), read from the
|
||||
* first layer's fused q|k|v: the activations then carry int8 code pairs at `trunk_g8` columns
|
||||
* a scale, written by the norms, the gated product and the attention output's quantiser. */
|
||||
bool trunk_i8 = false;
|
||||
int64_t trunk_g8 = RAD_FP8_BLOCK;
|
||||
|
||||
rad_buf b_x = 0, b_hout = 0, b_logits = 0;
|
||||
ActFP8 a_h{};
|
||||
rad_buf b_qkv = 0;
|
||||
@@ -101,7 +116,7 @@ struct Model {
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* The quantisation descriptor is the selection key but is checked anyway: `--arch` can override
|
||||
* the architecture id at convert time, and a plugin handed the wrong checkpoint should say which
|
||||
@@ -205,6 +220,13 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* The drafter's own stored format, which decides its activation pairs below. */
|
||||
RAD_ARCH_TRY(Dspark::probe_i8(b, nm, "draft", &dc.act_i8, &dc.act_g8));
|
||||
dc.fc_mapped = true;
|
||||
const uint32_t dqt = dc.act_i8 ? RAD_I8 : RAD_F8E4M3;
|
||||
const int64_t dqg = dc.act_i8 ? dc.act_g8 : (int64_t)RAD_FP8_BLOCK;
|
||||
auto dqcols = [dqg](int64_t n) { return (n + dqg - 1) / dqg; };
|
||||
|
||||
/* DSpark's published config sets `sliding_window: null`, so this is normally a full cache. */
|
||||
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, dc.window, base_layer, &m.kv_draft));
|
||||
|
||||
@@ -223,28 +245,35 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
dw.c = decl_b(b, nm.f("ds_c"), dg.act_dtype, {dg.max_tok, dg.n_embd});
|
||||
dw.ck = decl_b(b, nm.f("ds_ck"), dg.act_dtype, {dg.max_tok, kvd});
|
||||
dw.cv = decl_b(b, nm.f("ds_cv"), dg.act_dtype, {dg.max_tok, kvd});
|
||||
/* FP8 copies for the context pass. `srcq` is the largest (20 MiB at a 2048-token chunk, five
|
||||
* taps, hidden 2048) and halves the bytes of the context pass's dominant GEMM. */
|
||||
dw.srcq = decl_b(b, nm.f("ds_srcq"), RAD_F8E4M3, {dg.max_tok, dc.n_taps * dg.n_embd});
|
||||
dw.srcs = decl_b(b, nm.f("ds_srcs"), RAD_F32,
|
||||
{dg.max_tok, fp8_blocks(dc.n_taps * dg.n_embd)});
|
||||
dw.cq = decl_b(b, nm.f("ds_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd});
|
||||
dw.cs = decl_b(b, nm.f("ds_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)});
|
||||
/* Eight-bit copies for the context pass, at the code type and scale group the drafter's
|
||||
* linears read. `srcq` is the largest (20 MiB at a 2048-token chunk, five taps, hidden 2048)
|
||||
* and halves the bytes of the context pass's dominant GEMM. */
|
||||
if (dc.act_i8 && (qd % dqg || dg.n_embd % dqg || dg.n_ff % dqg)) {
|
||||
fprintf(stderr, "radiance: the DSpark drafter's int8 linears keep one scale a %lld of K, "
|
||||
"which does not divide its widths (hidden %lld, attention %lld, "
|
||||
"feed-forward %lld)\n",
|
||||
(long long)dqg, (long long)dg.n_embd, (long long)qd, (long long)dg.n_ff);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
dw.srcq = decl_b(b, nm.f("ds_srcq"), dqt, {dg.max_tok, dc.n_taps * dg.n_embd});
|
||||
dw.srcs = decl_b(b, nm.f("ds_srcs"), RAD_F32, {dg.max_tok, dqcols(dc.n_taps * dg.n_embd)});
|
||||
dw.cq = decl_b(b, nm.f("ds_cq"), dqt, {dg.max_tok, dg.n_embd});
|
||||
dw.cs = decl_b(b, nm.f("ds_cs"), RAD_F32, {dg.max_tok, dqcols(dg.n_embd)});
|
||||
|
||||
dw.x = decl_b(b, nm.f("ds_x"), dg.act_dtype, {qr, dg.n_embd});
|
||||
dw.h.x = decl_b(b, nm.f("ds_h"), dg.act_dtype, {qr, dg.n_embd});
|
||||
dw.h.q = decl_b(b, nm.f("ds_h.q"), RAD_F8E4M3, {qr, dg.n_embd});
|
||||
dw.h.s = decl_b(b, nm.f("ds_h.s"), RAD_F32, {qr, fp8_blocks(dg.n_embd)});
|
||||
dw.h.q = decl_b(b, nm.f("ds_h.q"), dqt, {qr, dg.n_embd});
|
||||
dw.h.s = decl_b(b, nm.f("ds_h.s"), RAD_F32, {qr, dqcols(dg.n_embd)});
|
||||
dw.q = decl_b(b, nm.f("ds_q"), dg.act_dtype, {qr, qd});
|
||||
dw.k = decl_b(b, nm.f("ds_k"), dg.act_dtype, {qr, kvd});
|
||||
dw.v = decl_b(b, nm.f("ds_v"), dg.act_dtype, {qr, kvd});
|
||||
dw.attn.x = decl_b(b, nm.f("ds_attn"), dg.act_dtype, {qr, qd});
|
||||
dw.attn.q = decl_b(b, nm.f("ds_attn.q"), RAD_F8E4M3, {qr, qd});
|
||||
dw.attn.s = decl_b(b, nm.f("ds_attn.s"), RAD_F32, {qr, fp8_blocks(qd)});
|
||||
dw.attn.q = decl_b(b, nm.f("ds_attn.q"), dqt, {qr, qd});
|
||||
dw.attn.s = decl_b(b, nm.f("ds_attn.s"), RAD_F32, {qr, dqcols(qd)});
|
||||
dw.gate_up = decl_b(b, nm.f("ds_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff});
|
||||
dw.ffn.x = decl_b(b, nm.f("ds_ffn"), dg.act_dtype, {qr, dg.n_ff});
|
||||
dw.ffn.q = decl_b(b, nm.f("ds_ffn.q"), RAD_F8E4M3, {qr, dg.n_ff});
|
||||
dw.ffn.s = decl_b(b, nm.f("ds_ffn.s"), RAD_F32, {qr, fp8_blocks(dg.n_ff)});
|
||||
dw.ffn.q = decl_b(b, nm.f("ds_ffn.q"), dqt, {qr, dg.n_ff});
|
||||
dw.ffn.s = decl_b(b, nm.f("ds_ffn.s"), RAD_F32, {qr, dqcols(dg.n_ff)});
|
||||
|
||||
dw.sel_h = decl_b(b, nm.f("ds_selh"), dg.act_dtype, {sr, dg.n_embd});
|
||||
dw.dq = decl_b(b, nm.f("ds_dq"), RAD_I8, {sr, dg.n_embd});
|
||||
@@ -310,9 +339,10 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -346,18 +376,58 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
|
||||
g.kv_dtype = rad_dtype_name(fd.dtype);
|
||||
|
||||
/* ---- activations. */
|
||||
/* ---- the trunk's stored format, read from the first layer's fused q|k|v before any
|
||||
* activation is declared: only an int8 trunk's activations carry an int8 code pair. The probe
|
||||
* maps the weight through the layer's own LinearFP8, which then does not map it again; the
|
||||
* resize before the layer loop keeps the layers sized here. */
|
||||
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
|
||||
m.layers.resize((size_t)m.n_main);
|
||||
if (m.n_main > 0) {
|
||||
const char* pre = "model.layers";
|
||||
RAD_ARCH_TRY(m.layers[0].attn.qkv.probe(
|
||||
b, nm, g, nm.f("blk.0.attn_qkv"),
|
||||
{ nm.ckpt("%s.0.self_attn.q_proj.weight", pre),
|
||||
nm.ckpt("%s.0.self_attn.k_proj.weight", pre),
|
||||
nm.ckpt("%s.0.self_attn.v_proj.weight", pre) }));
|
||||
RadEncoding enc{};
|
||||
m.trunk_i8 = weight_enc(b, nm.f("blk.0.attn_qkv.weight"), &enc) &&
|
||||
(linear_is_w8h(enc) || linear_is_wnh(enc));
|
||||
if (m.trunk_i8) m.trunk_g8 = linear_w8h_group(enc);
|
||||
}
|
||||
if (m.trunk_i8 && (g.n_embd % m.trunk_g8 || q_dim % m.trunk_g8 || g.n_ff % m.trunk_g8)) {
|
||||
fprintf(stderr, "radiance: llama: the int8 trunk keeps one scale a %lld of K, which does "
|
||||
"not divide this rank's widths (hidden %lld, attention %lld, "
|
||||
"feed-forward %lld)\n",
|
||||
(long long)m.trunk_g8, (long long)g.n_embd, (long long)q_dim, (long long)g.n_ff);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* ---- activations. An int8 trunk's quantisers sit in their producers where the kernels serve
|
||||
* the rotated forms: the norms write had_quant_act_i8g's codes for q|k|v and gate|up, the
|
||||
* gated product for the down projection, and the attention output's own quantiser for the
|
||||
* out-projection, so no projection declares one and the activation carries no E4M3 pair.
|
||||
* Where a form is not declared (the CPU kernels), the producer keeps its E4M3 pair and each
|
||||
* projection quantises its own input from the bf16 plane. */
|
||||
if (m.trunk_i8) {
|
||||
if (rad_op_declared(b, "rmsnorm_had_quant_i8g") &&
|
||||
(g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g")))
|
||||
m.a_h.q8_fed = m.a_h.q8_rot = true;
|
||||
if (rad_op_declared(b, "gated_had_quant_i8g")) m.a_ffn.q8_fed = m.a_ffn.q8_rot = true;
|
||||
if (rad_op_declared(b, "had_quant_act_i8g")) m.a_attn.q8_fed = m.a_attn.q8_rot = true;
|
||||
}
|
||||
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
m.a_h.x = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
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.a_h.q8_fed,
|
||||
m.trunk_g8));
|
||||
m.b_qkv = decl_b(b, nm.f("attn_qkv"), g.act_dtype, {g.max_tok, q_dim + 2 * kv_dim});
|
||||
m.b_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, q_dim});
|
||||
m.a_attn.x = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, q_dim});
|
||||
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,
|
||||
!m.a_attn.q8_fed, m.trunk_g8));
|
||||
m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff});
|
||||
m.a_ffn.x = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff});
|
||||
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, !m.a_ffn.q8_fed,
|
||||
m.trunk_g8));
|
||||
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
|
||||
|
||||
/* ---- the drafter's taps, only when the container carries a drafter that reads them and the
|
||||
@@ -431,7 +501,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
MlpFP8::Wire mw{};
|
||||
mw.x = m.b_x; mw.h = m.a_h; mw.gate_up = m.b_gate_up; mw.ffn = m.a_ffn;
|
||||
|
||||
m.layers.resize((size_t)m.n_main);
|
||||
for (int64_t l = 0; l < m.n_main; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
/* Residual fold and collective placement: rad_fp8.h, layer_fold. */
|
||||
@@ -496,6 +565,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
(long long)g.head_dim, (long long)m.n_rot, (long long)g.n_ff,
|
||||
(long long)g.vocab_off, (long long)(g.vocab_off + g.n_vocab));
|
||||
#if LLAMA_DENSE_SRC
|
||||
if (m.trunk_i8)
|
||||
rad_note(b, "a dense bf16 checkpoint, every linear quantised by the recipe to rotated "
|
||||
"int8 with one scale a [1 x %lld] of K, read against int8 activations with a "
|
||||
"scale per (token, %lld)", (long long)m.trunk_g8, (long long)m.trunk_g8);
|
||||
else
|
||||
rad_note(b, "a dense bf16 checkpoint, every linear quantised by the recipe to E4M3 with a "
|
||||
"bf16 [N/%d,K/%d] scale plane (scale = block amax / 448, rounded to bf16)",
|
||||
RAD_FP8_BLOCK, RAD_FP8_BLOCK);
|
||||
@@ -523,7 +597,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
/* A drafter pass; the sign gives the kind. Positive is the query pass, proposing the whole
|
||||
* block at once; negative is the context pass, turning the tokens the trunk just committed
|
||||
* into the drafter's own K and V. Zero is a trunk step. */
|
||||
@@ -579,6 +653,14 @@ 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;
|
||||
#if LLAMA_DENSE_SRC
|
||||
/* Chained launches pay on an IQ8R trunk with and without its drafter: libr4d's
|
||||
* rad_kernel_chain holds the IQ8R decode rows. MiniCPM5-2B on one R9700, ms a decode step
|
||||
* unchained / chained: 5.57 / 5.17 at one sequence and 6.09 / 5.71 at eight without a drafter,
|
||||
* and with DSpark 7.32 / 6.87 at one and 8.15 / 7.92 at four. A block-fp8 trunk gains less
|
||||
* and loses nowhere: 5.45 / 5.40 and 5.92 / 5.89 without, 7.14 / 7.12 and 8.17 / 8.16 with. */
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
#endif
|
||||
const char* da = rad_meta_gets(meta, "draft.architectures", "");
|
||||
if (da && (std::strstr(da, "DSpark") || std::strstr(da, "DFlash"))) {
|
||||
const long long bs = rad_meta_geti(meta, "draft.block_size", 0);
|
||||
@@ -596,6 +678,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
/* One more level of expansion so `#NS` sees the expanded namespace. */
|
||||
#define LLAMA_PROBE_X(NS) RAD_ARCH_PROBE(NS)
|
||||
#define LLAMA_PLUGIN_X(NS, ...) RAD_ARCH_PLUGIN(NS, __VA_ARGS__)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
LLAMA_PROBE_X(LLAMA_NS)
|
||||
#if LLAMA_DENSE_SRC
|
||||
LLAMA_PLUGIN_X(LLAMA_NS, "llama", LLAMA_QUANT, "0.1.0",
|
||||
|
||||
+45
-28
@@ -58,7 +58,8 @@
|
||||
*
|
||||
* Every network computes in bf16, as the reference loads it; the latents, the guidance and the
|
||||
* sampler are f32. The text encoder's, the connectors' and the DiT's large linears are bf16 or
|
||||
* block fp8 as the container holds them (data/recipes/ltx-2.5-fp8.recipe); the vocoder runs in
|
||||
* rotated int8 as the container holds them (data/recipes/ltx-2.5-bf16.recipe,
|
||||
* ltx-2.5-iq8r.recipe), one kind a container; the vocoder runs in
|
||||
* f32 (its anti-aliased activation's kernels are f32), its log-mel input rounded where the
|
||||
* reference's bf16 one is.
|
||||
*
|
||||
@@ -182,8 +183,11 @@ static int64_t positions(const RadVideoGeom* g, float* pos, int64_t cap) {
|
||||
}
|
||||
|
||||
/* ================================================================== linears */
|
||||
/* An activation a linear reads: its bf16 plane and, for block-fp8 linears, its codes, which a
|
||||
* quantiser makes from the plane (QuantFP8). */
|
||||
/* An activation a linear reads: its bf16 plane and, for block-fp8 or rotated int8 linears, its
|
||||
* codes, which a quantiser makes from the plane (QuantFP8: E4M3, or had_quant_act_i8g's int8 at
|
||||
* the weights' scale group). Rows narrower than that group carry no codes: a bf16 linear reads
|
||||
* them (the latents' projections in). Where no library serves the rotating quantiser, each int8
|
||||
* linear quantises its own input and this declares none. */
|
||||
struct Act {
|
||||
ActFP8 a{};
|
||||
QuantFP8 q{};
|
||||
@@ -196,27 +200,30 @@ struct Act {
|
||||
if (!a.x) return RAD_E_INVAL;
|
||||
Geom gg = g;
|
||||
gg.max_tok = rows;
|
||||
RAD_ARCH_TRY(a.declare_qs(b, nm, gg, name, width, rows));
|
||||
if (g.w_i8h && width % g.w_i8_group) return RAD_OK;
|
||||
RAD_ARCH_TRY(a.declare_pair(b, nm, gg, name, width, rows, g.w_i8h, g.w_i8_group,
|
||||
"had_quant_act_i8g"));
|
||||
if (g.w_i8h && !a.q8_fed) return RAD_OK;
|
||||
return q.declare(b, gg, a, width);
|
||||
}
|
||||
/* The codes of rows [r0, r0 + rows), at those rows' count. */
|
||||
void step(RadCtx* c, int64_t rows, int64_t r0 = 0) const {
|
||||
if (!q.op || rows <= 0) return;
|
||||
RAD_ISSUE_N(c, q.op, 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));
|
||||
brow_slice(a.cs(), r0, rows, n / a.cg()));
|
||||
}
|
||||
};
|
||||
|
||||
/* A linear, y = x W^T (+ b): `gemm_nt_bias` over the bf16 plane for a bf16 weight (the bias in the
|
||||
* GEMM's one rounding, as torch's), or `gemm_nt_q` over the codes for a block-fp8 one with the
|
||||
* bias added after (`table_add`, one more rounding). `small` keeps a weight bf16 in any container
|
||||
* (a gate's logits: too few rows for 128-row fp8 blocks). The input and output rows may sit at
|
||||
* different offsets of their buffers. */
|
||||
* GEMM's one rounding, as torch's), or `gemm_nt_q` over the codes for a block-fp8 or rotated int8
|
||||
* one with the bias added after (`table_add`, one more rounding). `small` keeps a weight bf16 in
|
||||
* any container (a gate's logits: too few rows for 128-row fp8 blocks). The input and output rows
|
||||
* may sit at different offsets of their buffers. */
|
||||
struct Lin {
|
||||
LinearFP8 l{};
|
||||
rad_weight w = 0, bias = 0;
|
||||
rad_op op = 0, op_b = 0;
|
||||
bool fp8 = false;
|
||||
bool fp8 = false; /* read through its codes: block fp8, or rotated int8 */
|
||||
bool mapped = false; /* the weight's name map was made already (a probe's) */
|
||||
int64_t N = 0, K = 0;
|
||||
|
||||
@@ -257,9 +264,11 @@ struct Lin {
|
||||
l.mapped = mapped;
|
||||
RAD_ARCH_TRY(l.declare(b, nm, g, base, N, K, RAD_SHARD_NONE, grp_layer(group), wsrc, in.a, y,
|
||||
max_rows, parts));
|
||||
if (l.bf16 || l.i8 || l.mx || l.w4 || l.paro || l.paro5) {
|
||||
fprintf(stderr, "radiance: ltx2: '%s' is not block fp8; this plugin reads bf16 or "
|
||||
"block-fp8 linears\n", base);
|
||||
const bool other = l.bf16 || l.mx || l.w4 || l.paro || l.paro5 || l.iqr;
|
||||
if (other || (g.w_i8h ? !(l.i8 && l.i8_rot) : l.i8)) {
|
||||
fprintf(stderr, "radiance: ltx2: '%s' is not %s as the first DiT projection is; this "
|
||||
"plugin reads bf16, block-fp8 or rotated int8 linears, one kind a "
|
||||
"container\n", base, g.w_i8h ? "rotated int8" : "block fp8");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
op = l.op;
|
||||
@@ -285,9 +294,12 @@ struct Lin {
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(in.a.x, ri, rows, K), RAD_W(w), out);
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(in.a.q, ri, rows, K),
|
||||
brow_slice(in.a.s, ri, rows, K / RAD_FP8_BLOCK), RAD_W(l.w), RAD_W(l.ws), out,
|
||||
RAD_NONE, RAD_NONE);
|
||||
if (l.i8)
|
||||
l.step(c, in.a, y, ri + rows, ri, rows, ro);
|
||||
else
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(in.a.q, ri, rows, K),
|
||||
brow_slice(in.a.s, ri, rows, K / RAD_FP8_BLOCK), RAD_W(l.w), RAD_W(l.ws),
|
||||
out, RAD_NONE, RAD_NONE);
|
||||
if (op_b) RAD_ISSUE_N(c, op_b, rows, out, RAD_W(bias), out);
|
||||
}
|
||||
};
|
||||
@@ -712,7 +724,7 @@ struct Model {
|
||||
rad_buf b_ddcu = 0, b_dsig = 0, b_dtg = 0, b_dgrid = 0, b_dg5 = 0;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* ================================================================== check_format */
|
||||
static long long tgeti(const RadModelMeta* m, const char* key, long long def) {
|
||||
@@ -2370,7 +2382,7 @@ static int declare_audio(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
for (const char* w : { "voc.conv_in.weight", "bwe.conv_in.weight" }) {
|
||||
if (weight_codes_dtype(b, w, RAD_F32) != RAD_F32) {
|
||||
fprintf(stderr, "radiance: ltx2: '%s' is stored %s; the vocoders run in f32 -- convert "
|
||||
"with data/recipes/ltx-2.5-bf16.recipe or ltx-2.5-fp8.recipe, which "
|
||||
"with one of data/recipes/ltx-2.5-*.recipe, which "
|
||||
"cast them\n", w, rad_dtype_name(weight_codes_dtype(b, w, RAD_F32)));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
@@ -3140,7 +3152,8 @@ static const double kStage2[] = { 0.909375, 0.725, 0.421875 };
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (ctx->is_draft) {
|
||||
fprintf(stderr, "radiance: ltx2: this plugin has no draft scope\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -3150,7 +3163,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"every head\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
Names& nm = m.nm;
|
||||
@@ -3217,8 +3230,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- bf16 or block fp8: what the container holds for the first DiT projection decides every
|
||||
* large linear (rad_fp8.h, Geom::w_bf16) */
|
||||
/* ---- bf16, block fp8 or rotated int8: what the container holds for the first DiT projection
|
||||
* decides every large linear (rad_arch.h, Geom::w_bf16 and w_i8h) */
|
||||
{
|
||||
LinearFP8 probe{};
|
||||
RAD_ARCH_TRY(probe.probe(b, nm, m.gd, "dit.blk.0.attn1.qkv",
|
||||
@@ -3226,9 +3239,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"transformer.transformer_blocks.0.attn1.to_k.weight",
|
||||
"transformer.transformer_blocks.0.attn1.to_v.weight" }));
|
||||
RadEncoding e{};
|
||||
const bool plain = weight_enc(b, nm.f("dit.blk.0.attn1.qkv.weight"), &e) &&
|
||||
rad_enc_is(&e, "plain");
|
||||
m.gd.w_bf16 = m.gt.w_bf16 = plain;
|
||||
const bool known = weight_enc(b, nm.f("dit.blk.0.attn1.qkv.weight"), &e);
|
||||
m.gd.w_bf16 = m.gt.w_bf16 = known && rad_enc_is(&e, "plain");
|
||||
m.gd.w_i8h = m.gt.w_i8h = known && linear_is_w8h(e);
|
||||
if (m.gd.w_i8h) m.gd.w_i8_group = m.gt.w_i8_group = linear_w8h_group(e);
|
||||
}
|
||||
|
||||
/* ---- the scheduler: the base model's shifted linspace, or the distilled release's sigmas */
|
||||
@@ -3371,7 +3385,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"bandwidth extender%s%s",
|
||||
distilled ? " distilled" : "", (long long)m.tL, (long long)m.tC, m.cv.blk.size(),
|
||||
m.ca.blk.size(), (long long)m.nb, (long long)m.D, (long long)m.Da,
|
||||
m.gd.w_bf16 ? "bf16" : "block-fp8", m.venc ? "decoder + encoder" : "decoder",
|
||||
m.gd.w_bf16 ? "bf16" : m.gd.w_i8h ? "rotated int8" : "block-fp8",
|
||||
m.venc ? "decoder + encoder" : "decoder",
|
||||
m.ups ? ", latent upsampler x2" : "", m.dur ? ", duration head" : "");
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -4144,7 +4159,7 @@ static void step_upscale(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->vgen_b) {
|
||||
rad_step_fail(c, "ltx2 is a video generator and runs its generator passes only");
|
||||
return;
|
||||
@@ -4179,12 +4194,14 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(ltx2)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(ltx2, "ltx2", "", "0.1.0",
|
||||
"LTX-2.5 (t2va, i2va): a Gemma 4 text encoder and connectors, the duration head, a "
|
||||
"22B dual-stream audio-video diffusion transformer with four-way guidance, the "
|
||||
"causal 3D video VAE (tiled past the default canvas) and the diffusion decoder, the "
|
||||
"audio VAE with a BigVGAN vocoder and bandwidth extension, the x2 latent upsampler; "
|
||||
"bf16 or block-fp8 linears")
|
||||
"bf16, block-fp8 or rotated int8 linears")
|
||||
|
||||
extern "C" int64_t rad_arch_video_positions(int which, const RadVideoGeom* g, float* pos,
|
||||
int64_t cap) {
|
||||
|
||||
+118
-28
@@ -288,10 +288,11 @@ struct DitBlock {
|
||||
rad_op op_kq = 0; /* the keys to int8 codes for the attention's scores */
|
||||
rad_op op_vq = 0; /* the values to E4M3 codes for the attention's P.V */
|
||||
/* The three modulation projections, one a modality, this rank's share of their rows; a
|
||||
* curve-form checkpoint's are bf16 (ada_w). */
|
||||
* curve-form checkpoint's are bf16 (ada_w). A rotated int8 one adds its bias after the GEMM
|
||||
* (op_ada_b). */
|
||||
DenseFP8 ada[3];
|
||||
rad_weight ada_w[3] = {}, ada_b[3] = {};
|
||||
rad_op op_ada[3] = {};
|
||||
rad_op op_ada[3] = {}, op_ada_b[3] = {};
|
||||
};
|
||||
|
||||
/* A video decoder block. */
|
||||
@@ -423,6 +424,7 @@ struct Model {
|
||||
/* ---- the lanes (PERSIST) */
|
||||
rad_buf b_text = 0; /* [lanes * kMaxText, D] bf16: the refined prompt */
|
||||
rad_buf b_ada = 0; /* [lanes * S, 150 * Ws] bf16: the modulation table */
|
||||
rad_buf b_adat = 0; /* [S, Ws] bf16: a rotated int8 projection's rows before its bias */
|
||||
rad_buf b_nout = 0; /* [lanes * S, 3 * 2D] bf16: norm_out's, by segment */
|
||||
rad_buf b_vstate = 0; /* [lanes * maxV, 96] f32 */
|
||||
rad_buf b_astate = 0; /* [lanes * maxA, 32] f32 */
|
||||
@@ -450,6 +452,12 @@ struct Model {
|
||||
ActFP8 a_hm{}, a_attn{}, a_ffn{};
|
||||
/* The DiT's linears are int8 (W8A8): their activations are int8 codes as well. */
|
||||
bool dit_i8 = false;
|
||||
/* The text encoder's, the refiner's and the modulation projections' linears are rotated int8
|
||||
* (IQ8R, or the 128-group form where K is not whole 256s), each read off its first weight:
|
||||
* their activations then carry int8 pairs at that weight's scale group in place of the E4M3
|
||||
* ones (ActFP8::declare_pair). */
|
||||
bool te_i8 = false, ref_i8 = false, ada_i8 = false;
|
||||
int64_t te_g8 = RAD_FP8_BLOCK, ref_g8 = RAD_FP8_BLOCK, ada_g8 = RAD_FP8_BLOCK;
|
||||
std::vector<DitBlock> dit;
|
||||
rad_weight w_no_n = 0, w_vout = 0, b_vout = 0, w_aout = 0, b_aout = 0;
|
||||
rad_op op_nout = 0, op_hcast = 0, op_vout = 0, op_aout = 0, op_ev = 0, op_ea = 0;
|
||||
@@ -561,7 +569,7 @@ struct Model {
|
||||
rad_buf b_enca = 0; /* [kEncSlotsA * kEncSlotRowsA, kAudioC] f32 PERSIST */
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* A space-separated list off the container (rad-convert flattens arrays that way). */
|
||||
static std::vector<double> meta_list(const RadModelMeta* m, const char* key) {
|
||||
@@ -704,16 +712,35 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
nm.ckpt("model.language_model.embed_tokens.weight")));
|
||||
m.w_tok = decl_w(b, nm.f("te.token_embd.weight"), RAD_BF16, { g.n_vocab_all, g.n_embd },
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
/* The linears' format, from layer 0's projection, before the activations' codes are declared:
|
||||
* rotated int8 ones read int8 pairs. */
|
||||
m.te.resize((size_t)g.n_layer);
|
||||
{
|
||||
const char* pre = "model.language_model.layers";
|
||||
RAD_ARCH_TRY(m.te[0].qkv.probe(b, nm, g, "te.blk.0.attn_qkv",
|
||||
{ nm.ckpt("%s.0.self_attn.q_proj.weight", pre),
|
||||
nm.ckpt("%s.0.self_attn.k_proj.weight", pre),
|
||||
nm.ckpt("%s.0.self_attn.v_proj.weight", pre) }));
|
||||
RadEncoding e{};
|
||||
if (weight_enc(b, nm.f("te.blk.0.attn_qkv.weight"), &e) &&
|
||||
(linear_is_w8h(e) || linear_is_wnh(e))) {
|
||||
m.te_i8 = true;
|
||||
m.te_g8 = linear_w8h_group(e);
|
||||
}
|
||||
}
|
||||
m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, g.n_embd });
|
||||
m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, g.n_embd });
|
||||
RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", g.n_embd));
|
||||
RAD_ARCH_TRY(m.a_th.declare_pair(b, nm, g, "te.h", g.n_embd, 0, m.te_i8, m.te_g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim });
|
||||
m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim });
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim));
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_pair(b, nm, g, "te.attn", q_dim, 0, m.te_i8, m.te_g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, g.n_embd });
|
||||
m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff));
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_pair(b, nm, g, "te.ffn", g.n_ff, 0, m.te_i8, m.te_g8,
|
||||
"gated_had_quant_i8g"));
|
||||
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", g.n_embd),
|
||||
@@ -887,15 +914,32 @@ static int declare_refiner(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.b_rh = decl_b(b, nm.f("ref.h"), RAD_BF16, { T, D });
|
||||
m.op_ce = dense_bias(b, nm, "ref.ctx", "transformer.context_embedder", RAD_BF16, "bf16", D,
|
||||
tdim, T, m.b_tx, m.b_rh, &m.w_ce, &m.b_ce, acc, gx);
|
||||
/* The refiner's linears' format, from block 0's projection (declare_te's note). */
|
||||
{
|
||||
const char* pre = nm.ckpt("transformer.token_refiner.refiner_blocks.0");
|
||||
RAD_ARCH_TRY(m.rb[0].qkv.probe(b, nm, g, "ref.blk.0.attn_qkv",
|
||||
{ nm.ckpt("%s.attn.to_q.weight", pre),
|
||||
nm.ckpt("%s.attn.to_k.weight", pre),
|
||||
nm.ckpt("%s.attn.to_v.weight", pre) }));
|
||||
RadEncoding e{};
|
||||
if (weight_enc(b, nm.f("ref.blk.0.attn_qkv.weight"), &e) &&
|
||||
(linear_is_w8h(e) || linear_is_wnh(e))) {
|
||||
m.ref_i8 = true;
|
||||
m.ref_g8 = linear_w8h_group(e);
|
||||
}
|
||||
}
|
||||
m.a_rh.x = decl_b(b, nm.f("ref.hn"), RAD_BF16, { T, D });
|
||||
RAD_ARCH_TRY(m.a_rh.declare_qs(b, nm, g, "ref.hn", D));
|
||||
RAD_ARCH_TRY(m.a_rh.declare_pair(b, nm, g, "ref.hn", D, 0, m.ref_i8, m.ref_g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_rqkv = decl_b(b, nm.f("ref.qkv"), RAD_BF16, { T, 3 * qd });
|
||||
m.a_rattn.x = decl_b(b, nm.f("ref.attn"), RAD_BF16, { T, qd });
|
||||
RAD_ARCH_TRY(m.a_rattn.declare_qs(b, nm, g, "ref.attn", qd));
|
||||
RAD_ARCH_TRY(m.a_rattn.declare_pair(b, nm, g, "ref.attn", qd, 0, m.ref_i8, m.ref_g8,
|
||||
"had_quant_act_i8g"));
|
||||
m.b_rao = decl_b(b, nm.f("ref.ao"), RAD_BF16, { T, D });
|
||||
m.b_rgu = decl_b(b, nm.f("ref.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_rffn.x = decl_b(b, nm.f("ref.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_rffn.declare_qs(b, nm, g, "ref.ffn", g.n_ff));
|
||||
RAD_ARCH_TRY(m.a_rffn.declare_pair(b, nm, g, "ref.ffn", g.n_ff, 0, m.ref_i8, m.ref_g8,
|
||||
"gated_had_quant_i8g"));
|
||||
const int64_t ff_all = g.n_ff_all;
|
||||
|
||||
for (int l = 0; l < 2; ++l) {
|
||||
@@ -1063,13 +1107,10 @@ static int declare_tables(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.op_ts = unary(b, "silu", TT, hd1, "f32", m.b_te1, m.b_te1s);
|
||||
m.op_t2 = dense_bias(b, nm, "tmb.l2", "transformer.time_embedder.linear_2", RAD_F32, "f32",
|
||||
td, hd1, TT, m.b_te1s, m.b_temb, &m.w_t2, &m.b_t2, acc, gx);
|
||||
/* silu(temb) in f32, rounded once to the bf16 the projections take. */
|
||||
Geom gs = g;
|
||||
gs.max_tok = TT;
|
||||
/* silu(temb) in f32, rounded once to the bf16 the projections take. Its codes are
|
||||
* declared below, once the first projection's encoding says which they are. */
|
||||
m.a_temb.x = decl_b(b, nm.f("tmb.act"), RAD_BF16, { TT, td });
|
||||
m.op_ts2 = unary(b, "silu", TT, td, "f32", m.b_temb, m.a_temb.x);
|
||||
RAD_ARCH_TRY(m.a_temb.declare_qs(b, nm, gs, "tmb.act", td, TT));
|
||||
RAD_ARCH_TRY(m.q_temb.declare(b, gs, m.a_temb, td));
|
||||
if (!m.op_temb || !m.op_temb_pv || !m.op_temb_pa || !m.op_t1 || !m.op_ts || !m.op_t2
|
||||
|| !m.op_ts2) return RAD_E_INVAL;
|
||||
}
|
||||
@@ -1106,16 +1147,58 @@ static int declare_tables(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_WEIGHTS(B.ada_w[md], B.ada_b[md])),
|
||||
{ m.a_temb.x }, { m.b_ada });
|
||||
} else {
|
||||
/* The embedding's codes, from the first projection's encoding: E4M3, or for
|
||||
* rotated int8 projections the int8 pair at their scale group. */
|
||||
if (l == 0 && md == 0) {
|
||||
RadEncoding e{};
|
||||
if (weight_enc(b, wn, &e) && linear_is_w8h(e)) {
|
||||
m.ada_i8 = true;
|
||||
m.ada_g8 = linear_w8h_group(e);
|
||||
}
|
||||
Geom gs = g;
|
||||
gs.max_tok = TT;
|
||||
RAD_ARCH_TRY(m.a_temb.declare_pair(b, nm, gs, "tmb.act", td, TT, m.ada_i8,
|
||||
m.ada_g8, "had_quant_act_i8g"));
|
||||
if (m.ada_i8 && !m.a_temb.q8_fed) {
|
||||
fprintf(stderr, "radiance: minimaxh3: rotated int8 modulation projections "
|
||||
"need had_quant_act_i8g, which no loaded library serves\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RAD_ARCH_TRY(m.q_temb.declare(b, gs, m.a_temb, td));
|
||||
}
|
||||
/* The row slice is mapped above (DenseFP8 takes that as its argument). */
|
||||
B.ada[md].w8h_ok = m.ada_i8;
|
||||
RAD_ARCH_TRY(B.ada[md].declare(b, nm, base, m.Ws, td, acc, RAD_SHARD_ROW,
|
||||
grp_layer(grp), { src_w }, {}, true));
|
||||
B.op_ada[md] = rw(b, RAD_OP(b, "gemm_nt_q_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", m.Ws),
|
||||
RAD_INT("K", td),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(B.ada[md].w, B.ada[md].s, B.ada_b[md])),
|
||||
{ m.a_temb.q, m.a_temb.s }, { m.b_ada });
|
||||
if (B.ada[md].w8h != m.ada_i8) {
|
||||
fprintf(stderr, "radiance: minimaxh3: '%s' is not encoded as the first "
|
||||
"modulation projection is\n", wn);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (m.ada_i8) {
|
||||
/* i8a8h has no biased row and writes whole rows: the GEMM goes to its own
|
||||
* rows, and the bias is added on the way into the table's cell. */
|
||||
if (!m.b_adat) m.b_adat = decl_b(b, nm.f("tmb.ada"), RAD_BF16, { S, m.Ws });
|
||||
if (!m.b_adat) return RAD_E_INVAL;
|
||||
B.op_ada[md] = B.ada[md].gemm(b, S, m.Ws, td,
|
||||
{ m.a_temb.cq(), m.a_temb.cs() }, { m.b_adat });
|
||||
B.op_ada_b[md] = rw(b, RAD_OP(b, "table_add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S),
|
||||
RAD_INT("n", m.Ws), RAD_INT("L", 1),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(B.ada_b[md])),
|
||||
{ m.b_adat }, { m.b_ada });
|
||||
if (!B.op_ada_b[md]) return RAD_E_INVAL;
|
||||
} else {
|
||||
B.op_ada[md] = rw(b, RAD_OP(b, "gemm_nt_q_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", m.Ws),
|
||||
RAD_INT("K", td),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(B.ada[md].w, B.ada[md].s,
|
||||
B.ada_b[md])),
|
||||
{ m.a_temb.q, m.a_temb.s }, { m.b_ada });
|
||||
}
|
||||
}
|
||||
if (!B.op_ada[md]) return RAD_E_INVAL;
|
||||
}
|
||||
@@ -2798,8 +2881,9 @@ static int declare_aenc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
/* ================================================================== declare */
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
Names& nm = m.nm;
|
||||
@@ -2923,8 +3007,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_ARCH_TRY(declare_dit(b, meta, m));
|
||||
if (m.dit[0].qkv.bf16) {
|
||||
fprintf(stderr, "radiance: minimaxh3: the DiT's linears are bf16; this plugin serves the "
|
||||
"block-fp8 container (data/recipes/minimax-h3-fp8.recipe) or the int8 one "
|
||||
"(data/recipes/minimax-h3-w8a8.recipe)\n");
|
||||
"int8 container (data/recipes/minimax-h3-i8.recipe)\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RAD_ARCH_TRY(declare_ups(b, meta, m));
|
||||
@@ -3203,10 +3286,15 @@ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const int64_t r0 = cell[(size_t)e].second;
|
||||
const RadOperand out =
|
||||
bcol_at(m.b_ada, base, L * kMaxSegs * m.Ws, (l * kMaxSegs + e) * m.Ws, m.Ws, S);
|
||||
if (m.curve > 0)
|
||||
if (m.curve > 0) {
|
||||
RAD_ISSUE_N(c, B.op_ada[md], S, brow_slice(m.a_temb.x, r0, S, td),
|
||||
RAD_W(B.ada_w[md]), RAD_W(B.ada_b[md]), RAD_NONE, out);
|
||||
else
|
||||
} else if (m.ada_i8) {
|
||||
RAD_ISSUE_N(c, B.op_ada[md], S, brow_slice(m.a_temb.q8, r0, S, td),
|
||||
brow_slice(m.a_temb.s8, r0, S, td / m.ada_g8), RAD_W(B.ada[md].w),
|
||||
RAD_W(B.ada[md].s), brows(m.b_adat, S), RAD_NONE, RAD_NONE);
|
||||
RAD_ISSUE_N(c, B.op_ada_b[md], S, brows(m.b_adat, S), RAD_W(B.ada_b[md]), out);
|
||||
} else
|
||||
RAD_ISSUE_N(c, B.op_ada[md], S, brow_slice(m.a_temb.q, r0, S, td),
|
||||
brow_slice(m.a_temb.s, r0, S, td / RAD_FP8_BLOCK), RAD_W(B.ada[md].w),
|
||||
RAD_W(B.ada[md].s), RAD_W(B.ada_b[md]), out);
|
||||
@@ -3934,7 +4022,7 @@ static void step_aenc(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->vgen_b) {
|
||||
rad_step_fail(c, "minimaxh3 is a video generator and runs its generator passes only");
|
||||
return;
|
||||
@@ -3987,6 +4075,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(minimaxh3)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(minimaxh3, "minimaxh3", "", "0.1.0",
|
||||
"MiniMax-H3 (t2va, i2va, l2va, fl2va, ref2va): Qwen3-VL-32B conditioning, a 33B "
|
||||
"single-stream diffusion transformer over text, soundtrack and video, a tiled ViT "
|
||||
|
||||
@@ -208,7 +208,7 @@ struct Model {
|
||||
rad_buf b_audio = 0;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* ================================================================== declare helpers */
|
||||
static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, rad_buf x,
|
||||
@@ -1083,8 +1083,9 @@ static int check_format(const RadModelMeta* meta) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -1381,7 +1382,7 @@ static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->agen_b) {
|
||||
rad_step_fail(c, "minimaxmusic3 is an audio generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1575,6 +1576,8 @@ RAD_ARCH_PROBE(minimaxmusic3)
|
||||
extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap) {
|
||||
return minimaxmusic3::text_prepare(field, in, out, cap);
|
||||
}
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(minimaxmusic3, "minimaxmusic3", "", "0.1.0",
|
||||
"MiniMax-Music3: a Qwen3-8B music language model with a residual-code depth "
|
||||
"decoder, a 2.4B flow-matching transformer over windows of frames, and a DAC "
|
||||
|
||||
@@ -36,7 +36,8 @@ struct Model {
|
||||
std::vector<Layer> layers;
|
||||
Pixtral vision;
|
||||
};
|
||||
static Model model;
|
||||
/* One per engine instance in the process, by slot (rad_builder.h, rad_build_slot). */
|
||||
static Model g_model[RAD_MAX_SLOTS];
|
||||
|
||||
/* JSON booleans reach plugins as 0/1, while out-of-tree callers may use their JSON spelling. */
|
||||
static bool false_value(const char* s) {
|
||||
@@ -86,7 +87,9 @@ static int read_rope(Geom& g, const RadModelMeta* meta) {
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->max_seqs <= 0) return RAD_E_INVAL;
|
||||
if (!b || !meta || !ctx || ctx->max_seqs <= 0 || ctx->rank < 0 ||
|
||||
rad_build_slot(ctx) >= RAD_MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (ctx->rank != 0 || ctx->world_size > 1 || ctx->is_draft || ctx->max_spec > 0) {
|
||||
std::fprintf(stderr, "radiance: nemotron35_embed serves BF16 at TP1, without drafting\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -116,8 +119,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rad_meta_geti(meta, "text_config.rope_parameters.original_max_position_embeddings", 0);
|
||||
if (!std::isfinite(beta) || beta < 0 || original <= 0) return RAD_E_INVAL;
|
||||
|
||||
model = Model{};
|
||||
Model& m = model;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.rerank =
|
||||
!std::strcmp(rad_meta_gets(meta, "architectures", ""), "Mistral3ForSequenceClassification");
|
||||
const char* architecture = rad_meta_gets(meta, "architectures", "");
|
||||
@@ -340,7 +343,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = model;
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
if (batch->enc) {
|
||||
m.vision.step(c, batch);
|
||||
@@ -399,6 +402,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
} // namespace nemotron35_embed
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(nemotron35_embed, "mistral3", "", "0.5.0",
|
||||
"Nemotron-3.5-Embed/Rerank: experimental BF16 text/image retrieval, TP1")
|
||||
RAD_ARCH_PROBE(nemotron35_embed)
|
||||
|
||||
@@ -393,7 +393,7 @@ struct Model {
|
||||
LiliCorr lili{};
|
||||
LiliCorr::Wire lw{};
|
||||
};
|
||||
static std::unique_ptr<Model> models[MAX_RANKS];
|
||||
static std::unique_ptr<Model> models[MAX_SLOTS];
|
||||
static thread_local std::unique_ptr<Model> probe_model;
|
||||
|
||||
static int read_shape(const RadModelMeta* meta, Shape& s) {
|
||||
@@ -765,10 +765,11 @@ static int declare_lilicorr(RadBuilder* b, const RadModelMeta* meta, const RadBu
|
||||
}
|
||||
|
||||
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)
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
const int world = ctx->world_size ? ctx->world_size : 1;
|
||||
auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank];
|
||||
auto& slot = ctx->shape_probe ? probe_model : models[rad_build_slot(ctx)];
|
||||
slot = std::make_unique<Model>();
|
||||
auto& m = *slot;
|
||||
auto& g = m.g;
|
||||
@@ -1054,7 +1055,7 @@ static void dump_draft(RadCtx* c, const RadBatch* batch, const char* what, const
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
auto& m = *models[rad_rank(c)];
|
||||
auto& m = *models[rad_slot(c)];
|
||||
const int64_t T = batch->n_tok, E = m.g.n_embd;
|
||||
if (batch->enc) {
|
||||
m.radio.step(c, batch);
|
||||
@@ -1137,6 +1138,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
} // namespace nemotronh
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(nemotronh)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(nemotronh, "nemotronh", "", "0.1.0",
|
||||
"Nemotron-H (nemotron_h_omni/puzzle): Mamba-2, latent relu^2 MoE and NoPE attention")
|
||||
#endif
|
||||
@@ -71,7 +71,7 @@ struct Model {
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* The layer schedule, read from moe_every_n_layers rather than derived: a wrong interval would
|
||||
* declare a MoE layer whose tensors the checkpoint does not hold. Layer l is routed when
|
||||
@@ -93,7 +93,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
/* A 475M-parameter encoder fits one card; tensor parallelism would only add an all-reduce per
|
||||
* layer. */
|
||||
if (ctx->world_size > 1) {
|
||||
@@ -102,7 +103,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
@@ -441,7 +442,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd;
|
||||
if (T <= 0 || S <= 0) return;
|
||||
@@ -500,6 +501,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
} /* namespace nomicbert */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(nomicbert, "nomicbert", "", "0.1.0",
|
||||
"Nomic BERT (nomic-embed-text-v2-moe): a bidirectional post-norm encoder with "
|
||||
"NeoX rotary attention, dense and routed GELU feed-forwards, mean-pooled to one "
|
||||
|
||||
@@ -103,14 +103,16 @@ struct Model {
|
||||
};
|
||||
|
||||
/* Declare runs once per rank, in one process, on the rank's own thread (spec §1, §9), so the
|
||||
* model state is indexed by rank and read back in step() with rad_rank(). */
|
||||
static Model g_model[MAX_RANKS];
|
||||
* model state is per instance: indexed by the instance's slot (unique across every engine in the
|
||||
* process, rad_build_slot) and read back in step() with rad_slot(). */
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
@@ -479,7 +481,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
|
||||
/* An encoder pass runs only the vision tower (RadBatch::enc). */
|
||||
if (batch->enc) {
|
||||
@@ -539,9 +541,23 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Chained launches pay on the plain-bf16 trunk with a drafter and without one: every kernel of
|
||||
* its decode step but the gated delta net's two and the vocabulary GEMM has a chained form
|
||||
* (libr4d's rad_kernel_chain). Ms a decode step unchained / chained: Qwen3.5-0.8B on one R9700
|
||||
* 3.89 / 3.60 at one sequence and 4.72 / 4.46 at four; Qwen3.8-27B as bf16 on two, where the
|
||||
* bf16 GEMMs are nearly all of the step, 48.04 / 47.41 and 49.57 / 48.81. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace qwen35_bf16 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PROBE(qwen35_bf16)
|
||||
RAD_ARCH_PLUGIN(qwen35_bf16, "qwen35", "", "0.1.0",
|
||||
"Qwen3.5 / 3.6 / 3.8 dense (0.8B..27B), bf16 weights and activations, gated "
|
||||
"attention over paged KV every fourth layer and gated delta net between")
|
||||
|
||||
+126
-81
@@ -56,16 +56,17 @@
|
||||
*
|
||||
* 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. */
|
||||
* identity. The int8 activation pairs follow from the probe.
|
||||
*
|
||||
* Both macros together are `qwen35moe_w8a8`, the routed build with that trunk: the experts are
|
||||
* rotated too (int8 at a bf16 scale a 128 of K, or the four-bit forms) and read the int8 codes the
|
||||
* trunk's own quantisers write (rad_block_moe_fp8.h, MoeFP8::a8). */
|
||||
#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)
|
||||
@@ -152,6 +153,8 @@ struct Model {
|
||||
/* 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 int8 trunk's scale group: 128, or 256 for IQ8R (linear_w8h_group). */
|
||||
int64_t trunk_g8 = RAD_FP8_BLOCK;
|
||||
|
||||
/* the residual stream and the two vocabulary edges */
|
||||
rad_buf b_x = 0, b_hout = 0, b_logits = 0;
|
||||
@@ -245,7 +248,7 @@ struct Model {
|
||||
bool pipe_serial_noted = false;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
#if !QWEN35_MOE
|
||||
/* The narrowest step the pipelined prefill takes, and its first piece: half the step rounded up
|
||||
@@ -267,9 +270,9 @@ static int check_format(const RadModelMeta* meta) {
|
||||
/* 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",
|
||||
fprintf(stderr, "radiance: " QWEN35_STR(QWEN35_NS) " serves a container converted for an "
|
||||
"int8 trunk (quant_method 'w8a8', fmt 'fwht128': data/recipes/"
|
||||
"q38-27b-iq8r.recipe's --set keys); this one says '%s' / '%s'.\n",
|
||||
method ? method : "(none)", fmt ? fmt : "(none)");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
@@ -399,22 +402,34 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, 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});
|
||||
/* FP8 copies. The drafter's six linears are block-scaled fp8 over a bf16 checkpoint
|
||||
* (rad_fp8.h's DenseFP8), so every activation feeding one has an E4M3 copy and an f32 scale
|
||||
* plane. `srcq` is the largest (50 MiB at a 2048-token chunk and five taps) and halves the
|
||||
* bytes of the context pass's dominant GEMM. */
|
||||
dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3,
|
||||
{dg.max_tok, dc.n_taps * dg.n_embd});
|
||||
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32,
|
||||
{dg.max_tok, fp8_blocks(dc.n_taps * 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.h2q = decl_b(b, nm.f("df_h2q"), RAD_F8E4M3, {qr, dg.n_embd});
|
||||
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, fp8_blocks(dg.n_embd)});
|
||||
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.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)});
|
||||
/* The codes the drafter's six linears read: every activation feeding one has an 8-bit copy
|
||||
* and an f32 scale plane. E4M3 with a scale per 128 for block fp8 or MXFP4 linears (rad_fp8.h's
|
||||
* DenseFP8), int8 with a scale per 128 or IQ8R's 256 for rotated int8 ones, which the drafter's
|
||||
* `fc` tells apart.
|
||||
* `srcq` is the largest (50 MiB at a 2048-token chunk and five taps) and halves the bytes of
|
||||
* the context pass's dominant GEMM. */
|
||||
RAD_ARCH_TRY(Dflash2::probe_i8(b, nm, "draft", &dc.act_i8, &dc.act_g8));
|
||||
dc.fc_mapped = true;
|
||||
const uint32_t dqt = dc.act_i8 ? RAD_I8 : RAD_F8E4M3;
|
||||
const int64_t dqg = dc.act_i8 ? dc.act_g8 : (int64_t)RAD_FP8_BLOCK;
|
||||
if (dc.act_i8 && ((dc.n_taps * dg.n_embd) % dqg || dg.n_embd % dqg || qd % dqg ||
|
||||
dg.n_ff % dqg)) {
|
||||
fprintf(stderr, "radiance: a rotated int8 drafter takes widths in whole %lld-column scale groups; "
|
||||
"this one is n_embd %lld, q %lld, n_ff %lld\n", (long long)dqg,
|
||||
(long long)dg.n_embd, (long long)qd, (long long)dg.n_ff);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto dqs = [&](int64_t n) { return (n + dqg - 1) / dqg; };
|
||||
dw.srcq = decl_b(b, nm.f("df_srcq"), dqt, {dg.max_tok, dc.n_taps * dg.n_embd});
|
||||
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, dqs(dc.n_taps * dg.n_embd)});
|
||||
dw.cq = decl_b(b, nm.f("df_cq"), dqt, {dg.max_tok, dg.n_embd});
|
||||
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, dqs(dg.n_embd)});
|
||||
dw.h2q = decl_b(b, nm.f("df_h2q"), dqt, {qr, dg.n_embd});
|
||||
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, dqs(dg.n_embd)});
|
||||
dw.atq = decl_b(b, nm.f("df_atq"), dqt, {qr, qd});
|
||||
dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, dqs(qd)});
|
||||
dw.ffq = decl_b(b, nm.f("df_ffq"), dqt, {qr, dg.n_ff});
|
||||
dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, dqs(dg.n_ff)});
|
||||
dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd});
|
||||
dw.hp = decl_b(b, nm.f("df_hp"), dg.act_dtype, {sr, dc.sel_rank});
|
||||
dw.dq = decl_b(b, nm.f("df_dq"), RAD_I8, {sr, dg.n_embd});
|
||||
@@ -518,9 +533,10 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
if (m.pipe_tbl) rad_dev_free(m.pipe_tbl, RAD_MEM_HOST_PINNED);
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
@@ -629,51 +645,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
|
||||
/* ---- the three KV groups. The attention cache is bf16 by default; `kv_dtype` follows it.
|
||||
*
|
||||
* --kv-cache-dtype fp8 makes it E4M3. The cache is `n_head_kv * head_dim * 2` bytes per token
|
||||
* per layer (2 KiB per rank here), paid only by the 16 attention layers; the 48 delta-net
|
||||
* layers carry fixed-size state. At eight sequences of 16k that is 4.3 GB of reads per step,
|
||||
* most of the cost of depth at that concurrency, and fp8 halves it along with each sequence's
|
||||
* KV pool footprint.
|
||||
* --kv-cache-dtype i8 makes it the int8 cache (abi/rad_builder.h): K and V as int8 codes
|
||||
* with one f16 scale each per token and head, half the bf16 cache's bytes. The cache is paid
|
||||
* only by the 16 attention layers; the 48 delta-net layers carry fixed-size state. At eight
|
||||
* sequences of 16k the bf16 cache is 8.6 GB of reads per step, most of the cost of depth at
|
||||
* that concurrency, and int8 halves it along with each sequence's KV pool footprint.
|
||||
*
|
||||
* Off by default for quality: greedy continuations from a long prompt agree for a few hundred
|
||||
* tokens and then diverge, and the fp8 side can produce syntactically broken code where bf16
|
||||
* stays clean, which matters for a coding model.
|
||||
*
|
||||
* The descales stay at libr4d's default of 1.0 (vLLM's default too); the kernels index them
|
||||
* per (sequence, head), so calibrated descales need no other mechanism. The fp8kv attention
|
||||
* rows and `kv_store_fp8` are in libr4d, the core sizes a page from the group's dtype, and the
|
||||
* drafter's cache takes the same dtype (declare_dflash2). */
|
||||
* Off by default because it changes the model's output slightly. The core sizes a page from
|
||||
* the group's dtype, and the drafter's cache takes the same dtype (declare_dflash2). */
|
||||
RadKVGroupDecl fd{};
|
||||
fd.kind = RAD_KV_FULL;
|
||||
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
fd.n_head_kv = g.n_head_kv;
|
||||
fd.head_dim = g.head_dim;
|
||||
/* --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 = 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));
|
||||
g.kv_dtype = rad_dtype_name(fd.dtype);
|
||||
|
||||
/* The SSM state cache is f32, or f16 under --state-cache-dtype f16 (RadBuildCtx::state_dtype).
|
||||
*
|
||||
@@ -716,6 +703,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RadEncoding enc{};
|
||||
m.trunk_i8 = weight_enc(b, nm.f("blk.%lld.ssm_inz.weight", (long long)l), &enc) &&
|
||||
(linear_is_w8h(enc) || linear_is_wnh(enc));
|
||||
if (m.trunk_i8) m.trunk_g8 = linear_w8h_group(enc);
|
||||
break;
|
||||
}
|
||||
if (!m.trunk_i8) {
|
||||
@@ -733,7 +721,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* (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, 0, m.trunk_i8));
|
||||
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.trunk_i8, true,
|
||||
m.trunk_g8));
|
||||
|
||||
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});
|
||||
@@ -749,7 +738,8 @@ 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, 0, m.trunk_i8));
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim, 0, m.trunk_i8, true,
|
||||
m.trunk_g8));
|
||||
|
||||
/* `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
|
||||
@@ -769,7 +759,8 @@ 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, 0, m.trunk_i8));
|
||||
RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim, 0, m.trunk_i8, true,
|
||||
m.trunk_g8));
|
||||
|
||||
#if QWEN35_MOE
|
||||
/* ---- the routing geometry, read here so a refusal names the container's key. `n_ff` is
|
||||
@@ -848,24 +839,60 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_BUF_PERSIST);
|
||||
m.b_egu = decl_b(b, nm.f("moe_gate_up"), g.act_dtype, {K, 2 * mc.n_ff_exp});
|
||||
m.a_eff.x = decl_b(b, nm.f("moe_ffn"), g.act_dtype, {K, mc.n_ff_exp});
|
||||
m.a_eff.q = decl_b(b, nm.f("moe_ffn.q"), RAD_F8E4M3, {K, mc.n_ff_exp});
|
||||
m.a_eff.s = decl_b(b, nm.f("moe_ffn.s"), RAD_F32, {K, fp8_blocks(mc.n_ff_exp)});
|
||||
if (m.trunk_i8) {
|
||||
/* An int8 trunk's routed arm is int8 throughout: the gated product's rotated codes
|
||||
* at one scale a 128 of K, an expert's width a rank being whole 128s and not always
|
||||
* whole 256s (MoeFP8::a8). */
|
||||
m.a_eff.g8 = RAD_FP8_BLOCK;
|
||||
m.a_eff.q8 = decl_b(b, nm.f("moe_ffn.q8"), RAD_I8, {K, mc.n_ff_exp});
|
||||
m.a_eff.s8 = decl_b(b, nm.f("moe_ffn.s8"), RAD_F32, {K, fp8_blocks(mc.n_ff_exp)});
|
||||
m.a_eff.q8_fed = m.a_eff.q8_rot = true;
|
||||
} else {
|
||||
m.a_eff.q = decl_b(b, nm.f("moe_ffn.q"), RAD_F8E4M3, {K, mc.n_ff_exp});
|
||||
m.a_eff.s = decl_b(b, nm.f("moe_ffn.s"), RAD_F32, {K, fp8_blocks(mc.n_ff_exp)});
|
||||
}
|
||||
m.b_edn = decl_b(b, nm.f("moe_down"), g.act_dtype, {K, g.n_embd});
|
||||
if (mc.n_ff_shared > 0) {
|
||||
m.b_emoe = decl_b(b, nm.f("moe_out"), g.act_dtype, {R, g.n_embd});
|
||||
m.b_sgu = decl_b(b, nm.f("shexp_gate_up"), g.act_dtype, {R, 2 * mc.n_ff_shared});
|
||||
m.a_sff.x = decl_b(b, nm.f("shexp_ffn"), g.act_dtype, {R, mc.n_ff_shared});
|
||||
if (m.trunk_i8) {
|
||||
/* The shared expert's down projection is a trunk linear, and its input's codes
|
||||
* take the group its own weight is stored at, read from layer 0's through that
|
||||
* layer's own LinearFP8 (which then maps it once): a recipe keeps it at a 128
|
||||
* where a rank's share of its width is not whole 256s. */
|
||||
LinearFP8& sd = m.layers[0].mlp.sh_down;
|
||||
RAD_ARCH_TRY(sd.probe(b, nm, g, nm.f("blk.0.ffn_down_shexp"),
|
||||
{ nm.ckpt("model.language_model.layers.0.mlp."
|
||||
"shared_expert.down_proj.weight") }));
|
||||
const int64_t sg = sd.probed_i8 ? sd.probed_g8 : m.trunk_g8;
|
||||
RAD_ARCH_TRY(m.a_sff.declare_pair(b, nm, g, "shexp_ffn", mc.n_ff_shared, R, true,
|
||||
sg, "gated_had_quant_i8g"));
|
||||
} else {
|
||||
m.a_sff.q = decl_b(b, nm.f("shexp_ffn.q"), RAD_F8E4M3, {R, mc.n_ff_shared});
|
||||
m.a_sff.s = decl_b(b, nm.f("shexp_ffn.s"), RAD_F32, {R, fp8_blocks(mc.n_ff_shared)});
|
||||
}
|
||||
m.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));
|
||||
/* The experts' rotated copy of the block input. An int8 trunk whose norms write rotated
|
||||
* int8 codes (below) needs none: the experts read `h`'s own. Where they do not (the CPU
|
||||
* kernels), had_quant_act_i8g writes this one at a scale a 128. */
|
||||
const bool h_fed = m.trunk_i8 && rad_op_declared(b, "rmsnorm_had_quant_i8g") &&
|
||||
(g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g"));
|
||||
if (m.trunk_i8 && !h_fed) {
|
||||
RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd, 0, true, false,
|
||||
RAD_FP8_BLOCK));
|
||||
m.a_hr.q8_fed = m.a_hr.q8_rot = true;
|
||||
} else if (mc.expert_rot && !m.trunk_i8) {
|
||||
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, 0, m.trunk_i8));
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.trunk_i8, true,
|
||||
m.trunk_g8));
|
||||
#endif
|
||||
|
||||
#if QWEN35_W8A8
|
||||
@@ -879,7 +906,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
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 !QWEN35_MOE
|
||||
if (rad_op_declared(b, "gated_had_quant_i8g")) m.a_ffn.q8_fed = m.a_ffn.q8_rot = true;
|
||||
#endif
|
||||
/* The delta net's output likewise, from the decode conv fold's epilogue
|
||||
* (gdn_conv_recurrent_update_had) and had_quant_act_i8g on the other rows (GdnFP8::q_o). */
|
||||
if (rad_op_declared(b, "gdn_conv_recurrent_update_had") && rad_op_declared(b, "had_quant_act_i8g"))
|
||||
@@ -1645,7 +1674,7 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
|
||||
#endif
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
|
||||
/* An encoder pass runs only the vision tower (RadBatch::enc). */
|
||||
if (batch->enc) {
|
||||
@@ -1772,17 +1801,22 @@ 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);
|
||||
}
|
||||
/* The delta-net state cache is declared at RadBuildCtx::state_dtype. */
|
||||
out->state_f16_ok = 1;
|
||||
#if QWEN35_W8A8 && !QWEN35_MOE
|
||||
/* Chained launches pay on an int8 or a trellis trunk with and without its drafter: every
|
||||
* kernel of its decode chain has a chained form (libr4d's rad_kernel_chain), the two-rank
|
||||
* junctions among them. Qwen3.8-27B, ms a decode step unchained / chained, on two R9700: as
|
||||
* IQ8R 32.14 / 21.98 without a drafter and 36.54 / 26.52 with DFlash2 (40.75 / 32.09 at four
|
||||
* sequences), as IQ4R-S-V4 with DFlash2 29.32 / 20.46 (35.37 / 26.81). On one R9700, which
|
||||
* has no junction to wait behind, the IQ8R trunk measured 49.57 / 47.94 without a drafter and
|
||||
* 56.13 / 54.23 with DFlash2.
|
||||
*
|
||||
* Not the routed build: its grouped GEMMs, router and gather have no chained form, and
|
||||
* Qwen3.6-35B-A3B on two R9700s measured a decode step of 10.27 / 11.77 / 12.35 ms at 1, 4 and
|
||||
* 8 sequences with them against 10.25 / 11.58 / 12.25 without. */
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
#endif
|
||||
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);
|
||||
@@ -1804,8 +1838,19 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
* expanded first, so these forward the expanded namespace. */
|
||||
#define QWEN35_PROBE_X(NS) RAD_ARCH_PROBE(NS)
|
||||
#define QWEN35_PLUGIN_X(NS, ...) RAD_ARCH_PLUGIN(NS, __VA_ARGS__)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
QWEN35_PROBE_X(QWEN35_NS)
|
||||
#if QWEN35_MOE
|
||||
#if QWEN35_MOE && QWEN35_W8A8
|
||||
QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "w8a8_fwht128", "0.1.0",
|
||||
"Qwen3.5 / 3.6 MoE (35B-A3B), an int8 trunk and int8 experts: i8 weights rotated "
|
||||
"by a 128-wide Hadamard against int8 activations the same rotation quantises; the "
|
||||
"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")
|
||||
/* An imported checkpoint is never a rotated int8 trunk: qwen35moe_fp8 serves those. */
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
#elif QWEN35_MOE
|
||||
QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "fp8_e4m3", "0.1.0",
|
||||
"Qwen3.5 / 3.6 MoE (35B-A3B), block-scaled fp8 weights and fp8 activations: the "
|
||||
"dense graph with a routed feed-forward (256 experts, 8 a token, and a shared "
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/qwen35moe_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(qwen35moe_w8a8 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(qwen35moe_w8a8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen35moe_w8a8.cpp)
|
||||
@@ -0,0 +1,19 @@
|
||||
/* qwen35moe_w8a8 -- Qwen3.5 / 3.6 MoE (35B-A3B) with an int8 trunk and int8 experts.
|
||||
*
|
||||
* arch/qwen35_fp8/qwen35_fp8.cpp built a fourth time, with both of its switches: the routed
|
||||
* feed-forward of qwen35moe_fp8 and the rotated int8 trunk of qwen35_w8a8. Every linear of the
|
||||
* trunk is IQ8R (`i8` codes rotated by a 128-wide Hadamard, read at i8a8h against int8
|
||||
* activations), and the routed experts are rotated int8 at a bf16 scale a (row, 128 of K) or one
|
||||
* of the rotated four-bit forms, read by the grouped GEMM's int8 rows from the codes the trunk's
|
||||
* own quantisers write (arch/common/rad_block_moe_fp8.h, MoeFP8::a8).
|
||||
*
|
||||
* A plugin of its own for the reason qwen35_w8a8 is: the quantisation descriptor is half of the
|
||||
* selection key (spec §2.4), and a container converted with data/recipes/q36-35b-a3b-iq8r.recipe
|
||||
* says `qwen35moe` and `w8a8_fwht128`.
|
||||
*/
|
||||
#define QWEN35_MOE 1
|
||||
#define QWEN35_W8A8 1
|
||||
#define QWEN35_NS qwen35moe_w8a8
|
||||
#define QWEN35_ARCH_ID "qwen35moe"
|
||||
|
||||
#include "../qwen35_fp8/qwen35_fp8.cpp"
|
||||
@@ -411,12 +411,13 @@ struct Model {
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
@@ -548,7 +549,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
/* An encoder pass runs the audio tower and nothing else (RadBatch::enc). */
|
||||
if (batch->enc) {
|
||||
m.aud.step(c, batch);
|
||||
@@ -615,6 +616,8 @@ static const RadAudioFormat* audio_format(const RadModelMeta* meta) {
|
||||
} /* namespace qwen3asr_bf16 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(qwen3asr_bf16, "qwen3asr", "", "0.1.0",
|
||||
"Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder; bf16 weights "
|
||||
"and activations")
|
||||
|
||||
@@ -95,6 +95,7 @@
|
||||
#include <arch/rad_block_moe_fp8.h>
|
||||
#include <arch/rad_block_mtp_hc.h>
|
||||
#include <arch/rad_block_ple.h>
|
||||
#include <arch/rad_calib_full.h>
|
||||
#include <arch/rad_qsa.h>
|
||||
#include <arch/rad_block_vit.h>
|
||||
|
||||
@@ -102,6 +103,23 @@ namespace qwen4exp_fp8 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
/* The delta net's out projection read into the on-die cache beside its decode recurrent update
|
||||
* (GdnFP8::op_pf_out): the update runs one workgroup per (sequence, head) and leaves the memory
|
||||
* mostly idle, and the projection behind it otherwise streams its weight cold. All of the weight
|
||||
* (the read stops at its end), on steps of up to kPrefetchRows rows and kGdnOutPrefetchSeqs
|
||||
* sequences. Flash-Next at tp 2 on two R9700s under the draft head at depth 3, ms a step without ->
|
||||
* with: one stream 12.78 -> 12.58, two 17.12 -> 16.95, four 23.57 -> 23.52 (level, as eight with
|
||||
* the window opened to it). The connection matrices read the same way, beside the recurrent update
|
||||
* or beside the writes in front of the reads, cost more than they gave (one stream 12.69 -> 12.88
|
||||
* and 13.17): a read here pays ~2 us of launch for what it saves. */
|
||||
constexpr int64_t kGdnOutPrefetchBytes = (int64_t)8 << 20;
|
||||
constexpr int64_t kGdnOutPrefetchSeqs = 4;
|
||||
/* A full-attention layer's out projection likewise, read behind its q, k and v projections
|
||||
* (AttnGatedFP8::op_pf_o): the prologue and the attention between them and the projection are
|
||||
* short launches with the memory idle. Twelve layers, so less: five interleaved rounds, ms a step
|
||||
* without -> with, one stream 12.51 -> 12.45 (every round), two 16.88 -> 16.85. */
|
||||
constexpr int64_t kAttnOutPrefetchBytes = (int64_t)8 << 20;
|
||||
|
||||
struct Layer {
|
||||
int full = 0;
|
||||
HyperConn hc_mix; /* in front of the attention or the delta net */
|
||||
@@ -115,6 +133,9 @@ struct Layer {
|
||||
* 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;
|
||||
/* The layer's calibration inputs (rad_calib_full.h, site_i8), -1 where this run records none:
|
||||
* the mixer's input (the delta net's in projection, or q, k and v) and its output projection's. */
|
||||
int cs_in = -1, cs_o = -1;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
@@ -125,6 +146,12 @@ struct Model {
|
||||
/* The trunk's linears are int8 (LinearFP8::i8), as read from the first delta-net layer's input
|
||||
* projection before the activation buffers are declared. */
|
||||
bool trunk_i8 = false;
|
||||
/* The trunk's int8 linears are stored rotated (i8a8h), read from the same weight: every
|
||||
* reader of the block input then takes the rotated codes the connections write. */
|
||||
bool trunk_rot = false;
|
||||
/* --calib-dir over the int8 trunk: the Hessian of each mixer linear's input, from the codes its
|
||||
* GEMM reads (rad_calib_full.h). */
|
||||
CalibFull calib;
|
||||
HyperConn::Config hccfg{};
|
||||
QsaIndexer::Config qsacfg{};
|
||||
QsaIndexer::Wire qsaw{};
|
||||
@@ -163,6 +190,9 @@ struct Model {
|
||||
* stays zero, since the bf16 source is `a_x`, unrotated. Declared only when the container asks
|
||||
* for a rotation; zero handles tell the MoE block the pair is absent. */
|
||||
ActFP8 a_hr{};
|
||||
/* The routed arm's activations are int8 (MoeFP8::a8): int8 connection codes under experts
|
||||
* with an int8 row. */
|
||||
bool arm8 = false;
|
||||
|
||||
rad_buf b_hout = 0, b_logits = 0;
|
||||
|
||||
@@ -215,7 +245,7 @@ struct Model {
|
||||
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* The n-gram table's row count, by prime search.
|
||||
*
|
||||
@@ -268,12 +298,13 @@ static void block_slice(int64_t nb, int world, int64_t place, int64_t* lo, int64
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* A sizing declare writes scratch: the step reads g_model, filled by the real declare at the
|
||||
* real max_tok (RadBuildCtx::shape_probe). */
|
||||
static thread_local Model probe_model;
|
||||
Model& m = ctx->shape_probe ? probe_model : g_model[ctx->rank];
|
||||
Model& m = ctx->shape_probe ? probe_model : g_model[rad_build_slot(ctx)];
|
||||
/* The reset drops the pinned window copy (pipe_bounds); free it first -- a re-declare of the
|
||||
* same rank (every rebuild, every test case) otherwise overwrites the pointer and leaks the
|
||||
* pin. The copy is read only by a step's memcpys, and no step runs across a declare. */
|
||||
@@ -663,36 +694,9 @@ 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;
|
||||
/* The MTP head's layer shares this group. */
|
||||
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
|
||||
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));
|
||||
g.kv_dtype = rad_dtype_name(fd.dtype);
|
||||
|
||||
RadKVGroupDecl sd{};
|
||||
sd.kind = RAD_KV_LINEAR;
|
||||
@@ -747,6 +751,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
{ nm.ckpt("%s.%lld.linear_attn.in_proj_qkv.weight", pre0, (long long)l),
|
||||
nm.ckpt("%s.%lld.linear_attn.in_proj_z.weight", pre0, (long long)l) }));
|
||||
m.trunk_i8 = m.layers[(size_t)l].gdn.in.probed_i8;
|
||||
/* Stored rotated (i8a8h: int8 codes or a narrower form on their grid, /fwht128): its
|
||||
* readers take had_quant_act_i8g's codes, one scale a 128 of K as the connections
|
||||
* write them. */
|
||||
RadEncoding enc{};
|
||||
m.trunk_rot = m.trunk_i8 &&
|
||||
weight_enc(b, nm.f("blk.%lld.ssm_inz.weight", (long long)l), &enc) &&
|
||||
(linear_is_w8h(enc) || linear_is_wnh(enc));
|
||||
if (m.trunk_rot && linear_w8h_group(enc) != RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: qwen4exp: the trunk's rotated int8 linears keep a scale "
|
||||
"a %lld of K; the connections write the block input's codes at one "
|
||||
"a %d\n", (long long)linear_w8h_group(enc), RAD_FP8_BLOCK);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -762,8 +779,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.b_h = decl_b(b, nm.f("h_wide"), g.act_dtype, {T, HN});
|
||||
m.a_x.x = decl_b(b, nm.f("x"), g.act_dtype, {T, g.n_embd});
|
||||
if (ctx->shape_probe) {
|
||||
m.span_on = g_model[ctx->rank].span_on;
|
||||
m.pipe_on = g_model[ctx->rank].pipe_on;
|
||||
m.span_on = g_model[rad_build_slot(ctx)].span_on;
|
||||
m.pipe_on = g_model[rad_build_slot(ctx)].pipe_on;
|
||||
} else {
|
||||
m.span_on = ctx->max_mixed_tok > 0 && ctx->max_mixed_tok < g.max_tok &&
|
||||
g.max_tok > m.moecfg.rows;
|
||||
@@ -790,8 +807,29 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* linear: the trunk's are, and the routed experts then read the rotated copy or the bf16
|
||||
* plane. When experts read the plain E4M3 codes, the connections keep those and the int8
|
||||
* linears quantise for themselves. */
|
||||
m.hccfg.codes_i8 = (m.trunk_i8 && (m.moecfg.expert_rot || m.moecfg.expert_bf16)) ? 1 : 0;
|
||||
/* A read's rotated copy takes its plain codes' dtype, so beside int8 codes the routed arm is
|
||||
* int8 too: the experts read had_quant_act_i8g's codes through the grouped GEMM's int8 rows
|
||||
* (MoeFP8::a8), which the rotated four-bit plane, the codebook at E4M3 scales a 64 or 32 of K
|
||||
* and rotated int8 experts have. The codebook at a bf16 scale a 128 and the five-bit one do
|
||||
* not: under them the connections keep E4M3 codes, as for unrotated experts. */
|
||||
const bool exp8 = m.moecfg.expert_rot && !m.moecfg.expert_w5 &&
|
||||
(!m.moecfg.expert_nl || m.moecfg.expert_g64);
|
||||
m.hccfg.codes_i8 = (m.trunk_i8 && (exp8 || m.moecfg.expert_bf16)) ? 1 : 0;
|
||||
m.a_x.q8_fed = m.hccfg.codes_i8 != 0;
|
||||
m.arm8 = m.hccfg.codes_i8 != 0 && exp8;
|
||||
/* A rotated trunk and the routed experts read one pair: the connections write the block
|
||||
* input's rotated codes as its own (HyperConn::xrot), and the routed arm takes those
|
||||
* (MoeFP8's gate_up input) with no second copy. */
|
||||
if (m.trunk_rot) {
|
||||
if (!m.hccfg.codes_i8) {
|
||||
fprintf(stderr, "radiance: qwen4exp: a rotated int8 trunk shares the block input's "
|
||||
"rotated codes with the routed experts, which then are rotated and "
|
||||
"have an int8 row (four-bit, the codebook at a 64 or 32 of K, int8), "
|
||||
"or plain bf16\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.a_x.q8_rot = true;
|
||||
}
|
||||
m.b_inj = decl_b(b, nm.f("hc_inj"), g.act_dtype, {T, m.hccfg.hc});
|
||||
|
||||
m.b_qg = decl_b(b, nm.f("attn_qg"), g.act_dtype, {T, g.n_head, 2 * g.head_dim});
|
||||
@@ -802,6 +840,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim, 0, m.trunk_i8));
|
||||
/* The gate epilogue in front of the int8 out projection writes its int8 codes itself. */
|
||||
m.a_attn.q8_fed = m.trunk_i8;
|
||||
m.a_attn.q8_rot = m.trunk_rot;
|
||||
/* The bf16 gate's own plane (AttnGatedFP8::Wire::gate); the fp8 path fuses it away. */
|
||||
if (g.w_bf16) m.b_gate = decl_b(b, nm.f("attn_gate"), g.act_dtype, {T, q_dim});
|
||||
/* The QSA indexer's planes, shared by every full-attention layer like `attn_out`. Declared
|
||||
@@ -869,6 +908,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* The delta net's output epilogue also writes its int8 codes; its prefill quantiser is the
|
||||
* int8 one. */
|
||||
m.a_go.q8_fed = m.trunk_i8;
|
||||
m.a_go.q8_rot = m.trunk_rot;
|
||||
|
||||
/* The model's expert count, not this rank's: the router is replicated and scores every
|
||||
* expert. */
|
||||
@@ -879,18 +919,36 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* PERSIST, not transient. `moe_scatter` writes the per-expert histogram and no declared op
|
||||
* reads it (rad_route_report is a handoff, not an op), so as a transient liveness would let a
|
||||
* later buffer alias it, and a wide prefill chunk would corrupt the counts (even negative).
|
||||
* One int32 per expert. */
|
||||
m.b_ecnt = decl_b(b, nm.f("moe_ecnt"), RAD_I32, {m.moecfg.n_expert},
|
||||
RAD_BUF_PERSIST);
|
||||
*
|
||||
* The model's routing table (rad_route_table): a row for each trunk layer and one for the
|
||||
* draft head, at the model's expert count, which is the core's pitch whatever share of the
|
||||
* experts this rank computes. Each router writes its layer's row, so a report copies nothing
|
||||
* and a layer's counts last until its next pass. */
|
||||
m.b_ecnt = decl_b(b, nm.f("moe_ecnt"), RAD_I32,
|
||||
{g.n_layer + 1, m.moecfg.n_expert_all}, RAD_BUF_PERSIST);
|
||||
RAD_ARCH_TRY(rad_route_table(b, m.b_ecnt));
|
||||
m.b_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {ER});
|
||||
m.b_egu = decl_b(b, nm.f("moe_egu"), g.act_dtype, {ER, 2 * m.moecfg.n_ff_exp});
|
||||
m.a_eff.x = decl_b(b, nm.f("moe_eff"), g.act_dtype, {ER, m.moecfg.n_ff_exp});
|
||||
/* ER rows, not max_tok: an expert plane has one row per (token, slot). declare_qs's default
|
||||
* would make it `top_k` times too short and the gated quantiser would overrun it (see
|
||||
* ActFP8::declare_qs). */
|
||||
RAD_ARCH_TRY(m.a_eff.declare_qs(b, nm, g, "moe_eff", m.moecfg.n_ff_exp, ER));
|
||||
if (m.moecfg.expert_rot)
|
||||
RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd));
|
||||
if (m.arm8) {
|
||||
/* The int8 routed arm's two pairs, rotated at a scale a 128 and written by their
|
||||
* producers: the gated product's by gated_had_quant_i8g, the input's by the read. */
|
||||
RAD_ARCH_TRY(m.a_eff.declare_qs(b, nm, g, "moe_eff", m.moecfg.n_ff_exp, ER, true, false,
|
||||
RAD_FP8_BLOCK));
|
||||
m.a_eff.q8_fed = m.a_eff.q8_rot = true;
|
||||
if (!m.trunk_rot) {
|
||||
RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd, 0, true, false,
|
||||
RAD_FP8_BLOCK));
|
||||
m.a_hr.q8_fed = m.a_hr.q8_rot = true;
|
||||
}
|
||||
} else {
|
||||
RAD_ARCH_TRY(m.a_eff.declare_qs(b, nm, g, "moe_eff", m.moecfg.n_ff_exp, ER));
|
||||
if (m.moecfg.expert_rot)
|
||||
RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd));
|
||||
}
|
||||
m.b_edn = decl_b(b, nm.f("moe_edn"), g.act_dtype, {ER, g.n_embd});
|
||||
m.b_emoe = decl_b(b, nm.f("moe_out"), g.act_dtype, {T, g.n_embd});
|
||||
if (m.moecfg.n_ff_shared > 0) {
|
||||
@@ -901,6 +959,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* The shared expert's gated quantiser in front of its int8 down projection writes its codes
|
||||
* too. */
|
||||
m.a_sff.q8_fed = m.trunk_i8;
|
||||
m.a_sff.q8_rot = m.trunk_rot;
|
||||
m.b_sout = decl_b(b, nm.f("moe_sout"), g.act_dtype, {T, g.n_embd});
|
||||
m.b_sgate = decl_b(b, nm.f("moe_sgate"), g.act_dtype, {T, 1});
|
||||
}
|
||||
@@ -994,6 +1053,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
mw.x = m.b_h; mw.h = m.a_x; mw.hr = m.a_hr;
|
||||
mw.logits = m.b_rlogits; mw.ids = m.b_eids; mw.ew = m.b_ew;
|
||||
mw.sorted = m.b_sorted; mw.eoff = m.b_eoff; mw.ecnt = m.b_ecnt;
|
||||
mw.ecnt_pitch = m.moecfg.n_expert_all;
|
||||
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;
|
||||
|
||||
@@ -1006,6 +1066,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* its collective a second time at `overlap` 1, for the rows that leave the CUs to that work
|
||||
* (the lane rows of libr4d/r4d_rows.cpp). */
|
||||
const int pipe_overlap = m.pipe_on ? 1 : 0;
|
||||
/* GPTQ calibration of the trunk (rad_calib_full.h). A bf16 trunk is recorded at any rank count
|
||||
* from the bf16 inputs, a column-split one gathered to its whole width; an int8 trunk at one
|
||||
* rank from the codes the connections and the mixers write themselves, so each tap reads what
|
||||
* the GEMM after it reads. */
|
||||
if (ctx->calib_dir && *ctx->calib_dir && m.trunk_i8 &&
|
||||
(g.world > 1 || !m.a_x.q8_fed || !m.a_attn.q8_fed || !m.a_go.q8_fed)) {
|
||||
fprintf(stderr, "radiance: qwen4exp: --calib-dir records an int8 trunk under int8-routed "
|
||||
"experts at --tp 1 only\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RAD_ARCH_TRY(m.calib.begin(b, nm, g, ctx, g.n_layer, std::max(q_dim, v_dim) * g.world,
|
||||
std::max<int64_t>(g.n_embd, std::max(q_dim, v_dim) * g.world)));
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.full = is_full_attention(l, interval) ? 1 : 0;
|
||||
@@ -1158,7 +1230,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* the shared arm takes, so the routed arm declares no quantiser of its own. */
|
||||
HyperConn::Config fcfg = m.hccfg;
|
||||
HyperConn::Wire fw = hw;
|
||||
if (m.moecfg.expert_rot) { fcfg.rotate = 1; fw.rq = m.a_hr.q; fw.rs = m.a_hr.s; }
|
||||
if (m.moecfg.expert_rot && !m.trunk_rot) {
|
||||
fcfg.rotate = 1; fw.rq = m.a_hr.cq(); fw.rs = m.a_hr.cs();
|
||||
}
|
||||
RAD_ARCH_TRY(lay.hc_ffn.declare(b, nm, g, nm.f("blk.%lld.ffn_hc", (long long)l),
|
||||
fcfg, fw, ffns));
|
||||
|
||||
@@ -1193,6 +1267,29 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* 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));
|
||||
|
||||
if (m.calib.records(l)) {
|
||||
/* Named by the container's weights, which is how a quantiser asks for a Hessian. */
|
||||
const ActFP8& ao = lay.full ? m.a_attn : m.a_go;
|
||||
const int64_t ko = lay.full ? q_dim : v_dim; /* this rank's columns of the output */
|
||||
const std::string L = "blk." + std::to_string(l);
|
||||
const std::string in_stem = L + (lay.full ? ".attn_qkv.input" : ".ssm_inz.input");
|
||||
const std::string in_lin = lay.full ? L + ".attn_qg," + L + ".attn_k," + L + ".attn_v"
|
||||
: L + ".ssm_inz";
|
||||
const std::string o_stem = L + (lay.full ? ".attn_output.input" : ".ssm_out.input");
|
||||
const std::string o_lin = L + (lay.full ? ".attn_output" : ".ssm_out");
|
||||
lay.cs_in = (int)m.calib.sites.size();
|
||||
if (m.trunk_i8) {
|
||||
const uint32_t dom = m.trunk_rot ? (uint32_t)RAD_FP8_BLOCK : 0u;
|
||||
RAD_ARCH_TRY(m.calib.site_i8(b, g, l, in_stem, in_lin, m.a_x.q8, m.a_x.s8, g.n_embd, dom));
|
||||
lay.cs_o = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site_i8(b, g, l, o_stem, o_lin, ao.q8, ao.s8, ko, dom));
|
||||
} else {
|
||||
RAD_ARCH_TRY(m.calib.site(b, g, l, in_stem, in_lin, m.a_x.x, g.n_embd, g.n_embd));
|
||||
lay.cs_o = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site(b, g, l, o_stem, o_lin, ao.x, ko, ko * g.world));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */
|
||||
@@ -1216,6 +1313,21 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_ARCH_TRY(m.mixer.declare(b, nm, g, nm.f("output_hc"), mc, mixw, mixs));
|
||||
}
|
||||
|
||||
/* ---- the delta nets' out projections, read beside their decode recurrent updates
|
||||
* (kGdnOutPrefetchBytes), and the full-attention layers' beside the attention
|
||||
* (kAttnOutPrefetchBytes). At more than one rank; --weight-prefetch off declares none. */
|
||||
if (g.world > 1 && !ctx->weight_prefetch_off && rad_op_declared(b, "prefetch")) {
|
||||
for (Layer& lay : m.layers) {
|
||||
if (lay.full) {
|
||||
lay.attn.op_pf_o = decl_prefetch(b, lay.attn.o.w, kAttnOutPrefetchBytes);
|
||||
continue;
|
||||
}
|
||||
lay.gdn.op_pf_out = decl_prefetch(b, lay.gdn.out.w, kGdnOutPrefetchBytes);
|
||||
lay.gdn.pf_out_rows = kPrefetchRows;
|
||||
lay.gdn.pf_out_seqs = kGdnOutPrefetchSeqs;
|
||||
}
|
||||
}
|
||||
|
||||
m.op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
@@ -1452,7 +1564,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
static bool pipelined(const Model& m, int64_t T) {
|
||||
const int64_t R = m.moecfg.rows;
|
||||
if (!m.pipe_on || R <= 0 || T <= R) return false;
|
||||
if (m.moecfg.calib || dbg_resid_on() || !m.op_embed_ar) return false;
|
||||
if (m.moecfg.calib || m.calib.on || dbg_resid_on() || !m.op_embed_ar) return false;
|
||||
for (const Layer& l : m.layers) {
|
||||
if (!(l.full ? l.attn.issues_ar(T) : l.gdn.issues_ar(T))) return false;
|
||||
if (!l.mlp.issues_ar(T, R)) return false;
|
||||
@@ -1626,10 +1738,14 @@ static void step_serial(RadCtx* c, const RadBatch* batch, Model& m, const int32_
|
||||
/* Before the attention connection reads the stream, which is where the reference puts it. */
|
||||
if (li == m.ple_layer) m.ple.step(c, batch);
|
||||
l.hc_mix.read_pieces(c, T);
|
||||
/* The calibration taps read the codes the mixer's GEMMs read: its input before it runs,
|
||||
* its output projection's input before the feed-forward's connection reuses the pair. */
|
||||
if (l.cs_in >= 0) m.calib.tap(c, (size_t)l.cs_in, T);
|
||||
/* The indexer runs first, since the attention reads its selection. The block's input is
|
||||
* already normed and quantised by the connection (`ext_in`), so `w.h` is final. */
|
||||
if (l.full) { l.qsa.step(c, l.attn.w.h, batch, pcu); l.attn.step(c, batch); }
|
||||
else l.gdn.step(c, batch);
|
||||
if (l.cs_o >= 0) m.calib.tap(c, (size_t)l.cs_o, T);
|
||||
l.hc_mix.write(c, T, 0, T);
|
||||
dbg_resid(c, (int)li, "mix", g.n_embd, m.b_h, m.a_x.x);
|
||||
l.hc_ffn.read_pieces(c, T);
|
||||
@@ -1639,10 +1755,11 @@ static void step_serial(RadCtx* c, const RadBatch* batch, Model& m, const int32_
|
||||
l.proj.step(c, batch, 0, T);
|
||||
dbg_resid(c, (int)li, "ffn", g.n_embd, m.b_h, m.a_x.x);
|
||||
}
|
||||
m.calib.after_step(c, T);
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
@@ -1669,8 +1786,12 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
* re-filling is idempotent. */
|
||||
if (m.op_rope_cs && T <= qk_fuse_rows(g) && !rope_mixed(batch))
|
||||
RAD_ISSUE_N(c, m.op_rope_cs, T, rope_pos1(batch, T), RAD_B(m.b_rope_cs));
|
||||
/* The n-gram rows of the pass's newest tokens, for the verify step that runs them:
|
||||
* hashed ahead of the head, fetched once the whole pass is issued (PleLayer::hint_ids). */
|
||||
if (m.ple_layer >= 0) m.ple.hint_ids(c, batch);
|
||||
m.mtp.qsa_win_cu = pipe_bounds(c, batch, m);
|
||||
m.mtp.step(c, batch);
|
||||
if (m.ple_layer >= 0) m.ple.hint_fetch(c, batch);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1700,34 +1821,16 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
uint64_t pass_key(RadCtx* c, const RadBatch* batch, const int32_t* used_max_h) {
|
||||
if (!c || !batch) return 0;
|
||||
if (batch->enc) return 1;
|
||||
/* Mixed batches split the query rows into decode and prefill subsets before attention; the
|
||||
* whole-batch host summary cannot key those subset geometries exactly. */
|
||||
if (batch->phase == RAD_PHASE_MIXED) return 0;
|
||||
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
/* Decode, verify and draft passes (the MTP head attends over the same KV group): every
|
||||
* attention launch covers all the pass's sequences, and the shape fields the core keys (n_tok,
|
||||
* n_seq, max_q_len, n_spec, draft_pass) fix each launch's q_len band and units. The live KV
|
||||
* length enters a split launcher's count only through the cap of eight 48-key tiles a split
|
||||
* (rad_prefill_splits_law; every head_dim 256 launcher has P_TILE 48), and from 64 splits up
|
||||
* the cap no longer binds. Keying that cap level lets these passes be recorded while each launch
|
||||
* still splits by its exact live length: answering 0 left them unrecorded (issue #402), and the
|
||||
* core's keyed bound for a plugin without the callback rounds the length up a bucket, which split
|
||||
* a short single-stream verify into several partials with a merge (x1 203 against 219 tok/s). */
|
||||
if (batch->phase != RAD_PHASE_PREFILL || batch->draft_pass != 0 || batch->n_spec > 0) {
|
||||
if (!m.kv_full || !used_max_h || !batch->kv) return 0;
|
||||
int group = -1;
|
||||
for (int i = 0; i < batch->n_kv_groups; ++i)
|
||||
if (batch->kv[i].group == m.kv_full) { group = i; break; }
|
||||
if (group < 0) return 2; // no full-attention KV in this pass: nothing splits by length
|
||||
const int used = used_max_h[group];
|
||||
if (used <= 0) return 0; // Missing host summary is not the same as an empty KV cache.
|
||||
constexpr int tile = 48;
|
||||
const int ctx = (m.g.max_ctx > 0 && used >= m.g.max_ctx) ? (int)m.g.max_ctx : used;
|
||||
const int cap = std::min(((ctx + tile - 1) / tile) / 8, 64);
|
||||
return 3 + (uint64_t)cap;
|
||||
}
|
||||
/* A decode pass, a speculative verify or an MTP draft included, issues every launch at the
|
||||
* step's keyed context bound (RadArgs::kv_used_max_h), never the live maximum, so the core's
|
||||
* key holds its geometry. */
|
||||
if (batch->phase == RAD_PHASE_DECODE) return 1;
|
||||
/* Mixed batches split the query rows into decode and prefill subsets before attention, which
|
||||
* read the live maximum. The whole-batch host summary cannot key those subset geometries
|
||||
* exactly, nor a drafter's or a verify's rows inside a prefill pass. */
|
||||
if (batch->phase == RAD_PHASE_MIXED || batch->draft_pass != 0 || batch->n_spec > 0) return 0;
|
||||
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
bool has_full_attention = false;
|
||||
for (const Layer& layer : m.layers) {
|
||||
if (!layer.full) continue;
|
||||
@@ -1772,23 +1875,12 @@ 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);
|
||||
}
|
||||
/* The gated residual applies a control vector after every block's write (HcProject). */
|
||||
out->control_vector_ok = 1;
|
||||
/* Chained launches pay with the MTP drafter: the speculative step's small kernels wait on the
|
||||
* previous one on the card instead of behind a queue barrier (libr4d/r4d_chain.h). On 2x R9700,
|
||||
* sampled at temperature 1 with a 25k prompt, MTP depth 3, with the chained hc_read forms:
|
||||
* 1/2/4/8/16 streams 174/291/458/657/851 -> 207/339/493/647/843 tok/s. */
|
||||
out->chain_pays = 1;
|
||||
/* A pass is about 930 launches, nearly all dependent, and the kernels of its decode heights
|
||||
* have chained forms: on two R9700 a full pass under the draft head went from 13.9 to 12.5 ms
|
||||
* and the step without the head from 9.98 to 9.17 ms at one sequence. */
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1796,6 +1888,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(qwen4exp_fp8)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(qwen4exp_fp8, "qwen4exp", "", "0.1.0",
|
||||
"Qwen4-Exp (Qwen3.8-Flash-Next): hybrid Gated DeltaNet / gated attention, a gated "
|
||||
"residual four streams wide and 512 routed experts, from a dense bf16 checkpoint "
|
||||
|
||||
@@ -29,9 +29,11 @@
|
||||
*
|
||||
* ============================== WHAT IS QUANTISED ==============================
|
||||
*
|
||||
* One plugin serves bf16 and block-fp8 containers: every linear of the language model and of the
|
||||
* DiT's blocks is a LinearFP8, which reads whatever the container holds (rad_fp8.h), and the model
|
||||
* is bf16 throughout when the first DiT projection is plain. The small linears around them
|
||||
* One plugin serves bf16, block-fp8 and rotated int8 (IQ8R) containers: every linear of the
|
||||
* language model and of the DiT's blocks is a LinearFP8, which reads whatever the container holds
|
||||
* (rad_fp8.h), and the model is bf16 throughout when the first DiT projection is plain. That
|
||||
* projection also says whether the linears are rotated int8, and then the activations they read
|
||||
* carry int8 codes in place of the E4M3 pair (declare_act). The small linears around them
|
||||
* (txt_in, img_in, the timestep MLP, the shared modulation, norm_out, proj_out), the vision tower
|
||||
* and the VAE stay bf16 in both, since they are read once per pass or less.
|
||||
*
|
||||
@@ -150,6 +152,11 @@ struct Model {
|
||||
ActFP8 a_hm{}, a_attn{}, a_ffn{};
|
||||
std::vector<DitLayer> dit;
|
||||
LinearFP8 qkv0{}; /* layer 0's qkv, as the probe that chose bf16 or fp8 mapped it */
|
||||
/* The linears of both networks are rotated int8 (IQ8R, or the 128-group int8 before it), read
|
||||
* off that same probe: the activations then carry int8 code pairs with one scale per (token,
|
||||
* `g8` columns) in place of the E4M3 pair. */
|
||||
bool i8 = false;
|
||||
int64_t g8 = RAD_FP8_BLOCK;
|
||||
int64_t C = 64; /* latent channels */
|
||||
rad_weight w_pout = 0;
|
||||
rad_op op_nout_ln = 0, op_pout = 0, op_euler = 0;
|
||||
@@ -168,7 +175,7 @@ struct Model {
|
||||
std::string lat_mean, lat_std;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* A space-separated list off the container (rad-convert flattens arrays that way). */
|
||||
static std::vector<double> meta_list(const RadModelMeta* m, const char* key) {
|
||||
@@ -239,6 +246,13 @@ static int check_format(const RadModelMeta* meta) {
|
||||
}
|
||||
|
||||
/* ================================================================== declare */
|
||||
/* An activation's code pair, `x` already declared: E4M3, or int8 for a rotated int8 model
|
||||
* (ActFP8::declare_pair). */
|
||||
static int declare_act(RadBuilder* b, Names& nm, const Geom& g, const Model& m, ActFP8& a,
|
||||
const char* name, int64_t n, const char* fed_op) {
|
||||
return a.declare_pair(b, nm, g, name, n, 0, m.i8, m.g8, fed_op);
|
||||
}
|
||||
|
||||
static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
Geom& g = m.gt;
|
||||
Names& nm = m.nm;
|
||||
@@ -253,14 +267,14 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, g.n_embd });
|
||||
m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, g.n_embd });
|
||||
RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", g.n_embd));
|
||||
RAD_ARCH_TRY(declare_act(b, nm, g, m, m.a_th, "te.h", g.n_embd, "had_quant_act_i8g"));
|
||||
m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim });
|
||||
m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim });
|
||||
RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim));
|
||||
RAD_ARCH_TRY(declare_act(b, nm, g, m, m.a_tattn, "te.attn", q_dim, "had_quant_act_i8g"));
|
||||
m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, g.n_embd });
|
||||
m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff));
|
||||
RAD_ARCH_TRY(declare_act(b, nm, g, m, m.a_tffn, "te.ffn", g.n_ff, "gated_had_quant_i8g"));
|
||||
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", g.n_embd),
|
||||
@@ -632,16 +646,16 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
|
||||
/* ---- the blocks */
|
||||
m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D });
|
||||
RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D));
|
||||
RAD_ARCH_TRY(declare_act(b, nm, g, m, m.a_hm, "dit.hm", D, "had_quant_act_i8g"));
|
||||
m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, 3 * qd });
|
||||
m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd });
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd));
|
||||
RAD_ARCH_TRY(declare_act(b, nm, g, m, m.a_attn, "dit.attn", qd, "had_quant_act_i8g"));
|
||||
m.b_ao = decl_b(b, nm.f("dit.ao"), RAD_BF16, { T, D });
|
||||
/* More than one rank: the all-reduces of b_ao's halves run on the second lane (step_blocks). */
|
||||
if (g.world > 1) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_ao));
|
||||
m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
|
||||
m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff });
|
||||
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff));
|
||||
RAD_ARCH_TRY(declare_act(b, nm, g, m, m.a_ffn, "dit.ffn", g.n_ff, "gated_had_quant_i8g"));
|
||||
|
||||
/* The rotary: three sections of adjacent pairs, (frame, row, column), each on its own ladder. */
|
||||
const std::vector<double> ax = meta_list(meta, "transformer.axes_dims_rope");
|
||||
@@ -667,12 +681,15 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
{ y, m.b_mod, x }, { x });
|
||||
};
|
||||
/* gate_add, ln_mod and the quantiser as one op, where the linears are fp8: `delta` is the
|
||||
* branch the norm adds in first, none for the first block's. */
|
||||
const bool fuse_norm = !g.w_bf16;
|
||||
* branch the norm adds in first, none for the first block's. An int8 model's is the rotating
|
||||
* twin, ln_mod_had_quant_i8g, where the kernels serve it and the codes are fed; otherwise it
|
||||
* takes the three apart. */
|
||||
const bool fuse_i8 = m.i8 && m.a_hm.q8_fed && rad_op_declared(b, "ln_mod_had_quant_i8g");
|
||||
const bool fuse_norm = m.i8 ? fuse_i8 : !g.w_bf16;
|
||||
auto ln_mod_q = [&](rad_buf delta) {
|
||||
rad_op op = RAD_OP(b, "ln_mod_quant_fp8",
|
||||
rad_op op = RAD_OP(b, m.i8 ? "ln_mod_had_quant_i8g" : "ln_mod_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_INT("group", m.a_hm.cg()),
|
||||
RAD_INT("gated", delta ? 1 : 0), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
if (!op) return op;
|
||||
@@ -812,8 +829,9 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -859,10 +877,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"transformer.transformer_blocks.0.attn.to_k.weight",
|
||||
"transformer.transformer_blocks.0.attn.to_v.weight" }));
|
||||
RadEncoding e{};
|
||||
const bool plain = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e) &&
|
||||
rad_enc_is(&e, "plain");
|
||||
const bool known = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e);
|
||||
const bool plain = known && rad_enc_is(&e, "plain");
|
||||
gd.w_bf16 = plain;
|
||||
m.gt.w_bf16 = plain;
|
||||
m.i8 = known && (linear_is_w8h(e) || linear_is_wnh(e));
|
||||
if (m.i8) m.g8 = linear_w8h_group(e);
|
||||
}
|
||||
|
||||
/* ---- the latent's normalisation, rounded to bf16 by the ops that read it */
|
||||
@@ -982,7 +1002,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.gt.rank, m.gt.world, meta_list(meta, "pipeline.sample_sigmas").empty() ? "" : " Turbo",
|
||||
(long long)m.gt.n_layer, (long long)m.gt.n_head, (long long)m.gt.n_head_kv,
|
||||
(long long)gd.n_layer, (long long)gd.n_head, (long long)gd.n_ff,
|
||||
gd.w_bf16 ? "bf16" : "block-fp8", m.media ? ", vision tower with deepstack" : "");
|
||||
gd.w_bf16 ? "bf16" : m.i8 ? "rotated int8" : "block-fp8",
|
||||
m.media ? ", vision tower with deepstack" : "");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1064,7 +1085,7 @@ static void step_blocks(RadCtx* c, const Model& m, int64_t R, int64_t S, const R
|
||||
const bool split = g.world > 1 && S == 1 && !slot && R >= 2;
|
||||
const int64_t hr0[2] = { 0, split ? R / 2 : R }, hn[2] = { hr0[1], R - hr0[1] };
|
||||
const int nh = split ? 2 : 1;
|
||||
const int64_t nD = D / RAD_FP8_BLOCK;
|
||||
const int64_t nD = D / m.a_hm.cg();
|
||||
|
||||
/* A half's all-reduce: on lane 1 behind everything lane 0 has issued, when split. */
|
||||
auto all_reduce = [&](rad_op op, int64_t r0, int64_t n) {
|
||||
@@ -1168,7 +1189,7 @@ static void step_encode(RadCtx* c, const Model& m, const uint16_t* px, int64_t h
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
const RadGenBatch* G = batch->gen_b;
|
||||
if (!batch->gen || !G) {
|
||||
rad_step_fail(c, "qwenimage21 is an image generator and runs generator passes only");
|
||||
@@ -1301,6 +1322,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(qwenimage21)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(qwenimage21, "qwenimage21", "", "0.1.0",
|
||||
"Qwen-Image 2.1 / 2.1-Turbo: Qwen3-VL-8B conditioning, a 7.1B single-stream "
|
||||
"diffusion transformer over a cached block-causal prefix, and a 2-D RGBA VAE; "
|
||||
|
||||
+7
-4
@@ -450,7 +450,7 @@ struct Model {
|
||||
rad_op op_dscale = 0, op_dcast = 0, op_rgb = 0;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* ================================================================== the recorded UNet's issue */
|
||||
RadOperand Net::opd(RadCtx* c, const Opd& o, const Geo& g) const {
|
||||
@@ -913,13 +913,14 @@ static int declare_decoder(RadBuilder* b, Model& m) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
if (ctx->world_size > 1) {
|
||||
fprintf(stderr, "radiance: sdxl runs on one card; serve it with a tensor-parallel size "
|
||||
"of 1\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
Names& nm = m.nm;
|
||||
@@ -1202,7 +1203,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
const Model& m = g_model[rad_slot(c)];
|
||||
if (!batch->gen || !batch->gen_b) {
|
||||
rad_step_fail(c, "sdxl is an image generator and runs generator passes only");
|
||||
return;
|
||||
@@ -1229,6 +1230,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(sdxl)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(sdxl, "sdxl", "", "0.1.0",
|
||||
"Stable Diffusion XL and its finetunes (Illustrious, NoobAI, Pony): CLIP ViT-L and "
|
||||
"OpenCLIP bigG text encoders, a 2.6B UNet sampled by k-diffusion's Euler, Euler "
|
||||
|
||||
@@ -59,7 +59,7 @@ struct Model {
|
||||
rad_kvgroup kv_draft = 0;
|
||||
bool have_ds = false;
|
||||
};
|
||||
static Model models[MAX_RANKS];
|
||||
static Model models[MAX_SLOTS];
|
||||
|
||||
/* Whether the container carries a drafter at all (`--draft-model` merged one under `draft.`), and
|
||||
* whether this file implements it. A drafter this plugin cannot run is refused at declare rather
|
||||
@@ -172,8 +172,10 @@ static bool needs_span(const Span& s, int64_t total, const Geom& g) {
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = models[ctx->rank];
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
Model& m = models[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
/* geom_from's even-only split cannot express a ragged GQA/FFN world. Read the whole geometry,
|
||||
@@ -399,7 +401,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rope.theta = (float)theta[kind];
|
||||
a.rq = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head, 0, rot[kind], "neox"), {m.q}, {m.q});
|
||||
a.rk = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head_kv, 0, rot[kind], "neox"), {m.k}, {m.k});
|
||||
a.attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
a.attn = rw(b, rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, T), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), RAD_INT("window", kind ? window : 0),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
@@ -468,7 +470,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = models[rad_rank(c)];
|
||||
Model& m = models[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
/* A drafter pass; the sign gives the kind. Positive is the query pass, which denoises the whole
|
||||
* block and proposes from it; negative is the context pass, which turns the tokens the trunk
|
||||
@@ -567,7 +569,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
#ifdef SPARK25_HAVE_PREFILL_SPLIT
|
||||
static uint64_t pass_key(RadCtx* c, const RadBatch* batch, const int32_t* used_max_h) {
|
||||
if (!c || !batch) return 0;
|
||||
Model& m = models[rad_rank(c)];
|
||||
Model& m = models[rad_slot(c)];
|
||||
int group = -1;
|
||||
if (batch->kv) for (int i = 0; i < batch->n_kv_groups; ++i)
|
||||
if (batch->kv[i].group == m.kv) { group = i; break; }
|
||||
@@ -615,6 +617,8 @@ static const RadChatFormat* chat_format(const RadModelMeta*) { return spark_chat
|
||||
}
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(spark25_bf16)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(spark25_bf16, "spark25", "", "0.1.0", "Spark X2.6 BF16")
|
||||
RAD_ARCH_CHAT_FORMAT(spark25_bf16)
|
||||
#ifdef SPARK25_HAVE_PREFILL_SPLIT
|
||||
|
||||
@@ -39,11 +39,13 @@ struct Request {
|
||||
#ifdef SPARK25_HAVE_PREFILL_SPLIT
|
||||
inline uint64_t pass_key(const Request& r) {
|
||||
if (r.enc) return 1;
|
||||
if (r.draft_pass != 0) return 0;
|
||||
/* Mixed and speculative passes can launch attention on sub-batches whose exact geometry
|
||||
* is not represented by the whole-batch summary. */
|
||||
if (r.phase == kPhaseMixed || r.n_spec > 0) return 0;
|
||||
if (r.phase != kPhasePrefill) return 1;
|
||||
/* A decode pass, a speculative verify or a draft included, issues every launch at the step's
|
||||
* keyed context bound (RadArgs::kv_used_max_h), never the live maximum, so the core's key
|
||||
* holds its geometry. */
|
||||
if (r.phase == kPhaseDecode) return 1;
|
||||
/* Mixed, drafting and speculative prefill passes can launch attention on sub-batches whose
|
||||
* exact geometry is not represented by the whole-batch summary. */
|
||||
if (r.phase == kPhaseMixed || r.draft_pass != 0 || r.n_spec > 0) return 0;
|
||||
if (r.head_dim != kHeadDim || r.gqa != kGqa || r.kv_heads <= 0 || !r.kv_group_found)
|
||||
return 0;
|
||||
/* For a singleton, these equalities prove the R4D q_len band and total_q used by its launch.
|
||||
|
||||
@@ -61,7 +61,7 @@ struct Model {
|
||||
rad_kvgroup kv_draft = 0;
|
||||
bool have_ds = false;
|
||||
};
|
||||
static Model models[MAX_RANKS];
|
||||
static Model models[MAX_SLOTS];
|
||||
|
||||
/* Whether the container carries a drafter at all (`--draft-model` merged one under `draft.`), and
|
||||
* whether this file implements it. A drafter this plugin cannot run is refused at declare rather
|
||||
@@ -186,9 +186,11 @@ static int check_format(const RadModelMeta* meta) {
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
|
||||
rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
Model& m = models[ctx->rank];
|
||||
Model& m = models[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
/* geom_from's even-only split cannot express a ragged GQA/FFN world. Read the whole geometry,
|
||||
@@ -454,7 +456,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
rope.theta = (float)theta[kind];
|
||||
a.rq = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head, 0, rot[kind], "neox"), {m.q}, {m.q});
|
||||
a.rk = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head_kv, 0, rot[kind], "neox"), {m.k}, {m.k});
|
||||
a.attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
a.attn = rw(b, rad_decl_op(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, T), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), RAD_INT("window", kind ? window : 0),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
@@ -520,7 +522,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = models[rad_rank(c)];
|
||||
Model& m = models[rad_slot(c)];
|
||||
const Geom& g = m.g;
|
||||
/* A drafter pass; the sign gives the kind. Positive is the query pass, which denoises the whole
|
||||
* block and proposes from it; negative is the context pass, which turns the tokens the trunk
|
||||
@@ -621,7 +623,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
#ifdef SPARK25_HAVE_PREFILL_SPLIT
|
||||
static uint64_t pass_key(RadCtx* c, const RadBatch* batch, const int32_t* used_max_h) {
|
||||
if (!c || !batch) return 0;
|
||||
Model& m = models[rad_rank(c)];
|
||||
Model& m = models[rad_slot(c)];
|
||||
int group = -1;
|
||||
if (batch->kv) for (int i = 0; i < batch->n_kv_groups; ++i)
|
||||
if (batch->kv[i].group == m.kv) { group = i; break; }
|
||||
@@ -669,6 +671,8 @@ static const RadChatFormat* chat_format(const RadModelMeta*) { return spark25_bf
|
||||
}
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(spark25_w8a8)
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PLUGIN(spark25_w8a8, "spark25", "w8a8_fwht128", "0.1.0",
|
||||
"Spark X2.6 with an int8 trunk: i8 weights with a bf16 scale a 128 of K, rotated "
|
||||
"by a 128-wide Hadamard, against int8 activations the same rotation quantises")
|
||||
|
||||
@@ -100,7 +100,7 @@ struct Model {
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
static Model g_model[MAX_SLOTS];
|
||||
|
||||
/* The per-MoE-layer norm and shared arm. The MoE block declares no norm in external-input mode,
|
||||
* and the shared expert must read the same normed row the routed experts do; the block's gather
|
||||
@@ -178,9 +178,10 @@ static int declare_moe_norm_and_shared(RadBuilder* b, Model& m, int l) {
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
Model& m = g_model[rad_build_slot(ctx)];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
@@ -488,7 +489,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
Model& m = g_model[rad_slot(c)];
|
||||
|
||||
if (batch->enc) {
|
||||
m.enc.step(c, batch);
|
||||
@@ -543,9 +544,22 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Chained launches pay on the plain-bf16 trunk: every kernel of its decode step but the cache's
|
||||
* two-dimensional copy and the vocabulary GEMM has a chained form (libr4d's rad_kernel_chain).
|
||||
* Unlimited-OCR on one R9700, ms a decode step unchained / chained: 2.79 / 2.49 at one sequence
|
||||
* and 4.51 / 4.19 at four. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->chain_pays = RAD_CHAIN_ALWAYS;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace unlimitedocr_bf16 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
|
||||
RAD_ARCH_MULTI_INSTANCE()
|
||||
RAD_ARCH_PROBE(unlimitedocr_bf16)
|
||||
RAD_ARCH_PLUGIN(unlimitedocr_bf16, "unlimitedocr", "", "0.1.0",
|
||||
"baidu/Unlimited-OCR decoder: 12-layer Llama-MoE (64 experts top-6 + 2 shared), "
|
||||
"bf16 weights and activations, full rotary MHA, with the DeepEncoder "
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# rad_simd_level_objects(<prefix> <source> <out-var> [DEFINE <macro>] [INCLUDES <dir>...])
|
||||
#
|
||||
# A host source compiled once per CPU level, as the core's util/simd_kernels.cpp is
|
||||
# (core/CMakeLists.txt): object libraries <prefix>_lvl0 .. _lvl4, each with <macro>=<level> and the
|
||||
# level's -m flags, position-independent so a plugin module can take them. <out-var> receives the
|
||||
# objects for target_sources. The levels: 0 baseline, 1 SSE4.1/4.2, 2 AVX, 3 AVX2 + FMA + F16C,
|
||||
# 4 AVX-512 F/BW/DQ/VL. Off x86-64 only level 0 is built; the source's dispatcher then has only the
|
||||
# scalar table. No other object may carry these flags: the dispatcher picks a level at runtime.
|
||||
function(rad_simd_level_objects prefix src out)
|
||||
cmake_parse_arguments(A "" "DEFINE" "INCLUDES" ${ARGN})
|
||||
if(NOT A_DEFINE)
|
||||
set(A_DEFINE RAD_SIMD_LEVEL)
|
||||
endif()
|
||||
set(flags_0 "")
|
||||
set(flags_1 -msse4.1 -msse4.2 -mpopcnt)
|
||||
set(flags_2 -mavx -mpopcnt)
|
||||
set(flags_3 -mavx2 -mfma -mf16c -mpopcnt)
|
||||
set(flags_4 -mavx512f -mavx512bw -mavx512dq -mavx512vl -mavx2 -mfma -mf16c -mpopcnt)
|
||||
if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$")
|
||||
set(levels 0 1 2 3 4)
|
||||
else()
|
||||
set(levels 0)
|
||||
endif()
|
||||
set(objs "")
|
||||
foreach(lvl ${levels})
|
||||
add_library(${prefix}_lvl${lvl} OBJECT ${src})
|
||||
target_compile_definitions(${prefix}_lvl${lvl} PRIVATE ${A_DEFINE}=${lvl})
|
||||
if(A_INCLUDES)
|
||||
target_include_directories(${prefix}_lvl${lvl} PRIVATE ${A_INCLUDES})
|
||||
endif()
|
||||
target_compile_options(${prefix}_lvl${lvl} PRIVATE ${flags_${lvl}})
|
||||
set_property(TARGET ${prefix}_lvl${lvl} PROPERTY POSITION_INDEPENDENT_CODE ON)
|
||||
list(APPEND objs $<TARGET_OBJECTS:${prefix}_lvl${lvl}>)
|
||||
endforeach()
|
||||
set(${out} ${objs} PARENT_SCOPE)
|
||||
endfunction()
|
||||
+47
-1
@@ -4,7 +4,7 @@
|
||||
# Sources are globbed per subdirectory with CONFIGURE_DEPENDS. Re-run cmake if a new file does not
|
||||
# appear.
|
||||
set(RAD_CORE_DIRS util device plugin build runtime mem sched place sample text server format mm diag gen
|
||||
lora kvstream)
|
||||
lora kvstream fleet)
|
||||
|
||||
set(RAD_CORE_SRC "")
|
||||
foreach(d ${RAD_CORE_DIRS})
|
||||
@@ -20,8 +20,54 @@ file(GLOB _top CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp)
|
||||
list(REMOVE_ITEM _top ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
|
||||
list(APPEND RAD_CORE_SRC ${_top})
|
||||
|
||||
# util/simd_kernels.cpp compiled once per ISA level, like libavx: the shipped binary runs on
|
||||
# machines it was not built on, so the level is picked at runtime (util/simd.cpp, baseline) and
|
||||
# no object outside these may carry a -m flag. The kernels plus the dispatcher form their own
|
||||
# small library rather than objects inside rad_core, because a no-core test compiles the
|
||||
# tokenizer translation units directly and still needs them. Off x86-64 only the scalar level
|
||||
# is built and the dispatcher never selects another.
|
||||
list(REMOVE_ITEM RAD_CORE_SRC ${CMAKE_CURRENT_SOURCE_DIR}/util/simd.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/util/simd_kernels.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/util/json.cpp)
|
||||
add_library(rad_core STATIC ${RAD_CORE_SRC})
|
||||
target_link_libraries(rad_core PUBLIC rad_abi ${CMAKE_DL_LIBS} Threads::Threads)
|
||||
|
||||
add_library(rad_simd STATIC ${CMAKE_CURRENT_SOURCE_DIR}/util/simd.cpp)
|
||||
target_include_directories(rad_simd PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
${CMAKE_SOURCE_DIR}/abi)
|
||||
set_property(TARGET rad_simd PROPERTY POSITION_INDEPENDENT_CODE ON)
|
||||
set(RAD_SIMD_FLAGS_0 "")
|
||||
set(RAD_SIMD_FLAGS_1 -msse4.1 -msse4.2 -mpopcnt)
|
||||
set(RAD_SIMD_FLAGS_2 -mavx -mpopcnt)
|
||||
set(RAD_SIMD_FLAGS_3 -mavx2 -mfma -mf16c -mpopcnt)
|
||||
set(RAD_SIMD_FLAGS_4 -mavx512f -mavx512bw -mavx512dq -mavx512vl -mavx2 -mfma -mf16c -mpopcnt)
|
||||
if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$")
|
||||
set(RAD_SIMD_LEVELS 0 1 2 3 4)
|
||||
target_compile_definitions(rad_simd PRIVATE RAD_SIMD_HAVE_X86_LEVELS=1)
|
||||
else()
|
||||
set(RAD_SIMD_LEVELS 0)
|
||||
endif()
|
||||
foreach(lvl ${RAD_SIMD_LEVELS})
|
||||
add_library(rad_simd_lvl${lvl} OBJECT ${CMAKE_CURRENT_SOURCE_DIR}/util/simd_kernels.cpp)
|
||||
target_compile_definitions(rad_simd_lvl${lvl} PRIVATE RAD_SIMD_LEVEL=${lvl})
|
||||
target_include_directories(rad_simd_lvl${lvl} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
${CMAKE_SOURCE_DIR}/abi)
|
||||
target_compile_options(rad_simd_lvl${lvl} PRIVATE ${RAD_SIMD_FLAGS_${lvl}})
|
||||
set_property(TARGET rad_simd_lvl${lvl} PROPERTY POSITION_INDEPENDENT_CODE ON)
|
||||
target_sources(rad_simd PRIVATE $<TARGET_OBJECTS:rad_simd_lvl${lvl}>)
|
||||
endforeach()
|
||||
target_link_libraries(rad_core PUBLIC rad_simd)
|
||||
|
||||
# The ordered JSON DOM (util/json.h), its own small library for the same reason rad_simd is:
|
||||
# the no-core test that compiles server/tokenizer units directly still needs it, and the
|
||||
# vendor chat lift links it without linking the core. yyjson stays an implementation detail
|
||||
# of util/json.cpp, so the link is private.
|
||||
add_library(rad_json STATIC ${CMAKE_CURRENT_SOURCE_DIR}/util/json.cpp)
|
||||
target_include_directories(rad_json PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
${CMAKE_SOURCE_DIR}/abi)
|
||||
set_property(TARGET rad_json PROPERTY POSITION_INDEPENDENT_CODE ON)
|
||||
target_link_libraries(rad_json PRIVATE rad_vendor_yyjson rad_simd)
|
||||
target_link_libraries(rad_core PUBLIC rad_json)
|
||||
target_compile_definitions(rad_core PUBLIC RAD_VERSION="${PROJECT_VERSION}")
|
||||
if(RAD_ENABLE_KV_ROLLBACK_TEST_HOOK)
|
||||
# Scheduler is embedded in Engine and its test-only callback changes its class layout.
|
||||
|
||||
@@ -133,6 +133,7 @@ public:
|
||||
int64_t from_hi, int64_t to_lo);
|
||||
int drafter_short_block(int64_t block);
|
||||
int drafter_tree(rad_buf parents);
|
||||
int route_table(rad_buf table);
|
||||
int declare_encoder(const RadEncoderDecl* d);
|
||||
int declare_generator(const RadGeneratorDecl* d);
|
||||
int declare_audio_generator(const RadAudioGenDecl* d);
|
||||
@@ -267,6 +268,8 @@ std::string dump_graph_str(const Program& p, const std::vector<std::string>* err
|
||||
|
||||
/* The same walk as JSON, for the server's Model view, grouped by (op, band table): an op declared
|
||||
* once per layer with one bucket table is one row with a count. */
|
||||
std::string dump_graph_json(const Program& p);
|
||||
/* `reg` is the registry the program was selected through (an engine's share), null for the process
|
||||
* registry; the dump replays selections against its device facts. */
|
||||
std::string dump_graph_json(const Program& p, Registry* reg = nullptr);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -191,11 +191,12 @@ rad_weight Builder::decl_weight(const char* name, const RadWeightDecl* d) {
|
||||
while (!role.empty() && role.front() == ' ') role.erase(role.begin());
|
||||
while (!role.empty() && role.back() == ' ') role.pop_back();
|
||||
const int k = rad_enc_find(&w.enc, role.c_str());
|
||||
char e[256];
|
||||
rad_enc_format(&w.enc, e, sizeof e);
|
||||
if (k < 0)
|
||||
if (k < 0) {
|
||||
char e[256];
|
||||
rad_enc_format(&w.enc, e, sizeof e);
|
||||
return err(RAD_E_SHAPE, "weight '%s' takes plane '%s' of '%s', which is %s and has "
|
||||
"no such plane", n.c_str(), role.c_str(), w.source.c_str(), e);
|
||||
}
|
||||
if (w.n_sel == RAD_ENC_MAX_PLANES)
|
||||
return err(RAD_E_INVAL, "weight '%s': more than %d planes", n.c_str(),
|
||||
RAD_ENC_MAX_PLANES);
|
||||
@@ -214,14 +215,15 @@ rad_weight Builder::decl_weight(const char* name, const RadWeightDecl* d) {
|
||||
(p0.dtype == RAD_BF16 || p0.dtype == RAD_F16);
|
||||
/* A bf16 readout head over an f32 checkpoint tensor: the loader rounds it to bf16. */
|
||||
const bool narrow = w.n_sel == 1 && d->dtype == RAD_BF16 && p0.dtype == RAD_F32;
|
||||
char e[256];
|
||||
rad_enc_format(&w.enc, e, sizeof e);
|
||||
if (!widen && !narrow)
|
||||
if (!widen && !narrow) {
|
||||
char e[256];
|
||||
rad_enc_format(&w.enc, e, sizeof e);
|
||||
return err(RAD_E_DTYPE, "weight '%s' is declared %s, and '%s' holds %s as %s: only an "
|
||||
"exact widening or narrowing is done at load; anything else "
|
||||
"is a quantisation, which a recipe does before the container "
|
||||
"is written (spec §4.4)", n.c_str(), rad_dtype_name(d->dtype),
|
||||
w.source.c_str(), p0.role, e);
|
||||
}
|
||||
w.widen = widen;
|
||||
w.narrow = narrow;
|
||||
}
|
||||
@@ -269,7 +271,7 @@ rad_weight Builder::decl_weight(const char* name, const RadWeightDecl* d) {
|
||||
w.stored_shape[i] = i < d->rank ? d->shape[i] : 0;
|
||||
w.align = RAD_ALIGN_UNIT;
|
||||
|
||||
prog_.weights.push_back(w);
|
||||
prog_.weights.push_back(std::move(w));
|
||||
const rad_weight h = (rad_weight)(prog_.weights.size() - 1);
|
||||
weight_by_name_.emplace(prog_.weights.back().name, h);
|
||||
return h;
|
||||
@@ -480,7 +482,8 @@ int64_t Builder::kv_layer_bytes(rad_kvgroup g) {
|
||||
const int64_t bs = kv_block_size(g);
|
||||
if (bs <= 0) return 0;
|
||||
const int64_t nh = gi.decl.n_head_kv > 0 ? gi.decl.n_head_kv : 1;
|
||||
return rad_dtype_bytes(gi.decl.dtype, 2 * bs * nh * gi.decl.head_dim);
|
||||
return rad_dtype_bytes(gi.decl.dtype,
|
||||
bs * nh * rad_kv_row_elems(gi.decl.dtype, gi.decl.head_dim));
|
||||
}
|
||||
|
||||
/* ================================================================== ops */
|
||||
@@ -2276,6 +2279,38 @@ int Builder::drafter_tree(rad_buf parents) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The routing counts' storage (rad_builder.h). The row count is checked in Ctx::bind_routing,
|
||||
* which knows the reporting layers. */
|
||||
int Builder::route_table(rad_buf table) {
|
||||
if (finished_) {
|
||||
err(RAD_E_STATE, "route_table after declare finished");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (prog_.route_table != RAD_NULL_HANDLE) {
|
||||
err(RAD_E_STATE, "route_table: buffer '%s' is already the routing table",
|
||||
prog_.buffers[prog_.route_table].name.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (table == RAD_NULL_HANDLE || (size_t)table >= prog_.buffers.size()) {
|
||||
err(RAD_E_INVAL, "route_table: buffer %u is not a declared buffer", (unsigned)table);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const BufferInfo& bi = prog_.buffers[table];
|
||||
if (bi.decl.dtype != RAD_I32) {
|
||||
err(RAD_E_DTYPE, "route_table: buffer '%s' is not i32", bi.name.c_str());
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (bi.decl.domain != RAD_DOMAIN_DEVICE || bi.decl.kind != RAD_BUF_PERSIST) {
|
||||
err(RAD_E_INVAL, "route_table: buffer '%s' must be a RAD_BUF_PERSIST device buffer: the "
|
||||
"core reads its rows at the end of every pass and between passes, where a "
|
||||
"transient's bytes belong to whichever buffer shares them",
|
||||
bi.name.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
prog_.route_table = table;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void Builder::note_v(const char* f, va_list ap) {
|
||||
char msg[1024];
|
||||
vsnprintf(msg, sizeof msg, f ? f : "", ap);
|
||||
@@ -2496,7 +2531,8 @@ void Builder::finish_kv_groups() {
|
||||
case RAD_KV_RING:
|
||||
/* One block holds K and V for block_size tokens, the block manager's unit. */
|
||||
gi.bytes_per_block =
|
||||
rad_dtype_bytes(d.dtype, 2 * gi.block_size * elem_n_head * d.head_dim) * n_bound;
|
||||
rad_dtype_bytes(d.dtype, gi.block_size * elem_n_head *
|
||||
rad_kv_row_elems(d.dtype, d.head_dim)) * n_bound;
|
||||
gi.bytes_per_state = 0;
|
||||
break;
|
||||
case RAD_KV_LINEAR:
|
||||
@@ -2838,6 +2874,11 @@ int rad_drafter_tree(RadBuilder* b, rad_buf parents) {
|
||||
return B(b)->drafter_tree(parents);
|
||||
}
|
||||
|
||||
int rad_route_table(RadBuilder* b, rad_buf table) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->route_table(table);
|
||||
}
|
||||
|
||||
int rad_chain_on(void) { return rad_dev_chain_enabled(); }
|
||||
|
||||
int rad_drafter_short_block(RadBuilder* b, int64_t block) {
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
#include "startup.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
@@ -27,7 +27,7 @@
|
||||
namespace rad {
|
||||
|
||||
/* ordered_json keeps keys in insertion order rather than alphabetical. */
|
||||
using json = nlohmann::ordered_json;
|
||||
using json = Json;
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -564,8 +564,8 @@ static json weight_json(const WeightInfo& w) {
|
||||
return j;
|
||||
}
|
||||
|
||||
std::string dump_graph_json(const Program& p) {
|
||||
Registry& reg = rad_tools_registry();
|
||||
std::string dump_graph_json(const Program& p, Registry* r) {
|
||||
Registry& reg = r ? *r : rad_tools_registry();
|
||||
json root;
|
||||
json meta;
|
||||
meta["arch"] = p.meta.arch_id ? p.meta.arch_id : "";
|
||||
|
||||
+105
-41
@@ -13,6 +13,8 @@
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -28,6 +30,44 @@ Registry& rad_tools_registry() {
|
||||
return *r;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ engines in one process */
|
||||
|
||||
namespace {
|
||||
std::mutex g_claim_mu;
|
||||
bool g_slot_held[RAD_MAX_SLOTS] = {};
|
||||
std::map<std::string, int> g_arch_engines; /* arch plugin -> engines holding it */
|
||||
} // namespace
|
||||
|
||||
int rad_engine_claim(const std::string& arch_plugin, int n_ranks, int* slot_base) {
|
||||
std::lock_guard<std::mutex> lk(g_claim_mu);
|
||||
const Plugin* ap = rad_tools_registry().plugin(arch_plugin);
|
||||
if (ap && !ap->arch_multi_instance && g_arch_engines[arch_plugin] > 0) {
|
||||
RAD_ERR("architecture plugin '%s' keeps one model's state per process and already backs "
|
||||
"a running model; it does not export rad_arch_multi_instance, so a second model on "
|
||||
"it cannot run beside the first", arch_plugin.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
for (int base = 0; base + n_ranks <= RAD_MAX_SLOTS; ++base) {
|
||||
bool free = true;
|
||||
for (int i = 0; i < n_ranks && free; ++i) free = !g_slot_held[base + i];
|
||||
if (!free) continue;
|
||||
for (int i = 0; i < n_ranks; ++i) g_slot_held[base + i] = true;
|
||||
++g_arch_engines[arch_plugin];
|
||||
*slot_base = base;
|
||||
return RAD_OK;
|
||||
}
|
||||
RAD_ERR("no %d free instance slot(s) in a row: the process holds at most %d ranks across its "
|
||||
"models (RAD_MAX_SLOTS)", n_ranks, RAD_MAX_SLOTS);
|
||||
return RAD_E_FULL;
|
||||
}
|
||||
|
||||
void rad_engine_release(const std::string& arch_plugin, int slot_base, int n_ranks) {
|
||||
std::lock_guard<std::mutex> lk(g_claim_mu);
|
||||
for (int i = 0; i < n_ranks && slot_base + i < RAD_MAX_SLOTS; ++i) g_slot_held[slot_base + i] = false;
|
||||
auto it = g_arch_engines.find(arch_plugin);
|
||||
if (it != g_arch_engines.end() && --it->second <= 0) g_arch_engines.erase(it);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the reference-kernel gate */
|
||||
|
||||
/* An op is "on the reference" when no band in any domain offers a non-reference kernel
|
||||
@@ -119,46 +159,10 @@ static std::vector<std::string> home_subdirs(const std::string& home, const char
|
||||
return out;
|
||||
}
|
||||
|
||||
int rad_tools_load_plugins(const std::string& home, const std::vector<std::string>& hierarchy,
|
||||
const std::string& arch_id, const std::string& quant,
|
||||
LoadedPlugins* out, bool imported) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = LoadedPlugins{};
|
||||
|
||||
Registry& r = rad_tools_registry();
|
||||
|
||||
/* Kernels first, in hierarchy order, then architectures (unordered: no two may claim the same
|
||||
* id). A home need not have every directory, but kernels/ and architectures/ must each exist
|
||||
* somewhere on the path, or the scan reports the first home's as missing. */
|
||||
const std::string first = rad_home_dirs(home).front();
|
||||
std::vector<std::string> kdirs = home_subdirs(home, "kernels");
|
||||
if (kdirs.empty()) kdirs.push_back(first + "/kernels");
|
||||
int s = r.load_dirs(kdirs, hierarchy);
|
||||
if (s < 0) return s;
|
||||
|
||||
std::vector<std::string> adirs = home_subdirs(home, "architectures");
|
||||
if (adirs.empty()) adirs.push_back(first + "/architectures");
|
||||
s = r.load_dirs(adirs, {});
|
||||
if (s < 0) return s;
|
||||
|
||||
/* Quantisers: rad-convert drives them, and the oracle decodes through them for schemes the
|
||||
* core does not define. Optional. */
|
||||
const std::vector<std::string> qdirs = home_subdirs(home, "quantizers");
|
||||
if (!qdirs.empty()) {
|
||||
s = r.load_dirs(qdirs, {});
|
||||
if (s < 0) return s;
|
||||
}
|
||||
|
||||
RAD_TRY(r.check_complete());
|
||||
|
||||
/* The tuning cache, once the kernel set is known. A missing file leaves every shape on its
|
||||
* plugin's first variant. Logged when it has rows; --debug-graph shows the per-shape
|
||||
* source. */
|
||||
const std::string tune = rad_home_file(home, TuneCache::rel_path(rad_machine_key()));
|
||||
const std::string tune_home = tune.substr(0, tune.size() - TuneCache::rel_path(rad_machine_key()).size() - 1);
|
||||
const int n_tuned = r.load_tune(tune_home);
|
||||
if (n_tuned > 0) RAD_INFO("tune cache: %d row(s) from %s", n_tuned, tune.c_str());
|
||||
|
||||
/* The architecture plugin for (arch_id, quant) among a loaded set, and the kernel libraries it
|
||||
* selects from, into *out. */
|
||||
static int pick_arch(Registry& r, const std::string& home, const std::string& arch_id,
|
||||
const std::string& quant, LoadedPlugins* out, bool imported) {
|
||||
/* The selection key is the (arch_id, quant) pair (spec §2.4), matched exactly with no
|
||||
* fallback; a mismatched plugin would only fail later at the name map with a worse message. */
|
||||
for (const Plugin& p : r.plugins()) {
|
||||
@@ -240,6 +244,66 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int rad_tools_load_plugins(const std::string& home, const std::vector<std::string>& hierarchy,
|
||||
const std::string& arch_id, const std::string& quant,
|
||||
LoadedPlugins* out, bool imported) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = LoadedPlugins{};
|
||||
|
||||
Registry& r = rad_tools_registry();
|
||||
|
||||
/* One plugin set serves every engine in the process (registry.h, Sharing): the first load
|
||||
* reads the homes, a later one finds the set loaded and only picks its architecture. The home
|
||||
* and the hierarchy are server-level settings, so every engine asks for the same set; a
|
||||
* different one is refused rather than served from the wrong libraries. */
|
||||
static std::string loaded_home;
|
||||
static std::vector<std::string> loaded_hierarchy;
|
||||
if (!r.plugins().empty()) {
|
||||
if (home != loaded_home || hierarchy != loaded_hierarchy) {
|
||||
RAD_ERR("the plugin set is already loaded from %s; every model in a process uses the "
|
||||
"same radiance-home and kernels", loaded_home.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
return pick_arch(r, home, arch_id, quant, out, imported);
|
||||
}
|
||||
loaded_home = home;
|
||||
loaded_hierarchy = hierarchy;
|
||||
|
||||
/* Kernels first, in hierarchy order, then architectures (unordered: no two may claim the same
|
||||
* id). A home need not have every directory, but kernels/ and architectures/ must each exist
|
||||
* somewhere on the path, or the scan reports the first home's as missing. */
|
||||
const std::string first = rad_home_dirs(home).front();
|
||||
std::vector<std::string> kdirs = home_subdirs(home, "kernels");
|
||||
if (kdirs.empty()) kdirs.push_back(first + "/kernels");
|
||||
int s = r.load_dirs(kdirs, hierarchy);
|
||||
if (s < 0) return s;
|
||||
|
||||
std::vector<std::string> adirs = home_subdirs(home, "architectures");
|
||||
if (adirs.empty()) adirs.push_back(first + "/architectures");
|
||||
s = r.load_dirs(adirs, {});
|
||||
if (s < 0) return s;
|
||||
|
||||
/* Quantisers: rad-convert drives them, and the oracle decodes through them for schemes the
|
||||
* core does not define. Optional. */
|
||||
const std::vector<std::string> qdirs = home_subdirs(home, "quantizers");
|
||||
if (!qdirs.empty()) {
|
||||
s = r.load_dirs(qdirs, {});
|
||||
if (s < 0) return s;
|
||||
}
|
||||
|
||||
RAD_TRY(r.check_complete());
|
||||
|
||||
/* The tuning cache, once the kernel set is known. A missing file leaves every shape on its
|
||||
* plugin's first variant. Logged when it has rows; --debug-graph shows the per-shape
|
||||
* source. */
|
||||
const std::string tune = rad_home_file(home, TuneCache::rel_path(rad_machine_key()));
|
||||
const std::string tune_home = tune.substr(0, tune.size() - TuneCache::rel_path(rad_machine_key()).size() - 1);
|
||||
const int n_tuned = r.load_tune(tune_home);
|
||||
if (n_tuned > 0) RAD_INFO("tune cache: %d row(s) from %s", n_tuned, tune.c_str());
|
||||
|
||||
return pick_arch(r, home, arch_id, quant, out, imported);
|
||||
}
|
||||
|
||||
/* Optional export. Without it, or on failure, every field is zero and the caller uses its own
|
||||
* defaults. A failed probe is not an error: the plugin can still refuse in declare, where it has
|
||||
* the whole configuration and can say why. */
|
||||
@@ -398,7 +462,7 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
|
||||
const LoraDeclare* lora) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
|
||||
Registry& r = rad_tools_registry();
|
||||
Registry& r = lp.registry ? *lp.registry : rad_tools_registry();
|
||||
const Plugin* ap = r.plugin(lp.arch_plugin);
|
||||
if (!ap || !ap->arch_declare) {
|
||||
RAD_ERR("architecture plugin '%s' is not loaded or exports no rad_arch_declare",
|
||||
|
||||
@@ -35,6 +35,9 @@ struct LoadedPlugins {
|
||||
std::string arch_id;
|
||||
/* The quantisation half of the selection key, "" for an unquantised container. */
|
||||
std::string arch_quant;
|
||||
/* The registry declare selects through: an engine's own share of the process set
|
||||
* (Registry::share), or null for the process registry itself, as the tools use. */
|
||||
Registry* registry = nullptr;
|
||||
|
||||
/* `name@version`, space separated, in hierarchy order; what a benchmark records as the
|
||||
* libraries measured. */
|
||||
@@ -178,4 +181,12 @@ int rad_gate_reference_kernels(const Program& p, bool allow, const char* what);
|
||||
|
||||
Registry& rad_tools_registry();
|
||||
|
||||
/* Engines in one process (docs/MULTIMODEL.md §3.3). Each holds, while it lives, a contiguous block
|
||||
* of `n_ranks` instance slots, whose first is its RadBuildCtx::slot_base, and a claim on its
|
||||
* architecture plugin. A plugin that does not export rad_arch_multi_instance backs one engine at a
|
||||
* time: a second claim on it is refused by name. RAD_OK with *slot_base set, or a negative status
|
||||
* after a RAD_ERR line saying why. Release returns the slots and the claim. */
|
||||
int rad_engine_claim(const std::string& arch_plugin, int n_ranks, int* slot_base);
|
||||
void rad_engine_release(const std::string& arch_plugin, int slot_base, int n_ranks);
|
||||
|
||||
} /* namespace rad */
|
||||
+29
-45
@@ -13,7 +13,7 @@
|
||||
#include "util/kernel_list.h"
|
||||
#include "place/planner.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
@@ -30,11 +30,7 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
struct Flag {
|
||||
const char* name;
|
||||
const char* arg; /* null for a boolean */
|
||||
const char* help;
|
||||
};
|
||||
using Flag = ConfigFlag;
|
||||
|
||||
/* Built from kDraftWindowDefault so the default is stated once. Defined before the table that
|
||||
* points at it, which fixes their initialisation order. */
|
||||
@@ -93,21 +89,19 @@ static const Flag g_flags[] = {
|
||||
"Not with --gpu-headroom-mib" },
|
||||
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96).\n"
|
||||
"Not with --gpu-memory-mib" },
|
||||
{ "--kv-cache-dtype", "T", "bf16 | 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" },
|
||||
{ "--kv-cache-dtype", "T", "bf16 (default) | i8 | fp8 -- i8 halves what a token of\n"
|
||||
"context costs: K and V as int8 with one scale each per token\n"
|
||||
"and head. fp8 (E4M3) is GLM-5.3's latent cache only" },
|
||||
{ "--state-cache-dtype", "T", "f32 (default) | f16 -- the recurrent state cache (delta net):\n"
|
||||
"f16 halves the state pool, its checkpoints and its traffic,\n"
|
||||
"and is lossy; the qwen35 plugins serve it" },
|
||||
{ "--attn-prefill-fp8", "MODE", "off (default) | qk | pv | both -- the prefill attention's\n"
|
||||
"Q.K^T, P.V or both as e4m3 WMMA over an fp8, fp8_v4 or\n"
|
||||
"k6_v4 cache: faster at long context, and lossy" },
|
||||
{ "--kv-resident", "N", "stream the sparse attention group's KV from host memory,\n"
|
||||
" keeping N tokens of it in a VRAM ring (0, the default, is\n"
|
||||
" off). Raised to 32768 and to what one decode step selects;\n"
|
||||
" a ring that covers the context (sequences x\n"
|
||||
" --max-model-len) streams nothing" },
|
||||
{ "--host-pool-mib", "N", "pinned host tier" },
|
||||
{ "--host-pool-mib", "N", "pinned host tier for weights, in all: the ranks of a model\n"
|
||||
" pin equal shares of it (N / --tp each)" },
|
||||
{ "--host-headroom-mib", "N", "host RAM to leave free for the system when radiance\n"
|
||||
" pins its host memory at startup (default 4096)" },
|
||||
{ "--embedding-placement", "WHERE", "ram (default) | vram: where the token embedding lives. ram\n"
|
||||
@@ -381,6 +375,11 @@ static const Flag g_flags[] = {
|
||||
{ "--help", nullptr, "this" },
|
||||
};
|
||||
|
||||
const ConfigFlag* config_flags(size_t* n) {
|
||||
*n = sizeof g_flags / sizeof g_flags[0];
|
||||
return g_flags;
|
||||
}
|
||||
|
||||
void config_usage(const char* argv0) {
|
||||
fprintf(stderr, "usage: %s --model FILE [options]\n\n", argv0);
|
||||
/* Align help continuation lines under the first, whatever indentation the string carries. */
|
||||
@@ -486,7 +485,7 @@ static bool parse_template_kwargs(const char* v, std::map<std::string, std::stri
|
||||
src += " " + text.substr(1);
|
||||
text = ss.str();
|
||||
}
|
||||
const nlohmann::json j = nlohmann::json::parse(text, nullptr, false);
|
||||
const Json j = Json::parse(text, nullptr, false);
|
||||
if (j.is_discarded() || !j.is_object()) {
|
||||
RAD_ERR("%s takes a JSON object, such as '{\"enable_thinking\": false}'", src.c_str());
|
||||
return false;
|
||||
@@ -511,6 +510,7 @@ static bool parse_template_kwargs(const char* v, std::map<std::string, std::stri
|
||||
/* Returns 0 on success, 1 for --help (caller exits 0), negative on a bad argument. An unknown flag
|
||||
* is an error, not a warning, since a mistyped budget flag changes the plan. */
|
||||
int config_parse(int argc, char** argv, Config* c) {
|
||||
bool pool_all = false; /* --host-pool-mib was given: a total, split among the ranks at the end */
|
||||
/* --help wins from anywhere on the line, even after an otherwise fatal argument. */
|
||||
for (int i = 1; i < argc; ++i)
|
||||
if (!std::strcmp(argv[i], "--help") || !std::strcmp(argv[i], "-h")) return 1;
|
||||
@@ -619,9 +619,13 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
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") && 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);
|
||||
if (!std::strcmp(v, "fp8_v4") || !std::strcmp(v, "k6_v4")) {
|
||||
RAD_ERR("--kv-cache-dtype %s: the packed caches are no longer served; i8 is the "
|
||||
"8-bit cache (int8 K and V, a scale each per token and head)", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (std::strcmp(v, "bf16") && std::strcmp(v, "i8") && std::strcmp(v, "fp8")) {
|
||||
RAD_ERR("--kv-cache-dtype takes bf16, i8 or fp8, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->kv_cache_dtype = v;
|
||||
@@ -634,19 +638,8 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
c->state_cache_dtype = v;
|
||||
}
|
||||
else if (S("--attn-prefill-fp8")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "off")) c->attn_prefill_fp8 = 0;
|
||||
else if (!std::strcmp(v, "qk")) c->attn_prefill_fp8 = RAD_ATTN_FP8_QK;
|
||||
else if (!std::strcmp(v, "pv")) c->attn_prefill_fp8 = RAD_ATTN_FP8_PV;
|
||||
else if (!std::strcmp(v, "both")) c->attn_prefill_fp8 = RAD_ATTN_FP8_QK | RAD_ATTN_FP8_PV;
|
||||
else {
|
||||
RAD_ERR("--attn-prefill-fp8 takes off, qk, pv or both, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--kv-resident")) { if (!num(0, INT64_MAX, &c->kv_resident)) return RAD_E_INVAL; }
|
||||
else if (S("--host-pool-mib")) { if (!num(0, INT64_MAX, &c->host_pool_mib)) return RAD_E_INVAL; }
|
||||
else if (S("--host-pool-mib")) { if (!num(0, INT64_MAX, &c->host_pool_mib)) return RAD_E_INVAL; pool_all = true; }
|
||||
else if (S("--embedding-placement") || S("--ngram-placement")) {
|
||||
const bool emb = S("--embedding-placement");
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
@@ -991,7 +984,7 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
else if (S("--dry-sequence-breakers")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
const nlohmann::json j = nlohmann::json::parse(v, nullptr, false);
|
||||
const Json j = Json::parse(v, nullptr, false);
|
||||
bool strings = j.is_array();
|
||||
if (strings) for (const auto& e : j) strings = strings && e.is_string();
|
||||
if (!strings) {
|
||||
@@ -1299,20 +1292,13 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
RAD_ERR("--video-min-pixels is above --video-max-pixels"); return RAD_E_INVAL; }
|
||||
if (c->video_min_frames && c->video_max_frames && *c->video_min_frames > *c->video_max_frames) {
|
||||
RAD_ERR("--video-min-frames is above --video-max-frames"); return RAD_E_INVAL; }
|
||||
/* --host-pool-mib is what the model pins for its weights in all; Config::host_pool_mib is a
|
||||
* rank's share of it, whichever of the two options came first. */
|
||||
if (pool_all) c->host_pool_mib /= std::max(c->tp, 1);
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
const char* attn_prefill_fp8_name(int bits) {
|
||||
switch (bits) {
|
||||
case 0: return "off";
|
||||
case RAD_ATTN_FP8_QK: return "qk";
|
||||
case RAD_ATTN_FP8_PV: return "pv";
|
||||
case RAD_ATTN_FP8_QK | RAD_ATTN_FP8_PV: return "both";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the startup report's rows */
|
||||
namespace {
|
||||
|
||||
@@ -1376,11 +1362,9 @@ 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; } },
|
||||
{ "--state-cache-dtype", [](const Config& c) { return c.state_cache_dtype; } },
|
||||
{ "--attn-prefill-fp8", [](const Config& c) {
|
||||
return std::string(attn_prefill_fp8_name(c.attn_prefill_fp8)); } },
|
||||
{ "--kv-resident", [](const Config& c) {
|
||||
return c.kv_resident > 0 ? num(c.kv_resident) : std::string("0 (off)"); } },
|
||||
{ "--host-pool-mib", [](const Config& c) { return num(c.host_pool_mib); } },
|
||||
{ "--host-pool-mib", [](const Config& c) { return num(c.host_pool_mib * std::max(c.tp, 1)); } },
|
||||
{ "--host-headroom-mib", [](const Config& c) { return num(c.host_headroom_mib); } },
|
||||
{ "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } },
|
||||
{ "--ngram-placement", [](const Config& c) {
|
||||
@@ -1469,8 +1453,8 @@ const ShowRow kShow[] = {
|
||||
{ "--dry-sequence-breakers", [](const Config& c) {
|
||||
/* Invalid UTF-8 is replaced, not thrown on: these strings come from outside. */
|
||||
return c.sample_dry_seq_breakers
|
||||
? nlohmann::json(*c.sample_dry_seq_breakers)
|
||||
.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace)
|
||||
? Json(*c.sample_dry_seq_breakers)
|
||||
.dump(-1, ' ', false, Json::error_handler_t::replace)
|
||||
: std::string("the request default"); } },
|
||||
{ "--xtc-probability", [](const Config& c) { return opt(c.sample_xtc_probability, "the request default"); } },
|
||||
{ "--xtc-threshold", [](const Config& c) { return opt(c.sample_xtc_threshold, "the request default"); } },
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@
|
||||
#include <cmath>
|
||||
#include <fstream>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
namespace rad {
|
||||
namespace {
|
||||
@@ -107,7 +107,7 @@ int read_package_json(const std::string& gguf_path, PackageJson* out, std::strin
|
||||
std::ifstream f(path);
|
||||
if (!f) return RAD_OK;
|
||||
try {
|
||||
const nlohmann::json j = nlohmann::json::parse(f);
|
||||
const Json j = Json::parse(f);
|
||||
if (const auto m = j.find("mode"); m != j.end() && m->is_string() &&
|
||||
m->get<std::string>() != "project") {
|
||||
*why = "control vector " + path + ": mode '" + m->get<std::string>() +
|
||||
|
||||
+632
-56
@@ -60,6 +60,7 @@
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
@@ -148,6 +149,7 @@ thread_local bool t_ours = false;
|
||||
|
||||
inline hipError_t ret(hipError_t e) { t_err = e; t_ours = true; return e; }
|
||||
thread_local uint8_t t_next_fence = 0;
|
||||
thread_local bool t_peer = false; /* a_peer_launch: the launches are a collective's */
|
||||
|
||||
/* Whether any work was forwarded to a HIP stream (a stream this backend does not own). Until
|
||||
* then HIP's default stream is empty and synchronising it is answered here; asking HIP would
|
||||
@@ -205,6 +207,9 @@ struct Registry {
|
||||
std::vector<Module*> order;
|
||||
};
|
||||
|
||||
/* Moves when a stub comes to name another kernel, which empties every thread's stub cache. */
|
||||
std::atomic<uint64_t> g_stub_epoch{0};
|
||||
|
||||
Registry& reg() {
|
||||
static Registry* r = new Registry(); /* never destroyed: unregistration runs from atexit */
|
||||
return *r;
|
||||
@@ -563,13 +568,14 @@ KernelRec* resolve(Func* fn, int ord) {
|
||||
}
|
||||
|
||||
/* One lookup per launch: a thread-local direct-mapped cache in front of the registry. */
|
||||
struct CacheEnt { const void* stub; int ord; KernelRec* k; };
|
||||
struct CacheEnt { const void* stub; int ord; KernelRec* k; uint64_t epoch; };
|
||||
thread_local CacheEnt t_cache[512];
|
||||
|
||||
KernelRec* kernel_for(const void* stub, int ord, std::string* why) {
|
||||
const size_t h = (((uintptr_t)stub >> 4) ^ ((uintptr_t)stub >> 13) ^ (size_t)ord) & 511u;
|
||||
CacheEnt& c = t_cache[h];
|
||||
if (c.stub == stub && c.ord == ord && c.k) return c.k;
|
||||
const uint64_t epoch = g_stub_epoch.load(std::memory_order_acquire);
|
||||
if (c.stub == stub && c.ord == ord && c.k && c.epoch == epoch) return c.k;
|
||||
Func* fn = nullptr;
|
||||
{
|
||||
Registry& r = reg();
|
||||
@@ -580,7 +586,7 @@ KernelRec* kernel_for(const void* stub, int ord, std::string* why) {
|
||||
if (!fn) { *why = "the kernel was never registered with HIP"; return nullptr; }
|
||||
KernelRec* k = resolve(fn, ord);
|
||||
if (!k) { *why = fn->name + ": " + fn->err[ord]; return nullptr; }
|
||||
c = { stub, ord, k };
|
||||
c = { stub, ord, k, epoch };
|
||||
return k;
|
||||
}
|
||||
|
||||
@@ -601,6 +607,7 @@ struct Stream {
|
||||
uint64_t epoch = 0; /* host epoch at the last system acquire */
|
||||
hsa_signal_t ride{}; /* rad_ride: the next dispatch's completion signal */
|
||||
bool agent_only = false; /* rad_xp_stream_create: never a system-scope acquire */
|
||||
bool high = false; /* created or last reused at high priority */
|
||||
std::atomic<int> gates{0}; /* closed gates (rad_stream_gate) on this queue */
|
||||
std::atomic<int> fault{0};
|
||||
char* bounce = nullptr; /* pinned, for pageable copies */
|
||||
@@ -610,11 +617,21 @@ struct Stream {
|
||||
* far, and whether the last packet on the queue was a chained kernel. */
|
||||
uint64_t* chain_ctr = nullptr;
|
||||
uint64_t chain_issued = 0;
|
||||
/* The blocks issued before the last packet that depends on what precedes it: what a chained
|
||||
* kernel played beside that packet (an overlap) waits for, since it reads nothing issued
|
||||
* from that packet on. */
|
||||
uint64_t chain_frontier = 0;
|
||||
/* Whether that packet went out without its barrier bit (a chained kernel behind chained ones):
|
||||
* packets before it may then still run while later packets launch. */
|
||||
bool frontier_open = false;
|
||||
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;
|
||||
/* Whether a collective's packet may still be running: one published since the last packet
|
||||
* whose barrier bit held it behind everything before (see "collectives on a shared card"). */
|
||||
bool peer_inflight = false;
|
||||
|
||||
void lock() {
|
||||
while (busy.exchange(true, std::memory_order_acquire))
|
||||
@@ -636,6 +653,19 @@ std::vector<uint32_t> g_queue_free; /* destroyed queues' slots
|
||||
uint32_t g_queue_next_slot = 0;
|
||||
uint32_t g_queue_gen[kMaxQueues];
|
||||
|
||||
/* Drained streams kept for the next rad_stream_create on their card, instead of destroyed.
|
||||
*
|
||||
* Destroying a hardware queue makes the scheduler firmware unmap it (MES REMOVE_QUEUE), and on
|
||||
* RDNA4 that request can fail while another queue keeps the same card busy; the driver then resets
|
||||
* the card and every allocation on it is lost. A process serving several models unloads one while
|
||||
* another computes on the card, so a model's queues outlive it here and the next engine on that
|
||||
* card takes them over. A kept queue holds its context save area on the card, about 41 MiB on an
|
||||
* R9700 (24 of them 0.99 GiB, measured). The queues of a card are destroyed at process exit, and
|
||||
* where the caller answers for nothing computing on the card (a_stream_trim). Keyed by card and
|
||||
* priority. */
|
||||
std::mutex g_spare_mu;
|
||||
std::vector<Stream*> g_spare[kMaxDevices][2];
|
||||
|
||||
/* The queue an id names, or null once it is destroyed. The slot's id is stored before its queue
|
||||
* (release), so a queue read here that belongs to a later generation is seen with that
|
||||
* generation's id and refused. */
|
||||
@@ -663,6 +693,10 @@ inline uint64_t steady_ns() {
|
||||
std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
void report_running(int card);
|
||||
|
||||
/* A queue the runtime stopped stays stopped, and `faulted` ends every wait in the process, so
|
||||
* nothing can serve after this: the report, then the exit a GPU memory fault takes. */
|
||||
void on_queue_error(hsa_status_t st, hsa_queue_t*, void* data) {
|
||||
Stream* s = static_cast<Stream*>(data);
|
||||
const char* m = nullptr;
|
||||
@@ -673,6 +707,9 @@ void on_queue_error(hsa_status_t st, hsa_queue_t*, void* data) {
|
||||
G().faulted.store(true, std::memory_order_release);
|
||||
hsa_signal_store_screlease(G().fault, 1);
|
||||
RAD_ERR("device %d: the AQL queue faulted: %s", s->ord, m ? m : "?");
|
||||
report_running(s->ord);
|
||||
fatal("a queue on device %d stopped for good (the report is above); exiting so a restart can "
|
||||
"bring the server back", s->ord);
|
||||
}
|
||||
|
||||
/* Queue dump, printed once when a host wait has not returned for 5 s. Nothing on the step path
|
||||
@@ -814,6 +851,7 @@ std::string where_is(uintptr_t a) {
|
||||
if (a >= f->base && a < f->base + (uintptr_t)f->bytes)
|
||||
return fmt("inside FREED %s, freed %.1f s ago", rec_str(*f, a).c_str(),
|
||||
(double)(now - f->freed_ns) * 1e-9);
|
||||
if (const std::string paged = dev_fault_where((const void*)a); !paged.empty()) return "in " + paged;
|
||||
std::string s = "in no range this process holds or recently freed";
|
||||
if (it != g_live.begin()) {
|
||||
const AllocRec& r = std::prev(it)->second;
|
||||
@@ -867,10 +905,16 @@ hsa_status_t on_system_event(const hsa_amd_event_t* e, void*) {
|
||||
RAD_ERR("device %d: GPU memory fault at %#" PRIxPTR " (%s ): %s; %s", card, va,
|
||||
why.empty() ? " ?" : why.c_str(), where_is(va).c_str(), runtime_view(va).c_str());
|
||||
}
|
||||
/* The running kernel and its arguments. A queue's read index stays on a packet until it
|
||||
* completes, so the packet there is in flight. Every pointer-shaped argument word is located
|
||||
* like the address, which names the operand that got a stale or short buffer. Only card
|
||||
* `card`'s queues; the host reads the arguments at the packet's kernarg_address. */
|
||||
report_running(card);
|
||||
fatal("a GPU memory fault on device %d stopped its queue for good (the report is above); "
|
||||
"exiting so a restart can bring the server back", card);
|
||||
}
|
||||
|
||||
/* The running kernel and its arguments. A queue's read index stays on a packet until it
|
||||
* completes, so the packet there is in flight. Every pointer-shaped argument word is located
|
||||
* like the address, which names the operand that got a stale or short buffer. Only card
|
||||
* `card`'s queues; the host reads the arguments at the packet's kernarg_address. */
|
||||
void report_running(int card) {
|
||||
std::lock_guard<std::mutex> sl(G().streams_mu);
|
||||
for (Stream* s : G().streams) {
|
||||
if (s->ord != card) continue;
|
||||
@@ -897,8 +941,6 @@ hsa_status_t on_system_event(const hsa_amd_event_t* e, void*) {
|
||||
RAD_ERR(" argument +%u = %#" PRIx64 ": %s", i * 8, w, where_is((uintptr_t)w).c_str());
|
||||
}
|
||||
}
|
||||
fatal("a GPU memory fault on device %d stopped its queue for good (the report is above); "
|
||||
"exiting so a restart can bring the server back", card);
|
||||
}
|
||||
|
||||
/* Stall detector for a spin loop. tick() reads the clock every 64k iterations, a few thousand
|
||||
@@ -968,6 +1010,17 @@ int64_t stuck_ms() {
|
||||
* kTapeOverlapRun consecutive packets (TapeRec::overlap), so the margin is that run plus one. */
|
||||
constexpr uint64_t kReserveMargin = (uint64_t)kTapeOverlapRun + 2;
|
||||
|
||||
/* The wait for room in a full ring sleeps rather than spins. A full queue holds thousands of
|
||||
* packets the card has yet to run, at least ~3 us each (the dispatch floor), so the card is many
|
||||
* milliseconds from idle and a nap of this length costs it nothing; a spinning wait held a core
|
||||
* for the whole of a long prefill, which outruns the card by the queue's depth. */
|
||||
constexpr long kFullNapNs = 100000;
|
||||
|
||||
inline void full_nap() {
|
||||
const timespec ts{0, kFullNapNs};
|
||||
nanosleep(&ts, nullptr);
|
||||
}
|
||||
|
||||
inline int reserve(Stream* s, uint64_t* out) {
|
||||
const uint64_t idx = s->wr;
|
||||
const uint64_t size = s->mask + 1;
|
||||
@@ -984,8 +1037,8 @@ inline int reserve(Stream* s, uint64_t* out) {
|
||||
"gate (rad_gate_open) first");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
st.tick();
|
||||
_mm_pause();
|
||||
st.check();
|
||||
full_nap();
|
||||
}
|
||||
}
|
||||
*out = idx;
|
||||
@@ -1033,6 +1086,8 @@ struct TapeRec {
|
||||
/* 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;
|
||||
/* A collective's launch (a_peer_launch). */
|
||||
uint8_t peer = 0;
|
||||
};
|
||||
|
||||
struct Tape {
|
||||
@@ -1059,6 +1114,7 @@ void tape_note_dispatch(Stream* s, const hsa_kernel_dispatch_packet_t* p, uint16
|
||||
r.kind = kTapeDispatch;
|
||||
r.fence = fence;
|
||||
r.chain = chain ? 1 : 0;
|
||||
r.peer = t_peer ? 1 : 0;
|
||||
r.s = s;
|
||||
r.pkt = *p;
|
||||
r.pkt.header = 0;
|
||||
@@ -1093,12 +1149,34 @@ 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) {
|
||||
/* Collectives on a shared card.
|
||||
*
|
||||
* A chained kernel launched behind a running one holds its wave slots while it waits in its
|
||||
* prologue, and the packet processor launches as far ahead as the card has slots. Behind a
|
||||
* collective that is a wait on another card: a collective's block finishes when the peer rank's
|
||||
* block of the same launch has run there. With one engine on the cards the peer's block always
|
||||
* gets its slot, because each rank's collective is launched before anything waits behind it. With
|
||||
* two engines it may not. Engine A's collective on card 0 waits for its half on card 1; card 1 is
|
||||
* full of engine B's chained kernels waiting behind B's collective; B's half on card 0 gets no
|
||||
* slot beside A's, since a prefill junction launches up to 512 blocks, more than the card runs at
|
||||
* once. Nothing advances from there: Qwen3.8-27B prefilling beside Gemma 4 12B decoding, both on
|
||||
* the same two R9700, stopped within 12 s.
|
||||
*
|
||||
* So on a card that more than one multi-card engine has claimed (a_cards_claim), a chained packet
|
||||
* keeps its barrier bit while a collective's packet may be running on its queue. Only the
|
||||
* collectives' own blocks then wait on the card for another card; everything else waiting there
|
||||
* waits for kernels that finish by themselves. An engine alone on its cards pays nothing. */
|
||||
std::atomic<int> g_card_claims[kMaxDevices];
|
||||
inline bool card_shared(const Stream* s) {
|
||||
return s->ord < kMaxDevices && g_card_claims[s->ord].load(std::memory_order_relaxed) > 1;
|
||||
}
|
||||
|
||||
/* The chain record of a chained launch (RadKernelChainFn) at `slot`: wait for the first `target`
|
||||
* chained blocks issued on `s`. `on` false writes a record no kernel accepts. */
|
||||
inline void chain_record(Stream* s, char* slot, bool on, uint64_t target) {
|
||||
uint64_t rec[4];
|
||||
rec[0] = on ? RAD_CHAIN_MAGIC : 0;
|
||||
rec[1] = s->chain_issued;
|
||||
rec[1] = target;
|
||||
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);
|
||||
@@ -1119,6 +1197,9 @@ int barrier(Stream* s, hsa_signal_t dep, hsa_signal_t done, int acq, int rel,
|
||||
if (rc < 0) { s->unlock(); return rc; }
|
||||
s->prev_chained = false;
|
||||
s->plain_inflight = false;
|
||||
s->peer_inflight = false;
|
||||
s->chain_frontier = s->chain_issued;
|
||||
s->frontier_open = 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));
|
||||
@@ -1184,7 +1265,7 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t
|
||||
/* 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 (k->chained) chain_record(s, slot, chain, s->chain_issued);
|
||||
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). */
|
||||
@@ -1196,11 +1277,15 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t
|
||||
const int rel = (fence & kFenceReleaseSystem) ? HSA_FENCE_SCOPE_SYSTEM : HSA_FENCE_SCOPE_AGENT;
|
||||
/* 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);
|
||||
const bool keep = !(chain && s->prev_chained && !s->plain_inflight && !p->completion_signal.handle &&
|
||||
!(s->peer_inflight && card_shared(s)));
|
||||
publish(s, idx, header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel, keep), setup);
|
||||
s->chain_frontier = s->chain_issued;
|
||||
s->frontier_open = !keep;
|
||||
if (chain) s->chain_issued += blocks_of(p);
|
||||
s->prev_chained = chain;
|
||||
s->plain_inflight = keep ? !chain : s->plain_inflight || !chain;
|
||||
s->peer_inflight = keep ? t_peer : s->peer_inflight || t_peer;
|
||||
s->unlock();
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -1298,14 +1383,21 @@ struct PlayRun {
|
||||
/* 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;
|
||||
const bool chain = r.chain && tape && s->chain_ctr && r.karg_len <= RAD_CHAIN_KARG_OFF;
|
||||
/* A dispatch that depends on what precedes it; the rest overlap the packets in flight
|
||||
* (they touch nothing issued since the last dependent one). A plain overlap counts as
|
||||
* dependent while the frontier is open: the analysis let it start beside the last
|
||||
* dependent packet because that packet's barrier held both behind everything earlier, and
|
||||
* a chained packet that dropped the bit holds only itself, in its prologue. */
|
||||
const bool dependent = foreign || !r.overlap || done.handle || (!chain && s->frontier_open);
|
||||
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);
|
||||
/* An overlap waits for the blocks before the packet it runs beside, and adds its
|
||||
* own, so the next dependent chained kernel waits for it too. */
|
||||
chain_record(s, slot, true, dependent ? s->chain_issued : s->chain_frontier);
|
||||
}
|
||||
}
|
||||
const int acq = acquire_scope(s, idx, (r.fence & kFenceAcquireSystem) != 0);
|
||||
@@ -1314,12 +1406,15 @@ struct PlayRun {
|
||||
/* 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. A chained kernel behind another chained one
|
||||
* on this queue waits in its prologue instead. */
|
||||
bool ordered = foreign || !r.overlap || done.handle;
|
||||
bool ordered = dependent;
|
||||
/* 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;
|
||||
/* Nor behind a collective on a shared card, which covers a chained overlap as well: its
|
||||
* prologue waits for blocks that may be the collective's. */
|
||||
if (chain && s->peer_inflight && card_shared(s)) ordered = true;
|
||||
if (stamp) {
|
||||
stamp->ordered = ordered;
|
||||
stamp->chained = chain;
|
||||
@@ -1328,9 +1423,14 @@ struct PlayRun {
|
||||
__atomic_store_n(reinterpret_cast<uint32_t*>(p), (uint32_t)h | ((uint32_t)r.pkt.setup << 16),
|
||||
__ATOMIC_RELEASE);
|
||||
foreign = false;
|
||||
if (dependent) {
|
||||
s->chain_frontier = s->chain_issued;
|
||||
s->frontier_open = !ordered;
|
||||
}
|
||||
if (chain) s->chain_issued += blocks_of(p);
|
||||
s->prev_chained = chain;
|
||||
s->plain_inflight = ordered ? !chain : s->plain_inflight || !chain;
|
||||
s->peer_inflight = ordered ? r.peer != 0 : s->peer_inflight || r.peer != 0;
|
||||
s->wr = idx + 1;
|
||||
next = idx + 1;
|
||||
*out_idx = idx;
|
||||
@@ -1342,9 +1442,16 @@ struct PlayRun {
|
||||
/* One interrupt signal per thread for synchronous waits (see "host waits"). A signal is only
|
||||
* waited on by the thread that armed it, so two threads waiting on one queue do not share. */
|
||||
hsa_signal_t thread_signal() {
|
||||
thread_local hsa_signal_t s{0};
|
||||
if (!s.handle && hsa_signal_create(0, 0, nullptr, &s) != HSA_STATUS_SUCCESS) s.handle = 0;
|
||||
return s;
|
||||
/* Destroyed when the thread ends: an engine's rank threads come and go with the engine, and a
|
||||
* process that loads and unloads models (docs/MULTIMODEL.md) would otherwise leak one signal
|
||||
* per thread it ever ran. Nothing waits on it then, since only its own thread arms it. */
|
||||
struct Owned {
|
||||
hsa_signal_t s{0};
|
||||
~Owned() { if (s.handle) hsa_signal_destroy(s); }
|
||||
};
|
||||
thread_local Owned o;
|
||||
if (!o.s.handle && hsa_signal_create(0, 0, nullptr, &o.s) != HSA_STATUS_SUCCESS) o.s.handle = 0;
|
||||
return o.s;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ host waits
|
||||
@@ -1555,6 +1662,27 @@ namespace {
|
||||
|
||||
using namespace aql;
|
||||
|
||||
/* A drained stream's queue, argument ring and bounce buffer back to the runtime. */
|
||||
void stream_close(Stream* s) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(G().streams_mu);
|
||||
auto& v = G().streams;
|
||||
for (size_t i = 0; i < v.size(); ++i) if (v[i] == s) { v.erase(v.begin() + (long)i); break; }
|
||||
}
|
||||
g_queue_by_id[s->id % kMaxQueues].store(nullptr, std::memory_order_release);
|
||||
hsa_queue_destroy(s->q);
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_queue_slot_mu);
|
||||
g_queue_free.push_back(s->id % kMaxQueues);
|
||||
}
|
||||
note_free(s->karg);
|
||||
note_free(s->bounce);
|
||||
hsa_amd_memory_pool_free(s->karg);
|
||||
hsa_amd_memory_pool_free(s->bounce);
|
||||
s->magic = 0;
|
||||
delete s;
|
||||
}
|
||||
|
||||
int a_stream_create(RadStream* out, int high_priority) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
int ord = 0;
|
||||
@@ -1563,8 +1691,40 @@ int a_stream_create(RadStream* out, int high_priority) {
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
const Dev& d = G().dev[(size_t)ord];
|
||||
if (ord < kMaxDevices) {
|
||||
Stream* r = nullptr;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_spare_mu);
|
||||
auto& v = g_spare[ord][high_priority ? 1 : 0];
|
||||
if (!v.empty()) { r = v.back(); v.pop_back(); }
|
||||
}
|
||||
if (r) {
|
||||
/* Every packet it held has completed (a_stream_destroy drained it), so its counters
|
||||
* start over; its packet indices keep counting, as the queue's own do. A new id, so
|
||||
* nothing recorded against the previous owner's id reaches this queue. */
|
||||
r->agent_only = false;
|
||||
r->chain_issued = 0;
|
||||
r->chain_frontier = 0;
|
||||
r->frontier_open = false;
|
||||
r->prev_chained = false;
|
||||
r->plain_inflight = false;
|
||||
r->peer_inflight = false;
|
||||
*reinterpret_cast<volatile uint64_t*>(r->chain_ctr) = 0;
|
||||
_mm_sfence();
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_queue_slot_mu);
|
||||
const uint32_t slot = r->id % kMaxQueues;
|
||||
r->id = g_queue_gen[slot]++ * kMaxQueues + slot;
|
||||
g_queue_id_at[slot].store(r->id, std::memory_order_release);
|
||||
g_queue_by_id[slot].store(r->q, std::memory_order_release);
|
||||
}
|
||||
*out = (RadStream)r;
|
||||
return RAD_OK;
|
||||
}
|
||||
}
|
||||
auto s = std::make_unique<Stream>();
|
||||
s->ord = ord;
|
||||
s->high = high_priority != 0;
|
||||
s->agent = d.agent;
|
||||
if (hsa_queue_create(d.agent, kQueuePackets, HSA_QUEUE_TYPE_SINGLE, on_queue_error, s.get(),
|
||||
UINT32_MAX, UINT32_MAX, &s->q) != HSA_STATUS_SUCCESS) {
|
||||
@@ -1641,23 +1801,67 @@ void a_stream_destroy(RadStream rs) {
|
||||
"argument ring stay allocated", rad_strerror(rc));
|
||||
return;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(G().streams_mu);
|
||||
auto& v = G().streams;
|
||||
for (size_t i = 0; i < v.size(); ++i) if (v[i] == s) { v.erase(v.begin() + (long)i); break; }
|
||||
/* Kept for the card's next stream (see g_spare); a faulted queue is not handed on. Its id
|
||||
* stops naming it at once, as a destroyed queue's would. */
|
||||
if (s->ord < kMaxDevices && s->fault.load(std::memory_order_acquire) == 0 &&
|
||||
s->gates.load(std::memory_order_acquire) == 0) {
|
||||
g_queue_by_id[s->id % kMaxQueues].store(nullptr, std::memory_order_release);
|
||||
std::lock_guard<std::mutex> lk(g_spare_mu);
|
||||
g_spare[s->ord][s->high ? 1 : 0].push_back(s);
|
||||
return;
|
||||
}
|
||||
g_queue_by_id[s->id % kMaxQueues].store(nullptr, std::memory_order_release);
|
||||
hsa_queue_destroy(s->q);
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_queue_slot_mu);
|
||||
g_queue_free.push_back(s->id % kMaxQueues);
|
||||
stream_close(s);
|
||||
}
|
||||
|
||||
/* How many hardware queues card `ord` has open, and how many of them are kept ones no stream
|
||||
* holds. */
|
||||
void a_stream_counts(int ord, int* open, int* idle) {
|
||||
int n = 0, k = 0;
|
||||
if (ord >= 0 && ord < kMaxDevices) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(G().streams_mu);
|
||||
for (const Stream* s : G().streams) n += s->ord == ord;
|
||||
}
|
||||
std::lock_guard<std::mutex> lk(g_spare_mu);
|
||||
k = (int)(g_spare[ord][0].size() + g_spare[ord][1].size());
|
||||
}
|
||||
note_free(s->karg);
|
||||
note_free(s->bounce);
|
||||
hsa_amd_memory_pool_free(s->karg);
|
||||
hsa_amd_memory_pool_free(s->bounce);
|
||||
s->magic = 0;
|
||||
delete s;
|
||||
if (open) *open = n;
|
||||
if (idle) *idle = k;
|
||||
}
|
||||
|
||||
/* Card `ord`'s kept queues destroyed until `keep` are left, the number destroyed. A queue takes
|
||||
* about 41 MiB of the card (its context save area, mostly), and the kept ones are what a model
|
||||
* that needs nearly all of a card is short of.
|
||||
*
|
||||
* Destroying a queue while another keeps the card busy is what g_spare exists to avoid, so
|
||||
* nothing is destroyed unless every queue of the card is empty, the ones streams hold included;
|
||||
* the caller answers for nothing being launched on the card meanwhile (a fleet with every other
|
||||
* model off the card and the one asking stopped in its bring-up). The kept queues were drained
|
||||
* when their streams closed. */
|
||||
int a_stream_trim(int ord, int keep) {
|
||||
if (ord < 0 || ord >= kMaxDevices) return 0;
|
||||
std::vector<Stream*> go;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_spare_mu);
|
||||
{
|
||||
std::lock_guard<std::mutex> ls(G().streams_mu);
|
||||
for (const Stream* s : G().streams)
|
||||
if (s->ord == ord && hsa_queue_load_read_index_scacquire(s->q) !=
|
||||
hsa_queue_load_write_index_scacquire(s->q))
|
||||
return 0;
|
||||
}
|
||||
size_t left = g_spare[ord][0].size() + g_spare[ord][1].size();
|
||||
for (int hi = 1; hi >= 0; --hi) {
|
||||
auto& v = g_spare[ord][hi];
|
||||
while (!v.empty() && left > (size_t)std::max(keep, 0)) {
|
||||
go.push_back(v.back());
|
||||
v.pop_back();
|
||||
--left;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Stream* s : go) stream_close(s);
|
||||
return (int)go.size();
|
||||
}
|
||||
|
||||
int a_stream_sync(RadStream rs) {
|
||||
@@ -2883,8 +3087,8 @@ int dma_put(DmaQueue* q, const uint32_t* dw, uint64_t n) {
|
||||
device_set_error("rad_memcpy_list_async: a queue faulted while the DMA ring was full");
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
st.tick();
|
||||
_mm_pause();
|
||||
st.check();
|
||||
full_nap();
|
||||
}
|
||||
}
|
||||
for (uint64_t i = 0; i < pad; ++i) q->rb[at + i] = 0;
|
||||
@@ -3341,6 +3545,54 @@ int a_link_hold(RadStream rs, int on) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void a_peer_launch(int on) { t_peer = on != 0; }
|
||||
|
||||
int a_cards_claim(const int* cards, int n, int on) {
|
||||
bool shared = false;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
if (cards[i] < 0 || cards[i] >= kMaxDevices) continue;
|
||||
/* Once a card, however many of the engine's ranks sit on it. */
|
||||
bool seen = false;
|
||||
for (int j = 0; j < i; ++j) seen = seen || cards[j] == cards[i];
|
||||
if (seen) continue;
|
||||
if (on) shared = g_card_claims[cards[i]].fetch_add(1) + 1 > 1 || shared;
|
||||
else g_card_claims[cards[i]].fetch_sub(1);
|
||||
}
|
||||
if (!on || !shared) return RAD_OK;
|
||||
/* The other engine may have chained packets in flight behind a collective, published before
|
||||
* the claim. Every packet after it sees the claim (the count is read under the queue's lock,
|
||||
* which the drain's barrier takes), so once each queue of the shared cards has drained, none
|
||||
* is left. The registry's lock is not held across the drains: every host wait reads the
|
||||
* queues' progress under it. A queue lives on as a spare after its engine (g_spare); the one
|
||||
* kind that is destroyed, a faulted one, is skipped. */
|
||||
std::vector<Stream*> queues;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(G().streams_mu);
|
||||
for (Stream* s : G().streams) {
|
||||
if (!card_shared(s) || s->fault.load(std::memory_order_acquire) != 0) continue;
|
||||
for (int i = 0; i < n; ++i)
|
||||
if (cards[i] == s->ord) { queues.push_back(s); break; }
|
||||
}
|
||||
}
|
||||
for (Stream* s : queues) {
|
||||
/* A queue at a closed gate drains once its owner opens the gate, within a step. */
|
||||
const uint64_t t0 = steady_ns();
|
||||
while (s->gates.load(std::memory_order_acquire) > 0) {
|
||||
if (steady_ns() - t0 > 30ull * 1000000000ull) {
|
||||
device_set_error("rad_dev_cards_claim: a queue on card %d stayed at a closed gate "
|
||||
"for 30 s", s->ord);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
if (const int rc = stream_drain(s); rc < 0) {
|
||||
device_set_error("rad_dev_cards_claim: a queue on card %d could not drain", s->ord);
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int a_dma_lane(int device, char* out, int cap) {
|
||||
if (device < 0 || device >= kMaxDevices || device >= (int)G().dev.size() || !out || cap <= 0)
|
||||
return RAD_E_INVAL;
|
||||
@@ -3441,14 +3693,88 @@ std::string card_holders(int ord) {
|
||||
return s + ".";
|
||||
}
|
||||
|
||||
/* ---- spare device memory.
|
||||
*
|
||||
* A decommit keeps the card memory it unmaps, as a handle of its size, and the next commit of that
|
||||
* size on that card maps it again. Memory handed back to the driver is wiped before its pages can
|
||||
* be had again, at ~95 GB/s on gfx1201 (0.66 ms a 64 MiB chunk), and a park followed by the next
|
||||
* model's page-in (the fleet's model swap) waited for the wipe of memory it was about to take
|
||||
* back: 2.8 s over the fleet bench's sequential plan. A spare counts as free in the card's figure
|
||||
* (a_props); a commit or allocation the driver cannot give gives the card's spares back first
|
||||
* (card_has_room, create_handle). A recycled handle holds what its last mapping left; a commit
|
||||
* reports that, so a caller that needs zeros clears it. */
|
||||
struct Spare { hsa_amd_vmem_alloc_handle_t h; int64_t bytes; };
|
||||
std::mutex g_spare_mu;
|
||||
std::vector<Spare> g_spares[kMaxDevices];
|
||||
std::atomic<int64_t> g_spare_bytes[kMaxDevices];
|
||||
|
||||
bool take_spare(int ord, int64_t bytes, hsa_amd_vmem_alloc_handle_t* h) {
|
||||
std::lock_guard<std::mutex> lk(g_spare_mu);
|
||||
std::vector<Spare>& v = g_spares[ord];
|
||||
for (size_t i = v.size(); i-- > 0;)
|
||||
if (v[i].bytes == bytes) {
|
||||
*h = v[i].h;
|
||||
v.erase(v.begin() + (ptrdiff_t)i);
|
||||
g_spare_bytes[ord].fetch_sub(bytes, std::memory_order_relaxed);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void put_spare(int ord, hsa_amd_vmem_alloc_handle_t h, int64_t bytes) {
|
||||
std::lock_guard<std::mutex> lk(g_spare_mu);
|
||||
g_spares[ord].push_back({ h, bytes });
|
||||
g_spare_bytes[ord].fetch_add(bytes, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
/* Gives card `ord`'s spares back to the driver; the bytes. */
|
||||
int64_t release_spares(int ord) {
|
||||
std::vector<Spare> v;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_spare_mu);
|
||||
v.swap(g_spares[ord]);
|
||||
g_spare_bytes[ord].store(0, std::memory_order_relaxed);
|
||||
}
|
||||
int64_t n = 0;
|
||||
for (const Spare& sp : v) {
|
||||
(void)hsa_amd_vmem_handle_release(sp.h);
|
||||
n += sp.bytes;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/* A device-memory handle of `bytes` on card `ord`. A refusal is retried for up to two seconds,
|
||||
* with the card's spares given back first: memory given back is counted free by the driver's
|
||||
* figure at once, but its pages come free only as the wipe reaches them. */
|
||||
bool create_handle(int ord, hsa_amd_memory_pool_t pool, int64_t bytes, hsa_amd_vmem_alloc_handle_t* h) {
|
||||
if (hsa_amd_vmem_handle_create(pool, (size_t)bytes, MEMORY_TYPE_NONE, 0, h) == HSA_STATUS_SUCCESS)
|
||||
return true;
|
||||
const int64_t gave = ord >= 0 && ord < kMaxDevices ? release_spares(ord) : 0;
|
||||
const auto until = std::chrono::steady_clock::now() + std::chrono::seconds(2);
|
||||
while (std::chrono::steady_clock::now() < until) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(5));
|
||||
if (hsa_amd_vmem_handle_create(pool, (size_t)bytes, MEMORY_TYPE_NONE, 0, h) == HSA_STATUS_SUCCESS)
|
||||
return true;
|
||||
}
|
||||
device_set_error("vmem: %lld bytes could not be backed on device %d (for two seconds, %s of "
|
||||
"spares given back; the driver has %s left to give)", (long long)bytes, ord,
|
||||
humanb(gave).c_str(), humanb(card_available(ord)).c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
/* True when card `ord` can take `bytes` more; otherwise false with the refusal set, `what` naming
|
||||
* the call. If the driver gives no figure the allocation is allowed. */
|
||||
* the call. If the driver gives no figure the allocation is allowed. Short with spares held, it
|
||||
* gives them back (the figure counts them at once) and looks again. */
|
||||
bool card_has_room(int ord, int64_t bytes, const char* what) {
|
||||
const int64_t avail = card_available(ord);
|
||||
int64_t avail = card_available(ord);
|
||||
if (avail < 0) return true;
|
||||
constexpr int64_t kUnit = (int64_t)2 << 20;
|
||||
const int64_t need = (bytes + kUnit - 1) / kUnit * kUnit;
|
||||
if (need <= avail) return true;
|
||||
if (ord >= 0 && ord < kMaxDevices && release_spares(ord) > 0) {
|
||||
avail = card_available(ord);
|
||||
if (avail < 0 || need <= avail) return true;
|
||||
}
|
||||
device_set_error("%s(%s) on card %d: the driver has %s left to give on it.%s Memory another "
|
||||
"process took after the VRAM budget was measured is the usual cause: stop "
|
||||
"that process, or start this one again once it has gone",
|
||||
@@ -3477,7 +3803,9 @@ bool card_has_room(int ord, int64_t bytes, const char* what) {
|
||||
struct VRes { uintptr_t base; uintptr_t end; int ord; };
|
||||
std::mutex g_vres_mu;
|
||||
std::vector<VRes> g_vres;
|
||||
std::unordered_map<uintptr_t, hsa_amd_vmem_alloc_handle_t> g_vmaps;
|
||||
/* A mapping's handle, and whether it is host memory (vmem_commit_host). */
|
||||
struct VMap { hsa_amd_vmem_alloc_handle_t h{}; bool host = false; int64_t bytes = 0; };
|
||||
std::unordered_map<uintptr_t, VMap> g_vmaps;
|
||||
|
||||
int vres_ord(const void* addr) {
|
||||
const uintptr_t a = (uintptr_t)addr;
|
||||
@@ -3602,12 +3930,11 @@ int a_vmem_commit(void* addr, int64_t bytes) {
|
||||
if (dev < 0 && hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE;
|
||||
if (dev < 0 || dev >= (int)G().dev.size()) return RAD_E_DEVICE;
|
||||
const Dev& d = G().dev[(size_t)dev];
|
||||
if (!card_has_room(dev, bytes, "vmem commit")) return RAD_E_NOMEM;
|
||||
hsa_amd_vmem_alloc_handle_t h{};
|
||||
if (hsa_amd_vmem_handle_create(d.vram, (size_t)bytes, MEMORY_TYPE_NONE, 0, &h) !=
|
||||
HSA_STATUS_SUCCESS) {
|
||||
device_set_error("vmem: %lld bytes could not be backed on device %d", (long long)bytes, dev);
|
||||
return RAD_E_NOMEM;
|
||||
const bool recycled = take_spare(dev, bytes, &h);
|
||||
if (!recycled) {
|
||||
if (!card_has_room(dev, bytes, "vmem commit")) return RAD_E_NOMEM;
|
||||
if (!create_handle(dev, d.vram, bytes, &h)) return RAD_E_NOMEM;
|
||||
}
|
||||
if (hsa_amd_vmem_map(addr, (size_t)bytes, 0, h, 0) != HSA_STATUS_SUCCESS) {
|
||||
(void)hsa_amd_vmem_handle_release(h);
|
||||
@@ -3621,9 +3948,173 @@ int a_vmem_commit(void* addr, int64_t bytes) {
|
||||
device_set_error("vmem: device %d could not be given access to %p", dev, addr);
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
std::lock_guard<std::mutex> lk(g_vres_mu);
|
||||
g_vmaps[(uintptr_t)addr] = h;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_vres_mu);
|
||||
g_vmaps[(uintptr_t)addr] = VMap{ h, false, bytes };
|
||||
}
|
||||
loc_forget(); /* the range is backed, no longer only reserved */
|
||||
return recycled ? 1 : RAD_OK;
|
||||
}
|
||||
|
||||
int a_vmem_commit_units(void* addr, int64_t bytes, int64_t unit) {
|
||||
if (!addr || bytes <= 0 || unit <= 0 || bytes % unit) return RAD_E_INVAL;
|
||||
int dev = vres_ord(addr);
|
||||
if (dev < 0 && hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE;
|
||||
if (dev < 0 || dev >= (int)G().dev.size()) return RAD_E_DEVICE;
|
||||
const Dev& d = G().dev[(size_t)dev];
|
||||
std::vector<hsa_amd_vmem_alloc_handle_t> hs;
|
||||
hs.reserve((size_t)(bytes / unit));
|
||||
/* Spares first, as many as there are; the rest is checked against the driver's figure. */
|
||||
std::vector<hsa_amd_vmem_alloc_handle_t> spare;
|
||||
for (int64_t o = 0; o < bytes; o += unit) {
|
||||
hsa_amd_vmem_alloc_handle_t h{};
|
||||
if (!take_spare(dev, unit, &h)) break;
|
||||
spare.push_back(h);
|
||||
}
|
||||
const bool recycled = !spare.empty();
|
||||
const int64_t fresh = bytes - (int64_t)spare.size() * unit;
|
||||
if (fresh > 0 && !card_has_room(dev, fresh, "vmem commit")) {
|
||||
for (const auto& h : spare) put_spare(dev, h, unit);
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
/* What this call mapped goes again in one unmap; its handles are let go. */
|
||||
auto undo = [&] {
|
||||
if (!hs.empty()) (void)hsa_amd_vmem_unmap(addr, hs.size() * (size_t)unit);
|
||||
for (const auto& h : hs) (void)hsa_amd_vmem_handle_release(h);
|
||||
for (size_t i = hs.size(); i < spare.size(); ++i) put_spare(dev, spare[i], unit);
|
||||
};
|
||||
for (int64_t o = 0; o < bytes; o += unit) {
|
||||
hsa_amd_vmem_alloc_handle_t h{};
|
||||
if (hs.size() < spare.size()) {
|
||||
h = spare[hs.size()];
|
||||
} else if (!create_handle(dev, d.vram, unit, &h)) {
|
||||
undo();
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
if (hsa_amd_vmem_map((char*)addr + o, (size_t)unit, 0, h, 0) != HSA_STATUS_SUCCESS) {
|
||||
if (hs.size() < spare.size()) spare.erase(spare.begin() + (ptrdiff_t)hs.size());
|
||||
(void)hsa_amd_vmem_handle_release(h);
|
||||
undo();
|
||||
device_set_error("vmem: a map of %lld bytes at %p failed", (long long)unit, (char*)addr + o);
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
hs.push_back(h);
|
||||
}
|
||||
const hsa_amd_memory_access_desc_t acc{ HSA_ACCESS_PERMISSION_RW, d.agent };
|
||||
if (hsa_amd_vmem_set_access(addr, (size_t)bytes, &acc, 1) != HSA_STATUS_SUCCESS) {
|
||||
undo();
|
||||
device_set_error("vmem: device %d could not be given access to %p", dev, addr);
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_vres_mu);
|
||||
for (size_t i = 0; i < hs.size(); ++i)
|
||||
g_vmaps[(uintptr_t)addr + i * (uintptr_t)unit] = VMap{ hs[i], false, unit };
|
||||
}
|
||||
loc_forget();
|
||||
return recycled ? 1 : RAD_OK;
|
||||
}
|
||||
|
||||
/* Access for a mapping at `addr` on card `dev`: the card alone for its own memory; the card and
|
||||
* the host for host memory, so the host can write a parked copy to disk straight out of it. */
|
||||
int vmem_grant(void* addr, int64_t bytes, int dev, bool host) {
|
||||
const Dev& d = G().dev[(size_t)dev];
|
||||
const hsa_amd_memory_access_desc_t acc[2] = { { HSA_ACCESS_PERMISSION_RW, d.agent },
|
||||
{ HSA_ACCESS_PERMISSION_RW, G().cpu } };
|
||||
return hsa_amd_vmem_set_access(addr, (size_t)bytes, acc, host ? 2 : 1) == HSA_STATUS_SUCCESS
|
||||
? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
/* The coarse-grained system pool: the card reads it at the link's full rate (27 GB/s on a
|
||||
* gfx1201 at PCIe 5 x16, against 15 GB/s from the fine-grained one). Parked weights need no
|
||||
* coherence with the host while a kernel runs. */
|
||||
hsa_amd_memory_pool_t* host_coarse_pool() {
|
||||
static hsa_amd_memory_pool_t pool{};
|
||||
static bool have = false;
|
||||
static std::once_flag once;
|
||||
std::call_once(once, [] {
|
||||
auto cb = [](hsa_amd_memory_pool_t p, void* data) -> hsa_status_t {
|
||||
hsa_amd_segment_t seg;
|
||||
uint32_t flags = 0;
|
||||
bool alloc = false;
|
||||
hsa_amd_memory_pool_get_info(p, HSA_AMD_MEMORY_POOL_INFO_SEGMENT, &seg);
|
||||
if (seg != HSA_AMD_SEGMENT_GLOBAL) return HSA_STATUS_SUCCESS;
|
||||
hsa_amd_memory_pool_get_info(p, HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS, &flags);
|
||||
hsa_amd_memory_pool_get_info(p, HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALLOWED, &alloc);
|
||||
auto* out = static_cast<std::pair<hsa_amd_memory_pool_t*, bool*>*>(data);
|
||||
if (alloc && (flags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_COARSE_GRAINED) && !*out->second) {
|
||||
*out->first = p;
|
||||
*out->second = true;
|
||||
}
|
||||
return HSA_STATUS_SUCCESS;
|
||||
};
|
||||
std::pair<hsa_amd_memory_pool_t*, bool*> out{ &pool, &have };
|
||||
hsa_amd_agent_iterate_memory_pools(G().cpu, cb, &out);
|
||||
});
|
||||
return have ? &pool : nullptr;
|
||||
}
|
||||
|
||||
int a_vmem_commit_host(void* addr, int64_t bytes) {
|
||||
if (!addr || bytes <= 0) return RAD_E_INVAL;
|
||||
int dev = vres_ord(addr);
|
||||
if (dev < 0 && hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE;
|
||||
if (dev < 0 || dev >= (int)G().dev.size()) return RAD_E_DEVICE;
|
||||
hsa_amd_memory_pool_t* pool = host_coarse_pool();
|
||||
if (!pool) {
|
||||
device_set_error("vmem: no coarse-grained host memory pool");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
hsa_amd_vmem_alloc_handle_t h{};
|
||||
if (hsa_amd_vmem_handle_create(*pool, (size_t)bytes, MEMORY_TYPE_NONE, 0, &h) != HSA_STATUS_SUCCESS) {
|
||||
device_set_error("vmem: %lld bytes of host memory could not be had", (long long)bytes);
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
if (hsa_amd_vmem_map(addr, (size_t)bytes, 0, h, 0) != HSA_STATUS_SUCCESS) {
|
||||
(void)hsa_amd_vmem_handle_release(h);
|
||||
device_set_error("vmem: a map of %lld bytes of host memory at %p failed", (long long)bytes, addr);
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
if (vmem_grant(addr, bytes, dev, true) < 0) {
|
||||
(void)hsa_amd_vmem_unmap(addr, (size_t)bytes);
|
||||
(void)hsa_amd_vmem_handle_release(h);
|
||||
device_set_error("vmem: device %d could not be given access to host memory at %p", dev, addr);
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_vres_mu);
|
||||
g_vmaps[(uintptr_t)addr] = VMap{ h, true, bytes };
|
||||
}
|
||||
loc_forget();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int a_vmem_swap(void* a, void* b, int64_t bytes) {
|
||||
if (!a || !b || bytes <= 0) return RAD_E_INVAL;
|
||||
const int da = vres_ord(a), db = vres_ord(b);
|
||||
if (da < 0 || db < 0) return RAD_E_INVAL;
|
||||
VMap ma, mb;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_vres_mu);
|
||||
auto ia = g_vmaps.find((uintptr_t)a), ib = g_vmaps.find((uintptr_t)b);
|
||||
if (ia == g_vmaps.end() || ib == g_vmaps.end()) {
|
||||
device_set_error("vmem: a swap of %p and %p names a range not mapped", a, b);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
ma = ia->second;
|
||||
mb = ib->second;
|
||||
}
|
||||
loc_forget();
|
||||
if (hsa_amd_vmem_unmap(a, (size_t)bytes) != HSA_STATUS_SUCCESS ||
|
||||
hsa_amd_vmem_unmap(b, (size_t)bytes) != HSA_STATUS_SUCCESS ||
|
||||
hsa_amd_vmem_map(a, (size_t)bytes, 0, mb.h, 0) != HSA_STATUS_SUCCESS ||
|
||||
hsa_amd_vmem_map(b, (size_t)bytes, 0, ma.h, 0) != HSA_STATUS_SUCCESS ||
|
||||
vmem_grant(a, bytes, da, mb.host) < 0 || vmem_grant(b, bytes, db, ma.host) < 0) {
|
||||
device_set_error("vmem: a swap of %lld bytes at %p and %p failed", (long long)bytes, a, b);
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
std::lock_guard<std::mutex> lk(g_vres_mu);
|
||||
g_vmaps[(uintptr_t)a] = mb;
|
||||
g_vmaps[(uintptr_t)b] = ma;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -3634,21 +4125,68 @@ int a_vmem_protect(void* addr, int64_t bytes) {
|
||||
int a_vmem_decommit(void* addr, int64_t bytes) {
|
||||
if (!addr || bytes <= 0) return RAD_E_INVAL;
|
||||
loc_forget();
|
||||
hsa_amd_vmem_alloc_handle_t h{};
|
||||
bool have = false;
|
||||
/* The mappings that tile the range, front to back. A range they do not tile exactly is the
|
||||
* one mapping at its start, unmapped as it was mapped. */
|
||||
std::vector<VMap> hs;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_vres_mu);
|
||||
auto it = g_vmaps.find((uintptr_t)addr);
|
||||
if (it != g_vmaps.end()) { h = it->second; have = true; g_vmaps.erase(it); }
|
||||
const uintptr_t a = (uintptr_t)addr, z = a + (uintptr_t)bytes;
|
||||
std::vector<uintptr_t> keys;
|
||||
uintptr_t at = a;
|
||||
while (at < z) {
|
||||
const auto it = g_vmaps.find(at);
|
||||
if (it == g_vmaps.end() || it->second.bytes <= 0) break;
|
||||
keys.push_back(at);
|
||||
hs.push_back(it->second);
|
||||
at += (uintptr_t)it->second.bytes;
|
||||
}
|
||||
if (at != z) {
|
||||
keys.clear();
|
||||
hs.clear();
|
||||
if (const auto it = g_vmaps.find(a); it != g_vmaps.end()) {
|
||||
keys.push_back(a);
|
||||
hs.push_back(it->second);
|
||||
}
|
||||
}
|
||||
for (const uintptr_t k : keys) g_vmaps.erase(k);
|
||||
}
|
||||
if (hsa_amd_vmem_unmap(addr, (size_t)bytes) != HSA_STATUS_SUCCESS) {
|
||||
device_set_error("vmem: an unmap of %lld bytes at %p failed", (long long)bytes, addr);
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
if (have) (void)hsa_amd_vmem_handle_release(h);
|
||||
/* Card memory is kept as spares (see "spare device memory"); host memory goes back. */
|
||||
const int dev = vres_ord(addr);
|
||||
for (const VMap& m : hs) {
|
||||
if (!m.host && dev >= 0 && dev < kMaxDevices) put_spare(dev, m.h, m.bytes);
|
||||
else (void)hsa_amd_vmem_handle_release(m.h);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Card `ord`'s spares back to the driver, or every card's for -1; the bytes. */
|
||||
int64_t a_vmem_trim(int ord) {
|
||||
int64_t n = 0;
|
||||
for (int d = 0; d < kMaxDevices; ++d)
|
||||
if (ord < 0 || ord == d) n += release_spares(d);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* The runtime's figures, with the spares counted as free: they are this process's to map again,
|
||||
* and any allocation that needs them gives them back first (card_has_room). Free memory is the
|
||||
* lower of the card's counter and what the driver will still give (card_available), which every
|
||||
* allocation and commit is checked against: under a fleet's load the driver's figure ran 90-230
|
||||
* MiB below the counter, past the room plan's headroom, and a restore planned on the counter was
|
||||
* refused its last commit. The counter is the lower one for a while after a free (it trails). */
|
||||
int (*g_hip_props)(int, RadDeviceProps*) = nullptr;
|
||||
int a_props(int device, RadDeviceProps* out) {
|
||||
const int rc = g_hip_props(device, out);
|
||||
if (rc >= 0 && device >= 0 && device < kMaxDevices) {
|
||||
if (const int64_t av = card_available(device); av >= 0 && av < out->vram_free) out->vram_free = av;
|
||||
out->vram_free += g_spare_bytes[device].load(std::memory_order_relaxed);
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ pinned host memory, in pieces
|
||||
*
|
||||
* Every pinned or mapped host allocation is one address range locked in pieces of at most
|
||||
@@ -3748,6 +4286,25 @@ const char* hsa_why(hsa_status_t st) {
|
||||
return hsa_status_string(st, &m) == HSA_STATUS_SUCCESS && m ? m : "unknown HSA status";
|
||||
}
|
||||
|
||||
/* Faults [p, p + len) in from several threads before the lock takes it. The lock faults what is
|
||||
* not yet present on the calling thread, page by page, and the kernel's zeroing of fresh pages
|
||||
* is most of a lock's cost: a 4 GiB pin takes 0.33 s locked as it is, 0.21 s faulted in by four
|
||||
* threads first (13 -> 20 GB/s; a 64 MiB pin 4.4 -> 2.2 ms). Locking the pieces in parallel
|
||||
* gains nothing, the driver serialises them. Small ranges are not worth a thread. */
|
||||
void prefault(char* p, int64_t len) {
|
||||
constexpr int64_t kMin = (int64_t)16 << 20;
|
||||
constexpr int kThreads = 4;
|
||||
if (len < kMin) return;
|
||||
const int64_t per = align_up((len + kThreads - 1) / kThreads, (int64_t)RAD_ALIGN_POOL);
|
||||
auto touch = [p, len](int64_t lo, int64_t hi) {
|
||||
for (int64_t o = lo; o < std::min(hi, len); o += 4096) ((volatile char*)p)[o] = 0;
|
||||
};
|
||||
std::thread th[kThreads - 1];
|
||||
for (int t = 1; t < kThreads; ++t) th[t - 1] = std::thread(touch, t * per, (t + 1) * per);
|
||||
touch(0, per);
|
||||
for (std::thread& x : th) if (x.joinable()) x.join();
|
||||
}
|
||||
|
||||
/* Whether the driver offers the SVM API, so a locked piece is mapped in place. */
|
||||
bool svm_in_place() {
|
||||
static const bool on = [] {
|
||||
@@ -3856,6 +4413,7 @@ void* pin_pieces(int64_t bytes) {
|
||||
warn_if_no_huge_pages();
|
||||
}
|
||||
(void)::madvise(p, (size_t)len, MADV_DONTFORK);
|
||||
prefault(p, len);
|
||||
|
||||
if (!lock_pieces(p, len, bytes, cards, "rad_dev_alloc")) {
|
||||
::munmap(p, (size_t)len);
|
||||
@@ -4074,6 +4632,11 @@ const DeviceBackend* aql_backend_if_present(void) {
|
||||
g_hip_free = hip->free;
|
||||
g_hip_host_ptr = hip->host_ptr;
|
||||
g_hip_device_ptr = hip->device_ptr;
|
||||
g_hip_props = hip->props;
|
||||
g_aql.props = a_props;
|
||||
g_aql.vmem_trim = a_vmem_trim;
|
||||
g_aql.stream_counts = a_stream_counts;
|
||||
g_aql.stream_trim = a_stream_trim;
|
||||
g_aql.alloc = a_alloc;
|
||||
g_aql.map_file = a_map_file;
|
||||
g_aql.free = a_free;
|
||||
@@ -4097,6 +4660,8 @@ const DeviceBackend* aql_backend_if_present(void) {
|
||||
g_aql.memcpy_list_async = a_memcpy_list_async;
|
||||
g_aql.link_hold = a_link_hold;
|
||||
g_aql.link_gate = a_link_gate;
|
||||
g_aql.peer_launch = a_peer_launch;
|
||||
g_aql.cards_claim = a_cards_claim;
|
||||
g_aql.xp_supported = a_xp_supported;
|
||||
g_aql.xp_stream_create = a_xp_stream_create;
|
||||
g_aql.ride = a_ride;
|
||||
@@ -4112,8 +4677,11 @@ const DeviceBackend* aql_backend_if_present(void) {
|
||||
g_aql.vmem_reserve = a_vmem_reserve;
|
||||
g_aql.vmem_release = a_vmem_release;
|
||||
g_aql.vmem_commit = a_vmem_commit;
|
||||
g_aql.vmem_commit_units = a_vmem_commit_units;
|
||||
g_aql.vmem_decommit = a_vmem_decommit;
|
||||
g_aql.vmem_protect = a_vmem_protect;
|
||||
g_aql.vmem_commit_host = a_vmem_commit_host;
|
||||
g_aql.vmem_swap = a_vmem_swap;
|
||||
g_aql.tape_begin = a_tape_begin;
|
||||
g_aql.tape_mark = a_tape_mark;
|
||||
g_aql.tape_pause = a_tape_pause;
|
||||
@@ -4200,6 +4768,14 @@ void __hipRegisterFunction(void** modules, const void* host_fn, char* device_fn,
|
||||
auto it = r.by_handle.find(modules);
|
||||
if (it == r.by_handle.end() || !host_fn || !device_name) return;
|
||||
Func*& f = r.by_stub[host_fn];
|
||||
/* A plugin closed when its model unloaded leaves its stubs here. The same library loaded again
|
||||
* names the same kernels and keeps their records, whose code is still loaded. Another library
|
||||
* could map a different kernel at the same address, which must not inherit the old record. */
|
||||
if (f && f->name != device_name) {
|
||||
RAD_WARN("device: a kernel stub at %p now names %s, not %s", host_fn, device_name, f->name.c_str());
|
||||
f = nullptr;
|
||||
g_stub_epoch.fetch_add(1, std::memory_order_release);
|
||||
}
|
||||
if (!f) f = new Func();
|
||||
f->mod = it->second;
|
||||
f->name = device_name;
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include <cstdint>
|
||||
|
||||
#include "aql.h"
|
||||
#include "chain_kernel.h"
|
||||
#include "device.h"
|
||||
|
||||
namespace {
|
||||
@@ -36,6 +37,22 @@ __global__ __launch_bounds__(kThreads) void aql_copy16(const u32x4* __restrict__
|
||||
for (; i < n; i += stride) dst[i] = src[i];
|
||||
}
|
||||
|
||||
/* aql_copy16 as a chained form (chain_kernel.h), launched where launches chain: a card-side copy
|
||||
* between two kernels of a pass (a routed layer's counts into the core's row) then costs no
|
||||
* barrier on either side. */
|
||||
__global__ __launch_bounds__(kThreads) void r4dchain_copy16(const u32x4* __restrict__ src,
|
||||
u32x4* __restrict__ dst, uint64_t n) {
|
||||
rad_chain_wait();
|
||||
const uint64_t stride = (uint64_t)gridDim.x * kThreads;
|
||||
uint64_t i = (uint64_t)blockIdx.x * kThreads + threadIdx.x;
|
||||
for (; i + 3 * stride < n; i += 4 * stride) {
|
||||
const u32x4 a = src[i], b = src[i + stride], c = src[i + 2 * stride], d = src[i + 3 * stride];
|
||||
dst[i] = a; dst[i + stride] = b; dst[i + 2 * stride] = c; dst[i + 3 * stride] = d;
|
||||
}
|
||||
for (; i < n; i += stride) dst[i] = src[i];
|
||||
rad_chain_done();
|
||||
}
|
||||
|
||||
/* A copy across the link (pinned host memory) is one workgroup of four waves.
|
||||
*
|
||||
* The link delivers ~29 GB/s regardless of grid size, so the copy should hold as few waves as
|
||||
@@ -190,6 +207,9 @@ extern "C" int rad_aql_blit_copy(void* dst, const void* src, uint64_t bytes, voi
|
||||
if (link)
|
||||
hipLaunchKernelGGL(aql_copy_link, dim3(1), dim3(kLinkThreads), 0, s,
|
||||
(const u32x4*)src, (u32x4*)dst, n);
|
||||
else if (rad_dev_chain_enabled())
|
||||
hipLaunchKernelGGL(r4dchain_copy16, dim3(blocks_for(n, 4 * kThreads)), dim3(kThreads),
|
||||
0, s, (const u32x4*)src, (u32x4*)dst, n);
|
||||
else
|
||||
hipLaunchKernelGGL(aql_copy16, dim3(blocks_for(n, 4 * kThreads)), dim3(kThreads), 0,
|
||||
s, (const u32x4*)src, (u32x4*)dst, n);
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/* chain_kernel.h -- the chained form's wait and completion for the core's own kernels
|
||||
* (RadKernelChainFn, abi/rad_abi.h).
|
||||
*
|
||||
* The backend gives a kernel named r4dchain* a record at RAD_CHAIN_KARG_OFF and drops its barrier
|
||||
* bit behind another chained kernel. Before the first read one lane waits for the queue's counter
|
||||
* to reach the record's target; after the last write the block releases and adds 1. A record that
|
||||
* does not check out means: run plain. Every block must reach rad_chain_done exactly once.
|
||||
*/
|
||||
#pragma once
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "rad_abi.h"
|
||||
|
||||
struct RadChainRec {
|
||||
unsigned long long magic, target;
|
||||
unsigned long long* ctr;
|
||||
unsigned long long check;
|
||||
};
|
||||
|
||||
__device__ __forceinline__ const RadChainRec* rad_chain_rec() {
|
||||
const RadChainRec* r = (const RadChainRec*)((const char*)__builtin_amdgcn_kernarg_segment_ptr() +
|
||||
RAD_CHAIN_KARG_OFF);
|
||||
const unsigned long long magic = r->magic, target = r->target, check = r->check;
|
||||
if (magic != RAD_CHAIN_MAGIC ||
|
||||
check != (magic ^ target ^ (unsigned long long)(uintptr_t)r->ctr ^ RAD_CHAIN_CHECK))
|
||||
return nullptr;
|
||||
return r;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ void rad_chain_wait() {
|
||||
const RadChainRec* r = rad_chain_rec();
|
||||
if (!r) return;
|
||||
if (threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0)
|
||||
while (__hip_atomic_load(r->ctr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < r->target)
|
||||
__builtin_amdgcn_s_sleep(1);
|
||||
__syncthreads();
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
|
||||
}
|
||||
|
||||
__device__ __forceinline__ void rad_chain_done() {
|
||||
const RadChainRec* r = rad_chain_rec();
|
||||
if (!r) return;
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
|
||||
__syncthreads();
|
||||
if (threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0)
|
||||
__hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
|
||||
}
|
||||
+315
-6
@@ -13,6 +13,8 @@
|
||||
#include "rad_device.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
@@ -39,8 +41,8 @@ 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, and only where the model's
|
||||
* plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter
|
||||
* decodes speculatively (rad_dev_chain_infer, from the engine before any row resolves). */
|
||||
* plugin measured a gain (RadArchProbe::chain_pays): with its drafter decoding speculatively, or
|
||||
* with and without one (rad_dev_chain_infer, from the engine before any row resolves). */
|
||||
extern "C" int rad_dev_chain_enabled(void);
|
||||
extern "C" void rad_dev_chain_infer(int pays);
|
||||
|
||||
@@ -91,6 +93,17 @@ extern "C" int rad_memcpy_list_async(const RadCopySeg* segs, int n, unsigned fla
|
||||
* copies; the step waits on the collective, while the copies have the rest of the layer. */
|
||||
extern "C" int rad_link_hold(RadStream s, int on);
|
||||
|
||||
/* The launches this thread issues between `on` 1 and `on` 0 are a collective's: their blocks wait
|
||||
* for the other ranks' blocks of the same launch on another card. A recorded pass keeps the mark.
|
||||
*
|
||||
* rad_dev_cards_claim tells the backend which cards an engine's collectives run on (`on` 1, once
|
||||
* per engine with more than one rank) and that the engine is gone (`on` 0). On a card more than one
|
||||
* engine has claimed, nothing may wait on the card behind a collective except the collective's own
|
||||
* blocks (aql.cpp, "collectives on a shared card"). A claim that makes a card shared returns once
|
||||
* everything issued before it on that card's streams has finished. */
|
||||
extern "C" void rad_dev_peer_launch(int on);
|
||||
extern "C" int rad_dev_cards_claim(const int* cards, int n, int on);
|
||||
|
||||
/* The hold word, for a launch that ends its own hold: a 64-bit word reachable by every engine and
|
||||
* kernel of the card, odd while the link is held. A launch handed this address releases the hold
|
||||
* by decrementing the word once, only if odd, as soon as its awaited bytes have landed; follow it
|
||||
@@ -280,9 +293,14 @@ struct DeviceBackend {
|
||||
*
|
||||
* Contract:
|
||||
* `vmem_reserve` takes address space, no pages.
|
||||
* `vmem_commit` backs one granule and `vmem_decommit` unbacks one. The driver unmaps a
|
||||
* mapping only exactly as it was mapped (four granules mapped in one call cannot be unmapped
|
||||
* singly), so VMem issues one call per granule.
|
||||
* `vmem_commit` backs one granule. The driver unmaps a mapping only exactly as it was
|
||||
* mapped (four granules mapped as one cannot be unmapped singly), so VMem maps a mapping per
|
||||
* granule, a run of them in one `vmem_commit_units` call where the backend has it. It
|
||||
* returns 1 when the backing is recycled memory that holds what its last mapping left, 0
|
||||
* when it reads zero.
|
||||
* `vmem_decommit` unbacks a range that is one mapping or a contiguous run of whole ones, in
|
||||
* one unmap: each unmap costs a driver round trip that grows with the mappings the process
|
||||
* holds (8.8 us a granule alone, 48 beside 6000 others; 26 for a run, per granule).
|
||||
* `vmem_protect` grants this device read/write access to an already-backed range. It is
|
||||
* separate from commit because access set on a granule adjacent to an accessible one is
|
||||
* refused, while the whole contiguous run is accepted; VMem names the run.
|
||||
@@ -355,6 +373,36 @@ struct DeviceBackend {
|
||||
|
||||
/* ---- see dev_stuck_ms. Null on a backend that cannot tell. */
|
||||
int64_t (*stuck_ms)(void);
|
||||
|
||||
/* ---- host-backed mappings, for parking (paging.cpp). `vmem_commit_host` backs a reserved
|
||||
* granule with pinned host memory that the reservation's card reads and writes in place, at
|
||||
* that address, and the host can too. `vmem_swap` exchanges what backs two mapped ranges of
|
||||
* equal size (each keeps its kind: a range of device memory stays device memory wherever it
|
||||
* is mapped). Remapped addresses need dev_settle_maps before the card writes them. Null on a
|
||||
* backend without them; parking then keeps no host copies. */
|
||||
int (*vmem_commit_host)(void* addr, int64_t bytes);
|
||||
int (*vmem_swap)(void* a, void* b, int64_t bytes);
|
||||
|
||||
/* ---- [addr, addr + bytes) backed as one mapping per `unit` bytes, each of which can be
|
||||
* unbacked alone later, with access granted once over the run: per granule, granting access
|
||||
* costs about as much as the map (41.9 us a granule backed singly, 24.6 as a run). All or
|
||||
* nothing: on failure nothing of the run stays backed. Null: VMem backs a granule at a time. */
|
||||
int (*vmem_commit_units)(void* addr, int64_t bytes, int64_t unit);
|
||||
|
||||
/* ---- device memory a decommit kept for the next commit of its size (counted as free in
|
||||
* props), given back to the driver: card `device`'s, or every card's for -1; the bytes. Null
|
||||
* on a backend that keeps none. */
|
||||
int64_t (*vmem_trim)(int device);
|
||||
/* rad_dev_peer_launch and rad_dev_cards_claim. Null on a backend that never launches a kernel
|
||||
* ahead of the one before it. */
|
||||
void (*peer_launch)(int on);
|
||||
int (*cards_claim)(const int* cards, int n, int on);
|
||||
/* ---- the hardware queues card `device` has open and how many of them no stream holds (a
|
||||
* closed stream's queue is kept for the card's next stream); and the kept ones destroyed
|
||||
* until `keep` are left, the number destroyed, none while any queue of the card holds a
|
||||
* packet. Null on a backend that keeps none. */
|
||||
void (*stream_counts)(int device, int* open, int* idle);
|
||||
int (*stream_trim)(int device, int keep);
|
||||
};
|
||||
|
||||
|
||||
@@ -411,12 +459,44 @@ constexpr int kTapeOverlapRun = 6;
|
||||
* kernel plugin that calls hipMalloc directly; see the ledger in dispatch.cpp. */
|
||||
void rad_dev_alloc_totals(int kind, int64_t* bytes, int64_t* count);
|
||||
|
||||
/* `fn` is called after every device-memory free (RAD_MEM_DEVICE) with the range freed: a kernel
|
||||
* library's rad_plugin_freed (abi/rad_abi.h), registered by the plugin loader. Registrations are
|
||||
* counted: every registry that loads the library registers its hook, and rad_dev_off_free, which
|
||||
* the loader calls before it closes the library, takes one back. The hook goes with the last,
|
||||
* once no free is calling it: a library opened again can land at another address, and a hook
|
||||
* left behind would call into memory nothing maps. */
|
||||
void rad_dev_on_free(void (*fn)(const void* base, int64_t bytes));
|
||||
void rad_dev_off_free(void (*fn)(const void* base, int64_t bytes));
|
||||
|
||||
/* Event handles created and not yet destroyed, process-wide. */
|
||||
int64_t rad_dev_live_events(void);
|
||||
/* Calls to rad_event_sync and rad_stream_sync since process start, from any thread: the host
|
||||
* blocks the ABI makes. */
|
||||
int64_t rad_dev_host_blocks(void);
|
||||
|
||||
/* A parked allocation's contents (docs/MULTIMODEL.md §7): in pinned host memory, in a file of the
|
||||
* disk tier, or both. A copy written to disk can let its host memory go and be read back later. */
|
||||
struct HostCopy {
|
||||
void* host = nullptr; /* pinned, `bytes` rounded up to the direct-I/O block */
|
||||
int64_t bytes = 0;
|
||||
std::string file; /* the disk tier's copy, when written */
|
||||
bool on_disk = false; /* `file` holds exactly what `host` holds (or held) */
|
||||
|
||||
int64_t ram() const { return host ? bytes : 0; }
|
||||
/* Pinned memory for `n` bytes; what the copy held before, host memory and file, is freed. */
|
||||
int alloc(int64_t n);
|
||||
/* Writes the host bytes to a new file under `dir` (O_DIRECT). Between pieces it asks `gate`
|
||||
* (when given): 0 goes on, 1 waits (a model loading reads its container from the same drive),
|
||||
* -1 abandons the write (RAD_E_STATE, no file left). */
|
||||
int spill(const std::string& dir, const std::function<int()>& gate = {});
|
||||
/* Frees the host memory of a copy that is on disk. */
|
||||
void drop_host();
|
||||
/* Reads the file back into fresh pinned memory when the host copy is gone. */
|
||||
int load();
|
||||
/* Frees everything: the host memory and the file. */
|
||||
void release();
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ elastic memory
|
||||
* One reserved address range and which granules inside it are backed.
|
||||
*
|
||||
@@ -444,10 +524,15 @@ public:
|
||||
/* Movable, since owners live in vectors. The source is left empty so its destructor does not
|
||||
* unmap the range the destination now owns. */
|
||||
VMem(VMem&& o) noexcept
|
||||
: base_(o.base_), size_(o.size_), committed_(o.committed_), ext_(std::move(o.ext_)) {
|
||||
: base_(o.base_), size_(o.size_), committed_(o.committed_), ext_(std::move(o.ext_)),
|
||||
device_(o.device_), copy_(std::move(o.copy_)), parked_(std::move(o.parked_)),
|
||||
discarded_(o.discarded_) {
|
||||
rekey(&o, this);
|
||||
o.base_ = nullptr;
|
||||
o.size_ = o.committed_ = 0;
|
||||
o.ext_.clear();
|
||||
o.copy_ = HostCopy{};
|
||||
o.parked_.clear();
|
||||
}
|
||||
VMem& operator=(VMem&& o) noexcept {
|
||||
if (this != &o) {
|
||||
@@ -456,9 +541,16 @@ public:
|
||||
size_ = o.size_;
|
||||
committed_ = o.committed_;
|
||||
ext_ = std::move(o.ext_);
|
||||
device_ = o.device_;
|
||||
copy_ = std::move(o.copy_);
|
||||
parked_ = std::move(o.parked_);
|
||||
discarded_ = o.discarded_;
|
||||
rekey(&o, this);
|
||||
o.base_ = nullptr;
|
||||
o.size_ = o.committed_ = 0;
|
||||
o.ext_.clear();
|
||||
o.copy_ = HostCopy{};
|
||||
o.parked_.clear();
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
@@ -482,19 +574,236 @@ public:
|
||||
* kernel. */
|
||||
bool is_committed(int64_t off, int64_t bytes) const;
|
||||
|
||||
/* Parking (dev_page_out): every backed extent copied to pinned host memory on `s`, then
|
||||
* unbacked; the bytes held on the host, or an error. page_in backs the same extents again and
|
||||
* copies them back. With `discard` nothing in the range is kept (a cache with no live
|
||||
* sequence and its index reset): page_out copies nothing and returns 0, and page_in backs the
|
||||
* extents again without copying anything back. */
|
||||
int64_t page_out(RadStream s, bool discard = false);
|
||||
int page_in(RadStream s);
|
||||
bool parked() const { return !parked_.empty(); }
|
||||
int64_t parked_bytes() const {
|
||||
int64_t n = 0;
|
||||
for (const auto& e : parked_) n += e.second;
|
||||
return n;
|
||||
}
|
||||
/* The card the range was reserved on, for the copies' stream. */
|
||||
int device() const { return device_; }
|
||||
/* Host bytes held for the parked extents (zero once they live only on disk). */
|
||||
int64_t host_bytes() const { return parked_.empty() ? 0 : copy_.ram(); }
|
||||
/* The disk tier (dev_page_spill): write the parked copy out, or let its host memory go. */
|
||||
int spill(const std::string& dir, const std::function<int()>& gate = {}) {
|
||||
return parked_.empty() ? RAD_OK : copy_.spill(dir, gate);
|
||||
}
|
||||
int64_t drop_host() {
|
||||
if (parked_.empty() || !copy_.on_disk || !copy_.host) return 0;
|
||||
const int64_t n = copy_.bytes;
|
||||
copy_.drop_host();
|
||||
return n;
|
||||
}
|
||||
|
||||
private:
|
||||
/* The owner registry follows the object when it moves (reserve() files it under the thread's
|
||||
* engine owner). */
|
||||
static void rekey(VMem* from, VMem* to);
|
||||
void* base_ = nullptr;
|
||||
int64_t size_ = 0;
|
||||
int64_t committed_ = 0;
|
||||
/* Backed extents (offset, bytes): sorted, disjoint and never adjacent, since a touching
|
||||
* commit merges. Length tracks live regions, not calls. */
|
||||
std::vector<std::pair<int64_t, int64_t>> ext_;
|
||||
int device_ = 0;
|
||||
HostCopy copy_; /* parked: the extents' contents */
|
||||
std::vector<std::pair<int64_t, int64_t>> parked_; /* parked: the extents to back again */
|
||||
bool discarded_ = false; /* parked without a copy */
|
||||
|
||||
/* Adds a newly mapped piece and merges it with whatever it touches. */
|
||||
void add_extent(int64_t off, int64_t bytes);
|
||||
void drop_extent(int64_t off, int64_t bytes);
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ parking (paging.cpp)
|
||||
* docs/MULTIMODEL.md §7. A device allocation of 2 MiB or more made on a thread working for an
|
||||
* engine (engine_owner, rad_internal.h) is reserved as one address range and mapped in chunks, and
|
||||
* an elastic range reserved on such a thread is filed under the engine too, so the engine's memory
|
||||
* can leave the card in part or whole and come back at the same addresses.
|
||||
*
|
||||
* A chunk out of the card is somewhere else: in pinned host memory, in a file of the disk tier,
|
||||
* both, or nowhere when it was discarded (its contents not needed: an expert slab's free slots).
|
||||
* Restoring maps every chunk out and copies back the ones that had a copy. The engine must be
|
||||
* quiet for both: nothing it issued still runs, nothing new is issued until the page-in. */
|
||||
constexpr int64_t kPageMin = (int64_t)2 << 20;
|
||||
/* For rad_dev_alloc and rad_dev_free: an engine's pageable allocation, and its release (false when
|
||||
* `p` is not one). */
|
||||
void* page_alloc(int64_t bytes, int owner, int device);
|
||||
bool page_free(void* p);
|
||||
/* Device bytes `owner` holds on card `device`: its allocations and elastic backing (a load in
|
||||
* flight, for the fleet's reservation). */
|
||||
int64_t dev_owner_bytes(int owner, int device);
|
||||
/* The backend rad_dev_* calls go to. */
|
||||
const DeviceBackend* active_backend();
|
||||
/* The owner's elastic ranges (dispatch.cpp's registry). */
|
||||
std::vector<VMem*> vmems_of(int owner);
|
||||
|
||||
struct PageOut {
|
||||
/* Bytes to take off each card; empty takes everything. */
|
||||
std::map<int, int64_t> want;
|
||||
/* New host memory the copies may take; past it they go to `dir`, and without a `dir` the
|
||||
* page-out stops there. */
|
||||
int64_t host_budget = INT64_MAX;
|
||||
std::string dir;
|
||||
/* The elastic ranges (the KV cache) are dropped, not copied. */
|
||||
bool discard_elastic = false;
|
||||
};
|
||||
struct PageResult {
|
||||
std::map<int, int64_t> freed; /* bytes unmapped on each card */
|
||||
int64_t host = 0; /* host bytes the copies took */
|
||||
int64_t disk = 0; /* bytes written straight to the disk tier */
|
||||
int64_t dropped = 0; /* bytes unmapped with nothing kept (discarded) */
|
||||
int64_t reused = 0; /* bytes unmapped against a copy made earlier */
|
||||
int64_t file = 0; /* bytes unmapped against the container they were loaded from */
|
||||
double quiet_s = 0; /* the engine coming to rest (responses drained, loop held) */
|
||||
double slab_s = 0; /* lent slots recalled and the expert slab emptied */
|
||||
double out_s = 0; /* the page-out itself */
|
||||
};
|
||||
int dev_page_out(int owner, const PageOut& req, PageResult* out);
|
||||
/* A stretch of memory a page-in mapped for its owner to fill (dev_page_refilled). */
|
||||
struct PageSpan { char* p; int64_t bytes; int device; };
|
||||
/* Every chunk of the owner that is out comes back. Those of an allocation the owner refills are
|
||||
* only mapped, and appended to `refill` for the owner to fill before anything reads them; a
|
||||
* page-in with such chunks out and no `refill` fails (RAD_E_STATE) and maps nothing. */
|
||||
int dev_page_in(int owner, std::vector<PageSpan>* refill = nullptr, bool elastic = true);
|
||||
/* The owner's elastic ranges backed again (and their copies, if they were kept), what a page-in
|
||||
* does last; then the cards' translations settled. A page-in with `elastic` false leaves this to
|
||||
* the caller, which can run it beside the refill: nothing of the refill reads those ranges, and
|
||||
* an image model's KV cache is ten thousand commits (0.5 s). */
|
||||
int dev_page_in_elastic(int owner);
|
||||
/* The owner's chunks wholly inside these ranges hold nothing that needs keeping: the next page-out
|
||||
* unmaps them first and copies nothing (an expert slab's slots after it dropped its units). */
|
||||
void dev_page_discard(int owner, const std::vector<std::pair<const void*, int64_t>>& ranges);
|
||||
/* Bytes mapped on cards, and bytes of host copies (parked or kept). */
|
||||
void dev_page_stats(int owner, int64_t* device, int64_t* host);
|
||||
/* Bytes of the owner's pageable memory still on each card. */
|
||||
std::map<int, int64_t> dev_page_mapped_bytes(int owner);
|
||||
/* Bytes the owner has out of the card right now, by card. With `live`, only what dev_page_in_live
|
||||
* would map: the sealed chunks parked in host memory stay out of the sum, read in place. */
|
||||
std::map<int, int64_t> dev_page_out_bytes(int owner, bool live = false);
|
||||
/* [off, off + bytes) of the pageable allocation `p` (all of it for bytes < 0) is never written after
|
||||
* the load (a static plan's weights pool, a tiered one's statics): a copy, once made, is kept after
|
||||
* the page-in, and later page-outs of those chunks only unmap. */
|
||||
void dev_page_seal(void* p, int64_t off = 0, int64_t bytes = -1);
|
||||
/* The pageable allocation `p` is rebuilt by its owner from its source (a weights pool from its
|
||||
* container) after a page-in: its sealed chunks leave the card with no copy at all, an unmap, and
|
||||
* dev_page_in hands them back to be filled. Its chunks are no longer checked against the
|
||||
* container (dev_page_source). */
|
||||
void dev_page_refilled(void* p);
|
||||
/* [p, p + bytes) is being written (an expert moved into a slab slot): the kept copies of the
|
||||
* chunks it touches are stale. A no-op for memory that is not pageable. Called when the write is
|
||||
* issued and again when it lands, so a copy made across it is never taken as exact. */
|
||||
void dev_page_invalidate(const void* p, int64_t bytes);
|
||||
/* Memory mapped again at an address that was mapped before (a page-in, a pool growing back) is not
|
||||
* written until the cards' translation caches have been flushed in full: a map flushes them only
|
||||
* lightly, and copies into such memory can land nowhere, so the memory reads back its previous
|
||||
* owner's bytes or zeros (Linux 7.1 with gfx1201; tests/device_test.cpp
|
||||
* two_allocations_of_one_owner_come_back_exact_from_the_disk_tier). Unpinning host memory makes
|
||||
* the driver flush every card it was mapped on in full, so this pins one page and unpins it.
|
||||
* Called after a batch of maps, before anything writes them. */
|
||||
/* Where address `a` lies among the elastic reservations and pageable allocations, for a fault report:
|
||||
* its owner, card, offset, whether it is backed and what its paging chunk holds. Empty when it is in
|
||||
* none. Takes no lock it would wait for, since a fault can arrive while one is held. */
|
||||
std::string dev_fault_where(const void* a);
|
||||
|
||||
int dev_settle_maps();
|
||||
|
||||
/* VMem::commit on this thread leaves its flush (dev_settle_maps) for the end of this scope, so a
|
||||
* run of ranges mapped together flushes once. Nothing may write the new ranges before end(), which
|
||||
* reports the flush's result; the destructor ends a batch left open by an early return. */
|
||||
class MapBatch {
|
||||
public:
|
||||
MapBatch();
|
||||
~MapBatch();
|
||||
MapBatch(const MapBatch&) = delete;
|
||||
MapBatch& operator=(const MapBatch&) = delete;
|
||||
int end();
|
||||
private:
|
||||
bool ended_ = false;
|
||||
};
|
||||
/* The backend's kept device memory on card `device` (-1: every card) back to the driver, the
|
||||
* bytes; its pages come free as the driver wipes them (~95 GB/s). For a caller about to allocate
|
||||
* outside the elastic calls, or done with the swap that would have reused it. */
|
||||
int64_t dev_vmem_trim(int device);
|
||||
/* The hardware queues card `device` has open, and how many of them are kept for its next streams
|
||||
* (0 and 0 on a backend that keeps none). */
|
||||
void dev_stream_counts(int device, int* open, int* idle);
|
||||
/* Card `device`'s kept queues destroyed until `keep` are left: the number destroyed, about 41 MiB
|
||||
* of the card each. Nothing is destroyed while any queue of the card holds a packet, and the
|
||||
* caller sees to it that nothing is launched on the card during the call: destroying a queue
|
||||
* beside a busy one can reset the card. */
|
||||
int dev_stream_trim(int device, int keep);
|
||||
/* The device this thread last selected with rad_dev_set. */
|
||||
int dev_current();
|
||||
/* The container at `path`, by an id for dev_page_source (the same path gives the same id). */
|
||||
int dev_page_file(const char* path);
|
||||
/* The load copied container `file`'s rows [0, ny) of wb bytes at foff + y * sp verbatim onto
|
||||
* [dst, dst + ny * wb). A chunk of pageable memory filled this way can go out against the container
|
||||
* instead of a copy: a page-out (or backup) reads the device bytes back, compares them with the
|
||||
* container (zero where nothing was loaded) and writes nothing when they match; the page-in reads
|
||||
* the container. A chunk written since (dev_page_invalidate) is copied as any other. A no-op for
|
||||
* memory that is not pageable. */
|
||||
void dev_page_source(const void* dst, int file, int64_t foff, int64_t wb, int64_t ny, int64_t sp);
|
||||
/* Bytes of the owner's mapped chunks a page-out would have to copy (no discard, no kept copy,
|
||||
* not loaded verbatim from a container, not refilled by the owner). */
|
||||
int64_t dev_page_uncopied(int owner);
|
||||
/* A restore that serves at once: like dev_page_in, but a sealed chunk parked in host memory stays
|
||||
* there, read in place over the link, until dev_page_promote moves it; *left is how much. */
|
||||
int dev_page_in_live(int owner, int64_t* left, std::vector<PageSpan>* refill = nullptr,
|
||||
bool elastic = true);
|
||||
/* dev_page_in (`left` null) or dev_page_in_live in two halves, for an owner that refills: the begin
|
||||
* maps every chunk, hands back those to refill and starts the copies of the chunks held in host
|
||||
* memory; the end waits for those copies and swaps their memory in, and must follow every begin
|
||||
* that succeeded. The refill runs between the two, beside the copies: it writes none of those
|
||||
* chunks. Elastic ranges are left to dev_page_in_elastic. */
|
||||
int dev_page_in_begin(int owner, int64_t* left, std::vector<PageSpan>* refill);
|
||||
int dev_page_in_end(int owner);
|
||||
/* Between the two halves: waits for the clears the begin issued on recycled refill chunks, which
|
||||
* it does not wait for itself. The refill calls it before its first write into them; the end
|
||||
* waits for them too. The calling thread's current device is kept. */
|
||||
int dev_page_in_cleared(int owner);
|
||||
/* Moves up to `max_bytes` of the chunks dev_page_in_live left in host memory onto their cards,
|
||||
* while the engine serves: each is copied to device memory first, then `quiet` runs the swap of
|
||||
* mappings with nothing of the engine in flight (Engine::run_quiet). Returns the bytes moved, 0
|
||||
* when none is left, or an error (no device memory for them: the rest stays in host memory). */
|
||||
int64_t dev_page_promote(int owner, int64_t max_bytes,
|
||||
const std::function<int(const std::function<int()>&)>& quiet);
|
||||
/* Bytes of `owner`'s chunks served from host memory in place, on `device` (-1: all). */
|
||||
int64_t dev_page_live_bytes(int owner, int device = -1);
|
||||
/* Host memory all parked and kept copies hold (they are host-backed mappings, not pinned
|
||||
* allocations, so rad_dev_alloc_totals does not count them). */
|
||||
int64_t dev_page_host_bytes();
|
||||
/* Frees host copies of mapped sealed chunks (a file copy stays). The host bytes freed. */
|
||||
int64_t dev_page_drop_copies(int owner);
|
||||
/* Writes every host copy without a file copy to the disk tier; `gate` as HostCopy::spill. */
|
||||
int64_t dev_page_spill(int owner, const std::string& dir, const std::function<int()>& gate = {});
|
||||
/* Frees host copies that have a file copy. The host bytes freed. */
|
||||
int64_t dev_page_drop_host(int owner);
|
||||
/* A parked owner's chunks whose only copy is the disk tier or its container: their bytes. */
|
||||
int64_t dev_page_fillable(int owner);
|
||||
/* The owner's parked chunks of allocations it refills that have no host memory yet, one span a
|
||||
* chunk, in address order. */
|
||||
std::vector<PageSpan> dev_page_refill_chunks(int owner);
|
||||
/* A host fill by the owner (Engine::fill_host): host memory mapped at each of these chunks (from
|
||||
* dev_page_refill_chunks), as a park to host memory leaves a chunk, for the owner to fill from its
|
||||
* source; then dev_page_fill_end: `filled`, the chunks' host copies are theirs and the next restore
|
||||
* copies them over the link (exact until written, so a later park keeps them); otherwise the host
|
||||
* memory goes again and the chunks stay to be refilled. */
|
||||
int dev_page_fill_begin(int owner, const std::vector<PageSpan>& chunks);
|
||||
void dev_page_fill_end(int owner, const std::vector<PageSpan>& chunks, bool filled);
|
||||
/* Up to max_bytes of those read into host memory and mapped at their own addresses, as a park to
|
||||
* host memory leaves them, so the next restore copies over the link instead of reading the drive
|
||||
* (and a live restore serves from them in place). The owner must be parked and idle. Returns the
|
||||
* bytes filled, or a negative status. */
|
||||
int64_t dev_page_fill_host(int owner, int64_t max_bytes);
|
||||
|
||||
/* Bytes backed by every VMem in the process, for Engine::start's receipt. VMem commits bypass the
|
||||
* rad_dev_alloc ledger, so without this the engine's accounting would miss the elastic pools. */
|
||||
int64_t rad_dev_vmem_committed(void);
|
||||
|
||||
+411
-43
@@ -7,6 +7,7 @@
|
||||
* with ROCm headers and no /dev/kfd); the chosen backend is logged at Info.
|
||||
*/
|
||||
#include "device.h"
|
||||
#include "directio.h"
|
||||
#include "../rad_internal.h"
|
||||
|
||||
#include <algorithm>
|
||||
@@ -18,10 +19,18 @@
|
||||
#include <iterator>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <unordered_map>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#include <thread>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <unistd.h>
|
||||
|
||||
/* The device rad_dev_set last bound on this thread. */
|
||||
static thread_local int t_device = 0;
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -147,24 +156,43 @@ Ledger g_ledger[4]; /* indexed by RAD_MEM_*; rad_dev_alloc bounds the kin
|
||||
/* Each live allocation's size, so rad_dev_free (which has none) takes it back off the ledger's
|
||||
* bytes: pinned ranges are freed and taken again during bring-up, and the pin-cap check reads the
|
||||
* ledger as what the process holds. Allocations are rare, never per step. */
|
||||
struct LiveAlloc { int64_t bytes; int kind; };
|
||||
struct LiveAlloc { int64_t bytes; int kind; int owner; int device; };
|
||||
/* Device bytes each engine holds on each card (dev_owner_bytes): its rad_dev_alloc allocations and
|
||||
* its elastic ranges' backing. */
|
||||
std::mutex g_owner_mu;
|
||||
std::map<std::pair<int, int>, int64_t> g_owner_bytes;
|
||||
void owner_add(int owner, int device, int64_t n) {
|
||||
if (owner <= 0 || n == 0) return;
|
||||
std::lock_guard<std::mutex> lk(g_owner_mu);
|
||||
g_owner_bytes[{ owner, device }] += n;
|
||||
}
|
||||
std::mutex g_ledger_mu;
|
||||
std::unordered_map<void*, LiveAlloc> g_ledger_live;
|
||||
|
||||
void ledger_add(void* p, int64_t bytes, int kind) {
|
||||
void ledger_add(void* p, int64_t bytes, int kind, int owner, int device) {
|
||||
g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed);
|
||||
if (kind == RAD_MEM_DEVICE) owner_add(owner, device, bytes);
|
||||
std::lock_guard<std::mutex> lk(g_ledger_mu);
|
||||
g_ledger_live[p] = LiveAlloc{ bytes, kind };
|
||||
g_ledger_live[p] = LiveAlloc{ bytes, kind, owner, device };
|
||||
}
|
||||
void ledger_drop(void* p) {
|
||||
if (!p) return;
|
||||
/* The allocation's bytes, or 0 when the ledger does not know it. */
|
||||
int64_t ledger_drop(void* p) {
|
||||
if (!p) return 0;
|
||||
std::lock_guard<std::mutex> lk(g_ledger_mu);
|
||||
const auto it = g_ledger_live.find(p);
|
||||
if (it == g_ledger_live.end()) return;
|
||||
g_ledger[it->second.kind].bytes.fetch_sub(it->second.bytes, std::memory_order_relaxed);
|
||||
if (it == g_ledger_live.end()) return 0;
|
||||
const int64_t bytes = it->second.bytes;
|
||||
g_ledger[it->second.kind].bytes.fetch_sub(bytes, std::memory_order_relaxed);
|
||||
if (it->second.kind == RAD_MEM_DEVICE) owner_add(it->second.owner, it->second.device, -bytes);
|
||||
g_ledger_live.erase(it);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/* rad_dev_on_free's hooks and how many registrations each has. Registered at plugin load and
|
||||
* read on every device free, which holds the lock shared while it calls them. */
|
||||
std::shared_mutex g_free_hooks_mu;
|
||||
std::vector<std::pair<void (*)(const void*, int64_t), int>> g_free_hooks;
|
||||
|
||||
/* Live event handles, counted here so the number is backend-independent; the only place an
|
||||
* event leaked at teardown shows. */
|
||||
std::atomic<int64_t> g_live_events{0};
|
||||
@@ -224,6 +252,24 @@ const char* kind_name(int kind) {
|
||||
|
||||
} /* namespace */
|
||||
|
||||
void rad_dev_on_free(void (*fn)(const void* base, int64_t bytes)) {
|
||||
if (!fn) return;
|
||||
std::unique_lock<std::shared_mutex> lk(g_free_hooks_mu);
|
||||
for (auto& h : g_free_hooks)
|
||||
if (h.first == fn) { ++h.second; return; }
|
||||
g_free_hooks.push_back({ fn, 1 });
|
||||
}
|
||||
|
||||
void rad_dev_off_free(void (*fn)(const void* base, int64_t bytes)) {
|
||||
if (!fn) return;
|
||||
std::unique_lock<std::shared_mutex> lk(g_free_hooks_mu);
|
||||
for (auto it = g_free_hooks.begin(); it != g_free_hooks.end(); ++it)
|
||||
if (it->first == fn) {
|
||||
if (--it->second == 0) g_free_hooks.erase(it);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void rad_dev_alloc_totals(int kind, int64_t* bytes, int64_t* count) {
|
||||
if (kind < 0 || kind >= (int)std::size(g_ledger)) {
|
||||
if (bytes) *bytes = 0;
|
||||
@@ -243,8 +289,19 @@ int64_t rad_dev_host_blocks(void) { return g_host_blocks.load(std::memory_order_
|
||||
|
||||
namespace {
|
||||
std::atomic<int64_t> g_vmem_committed{0};
|
||||
|
||||
/* Elastic ranges (VMem) reserved on a thread working for an engine are filed under it, so its
|
||||
* park (paging.cpp) finds them. */
|
||||
std::mutex g_page_mu;
|
||||
std::map<VMem*, int> g_vmem_owner;
|
||||
} /* namespace */
|
||||
|
||||
static int vmem_owner_of(const VMem* v) {
|
||||
std::lock_guard<std::mutex> lk(g_page_mu);
|
||||
auto it = g_vmem_owner.find(const_cast<VMem*>(v));
|
||||
return it == g_vmem_owner.end() ? 0 : it->second;
|
||||
}
|
||||
|
||||
int64_t rad_dev_vmem_committed(void) { return g_vmem_committed.load(std::memory_order_relaxed); }
|
||||
|
||||
/* Both checks: a backend may have the entries on a driver with no virtual memory manager
|
||||
@@ -274,18 +331,34 @@ int VMem::reserve(int64_t bytes, int64_t align) {
|
||||
size_ = want;
|
||||
committed_ = 0;
|
||||
ext_.clear();
|
||||
device_ = t_device;
|
||||
if (const int owner = engine_owner(); owner > 0) {
|
||||
std::lock_guard<std::mutex> lk(g_page_mu);
|
||||
g_vmem_owner[this] = owner;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void VMem::rekey(VMem* from, VMem* to) {
|
||||
std::lock_guard<std::mutex> lk(g_page_mu);
|
||||
auto it = g_vmem_owner.find(from);
|
||||
if (it == g_vmem_owner.end()) return;
|
||||
const int owner = it->second;
|
||||
g_vmem_owner.erase(it);
|
||||
if (to) g_vmem_owner[to] = owner;
|
||||
}
|
||||
|
||||
void VMem::release() {
|
||||
owner_add(vmem_owner_of(this), device_, -committed_);
|
||||
rekey(this, nullptr);
|
||||
copy_.release();
|
||||
parked_.clear();
|
||||
if (!base_) { size_ = 0; committed_ = 0; ext_.clear(); return; }
|
||||
/* Decommit before release: releasing a range with pages still mapped leaks them, and some
|
||||
* drivers refuse the free. One granule at a time, as each was mapped. */
|
||||
const int64_t g = granularity();
|
||||
* drivers refuse the free. An extent is a run of whole mappings (one a granule), so it goes in
|
||||
* one unmap. */
|
||||
for (const auto& e : ext_) {
|
||||
if (dev()->vmem_decommit && g > 0)
|
||||
for (int64_t o = e.first; o < e.first + e.second; o += g)
|
||||
(void)dev()->vmem_decommit((char*)base_ + o, g);
|
||||
if (dev()->vmem_decommit) (void)dev()->vmem_decommit((char*)base_ + e.first, e.second);
|
||||
g_vmem_committed.fetch_sub(e.second, std::memory_order_relaxed);
|
||||
}
|
||||
if (dev()->vmem_release) dev()->vmem_release(base_, size_);
|
||||
@@ -311,6 +384,23 @@ bool VMem::is_committed(int64_t off, int64_t bytes) const {
|
||||
* - Access cannot be granted per granule: a granule adjacent to an accessible one is refused on
|
||||
* its own. Access is granted once per merged extent the new granules belong to; re-granting
|
||||
* access to a range is free. */
|
||||
namespace {
|
||||
thread_local int t_map_batch = 0;
|
||||
thread_local bool t_map_due = false;
|
||||
}
|
||||
|
||||
MapBatch::MapBatch() { ++t_map_batch; }
|
||||
|
||||
MapBatch::~MapBatch() { (void)end(); }
|
||||
|
||||
int MapBatch::end() {
|
||||
if (ended_) return RAD_OK;
|
||||
ended_ = true;
|
||||
if (--t_map_batch > 0 || !t_map_due) return RAD_OK;
|
||||
t_map_due = false;
|
||||
return dev_settle_maps();
|
||||
}
|
||||
|
||||
int VMem::commit(int64_t off, int64_t bytes) {
|
||||
if (!base_ || bytes <= 0) return bytes <= 0 ? RAD_OK : RAD_E_INVAL;
|
||||
const int64_t g = granularity();
|
||||
@@ -328,13 +418,27 @@ int VMem::commit(int64_t off, int64_t bytes) {
|
||||
if (want.empty()) return RAD_OK;
|
||||
|
||||
/* On a failure part way, what already mapped stays mapped and recorded: a partial grow is
|
||||
* usable, untracked mappings are not. */
|
||||
* usable, untracked mappings are not. A contiguous run goes in one call; one that fails (the
|
||||
* card lacks room for all of it) is backed a granule at a time, so it grows by what fits.
|
||||
* `took`: the granules of `want` backed, a prefix of it. */
|
||||
int rc = RAD_OK;
|
||||
size_t took = 0;
|
||||
for (; took < want.size(); ++took) {
|
||||
rc = dev()->vmem_commit((char*)base_ + want[took], g);
|
||||
if (rc < 0) break;
|
||||
add_extent(want[took], g);
|
||||
while (took < want.size() && rc >= 0) {
|
||||
size_t j = took + 1;
|
||||
while (j < want.size() && want[j] == want[j - 1] + g) ++j;
|
||||
const int64_t run = (int64_t)(j - took) * g;
|
||||
if (j - took > 1 && dev()->vmem_commit_units &&
|
||||
dev()->vmem_commit_units((char*)base_ + want[took], run, g) >= 0) {
|
||||
add_extent(want[took], run);
|
||||
took = j;
|
||||
continue;
|
||||
}
|
||||
for (; took < j; ++took) {
|
||||
rc = dev()->vmem_commit((char*)base_ + want[took], g);
|
||||
if (rc < 0) break;
|
||||
rc = RAD_OK; /* recycled memory (1) is fine here: a pool's contents are written before they are read */
|
||||
add_extent(want[took], g);
|
||||
}
|
||||
}
|
||||
|
||||
/* Grant access even if the grow stopped short, so the granules that did map are usable. */
|
||||
@@ -355,6 +459,10 @@ int VMem::commit(int64_t off, int64_t bytes) {
|
||||
}
|
||||
return prc;
|
||||
}
|
||||
if (took > 0) {
|
||||
if (t_map_batch > 0) t_map_due = true;
|
||||
else if (const int src = dev_settle_maps(); src < 0) return src;
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
@@ -368,20 +476,30 @@ int VMem::decommit(int64_t off, int64_t bytes) {
|
||||
if (hi > size_) hi = size_;
|
||||
if (lo >= hi) return RAD_OK;
|
||||
|
||||
/* Gathered first and unmapped per granule, as in commit. */
|
||||
/* Gathered first; each contiguous run of granules (a mapping each) goes in one unmap. */
|
||||
std::vector<int64_t> drop;
|
||||
for (int64_t o = lo; o < hi; o += g)
|
||||
if (is_committed(o, g)) drop.push_back(o);
|
||||
|
||||
for (const int64_t o : drop) {
|
||||
const int rc = dev()->vmem_decommit((char*)base_ + o, g);
|
||||
if (rc < 0) return rc;
|
||||
drop_extent(o, g);
|
||||
for (size_t i = 0; i < drop.size();) {
|
||||
size_t j = i + 1;
|
||||
while (j < drop.size() && drop[j] == drop[j - 1] + g) ++j;
|
||||
const int64_t run = (int64_t)(j - i) * g;
|
||||
if (const int rc = dev()->vmem_decommit((char*)base_ + drop[i], run); rc < 0) return rc;
|
||||
drop_extent(drop[i], run);
|
||||
i = j;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int64_t dev_owner_bytes(int owner, int device) {
|
||||
std::lock_guard<std::mutex> lk(g_owner_mu);
|
||||
auto it = g_owner_bytes.find({ owner, device });
|
||||
return it == g_owner_bytes.end() ? 0 : it->second;
|
||||
}
|
||||
|
||||
void VMem::add_extent(int64_t off, int64_t bytes) {
|
||||
owner_add(vmem_owner_of(this), device_, bytes);
|
||||
committed_ += bytes;
|
||||
g_vmem_committed.fetch_add(bytes, std::memory_order_relaxed);
|
||||
/* Insert in order, then merge touching neighbours, so is_committed() stays a short scan
|
||||
@@ -401,9 +519,215 @@ void VMem::add_extent(int64_t off, int64_t bytes) {
|
||||
}
|
||||
}
|
||||
|
||||
int64_t VMem::page_out(RadStream s, bool discard) {
|
||||
if (!base_ || ext_.empty() || !parked_.empty()) return 0;
|
||||
int64_t total = 0;
|
||||
for (const auto& e : ext_) total += e.second;
|
||||
if (discard) {
|
||||
/* Nothing in the range is kept: back it again on page_in with whatever the pages hold. */
|
||||
parked_ = ext_;
|
||||
discarded_ = true;
|
||||
for (const auto& e : parked_)
|
||||
if (const int rc = decommit(e.first, e.second); rc < 0) return rc;
|
||||
return 0;
|
||||
}
|
||||
discarded_ = false;
|
||||
if (const int rc = copy_.alloc(total); rc < 0) return rc;
|
||||
int64_t at = 0;
|
||||
for (const auto& e : ext_) {
|
||||
if (const int rc = rad_memcpy_async((char*)copy_.host + at, (char*)base_ + e.first, e.second, s); rc < 0)
|
||||
return rc;
|
||||
at += e.second;
|
||||
}
|
||||
if (const int rc = rad_stream_sync(s); rc < 0) return rc;
|
||||
parked_ = ext_;
|
||||
for (const auto& e : parked_)
|
||||
if (const int rc = decommit(e.first, e.second); rc < 0) return rc;
|
||||
return total;
|
||||
}
|
||||
|
||||
int dev_current() { return t_device; }
|
||||
|
||||
int64_t dev_vmem_trim(int device) {
|
||||
return dev()->vmem_trim ? dev()->vmem_trim(device) : 0;
|
||||
}
|
||||
|
||||
void dev_stream_counts(int device, int* open, int* idle) {
|
||||
if (open) *open = 0;
|
||||
if (idle) *idle = 0;
|
||||
if (dev()->stream_counts) dev()->stream_counts(device, open, idle);
|
||||
}
|
||||
|
||||
int dev_stream_trim(int device, int keep) {
|
||||
return dev()->stream_trim ? dev()->stream_trim(device, keep) : 0;
|
||||
}
|
||||
|
||||
std::string dev_page_where(uintptr_t a);
|
||||
|
||||
std::string dev_fault_where(const void* p) {
|
||||
const uintptr_t a = (uintptr_t)p;
|
||||
std::string s = dev_page_where(a);
|
||||
std::unique_lock<std::mutex> lk(g_page_mu, std::try_to_lock);
|
||||
if (!lk.owns_lock()) return s;
|
||||
for (const auto& [v, owner] : g_vmem_owner) {
|
||||
const uintptr_t b = (uintptr_t)v->base();
|
||||
if (!b || a < b || a >= b + (uintptr_t)v->size()) continue;
|
||||
const int64_t off = (int64_t)(a - b), g = std::max<int64_t>(VMem::granularity(), 1);
|
||||
return (s.empty() ? s : s + "; ") + fmt("elastic reservation of owner %d card %d, %s long, %s backed, +%s %s", owner, v->device(),
|
||||
humanb(v->size()).c_str(), humanb(v->committed()).c_str(), humanb(off).c_str(),
|
||||
v->is_committed(off / g * g, g) ? "is backed" : "is NOT backed");
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
int dev_settle_maps() {
|
||||
if (device_is_host()) return RAD_OK;
|
||||
void* x = dev()->alloc(4096, RAD_MEM_HOST_PINNED);
|
||||
if (!x) {
|
||||
device_set_error("vmem: no page of pinned host memory to flush the cards' translations with");
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
dev()->free(x, RAD_MEM_HOST_PINNED);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int VMem::page_in(RadStream s) {
|
||||
if (parked_.empty()) return RAD_OK;
|
||||
MapBatch maps;
|
||||
if (discarded_) {
|
||||
for (const auto& e : parked_)
|
||||
if (const int rc = commit(e.first, e.second); rc < 0) return rc;
|
||||
if (const int rc = maps.end(); rc < 0) return rc;
|
||||
parked_.clear();
|
||||
discarded_ = false;
|
||||
return RAD_OK;
|
||||
}
|
||||
if (const int rc = copy_.load(); rc < 0) return rc;
|
||||
for (const auto& e : parked_)
|
||||
if (const int rc = commit(e.first, e.second); rc < 0) return rc;
|
||||
if (const int rc = maps.end(); rc < 0) return rc;
|
||||
int64_t at = 0;
|
||||
for (const auto& e : parked_) {
|
||||
if (const int rc = rad_memcpy_async((char*)base_ + e.first, (char*)copy_.host + at, e.second, s); rc < 0)
|
||||
return rc;
|
||||
at += e.second;
|
||||
}
|
||||
if (const int rc = rad_stream_sync(s); rc < 0) return rc;
|
||||
parked_.clear();
|
||||
copy_.release();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- HostCopy */
|
||||
|
||||
namespace {
|
||||
std::atomic<uint64_t> g_copy_seq{0};
|
||||
/* The unit of a copy's file I/O: what one write asks the gate about, what one reader takes. */
|
||||
constexpr int64_t kCopyPiece = (int64_t)64 << 20;
|
||||
}
|
||||
|
||||
int HostCopy::alloc(int64_t n) {
|
||||
release();
|
||||
bytes = n;
|
||||
host = rad_dev_alloc(align_up(n, DirectFile::alignment()), RAD_MEM_HOST_PINNED);
|
||||
if (!host) {
|
||||
device_set_error("parking: no pinned host memory for %s", humanb(n).c_str());
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int HostCopy::spill(const std::string& dir, const std::function<int()>& gate) {
|
||||
if (on_disk || !host || bytes <= 0) return RAD_OK;
|
||||
/* Not the page files' name: their counter is another one (paging.cpp). */
|
||||
const std::string path = dir + "/radiance-vmem-" + std::to_string((long long)getpid()) + "-" +
|
||||
std::to_string((unsigned long long)g_copy_seq.fetch_add(1)) + ".bin";
|
||||
DirectFile f;
|
||||
if (const int rc = f.open(path.c_str(), RAD_DIO_WRITE | RAD_DIO_CREATE | RAD_DIO_TRUNC); rc < 0)
|
||||
return rc;
|
||||
const int64_t n = align_up(bytes, DirectFile::alignment());
|
||||
int rc = RAD_OK;
|
||||
for (int64_t at = 0; at < n; at += kCopyPiece) {
|
||||
int g = gate ? gate() : 0;
|
||||
while (g == 1) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
||||
g = gate();
|
||||
}
|
||||
if (g < 0) { rc = RAD_E_STATE; break; }
|
||||
if ((rc = f.write_at((const char*)host + at, at, std::min(kCopyPiece, n - at))) < 0) break;
|
||||
}
|
||||
f.close();
|
||||
if (rc < 0) {
|
||||
::unlink(path.c_str());
|
||||
return rc;
|
||||
}
|
||||
file = path;
|
||||
on_disk = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void HostCopy::drop_host() {
|
||||
if (!on_disk || !host) return;
|
||||
rad_dev_free(host, RAD_MEM_HOST_PINNED);
|
||||
host = nullptr;
|
||||
}
|
||||
|
||||
int HostCopy::load() {
|
||||
if (host) return RAD_OK;
|
||||
if (!on_disk) {
|
||||
device_set_error("parking: a copy has neither host memory nor a file");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const int64_t n = align_up(bytes, DirectFile::alignment());
|
||||
host = rad_dev_alloc(n, RAD_MEM_HOST_PINNED);
|
||||
if (!host) {
|
||||
device_set_error("parking: no pinned host memory to read %s back", humanb(bytes).c_str());
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
/* A read that fails leaves no host memory behind, so the next load() reads again instead of
|
||||
* taking a partial copy as the copy. */
|
||||
auto fail = [&](int rc) {
|
||||
rad_dev_free(host, RAD_MEM_HOST_PINNED);
|
||||
host = nullptr;
|
||||
return rc;
|
||||
};
|
||||
DirectFile f;
|
||||
if (const int rc = f.open(file.c_str(), RAD_DIO_READ); rc < 0) return fail(rc);
|
||||
/* Four readers over the file: one stream of O_DIRECT reads leaves an NVMe drive half idle. */
|
||||
std::atomic<int64_t> next{0};
|
||||
std::atomic<int> err{RAD_OK};
|
||||
auto reader = [&] {
|
||||
DirectFile g;
|
||||
if (g.open(file.c_str(), RAD_DIO_READ) < 0) { err.store(RAD_E_IO); return; }
|
||||
for (;;) {
|
||||
const int64_t at = next.fetch_add(kCopyPiece);
|
||||
if (at >= n || err.load() < 0) return;
|
||||
if (g.read_at((char*)host + at, at, std::min(kCopyPiece, n - at)) < 0) { err.store(RAD_E_IO); return; }
|
||||
}
|
||||
};
|
||||
std::vector<std::thread> th;
|
||||
for (int i = 0; i < 4; ++i) th.emplace_back(reader);
|
||||
for (auto& t : th) t.join();
|
||||
if (err.load() < 0) {
|
||||
device_set_error("parking: reading %s back failed", file.c_str());
|
||||
return fail(err.load());
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void HostCopy::release() {
|
||||
if (host) rad_dev_free(host, RAD_MEM_HOST_PINNED);
|
||||
host = nullptr;
|
||||
if (!file.empty()) ::unlink(file.c_str());
|
||||
file.clear();
|
||||
on_disk = false;
|
||||
bytes = 0;
|
||||
}
|
||||
|
||||
/* Precondition: the piece lies wholly inside one extent (decommit only drops committed granules).
|
||||
* What remains of that extent is nothing, a head, a tail, or both. */
|
||||
void VMem::drop_extent(int64_t off, int64_t bytes) {
|
||||
owner_add(vmem_owner_of(this), device_, -bytes);
|
||||
committed_ -= bytes;
|
||||
g_vmem_committed.fetch_sub(bytes, std::memory_order_relaxed);
|
||||
for (size_t i = 0; i < ext_.size(); ++i) {
|
||||
@@ -416,6 +740,16 @@ void VMem::drop_extent(int64_t off, int64_t bytes) {
|
||||
}
|
||||
}
|
||||
|
||||
const DeviceBackend* active_backend() { return dev(); }
|
||||
|
||||
std::vector<VMem*> vmems_of(int owner) {
|
||||
std::vector<VMem*> v;
|
||||
std::lock_guard<std::mutex> lk(g_page_mu);
|
||||
for (auto& [m, o] : g_vmem_owner)
|
||||
if (o == owner) v.push_back(m);
|
||||
return v;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
|
||||
/* ------------------------------------------------------------------ the ABI surface */
|
||||
@@ -425,8 +759,7 @@ using rad::dev;
|
||||
extern "C" {
|
||||
|
||||
int rad_dev_count(void) { return dev()->count(); }
|
||||
/* The device this thread last selected, for the poison fill's stream (rad_dev_alloc). */
|
||||
static thread_local int t_device = 0;
|
||||
/* This thread's stream for the poison fill (rad_dev_alloc), one per device. */
|
||||
static thread_local std::map<int, RadStream> t_poison_stream;
|
||||
int rad_dev_set(int device) {
|
||||
const int st = dev()->set(device);
|
||||
@@ -440,9 +773,16 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
|
||||
/* Poison ordinals are per thread: each rank allocates in a fixed order on its own thread, but
|
||||
* threads interleave, so a process-wide ordinal would not be repeatable. */
|
||||
thread_local int64_t t_device_ordinal = 0;
|
||||
void* p = dev()->alloc(bytes, kind);
|
||||
void* p = nullptr;
|
||||
const int owner = rad::engine_owner();
|
||||
/* A large device allocation for an engine is mapped in chunks it can be parked by
|
||||
* (paging.cpp). Where the backend has no virtual memory manager it is an ordinary allocation,
|
||||
* and the model parks only by unloading. */
|
||||
if (kind == RAD_MEM_DEVICE && bytes >= rad::kPageMin && owner > 0 && rad::VMem::supported())
|
||||
p = rad::page_alloc(bytes, owner, t_device);
|
||||
if (!p) p = dev()->alloc(bytes, kind);
|
||||
if (p && kind >= 0 && kind < (int)std::size(rad::g_ledger)) {
|
||||
rad::ledger_add(p, bytes, kind);
|
||||
rad::ledger_add(p, bytes, kind, owner, t_device);
|
||||
const int64_t total = rad::g_ledger[kind].count.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
const int64_t ordinal = kind == RAD_MEM_DEVICE ? ++t_device_ordinal : total;
|
||||
const int64_t floor_ = rad::trace_floor();
|
||||
@@ -468,8 +808,13 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
|
||||
return p;
|
||||
}
|
||||
void rad_dev_free(void* p, int kind) {
|
||||
rad::ledger_drop(p);
|
||||
dev()->free(p, kind);
|
||||
const int64_t bytes = rad::ledger_drop(p);
|
||||
if (!(p && kind == RAD_MEM_DEVICE && rad::page_free(p))) dev()->free(p, kind);
|
||||
/* Kernel libraries drop state they keep for addresses in the freed range (rad_plugin_freed). */
|
||||
if (p && bytes > 0 && kind == RAD_MEM_DEVICE) {
|
||||
std::shared_lock<std::shared_mutex> lk(rad::g_free_hooks_mu);
|
||||
for (const auto& h : rad::g_free_hooks) h.first(p, bytes);
|
||||
}
|
||||
}
|
||||
void* rad_dev_host_ptr(void* p) { return dev()->host_ptr(p); }
|
||||
void* rad_dev_device_ptr(void* p) { return dev()->device_ptr(p); }
|
||||
@@ -587,23 +932,38 @@ int rad_event_sync(RadEvent e) {
|
||||
}
|
||||
void rad_dev_host_wrote(void) { dev()->host_wrote(); }
|
||||
|
||||
/* Whether launches chain, 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};
|
||||
/* Whether launches chain, by engine: rad_dev_chain_infer on a thread of an engine (EngineScope)
|
||||
* records that engine's answer and rad_dev_chain_enabled on any of its threads reads it. A process
|
||||
* serves several models, each with its own plugin's answer; a single answer for the process was
|
||||
* the answer of whichever model started last. Owner 0 is a thread outside every engine (a tool, a
|
||||
* test). 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::mutex g_chain_mu;
|
||||
static std::map<int, int> g_chain_pays; /* by owner */
|
||||
static std::atomic<uint64_t> g_chain_gen{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);
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_chain_mu);
|
||||
g_chain_pays[rad::engine_owner()] = pays ? 1 : 0;
|
||||
}
|
||||
g_chain_gen.fetch_add(1, std::memory_order_release);
|
||||
}
|
||||
int rad_dev_chain_enabled(void) {
|
||||
int on = g_chain.load(std::memory_order_relaxed);
|
||||
if (on < 0) {
|
||||
on = g_chain_pays.load(std::memory_order_relaxed) != 0 &&
|
||||
std::strcmp(rad::device_backend_name(), "aql") == 0
|
||||
? 1
|
||||
: 0;
|
||||
g_chain.store(on, std::memory_order_relaxed);
|
||||
/* Asked on every launch: a thread keeps its engine's answer until some answer changes. */
|
||||
thread_local uint64_t seen = 0;
|
||||
thread_local int owner = -1, on = 0;
|
||||
const uint64_t gen = g_chain_gen.load(std::memory_order_acquire);
|
||||
const int o = rad::engine_owner();
|
||||
if (seen != gen || owner != o) {
|
||||
int pays = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_chain_mu);
|
||||
const auto it = g_chain_pays.find(o);
|
||||
if (it != g_chain_pays.end()) pays = it->second;
|
||||
}
|
||||
on = pays && std::strcmp(rad::device_backend_name(), "aql") == 0 ? 1 : 0;
|
||||
seen = gen;
|
||||
owner = o;
|
||||
}
|
||||
return on;
|
||||
}
|
||||
@@ -643,6 +1003,14 @@ void* rad_link_gate(RadStream s) {
|
||||
if (const auto f = dev()->link_gate) return f(s);
|
||||
return nullptr;
|
||||
}
|
||||
void rad_dev_peer_launch(int on) {
|
||||
if (const auto f = dev()->peer_launch) f(on);
|
||||
}
|
||||
int rad_dev_cards_claim(const int* cards, int n, int on) {
|
||||
if (!cards || n <= 0) return RAD_E_INVAL;
|
||||
if (const auto f = dev()->cards_claim) return f(cards, n, on);
|
||||
return RAD_OK;
|
||||
}
|
||||
int rad_xp_supported(int device) {
|
||||
const auto* d = dev();
|
||||
return d->xp_supported && d->xp_stream_create && d->ride && d->ride_wait && d->ride_release && d->xp_list &&
|
||||
@@ -685,7 +1053,7 @@ void* rad_dev_map_file(int fd, int64_t foff, int64_t bytes) {
|
||||
}
|
||||
void* p = f(fd, foff, bytes);
|
||||
if (p) {
|
||||
rad::ledger_add(p, bytes, RAD_MEM_HOST_MAPPED);
|
||||
rad::ledger_add(p, bytes, RAD_MEM_HOST_MAPPED, 0, t_device);
|
||||
rad::g_ledger[RAD_MEM_HOST_MAPPED].count.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
return p;
|
||||
|
||||
+101
-11
@@ -22,6 +22,7 @@
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
@@ -100,6 +101,8 @@ struct HostStream {
|
||||
|
||||
uint64_t submitted = 0; /* tasks ever pushed */
|
||||
uint64_t retired = 0; /* tasks ever finished executing */
|
||||
int sync_waiters = 0; /* h_stream_sync calls inside cv_done.wait */
|
||||
int room_waiters = 0; /* stream_push calls inside cv_room.wait */
|
||||
int gates = 0; /* closed gates (rad_stream_gate) queued on this stream */
|
||||
|
||||
std::thread worker;
|
||||
@@ -117,27 +120,48 @@ int stream_push(HostStream* s, const Task& t) {
|
||||
"(rad_gate_open) first");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
++s->room_waiters;
|
||||
s->cv_room.wait(lk, [s] { return s->count < s->ring.size(); });
|
||||
--s->room_waiters;
|
||||
/* The worker can only be asleep on cv_work when the ring was empty, so only that push pays
|
||||
* the futex wake; its wait re-tests the predicate under the lock, so a wake it did not need
|
||||
* (it was already running) is the only kind this can lose. */
|
||||
const bool was_empty = s->count == 0;
|
||||
s->ring[s->tail] = t;
|
||||
s->tail = (s->tail + 1) % s->ring.size();
|
||||
++s->count;
|
||||
++s->submitted;
|
||||
lk.unlock();
|
||||
s->cv_work.notify_one();
|
||||
if (was_empty) s->cv_work.notify_one();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Pop the head task, with the stream lock held. Notifies are the caller's, after the unlock:
|
||||
* cv_room is only worth a wake while a producer is asleep on it (room_waiters). Every pop
|
||||
* wakes one while any is: a pop that only wakes on leaving a full ring loses the second of two
|
||||
* producers behind it, when the next pop comes before the first one has pushed. */
|
||||
static Task stream_pop_locked(HostStream* s, bool* wake_room) {
|
||||
*wake_room = s->room_waiters > 0;
|
||||
Task t = s->ring[s->head];
|
||||
s->head = (s->head + 1) % s->ring.size();
|
||||
--s->count;
|
||||
return t;
|
||||
}
|
||||
|
||||
void stream_run(HostStream* s) {
|
||||
Task t;
|
||||
bool have = false; /* t holds a task popped under the previous task's retire lock */
|
||||
for (;;) {
|
||||
Task t;
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(s->m);
|
||||
s->cv_work.wait(lk, [s] { return s->count > 0; });
|
||||
t = s->ring[s->head];
|
||||
s->head = (s->head + 1) % s->ring.size();
|
||||
--s->count;
|
||||
if (!have) {
|
||||
bool wake_room = false;
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(s->m);
|
||||
s->cv_work.wait(lk, [s] { return s->count > 0; });
|
||||
t = stream_pop_locked(s, &wake_room);
|
||||
}
|
||||
if (wake_room) s->cv_room.notify_one();
|
||||
}
|
||||
s->cv_room.notify_one();
|
||||
have = false;
|
||||
|
||||
bool done = false;
|
||||
switch (t.kind) {
|
||||
@@ -191,11 +215,22 @@ void stream_run(HostStream* s) {
|
||||
/* After the event lock is released: this may be the last reference. */
|
||||
if (t.ev) event_release(t.ev);
|
||||
|
||||
/* Retire this task and take the next under the same lock, so a busy stream pays one lock
|
||||
* a task instead of two. cv_done is only worth a futex wake when a sync is actually
|
||||
* asleep on it (sync_waiters, under this lock; the wait's predicate is re-tested under
|
||||
* the lock too, so no retire can be missed). */
|
||||
bool notify_done = false, wake_room = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(s->m);
|
||||
++s->retired;
|
||||
notify_done = s->sync_waiters > 0;
|
||||
if (!done && s->count > 0) {
|
||||
t = stream_pop_locked(s, &wake_room);
|
||||
have = true;
|
||||
}
|
||||
}
|
||||
s->cv_done.notify_all();
|
||||
if (notify_done) s->cv_done.notify_all();
|
||||
if (wake_room) s->cv_room.notify_one();
|
||||
if (done) return;
|
||||
}
|
||||
}
|
||||
@@ -446,7 +481,9 @@ int h_stream_sync(RadStream st) {
|
||||
/* Waits only for work submitted before this call, as hipStreamSynchronize does; the
|
||||
* scheduler relies on sync returning while another thread keeps pushing. */
|
||||
const uint64_t target = s->submitted;
|
||||
++s->sync_waiters;
|
||||
s->cv_done.wait(lk, [s, target] { return s->retired >= target; });
|
||||
--s->sync_waiters;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -784,8 +821,24 @@ int h_vmem_commit(void* addr, int64_t bytes) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Pages are what an mmap backs, so a run is one commit and any part of it decommits alone. */
|
||||
int h_vmem_commit_units(void* addr, int64_t bytes, int64_t unit) {
|
||||
if (unit <= 0 || bytes % unit) return RAD_E_INVAL;
|
||||
return h_vmem_commit(addr, bytes);
|
||||
}
|
||||
|
||||
/* Ranges backed as host memory (h_vmem_commit_host): not counted as the device's. */
|
||||
std::mutex g_hostkind_mu;
|
||||
std::set<const char*> g_hostkind;
|
||||
|
||||
bool take_hostkind(const void* addr) {
|
||||
std::lock_guard<std::mutex> lk(g_hostkind_mu);
|
||||
return g_hostkind.erase((const char*)addr) > 0;
|
||||
}
|
||||
|
||||
int h_vmem_decommit(void* addr, int64_t bytes) {
|
||||
if (!addr || bytes <= 0) return RAD_E_INVAL;
|
||||
const bool host = take_hostkind(addr);
|
||||
/* MAP_FIXED rather than munmap: a hole in the reservation could be handed to an unrelated
|
||||
* mmap. */
|
||||
void* p = ::mmap(addr, (size_t)bytes, PROT_NONE,
|
||||
@@ -794,7 +847,40 @@ int h_vmem_decommit(void* addr, int64_t bytes) {
|
||||
device_set_error("vmem_decommit(%p, %lld): mmap failed", addr, (long long)bytes);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g_used[vmem_device_of(addr)].fetch_sub(bytes, std::memory_order_relaxed);
|
||||
if (!host) g_used[vmem_device_of(addr)].fetch_sub(bytes, std::memory_order_relaxed);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Host memory is all there is here: the same pages as a commit, not charged to the device. */
|
||||
int h_vmem_commit_host(void* addr, int64_t bytes) {
|
||||
if (!addr || bytes <= 0) return RAD_E_INVAL;
|
||||
void* p = ::mmap(addr, (size_t)bytes, PROT_READ | PROT_WRITE,
|
||||
MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
if (p != addr) {
|
||||
device_set_error("vmem_commit_host(%p, %lld): mmap failed", addr, (long long)bytes);
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
std::lock_guard<std::mutex> lk(g_hostkind_mu);
|
||||
g_hostkind.insert((const char*)addr);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The pages move with mremap, through a spare range, so each keeps its bytes and its kind. */
|
||||
int h_vmem_swap(void* a, void* b, int64_t bytes) {
|
||||
if (!a || !b || bytes <= 0) return RAD_E_INVAL;
|
||||
const size_t n = (size_t)bytes;
|
||||
void* t = ::mmap(nullptr, n, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
|
||||
if (t == MAP_FAILED) return RAD_E_NOMEM;
|
||||
if (::mremap(a, n, n, MREMAP_MAYMOVE | MREMAP_FIXED, t) != t ||
|
||||
::mremap(b, n, n, MREMAP_MAYMOVE | MREMAP_FIXED, a) != a ||
|
||||
::mremap(t, n, n, MREMAP_MAYMOVE | MREMAP_FIXED, b) != b) {
|
||||
device_set_error("vmem_swap(%p, %p, %lld): mremap failed", a, b, (long long)bytes);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
std::lock_guard<std::mutex> lk(g_hostkind_mu);
|
||||
const bool ha = g_hostkind.erase((const char*)a) > 0, hb = g_hostkind.erase((const char*)b) > 0;
|
||||
if (hb) g_hostkind.insert((const char*)a);
|
||||
if (ha) g_hostkind.insert((const char*)b);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -842,6 +928,10 @@ const DeviceBackend g_host = {
|
||||
|
||||
h_stream_gate, h_gate_open, h_gate_room,
|
||||
nullptr, /* event_dma: no DMA queue */
|
||||
nullptr, /* map_file */
|
||||
nullptr, /* stuck_ms */
|
||||
h_vmem_commit_host, h_vmem_swap,
|
||||
h_vmem_commit_units,
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -385,7 +385,7 @@ void check_engine(const Facts& f, const RunFacts& r, std::vector<Finding>* out)
|
||||
"a prefill step streams every routed layer's pooled experts onto the card, so its speed "
|
||||
"is bounded by the link; decode reads the ones it routes to",
|
||||
"more VRAM for the experts: a shorter --max-model-len or fewer --max-num-seqs, "
|
||||
"--embedding-placement ram, --kv-cache-dtype fp8, or more cards (--tp)");
|
||||
"--embedding-placement ram, --kv-cache-dtype i8, or more cards (--tp)");
|
||||
if (r.file_weight_bytes > 0)
|
||||
add(out, Finding::Warn, "weights-from-disk",
|
||||
fmt("%s of weights a rank are read from the container on disk as they are needed",
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
#include "diag/diag.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
@@ -202,7 +202,7 @@ std::string render(const std::vector<ConfigRow>& config, const std::vector<Decis
|
||||
|
||||
std::string to_json(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
|
||||
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings) {
|
||||
using J = nlohmann::ordered_json;
|
||||
using J = Json;
|
||||
J o;
|
||||
o["startup_failed"] = r.failed;
|
||||
o["unsupported_configuration"] = r.unsupported;
|
||||
|
||||
+619
-73
@@ -20,6 +20,7 @@
|
||||
#include "sample/accept.h"
|
||||
#include "sched/scheduler.h"
|
||||
#include "server/adapters.h"
|
||||
#include "server/front.h"
|
||||
#include "server/server.h"
|
||||
#include "server/sink.h"
|
||||
#include "server/liveview.h"
|
||||
@@ -28,7 +29,6 @@
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <csignal>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cstdint>
|
||||
@@ -256,9 +256,493 @@ void kv_test_rollback(uint64_t seq, int proposals, int accepted, int64_t valid,
|
||||
} // namespace
|
||||
#endif
|
||||
|
||||
/* Owner ids for the device layer (engine_owner), one per engine; 0 is no engine. */
|
||||
namespace {
|
||||
std::atomic<int> g_next_owner{1};
|
||||
}
|
||||
|
||||
/* The operator's RADIANCE_* names, captured at construction for the diagnostics report. */
|
||||
Engine::Engine(Config cfg)
|
||||
: cfg_(std::move(cfg)), env_set_(diag::env_names(environ, "RADIANCE_")) {}
|
||||
: cfg_(std::move(cfg)), owner_(g_next_owner.fetch_add(1)),
|
||||
env_set_(diag::env_names(environ, "RADIANCE_")) {}
|
||||
|
||||
/* Every rank's compute stream, the mover's transfer stream and the KV tiers' copy stream,
|
||||
* synchronised. A tier copy reads the KV pool long after the step that issued it, and nothing on
|
||||
* the compute stream waits for it, so memory leaving the card must wait for it here: a gather over
|
||||
* a range just unbacked is a GPU memory fault. The compute stream goes first because the copy is
|
||||
* ordered after it. */
|
||||
void Engine::drain_streams() {
|
||||
const int dev = dev_current();
|
||||
for (auto& rk : ranks_) {
|
||||
(void)rad_stream_sync(rk->ctx.stream());
|
||||
if (RadStream t = rk->mover.transfer_stream()) (void)rad_stream_sync(t);
|
||||
rk->tierx.quiesce();
|
||||
}
|
||||
(void)rad_dev_set(dev);
|
||||
}
|
||||
|
||||
std::vector<int> Engine::rank_devices() const {
|
||||
std::vector<int> cards;
|
||||
cards.reserve(ranks_.size());
|
||||
for (auto& r : ranks_) cards.push_back(r->device);
|
||||
return cards;
|
||||
}
|
||||
|
||||
/* The step loop's rest point for a park: idle, nothing issued that still runs. The streams are
|
||||
* drained before the loop answers, so the fleet may page the memory out at once. */
|
||||
void Engine::hold_point(StallWatch* watch) {
|
||||
if (!hold_req_.load(std::memory_order_acquire)) return;
|
||||
drain_streams();
|
||||
hold_ack_.store(true, std::memory_order_release);
|
||||
/* A park lasts as long as the fleet keeps the model off its cards. The loop sleeps until the
|
||||
* hold clears or the engine stops, waking once a second besides to mark the step watch, so a
|
||||
* model parked for minutes is not reported as a step that stopped (and is not woken a thousand
|
||||
* times a second to look). */
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(hold_mu_);
|
||||
while (hold_req_.load(std::memory_order_acquire) && !stopping_.load(std::memory_order_acquire)) {
|
||||
hold_cv_.wait_for(lk, std::chrono::seconds(1));
|
||||
if (watch) watch->progress();
|
||||
}
|
||||
}
|
||||
hold_ack_.store(false, std::memory_order_release);
|
||||
}
|
||||
|
||||
void Engine::hold_release() {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(hold_mu_);
|
||||
hold_req_.store(false, std::memory_order_release);
|
||||
}
|
||||
hold_cv_.notify_all();
|
||||
}
|
||||
|
||||
void Engine::wake_hold() {
|
||||
{ std::lock_guard<std::mutex> lk(hold_mu_); }
|
||||
hold_cv_.notify_all();
|
||||
}
|
||||
|
||||
int Engine::park(int64_t drain_ms, const PageOut& req, PageResult* got, std::string* why) {
|
||||
using clk = std::chrono::steady_clock;
|
||||
const auto secs = [](clk::time_point a, clk::time_point b) {
|
||||
return std::chrono::duration<double>(b - a).count();
|
||||
};
|
||||
const auto t0 = clk::now();
|
||||
auto page_out = [&] {
|
||||
PageOut r = req;
|
||||
r.discard_elastic = true;
|
||||
return dev_page_out(owner_, r, got);
|
||||
};
|
||||
/* Already parked: more of it leaves. */
|
||||
if (parked_.load()) {
|
||||
EngineScope es(owner_, cfg_.served_model_name.c_str());
|
||||
const int rc = page_out();
|
||||
got->out_s = secs(t0, clk::now());
|
||||
if (rc < 0) {
|
||||
*why = std::string("paging out failed: ") + rad_dev_last_error();
|
||||
return rc;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
if (!VMem::supported()) {
|
||||
*why = "the card has no virtual memory manager, so nothing can leave it at the same address";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (!front_ || !srv_) {
|
||||
*why = "the engine is not serving behind a front";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const std::string& name = cfg_.served_model_name;
|
||||
if (!front_->detach(name, (int)std::min<int64_t>(drain_ms, INT32_MAX))) {
|
||||
RAD_WARN("model %s: responses still open after %lld ms; ending them to park",
|
||||
name.c_str(), (long long)drain_ms);
|
||||
srv_->end_streams(true);
|
||||
const bool gone = front_->detach(name, 60000);
|
||||
srv_->end_streams(false);
|
||||
if (!gone) {
|
||||
*why = "responses still held a minute after they were ended";
|
||||
front_->attach(name, front_aliases_, srv_);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
}
|
||||
hold_req_.store(true, std::memory_order_release);
|
||||
sched_.wake();
|
||||
for (int i = 0; i < 60000 && !hold_ack_.load(std::memory_order_acquire); ++i) {
|
||||
if (loop_status_.load(std::memory_order_acquire) < 0) break;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
if (!hold_ack_.load(std::memory_order_acquire)) {
|
||||
hold_release();
|
||||
front_->attach(name, front_aliases_, srv_);
|
||||
*why = "the step loop did not come to rest";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const auto t1 = clk::now();
|
||||
EngineScope es(owner_, name.c_str());
|
||||
/* What need not be copied: the expert slab once its units are back at their host copies
|
||||
* (the heat engine fills it again after the restore), the KV cache once its index is reset
|
||||
* (nothing runs, so no block is live), and the activation arena above its fixed region:
|
||||
* transients live within one step, and the loop rests between steps. A unit still in a slot
|
||||
* the arena lent keeps the arena copied. */
|
||||
std::vector<std::pair<const void*, int64_t>> spare;
|
||||
for (auto& r : ranks_) {
|
||||
if (rad_dev_set(r->device) < 0) continue;
|
||||
if (r->mover.flex_capacity() > 0) {
|
||||
(void)r->mover.reclaim(Mover::kLendKV, 0, &r->heat);
|
||||
(void)r->mover.reclaim(Mover::kLendArena, 0, &r->heat);
|
||||
(void)r->mover.reclaim(Mover::kLendFleet, 0, &r->heat);
|
||||
}
|
||||
/* The fleet's loan is unbacked, not copied: nothing in it outlives the recall. */
|
||||
if (r->xflex.committed() > 0 && r->mover.loan_held(Mover::kLendFleet) == 0)
|
||||
(void)r->xflex.decommit(0, r->xflex.size());
|
||||
if (r->heat.enabled() && r->mover.drop_slab(&r->heat, &spare) < 0)
|
||||
RAD_WARN("rank %d: the expert slab could not be emptied for the park; it is copied", r->index);
|
||||
const int64_t fixed = r->program.arena_fixed_bytes, top = r->ctx.arena_bytes();
|
||||
if (r->ctx.arena_base() && top > fixed && r->mover.loan_held(Mover::kLendArena) == 0)
|
||||
spare.push_back({ (const char*)r->ctx.arena_base() + fixed, top - fixed });
|
||||
}
|
||||
if (!spare.empty()) dev_page_discard(owner_, spare);
|
||||
(void)xflex_settle();
|
||||
if (cfg_.prefix_cache) (void)sched_.reset_prefix_cache();
|
||||
const auto t2 = clk::now();
|
||||
const int rc = page_out();
|
||||
got->quiet_s = secs(t0, t1);
|
||||
got->slab_s = secs(t1, t2);
|
||||
got->out_s = secs(t2, clk::now());
|
||||
if (rc < 0) {
|
||||
/* Whatever left comes back, and the model serves as before. */
|
||||
*why = std::string("paging out failed: ") + rad_dev_last_error();
|
||||
(void)page_back_in(nullptr);
|
||||
hold_release();
|
||||
front_->attach(name, front_aliases_, srv_);
|
||||
return rc;
|
||||
}
|
||||
parked_.store(true, std::memory_order_release);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int64_t Engine::flex_bytes() const {
|
||||
const int64_t x = xflex_bytes_.load(std::memory_order_acquire);
|
||||
if (ranks_.empty() || !ranks_[0]->kv.flex()) return x;
|
||||
return x + std::max<int64_t>(ranks_[0]->pools.kv().committed() - flex_floor_bytes_, 0);
|
||||
}
|
||||
|
||||
int64_t Engine::flex_release(int64_t bytes, bool preempt, int64_t wait_ms, bool kv) {
|
||||
if (bytes <= 0 || ranks_.empty() || parked_.load()) return 0;
|
||||
const bool has_kv = kv && ranks_[0]->kv.flex();
|
||||
if (!has_kv && xflex_bytes_.load() <= 0) return 0;
|
||||
std::unique_lock<std::mutex> lk(flex_mu_);
|
||||
flex_want_ = bytes;
|
||||
flex_preempt_ = preempt;
|
||||
flex_kv_ = has_kv;
|
||||
flex_got_ = -1;
|
||||
flex_pending_.store(true, std::memory_order_release);
|
||||
flex_cv_.wait_for(lk, std::chrono::milliseconds(wait_ms), [&] {
|
||||
return flex_got_ >= 0 || stopping_.load(std::memory_order_acquire);
|
||||
});
|
||||
flex_pending_.store(false, std::memory_order_release);
|
||||
return flex_got_ > 0 ? flex_got_ : 0;
|
||||
}
|
||||
|
||||
/* On the step loop's thread, between steps with nothing issued ahead: the expert slab's fleet loan
|
||||
* first, then (unless only the experts' flex was asked for) the cache's free top, the prefix
|
||||
* cache and, with `flex_preempt_`, the running requests, until `flex_want_` bytes can go; then the
|
||||
* mark moves on every rank and the stripes above it are unbacked. */
|
||||
void Engine::flex_service() {
|
||||
if (!flex_pending_.load(std::memory_order_acquire)) return;
|
||||
std::lock_guard<std::mutex> lk(flex_mu_);
|
||||
if (flex_got_ >= 0) return;
|
||||
drain_streams();
|
||||
/* The experts' loan first: giving it back is an address change for each unit in it. */
|
||||
const int64_t xgot = xflex_give(flex_want_);
|
||||
if (xgot >= flex_want_ || !flex_kv_) {
|
||||
flex_got_ = xgot;
|
||||
flex_cv_.notify_all();
|
||||
return;
|
||||
}
|
||||
KVManager& k0 = ranks_[0]->kv;
|
||||
const int64_t tb = std::max<int64_t>(k0.flex_token_bytes(), 1);
|
||||
const int64_t want = (flex_want_ - xgot + tb - 1) / tb;
|
||||
const int64_t floor_loan = k0.flex_floor_loan();
|
||||
const int64_t cur = sched_.locked([&] { return k0.loan_tokens(); });
|
||||
/* spare_tokens() counts from the top of the carve, and a flex carve's top is the unbacked
|
||||
* reservation: what is free below the live mark is that less the loan. Never below the floor
|
||||
* the claim pays for. */
|
||||
auto room_locked = [&] {
|
||||
return std::max<int64_t>(std::min(k0.spare_tokens() - cur, floor_loan - cur), 0);
|
||||
};
|
||||
auto room = [&] { return sched_.locked(room_locked); };
|
||||
int64_t spare = room();
|
||||
/* What the floor lets go however empty the cache is. Past that, evicting or preempting costs
|
||||
* conversations and frees nothing the fleet can have. */
|
||||
const int64_t goal = std::min(want, std::max<int64_t>(floor_loan - cur, 0));
|
||||
if (spare < goal && cfg_.prefix_cache) {
|
||||
(void)sched_.evict_prefix_until([&] { return room_locked() >= goal; });
|
||||
spare = room();
|
||||
}
|
||||
if (spare < goal && flex_preempt_) {
|
||||
const int n = sched_.preempt_until([&] { return room_locked() >= goal; });
|
||||
if (sched_.has_deferred()) sched_.release_deferred();
|
||||
if (n > 0)
|
||||
RAD_INFO("flex: %d running request(s) go back to the queue so a higher-priority model "
|
||||
"takes the cache", n);
|
||||
spare = room();
|
||||
}
|
||||
const int64_t take = std::min(goal, spare);
|
||||
const int64_t before = ranks_[0]->pools.kv().committed();
|
||||
if (take > 0 && sched_.locked([&] { return k0.set_loan(cur + take); }) == RAD_OK) {
|
||||
for (size_t i = 1; i < ranks_.size(); ++i) (void)ranks_[i]->kv.set_loan(cur + take);
|
||||
for (auto& r : ranks_) {
|
||||
(void)rad_dev_set(r->device);
|
||||
if (const int rc = r->kv.flex_unback_above(cur + take); rc < 0)
|
||||
RAD_WARN("flex: rank %d could not unback its cache above the new mark: %s (%s)",
|
||||
r->index, rad_strerror(rc), rad_dev_last_error());
|
||||
}
|
||||
(void)rad_dev_set(ranks_[0]->device);
|
||||
}
|
||||
flex_got_ = xgot + std::max<int64_t>(before - ranks_[0]->pools.kv().committed(), 0);
|
||||
RAD_INFO("flex: asked for %s, the cache could give %lld of %lld tokens, gave back %s",
|
||||
humanb(flex_want_).c_str(), (long long)take, (long long)want, humanb(flex_got_).c_str());
|
||||
flex_cv_.notify_all();
|
||||
}
|
||||
|
||||
/* The slab's backed bytes a card after a recall, the most any rank still has backed; also clears
|
||||
* what the slab asks the fleet for. */
|
||||
int64_t Engine::xflex_settle() {
|
||||
int64_t left = 0;
|
||||
for (auto& r : ranks_) left = std::max(left, r->xflex.committed());
|
||||
xflex_bytes_.store(left, std::memory_order_release);
|
||||
xflex_want_.store(0, std::memory_order_release);
|
||||
return left;
|
||||
}
|
||||
|
||||
/* On the step loop, every stream drained: the slab's units in the fleet's slots past the new loan
|
||||
* go back to their host copies (Mover::reclaim), and the granules they leave are unbacked. The
|
||||
* bytes given back on each card. The slab does not grow again for five seconds, so the model that
|
||||
* asked for the room gets it first. */
|
||||
int64_t Engine::xflex_give(int64_t bytes) {
|
||||
const int64_t cur = xflex_bytes_.load(std::memory_order_acquire);
|
||||
if (bytes <= 0 || cur <= 0) return 0;
|
||||
const int64_t g = std::max<int64_t>(VMem::granularity(), 1);
|
||||
int64_t to = std::max<int64_t>(cur - (bytes + g - 1) / g * g, 0);
|
||||
for (auto& r : ranks_) {
|
||||
if (rad_dev_set(r->device) < 0) continue;
|
||||
if (const int st = r->mover.reclaim(Mover::kLendFleet, to, &r->heat); st < 0)
|
||||
RAD_WARN("expert flex: rank %d could not recall its slab to %s: %s", r->index,
|
||||
humanb(to).c_str(), rad_strerror(st));
|
||||
/* What a unit still holds stays backed. */
|
||||
to = std::max(to, (r->mover.loan_held(Mover::kLendFleet) + g - 1) / g * g);
|
||||
}
|
||||
for (auto& r : ranks_) {
|
||||
if (rad_dev_set(r->device) < 0) continue;
|
||||
const int64_t top = r->xflex.size();
|
||||
(void)r->mover.set_loan(Mover::kLendFleet, to);
|
||||
if (const int st = r->xflex.decommit(std::max<int64_t>(top - cur, 0), cur - to); st < 0)
|
||||
RAD_WARN("expert flex: rank %d could not unback %s: %s (%s)", r->index,
|
||||
humanb(cur - to).c_str(), rad_strerror(st), rad_dev_last_error());
|
||||
}
|
||||
(void)rad_dev_set(ranks_[0]->device);
|
||||
const int64_t left = xflex_settle();
|
||||
xflex_retry_ns_ = rad_mono_ns() + 5000000000ull;
|
||||
const int64_t got = std::max<int64_t>(cur - left, 0);
|
||||
if (got > 0)
|
||||
RAD_INFO("expert flex: the slab gave back %s a card, keeps %s", humanb(got).c_str(),
|
||||
humanb(left).c_str());
|
||||
return got;
|
||||
}
|
||||
|
||||
/* Every tenth of a second on the step loop. While the engine has been busy in the last five
|
||||
* seconds, the slab grows a GiB at a time into memory the fleet says no model holds, and grows
|
||||
* again only once the units fill what it already has, leaving no more than the turnover slots and
|
||||
* half a step empty (an empty slot is VRAM nothing uses). A refusal is remembered, so the fleet
|
||||
* can make room for it (expert_flex_wanted), and asked again a second later; a backing that fails
|
||||
* waits five seconds. */
|
||||
void Engine::xflex_tick(bool busy) {
|
||||
if (xflex_cap_ <= 0 || !broker_) return;
|
||||
const uint64_t now = rad_mono_ns();
|
||||
if (busy) xflex_busy_ns_ = now;
|
||||
if (now - xflex_ns_ < 100000000ull) return;
|
||||
xflex_ns_ = now;
|
||||
const int64_t cur = xflex_bytes_.load(std::memory_order_acquire);
|
||||
if (cur >= xflex_cap_ || now - xflex_busy_ns_ > 5000000000ull) {
|
||||
xflex_want_.store(0, std::memory_order_release);
|
||||
return;
|
||||
}
|
||||
if (now < xflex_retry_ns_) return;
|
||||
const Mover& m0 = ranks_[0]->mover;
|
||||
const int64_t g = std::max<int64_t>(VMem::granularity(), 1);
|
||||
const int64_t step = std::min<int64_t>(((int64_t)1 << 30) / g * g, xflex_cap_ - cur);
|
||||
/* Still filling: what the loans offer and no unit holds, past the slots kept free for swaps. */
|
||||
const int64_t kept = m0.turnover_bytes();
|
||||
if (m0.flex_offered_bytes() - m0.flex_used_bytes() > kept + step / 2) return;
|
||||
if (!broker_->flex_grow(rank_devices(), step)) {
|
||||
xflex_want_.store(xflex_cap_ - cur, std::memory_order_release);
|
||||
xflex_retry_ns_ = now + 1000000000ull;
|
||||
return;
|
||||
}
|
||||
struct Landed { VramBroker* b; ~Landed() { b->flex_done(); } } landed{ broker_ };
|
||||
const int64_t to = cur + step;
|
||||
bool ok = true;
|
||||
for (auto& r : ranks_) {
|
||||
if (rad_dev_set(r->device) < 0) { ok = false; break; }
|
||||
const int64_t top = r->xflex.size();
|
||||
if (r->xflex.commit(std::max<int64_t>(top - to, 0), std::min(step, top)) < 0) { ok = false; break; }
|
||||
}
|
||||
if (!ok) {
|
||||
RAD_WARN("expert flex: backing %s more a card failed (%s); trying again later",
|
||||
humanb(step).c_str(), rad_dev_last_error());
|
||||
for (auto& r : ranks_) {
|
||||
if (rad_dev_set(r->device) < 0) continue;
|
||||
const int64_t top = r->xflex.size();
|
||||
(void)r->xflex.decommit(std::max<int64_t>(top - to, 0), step);
|
||||
}
|
||||
(void)rad_dev_set(ranks_[0]->device);
|
||||
xflex_retry_ns_ = now + 5000000000ull;
|
||||
return;
|
||||
}
|
||||
for (auto& r : ranks_) {
|
||||
if (rad_dev_set(r->device) < 0) continue;
|
||||
(void)r->mover.set_loan(Mover::kLendFleet, to);
|
||||
}
|
||||
(void)rad_dev_set(ranks_[0]->device);
|
||||
xflex_bytes_.store(to, std::memory_order_release);
|
||||
xflex_want_.store(0, std::memory_order_release);
|
||||
if (to >= xflex_cap_ || cur == 0)
|
||||
RAD_INFO("expert flex: the slab grows into memory no model holds: %s a card of up to %s",
|
||||
humanb(to).c_str(), humanb(xflex_cap_).c_str());
|
||||
}
|
||||
|
||||
/* What the fleet could still grow the cache by, for admission, every tenth of a second. */
|
||||
void Engine::flex_room_tick(uint64_t now_ns) {
|
||||
if (!broker_ || ranks_.empty() || !ranks_[0]->kv.flex()) return;
|
||||
if (now_ns - flex_room_ns_ < 100000000ull) return;
|
||||
flex_room_ns_ = now_ns;
|
||||
const int64_t tb = std::max<int64_t>(ranks_[0]->kv.flex_token_bytes(), 1);
|
||||
ranks_[0]->kv.set_flex_room(broker_->flex_room(rank_devices()) / tb);
|
||||
}
|
||||
|
||||
int64_t Engine::release_host_spare() {
|
||||
if (!parked_.load() || ck_released_.load() || !ck_store_.enabled() || ck_store_.used_slots() > 0) return 0;
|
||||
EngineScope es(owner_, cfg_.served_model_name.c_str());
|
||||
ck_slot_ = ck_store_.slot_bytes();
|
||||
ck_cap_ = ck_store_.cap_bytes();
|
||||
ck_store_.close();
|
||||
ck_released_.store(true, std::memory_order_release);
|
||||
return ck_cap_;
|
||||
}
|
||||
|
||||
int Engine::repin_host_spare(std::string* why) {
|
||||
if (!ck_released_.load()) return RAD_OK;
|
||||
if (ck_store_.open(ck_slot_, ck_cap_) != RAD_OK) {
|
||||
*why = "the checkpoint slots' " + humanb(ck_cap_) + " of pinned host memory could not be pinned again";
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
ck_released_.store(false, std::memory_order_release);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Engine::unpark(std::string* why) { return unpark_with(why, nullptr); }
|
||||
|
||||
int Engine::page_back_in(int64_t* left) {
|
||||
std::vector<PageSpan> refill;
|
||||
if (const int rc = dev_page_in_begin(owner_, left, &refill); rc < 0) return rc;
|
||||
/* The elastic ranges (the KV cache, the expert flex) are backed, and the chunks held in host
|
||||
* memory copied back (q27: 6 GiB, 0.3 s), beside the refill, which reads the drive and writes
|
||||
* none of them. */
|
||||
int erc = RAD_OK;
|
||||
std::string elastic_why; /* the device error is per thread: carried back to this one */
|
||||
std::thread elastic([&] {
|
||||
EngineScope es(owner_, cfg_.served_model_name.c_str());
|
||||
erc = dev_page_in_elastic(owner_);
|
||||
if (erc < 0) {
|
||||
const char* w = rad_dev_last_error();
|
||||
elastic_why = w && *w ? w : rad_strerror(erc);
|
||||
}
|
||||
});
|
||||
/* The refill's writes wait for the begin's clears of recycled chunks, which run beside its
|
||||
* first read. */
|
||||
const int frc = refill_weights(refill, "restore", [this] { return dev_page_in_cleared(owner_); });
|
||||
elastic.join();
|
||||
const int irc = dev_page_in_end(owner_);
|
||||
if (frc < 0) {
|
||||
device_set_error("the weights paged back empty could not be read from the container again (%s)",
|
||||
rad_strerror(frc));
|
||||
return frc;
|
||||
}
|
||||
if (irc < 0) return irc;
|
||||
if (erc < 0)
|
||||
device_set_error("the KV cache and expert ranges could not be backed again: %s",
|
||||
elastic_why.c_str());
|
||||
return erc;
|
||||
}
|
||||
|
||||
int Engine::unpark_live(std::string* why, int64_t* left) {
|
||||
*left = 0;
|
||||
return unpark_with(why, left);
|
||||
}
|
||||
|
||||
/* unpark() with `left` null, unpark_live() otherwise: the memory comes back (whole, or live with
|
||||
* `left` bytes still in host memory), the step loop leaves its rest, and the front routes to the
|
||||
* model again. */
|
||||
int Engine::unpark_with(std::string* why, int64_t* left) {
|
||||
if (!parked_.load()) return RAD_OK;
|
||||
EngineScope es(owner_, cfg_.served_model_name.c_str());
|
||||
/* The snapshot store is pinned again beside the page-in (q27's 4 GiB takes 0.2-0.3 s), not
|
||||
* before it: neither waits on the other, and the step loop stays at rest until both are done.
|
||||
* On a failure of either the fleet unloads the model, so the order of the two is free. */
|
||||
std::string pin_why;
|
||||
int pin_rc = RAD_OK;
|
||||
std::thread pin;
|
||||
if (ck_released_.load())
|
||||
pin = std::thread([&] {
|
||||
EngineScope pes(owner_, cfg_.served_model_name.c_str());
|
||||
pin_rc = repin_host_spare(&pin_why);
|
||||
});
|
||||
const int prc = page_back_in(left);
|
||||
if (pin.joinable()) pin.join();
|
||||
if (prc < 0) {
|
||||
*why = std::string("paging in failed: ") + rad_dev_last_error();
|
||||
return prc;
|
||||
}
|
||||
if (pin_rc < 0) {
|
||||
*why = pin_why;
|
||||
return pin_rc;
|
||||
}
|
||||
parked_.store(false, std::memory_order_release);
|
||||
hold_release();
|
||||
while (hold_ack_.load(std::memory_order_acquire) && !stopping_.load())
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(100));
|
||||
front_->attach(cfg_.served_model_name, front_aliases_, srv_);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Engine::run_quiet(const std::function<int()>& fn) {
|
||||
std::unique_lock<std::mutex> lk(quiet_mu_);
|
||||
quiet_fn_ = &fn;
|
||||
quiet_done_ = false;
|
||||
quiet_pending_.store(true, std::memory_order_release);
|
||||
sched_.wake();
|
||||
/* Polled for a stop: the step loop may end without passing a step boundary again. */
|
||||
while (!quiet_cv_.wait_for(lk, std::chrono::milliseconds(50), [&] {
|
||||
return quiet_done_ || stopping_.load(std::memory_order_acquire);
|
||||
})) {}
|
||||
quiet_pending_.store(false, std::memory_order_release);
|
||||
quiet_fn_ = nullptr;
|
||||
return quiet_done_ ? quiet_rc_ : RAD_E_STATE;
|
||||
}
|
||||
|
||||
/* On the step loop's thread, with nothing issued ahead: every rank's streams drained (the compute
|
||||
* stream and the mover's, as for a park), then run_quiet's function. */
|
||||
void Engine::quiet_service() {
|
||||
if (!quiet_pending_.load(std::memory_order_acquire)) return;
|
||||
std::lock_guard<std::mutex> lk(quiet_mu_);
|
||||
if (quiet_done_ || !quiet_fn_) return;
|
||||
const int dev = dev_current();
|
||||
drain_streams();
|
||||
quiet_rc_ = (*quiet_fn_)();
|
||||
(void)rad_dev_set(dev);
|
||||
quiet_done_ = true;
|
||||
quiet_cv_.notify_all();
|
||||
}
|
||||
|
||||
int32_t* Engine::Readback::reserve(int64_t count) {
|
||||
if (count <= n) return p;
|
||||
@@ -309,13 +793,24 @@ Engine::~Engine() {
|
||||
* and frees the arena, but the mover's stream also copies into the arena (the prefill
|
||||
* stager's ring, lent slab slots) and would otherwise drain only later, with the mover. A fill
|
||||
* landing in a freed arena is a GPU memory fault. */
|
||||
for (auto& r : ranks_)
|
||||
for (auto& r : ranks_) {
|
||||
if (RadStream s = r->mover.transfer_stream()) (void)rad_stream_sync(s);
|
||||
r->tierx.quiesce();
|
||||
}
|
||||
for (auto& r : ranks_) r->ctx.shutdown();
|
||||
if (cards_claimed_) {
|
||||
const std::vector<int> cards = rank_devices();
|
||||
(void)rad_dev_cards_claim(cards.data(), (int)cards.size(), 0);
|
||||
cards_claimed_ = false;
|
||||
}
|
||||
/* The streamed groups' host mirrors are pinned outside every pool; freed after the contexts,
|
||||
* since a pass reads them. Safe after a failed bring-up. */
|
||||
for (auto& r : ranks_) r->kv.free_stream(rad_device_allocator());
|
||||
step_state_fini();
|
||||
/* The step batch's staging, events and media buffers (BatchBuilder), freed while the ranks'
|
||||
* KV managers the scheduler releases sequences into still exist. A process that unloads
|
||||
* models would otherwise keep every engine's. */
|
||||
sched_.fini();
|
||||
ranks_.clear();
|
||||
for (TableCopy& c : table_copies_) table_copy_free(&c);
|
||||
table_copies_.clear();
|
||||
@@ -325,7 +820,8 @@ Engine::~Engine() {
|
||||
card_copies_.clear();
|
||||
for (TableShare& t : table_shares_) table_share_close(&t);
|
||||
table_shares_.clear();
|
||||
rad_tools_registry().close();
|
||||
if (reg_) reg_->close();
|
||||
if (slot_base_ >= 0) rad_engine_release(plugins_.arch_plugin, slot_base_, cfg_.tp);
|
||||
}
|
||||
|
||||
/* ================================================================== 7. serve */
|
||||
@@ -720,6 +1216,9 @@ int Engine::prepare_release(const RadBatch* b) {
|
||||
int Engine::issue_ahead(const RadBatch** out) {
|
||||
*out = nullptr;
|
||||
if (!pipelining_) return RAD_OK;
|
||||
/* A flex release or a quiet window waits for a step boundary with nothing in flight. */
|
||||
if (flex_pending_.load(std::memory_order_acquire) || quiet_pending_.load(std::memory_order_acquire))
|
||||
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)
|
||||
@@ -762,6 +1261,7 @@ void Engine::phase_mark(int p) {
|
||||
* error instead of queueing requests nothing will drain (spec §17). */
|
||||
int Engine::fail_loop(int st) {
|
||||
stopping_.store(true, std::memory_order_release);
|
||||
wake_hold();
|
||||
if (barrier_) barrier_->abort();
|
||||
sched_.shutdown("the engine stopped on an error and is not serving", st < 0 ? st : RAD_E_STATE);
|
||||
loop_status_.store(st < 0 ? st : RAD_E_STATE, std::memory_order_release);
|
||||
@@ -814,9 +1314,17 @@ int Engine::step_loop() {
|
||||
if (!ahead && sched_.encodes_pending()) {
|
||||
if (const int es = run_encodes(); es < 0) return fail_loop(es);
|
||||
}
|
||||
if (!ahead) {
|
||||
flex_service();
|
||||
quiet_service();
|
||||
flex_room_tick(rad_mono_ns());
|
||||
}
|
||||
const bool issued = ahead != nullptr;
|
||||
const RadBatch* b = ahead;
|
||||
ahead = nullptr;
|
||||
/* Read before the step looks for work, so a request added after it found none still wakes
|
||||
* the idle wait below. */
|
||||
const uint64_t woke = issued ? 0 : sched_.wake_seq();
|
||||
if (issued) sched_.promote_next();
|
||||
else b = sched_.step();
|
||||
if (!b) {
|
||||
@@ -837,10 +1345,20 @@ int Engine::step_loop() {
|
||||
sched_.release_deferred();
|
||||
}
|
||||
tier_tick();
|
||||
/* A park waits here once the tiers' copies have landed, before the idle work that
|
||||
* would touch the card (the loan's fills). */
|
||||
if (hold_req_.load(std::memory_order_acquire) && !(pump_ && !pump_->copy.empty())) {
|
||||
hold_point(&step_watch);
|
||||
continue;
|
||||
}
|
||||
expire_tick(rad_mono_ns());
|
||||
loan_tick(/*idle=*/true);
|
||||
xflex_tick(/*busy=*/false);
|
||||
/* A request (or a cancel, a park, a quiet call) wakes the wait at once; otherwise it
|
||||
* lengthens, up to 20 ms, which the periodic idle work above tolerates. Polling at
|
||||
* 1 ms woke an idle engine a thousand times a second. */
|
||||
if (idle < 200) ++idle;
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(idle * 5));
|
||||
sched_.wait_idle(woke, std::chrono::microseconds(idle * 100));
|
||||
continue;
|
||||
}
|
||||
idle = 0;
|
||||
@@ -1152,6 +1670,7 @@ int Engine::step_loop() {
|
||||
sched_.step_finished();
|
||||
tier_tick();
|
||||
loan_tick(/*idle=*/false);
|
||||
xflex_tick(/*busy=*/true);
|
||||
const uint64_t now = rad_mono_ns();
|
||||
arena_tick(now);
|
||||
expire_tick(now);
|
||||
@@ -2039,6 +2558,7 @@ void Engine::clear_fresh_states() {
|
||||
}
|
||||
|
||||
int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
EngineScope es(owner_, cfg_.served_model_name.c_str());
|
||||
startup_watch_ = std::move(watch);
|
||||
if (ranks_.empty() || !ranks_[0]->ctx.program()) {
|
||||
RAD_ERR("serve: start() has not run, or stopped at --debug-graph");
|
||||
@@ -2308,8 +2828,17 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
done_.reserve((size_t)cfg_.max_seqs);
|
||||
|
||||
rank_threads_.clear();
|
||||
for (int i = 0; i < cfg_.tp; ++i) rank_threads_.emplace_back([this, i] { rank_loop(i); });
|
||||
std::thread stepper([this] { if (gen_) gen_loop(); else step_loop(); });
|
||||
for (int i = 0; i < cfg_.tp; ++i)
|
||||
rank_threads_.emplace_back([this, i] {
|
||||
EngineScope es(owner_, cfg_.served_model_name.c_str());
|
||||
rank_loop(i);
|
||||
});
|
||||
std::atomic<bool> stepped{false};
|
||||
std::thread stepper([this, &stepped] {
|
||||
EngineScope es(owner_, cfg_.served_model_name.c_str());
|
||||
if (gen_) gen_loop(); else step_loop();
|
||||
stepped.store(true, std::memory_order_release);
|
||||
});
|
||||
|
||||
if (cfg_.kld() || cfg_.calib()) {
|
||||
print_startup_report(RAD_OK);
|
||||
@@ -2321,7 +2850,16 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
/* Stop the step loop before the server's storage is destroyed: Request::sink points into it,
|
||||
* and an unfinished request still writes there (server.h). */
|
||||
stopping_.store(true, std::memory_order_release);
|
||||
wake_hold();
|
||||
barrier_->abort();
|
||||
/* A step loop that does not come back holds its cards and every model waiting for them, and
|
||||
* only a restart can free them, so past five minutes the process exits as for a GPU fault. */
|
||||
for (int t = 0; !stepped.load(std::memory_order_acquire); ++t) {
|
||||
if (t == 30000)
|
||||
fatal("model %s: the step loop has not come back five minutes after it was stopped; "
|
||||
"exiting so a restart can bring the server back", cfg_.served_model_name.c_str());
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
if (stepper.joinable()) stepper.join();
|
||||
for (auto& t : rank_threads_) if (t.joinable()) t.join();
|
||||
rank_threads_.clear();
|
||||
@@ -2355,7 +2893,7 @@ bool Engine::state_slots_of(uint64_t seq, std::vector<int32_t>* out) const {
|
||||
* 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;
|
||||
Json o;
|
||||
o["available"] = cvec_.loaded();
|
||||
o["default"] = cvec_default_.load();
|
||||
if (cvec_.loaded()) {
|
||||
@@ -2377,7 +2915,7 @@ std::string Engine::cvec_json() const {
|
||||
* The server holds only interfaces, so the engine renders this object and the server splices it in
|
||||
* verbatim. */
|
||||
std::string Engine::engine_info() const {
|
||||
nlohmann::ordered_json e;
|
||||
Json e;
|
||||
e["arch"] = meta_.arch_id ? meta_.arch_id : "";
|
||||
e["quant"] = meta_.quant ? meta_.quant : "";
|
||||
e["n_layers"] = meta_.n_layers;
|
||||
@@ -2389,7 +2927,6 @@ std::string Engine::engine_info() const {
|
||||
e["tensor_parallel"] = cfg_.tp;
|
||||
e["tp_wire"] = cfg_.tp > 1 ? (cfg_.tp_wire_exact ? "exact" : "wht6") : "n/a";
|
||||
e["tp_wire_min_kb"] = cfg_.tp_wire_exact ? 0 : cfg_.tp_wire_min_kb;
|
||||
e["attn_prefill_fp8"] = attn_prefill_fp8_name(cfg_.attn_prefill_fp8);
|
||||
e["tp_attn_split"] = cfg_.tp_attn_rows ? "rows" : "heads";
|
||||
e["weight_prefetch"] = cfg_.weight_prefetch;
|
||||
e["max_num_batched_tokens"] = cfg_.max_tok;
|
||||
@@ -2402,15 +2939,15 @@ 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["control_vector"] = Json::parse(cvec_json());
|
||||
e["checkpoint_slots"] = cfg_.checkpoint_slots;
|
||||
e["deterministic"] = cfg_.deterministic;
|
||||
|
||||
nlohmann::ordered_json devs = nlohmann::ordered_json::array();
|
||||
Json devs = Json::array();
|
||||
for (const auto& r : ranks_) {
|
||||
RadDeviceProps p{};
|
||||
if (rad_dev_props(r->device, &p) < 0) continue;
|
||||
nlohmann::ordered_json d;
|
||||
Json d;
|
||||
d["rank"] = r->index;
|
||||
d["device"] = r->device;
|
||||
d["name"] = p.name;
|
||||
@@ -2427,13 +2964,13 @@ std::string Engine::engine_info() const {
|
||||
e["ops"] = (int64_t)p0.ops.size() - 1;
|
||||
e["weights"] = (int64_t)p0.weights.size() - 1;
|
||||
|
||||
nlohmann::ordered_json kvs = nlohmann::ordered_json::array();
|
||||
Json kvs = Json::array();
|
||||
const KVManager& kv = ranks_[0]->kv;
|
||||
for (int32_t g = 0; g < kv.n_groups(); ++g) {
|
||||
const KVGroupPlan* pl = kv.plan(g);
|
||||
/* Skip group 0, the sentinel that makes handle 0 mean "none". */
|
||||
if (!pl || pl->name.empty() || pl->n_layers <= 0) continue;
|
||||
nlohmann::ordered_json k;
|
||||
Json k;
|
||||
k["name"] = pl->name;
|
||||
k["kind"] = bld_kv_kind_name(pl->kind);
|
||||
k["n_layers"] = pl->n_layers;
|
||||
@@ -2449,7 +2986,7 @@ std::string Engine::engine_info() const {
|
||||
}
|
||||
e["kv_groups"] = std::move(kvs);
|
||||
|
||||
nlohmann::ordered_json sp;
|
||||
Json sp;
|
||||
if (drafter_.kind == RAD_DRAFT_NONE) {
|
||||
sp["enabled"] = false;
|
||||
} else {
|
||||
@@ -2464,18 +3001,7 @@ std::string Engine::engine_info() const {
|
||||
return e.dump();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ a clean stop
|
||||
*
|
||||
* SIGINT and SIGTERM are handled so `~Engine` runs: --profile-ops prints its table, the placement
|
||||
* summary prints, and in-flight requests drain instead of being cut.
|
||||
*
|
||||
* The handler only stores to a lock-free atomic; a watcher thread does the work, because
|
||||
* `Server::stop` takes locks and joins threads, which is not async-signal-safe. A second signal
|
||||
* gets the default disposition, so the operator can still force an immediate kill.
|
||||
*/
|
||||
namespace {
|
||||
std::atomic<bool> g_signalled{false};
|
||||
void on_signal(int) { g_signalled.store(true, std::memory_order_relaxed); }
|
||||
|
||||
/* ================================================================== sampling defaults */
|
||||
/* The sampler for a request that sends no sampler settings. Parsing and range checks live in
|
||||
@@ -2777,6 +3303,8 @@ int Engine::run_server() {
|
||||
|
||||
server::Deps d{};
|
||||
d.sched = &sched_bridge;
|
||||
d.background = &background_jobs_;
|
||||
d.front = front_;
|
||||
d.tok = &tok_bridge;
|
||||
d.grammar = &grammar_bridge;
|
||||
d.live = snap;
|
||||
@@ -2901,6 +3429,13 @@ int Engine::run_server() {
|
||||
if (cfg_.max_n <= 0)
|
||||
decide("--max-n", std::to_string(o.max_n), "the larger of 8 and --max-num-seqs");
|
||||
o.max_ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
|
||||
if (!gen_ && !ranks_.empty()) {
|
||||
o.kv_cache_dtype = cfg_.kv_cache_dtype;
|
||||
for (const KVGroupInfo& kg : ranks_[0]->program.kv_groups)
|
||||
if (kg.block_size > 0) { o.kv_block_size = kg.block_size; break; }
|
||||
o.prefix_cache = cfg_.prefix_cache;
|
||||
o.prefix_cache_mib = cfg_.prefix_cache_mib;
|
||||
}
|
||||
o.model_path = cfg_.model;
|
||||
o.default_reasoning_effort = cfg_.reasoning_effort;
|
||||
o.reasoning_effort_map = cfg_.reasoning_effort_map;
|
||||
@@ -2955,7 +3490,7 @@ int Engine::run_server() {
|
||||
o.engine_info = engine_info();
|
||||
/* Per request, since OpInfo::issued changes once the run phase runs
|
||||
* (ServerOptions::graph_json). */
|
||||
o.graph_json = [this] { return dump_graph_json(ranks_[0]->program); };
|
||||
o.graph_json = [this] { return dump_graph_json(ranks_[0]->program, reg_.get()); };
|
||||
/* Per request, from a reading at most a second old (Engine::diagnostics_json). */
|
||||
o.diagnostics_json = [this] { return diagnostics_json(); };
|
||||
if (cfg_.lora.enabled() && ranks_[0]->program.is_pass_driven()) {
|
||||
@@ -3549,6 +4084,8 @@ int Engine::run_server() {
|
||||
: "takes no images or video");
|
||||
|
||||
server::Server srv(d, o);
|
||||
srv_ = &srv;
|
||||
struct ClearSrv { server::Server** p; ~ClearSrv() { *p = nullptr; } } clear_srv{ &srv_ };
|
||||
if (cfg_.max_queued_requests <= 0)
|
||||
decide("--max-queued-requests", std::to_string(srv.queue_cap()), "8 x --max-num-seqs");
|
||||
|
||||
@@ -3602,26 +4139,26 @@ int Engine::run_server() {
|
||||
why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
print_startup_report(RAD_OK);
|
||||
if (!cfg_.report_once) print_startup_report(RAD_OK);
|
||||
const char* const keyed = o.api_key.empty() ? "" : "; a bearer key is required";
|
||||
if (embedding_)
|
||||
RAD_INFO("serving on http://%s:%d (/v1/embeddings; completions and chat are 501%s)",
|
||||
o.host.c_str(), o.port, keyed);
|
||||
RAD_INFO("model %s serves (/v1/embeddings; completions and chat are 501%s)",
|
||||
cfg_.served_model_name.c_str(), keyed);
|
||||
else if (aud_gen_)
|
||||
RAD_INFO("serving on http://%s:%d (/v1/audio/speech; completions and chat are 501%s)",
|
||||
o.host.c_str(), o.port, keyed);
|
||||
RAD_INFO("model %s serves (/v1/audio/speech; completions and chat are 501%s)",
|
||||
cfg_.served_model_name.c_str(), keyed);
|
||||
else if (vid_gen_)
|
||||
RAD_INFO("serving on http://%s:%d (/v1/videos; completions and chat are 501%s)",
|
||||
o.host.c_str(), o.port, keyed);
|
||||
RAD_INFO("model %s serves (/v1/videos; completions and chat are 501%s)",
|
||||
cfg_.served_model_name.c_str(), keyed);
|
||||
else if (shp_gen_)
|
||||
RAD_INFO("serving on http://%s:%d (/generate, /send and /status/{uid}; completions and "
|
||||
"chat are 501%s)", o.host.c_str(), o.port, keyed);
|
||||
RAD_INFO("model %s serves (/generate, /send and /status/{uid}; completions and "
|
||||
"chat are 501%s)", cfg_.served_model_name.c_str(), keyed);
|
||||
else if (gen_)
|
||||
RAD_INFO("serving on http://%s:%d (/v1/images/generations%s; completions and chat are "
|
||||
"501%s)", o.host.c_str(), o.port,
|
||||
RAD_INFO("model %s serves (/v1/images/generations%s; completions and chat are "
|
||||
"501%s)", cfg_.served_model_name.c_str(),
|
||||
d.images && d.images->info().max_refs > 0 ? " and /v1/images/edits" : "", keyed);
|
||||
else
|
||||
RAD_INFO("serving on http://%s:%d (/v1/completions%s%s)", o.host.c_str(), o.port,
|
||||
RAD_INFO("model %s serves (/v1/completions%s%s)", cfg_.served_model_name.c_str(),
|
||||
d.chat ? "; /v1/chat/completions with tools and reasoning" : "; chat is 501",
|
||||
keyed);
|
||||
|
||||
@@ -3635,43 +4172,52 @@ int Engine::run_server() {
|
||||
live->start();
|
||||
}
|
||||
|
||||
struct sigaction sa {};
|
||||
sa.sa_handler = on_signal;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sa.sa_flags = SA_RESETHAND; /* a second one takes the default disposition and kills */
|
||||
sigaction(SIGINT, &sa, nullptr);
|
||||
sigaction(SIGTERM, &sa, nullptr);
|
||||
|
||||
std::atomic<bool> watching{true};
|
||||
std::thread watcher([&] {
|
||||
while (watching.load(std::memory_order_relaxed)) {
|
||||
if (g_signalled.load(std::memory_order_relaxed)) {
|
||||
RAD_INFO("stopping: draining in-flight requests");
|
||||
srv.stop();
|
||||
return;
|
||||
}
|
||||
/* The step loop died and its requests were already failed (Engine::fail_loop); stop
|
||||
* the transport so no new request is queued. */
|
||||
if (loop_status_.load(std::memory_order_acquire) < 0) {
|
||||
RAD_ERR("stopping: the step loop failed with %s",
|
||||
rad_strerror(loop_status_.load(std::memory_order_acquire)));
|
||||
srv.stop();
|
||||
return;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
}
|
||||
});
|
||||
|
||||
/* A model serves behind the process's front (server/front.h); the process's signals are the
|
||||
* fleet's (fleet/fleet.cpp). This model ends when the front stops or the fleet asks it to. */
|
||||
if (!front_) {
|
||||
RAD_ERR("model %s: no front to serve behind", cfg_.served_model_name.c_str());
|
||||
if (live) live->stop();
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
/* 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. */
|
||||
watching.store(false, std::memory_order_relaxed);
|
||||
watcher.join();
|
||||
front_->attach(cfg_.served_model_name, front_aliases_, &srv);
|
||||
serving_.store(true, std::memory_order_release);
|
||||
RAD_INFO("model %s: ready", cfg_.served_model_name.c_str());
|
||||
while (!front_->stopping() && !stop_requested_.load(std::memory_order_acquire)) {
|
||||
if (loop_status_.load(std::memory_order_acquire) < 0) {
|
||||
RAD_ERR("model %s: stopping: the step loop failed with %s",
|
||||
cfg_.served_model_name.c_str(),
|
||||
rad_strerror(loop_status_.load(std::memory_order_acquire)));
|
||||
break;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
}
|
||||
serving_.store(false, std::memory_order_release);
|
||||
/* The responses already handed out run to their end, for as long as the stop allows: a
|
||||
* stream holds its lease until the client has it all or leaves. Past that the server ends
|
||||
* them (Server::retire stops every stream and job), and they let go at once. */
|
||||
const int64_t drain = stop_drain_ms_.load(std::memory_order_relaxed);
|
||||
if (!front_->detach(cfg_.served_model_name, (int)std::min<int64_t>(drain, INT32_MAX))) {
|
||||
RAD_WARN("model %s: responses still open after %lld ms; ending them",
|
||||
cfg_.served_model_name.c_str(), (long long)drain);
|
||||
srv.retire();
|
||||
/* `srv` lives in this frame and a response names it to the last, so it cannot go while one
|
||||
* is held. Past five minutes the model is wedged, and the process exits as for a GPU fault
|
||||
* so a restart brings the others back. */
|
||||
for (int min = 1; !front_->detach(cfg_.served_model_name, 60000); ++min) {
|
||||
if (min >= 5)
|
||||
fatal("model %s: responses still held %d minutes after they were ended; exiting "
|
||||
"so a restart can bring the server back", cfg_.served_model_name.c_str(), min);
|
||||
RAD_WARN("model %s: responses still held %d minute(s) after they were ended",
|
||||
cfg_.served_model_name.c_str(), min);
|
||||
}
|
||||
}
|
||||
srv.retire();
|
||||
if (live) live->stop();
|
||||
return rc;
|
||||
const int st = loop_status_.load(std::memory_order_acquire);
|
||||
return st < 0 ? st : RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+186
-1
@@ -37,6 +37,7 @@
|
||||
#include "format/table_share.h"
|
||||
#include "lora/adapter.h"
|
||||
#include "lora/slots.h"
|
||||
#include "fleet/broker.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
@@ -48,10 +49,14 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* While on, the sweeps' pinned staging is kept for the next sweep, for a process that restores
|
||||
* models again and again; off frees what is kept. */
|
||||
void sweep_buffers_keep(bool on);
|
||||
|
||||
class Kld;
|
||||
class StallWatch;
|
||||
namespace gen { class Driver; class AudioDriver; class VideoDriver; class ShapeDriver; struct IPassDriver; }
|
||||
namespace server { class Sink; }
|
||||
namespace server { class Sink; class Front; class Server; }
|
||||
struct TierPump;
|
||||
struct TierJob;
|
||||
struct StepSlot;
|
||||
@@ -77,6 +82,101 @@ public:
|
||||
* reports where it waits like start() itself. */
|
||||
int serve(std::unique_ptr<StallWatch> watch);
|
||||
|
||||
/* Serve behind `front` (server/front.h) instead of listening: serve() attaches this model's
|
||||
* server under its name and `aliases` once it is ready, and returns after the front stops or
|
||||
* request_stop() is called, detaching first so no response outlives the server. Set before
|
||||
* serve(). */
|
||||
void set_front(server::Front* front, std::vector<std::string> aliases) {
|
||||
front_ = front;
|
||||
front_aliases_ = std::move(aliases);
|
||||
}
|
||||
/* Ends serve() behind a front: the model stops taking requests, its in-flight responses are
|
||||
* waited for, and serve() returns. Safe from any thread. */
|
||||
void request_stop(int64_t drain_ms = 600000) {
|
||||
stop_drain_ms_.store(drain_ms, std::memory_order_relaxed);
|
||||
stop_requested_.store(true, std::memory_order_release);
|
||||
}
|
||||
/* The fleet that grants this engine its part of the cards (fleet/broker.h); null splits the
|
||||
* cards as a process of one model does. Set before start(). */
|
||||
void set_broker(VramBroker* b) { broker_ = b; }
|
||||
/* For the broker while its grant waits for room: other engines' bring-ups go on meanwhile,
|
||||
* since only this engine's own steps need the bring-up lock (engine_bringup.cpp). Called on
|
||||
* the starting thread, inside the grant. */
|
||||
/* What this engine keeps pinned in host memory: its pools, its tables and its prefix cache's
|
||||
* host tier, as configured. */
|
||||
int64_t host_pinned_bytes() const {
|
||||
return ((int64_t)cfg_.tp * (cfg_.host_pool_mib + cfg_.embedding_host_mib + cfg_.tower_host_mib) +
|
||||
cfg_.prefix_cache_mib) << 20;
|
||||
}
|
||||
void bringup_pause() { if (bringup_lk_ && bringup_lk_->owns_lock()) bringup_lk_->unlock(); }
|
||||
void bringup_resume() { if (bringup_lk_ && !bringup_lk_->owns_lock()) bringup_lk_->lock(); }
|
||||
|
||||
/* ---- parking (docs/MULTIMODEL.md §7). park() stops taking requests (the ones handed out
|
||||
* finish within `drain_ms`, then are ended), brings the step loop to rest, and pages the
|
||||
* engine's memory out to pinned host memory at the same addresses (dev_page_out): the engine
|
||||
* keeps its threads, queues, server, kernels and recorded passes, and holds only its small
|
||||
* allocations on the card. unpark() pages it back in and takes requests again. From the
|
||||
* fleet's thread, while serve() runs behind a front. RAD_E_UNSUPPORTED when the card has no
|
||||
* virtual memory manager, since nothing could leave at the same address.
|
||||
*
|
||||
* `req` says how much to take off each card (empty: everything), the host memory the copies
|
||||
* may take and the disk tier for the rest (device.h, PageOut); `got` what left. A parked
|
||||
* engine may be asked again for more. */
|
||||
int park(int64_t drain_ms, const PageOut& req, PageResult* got, std::string* why);
|
||||
int unpark(std::string* why);
|
||||
/* unpark() that takes requests at once: the weights parked in host memory stay there, read in
|
||||
* place over the link, and dev_page_promote moves them onto the card while the engine serves
|
||||
* (`left` is how much stays for now). */
|
||||
int unpark_live(std::string* why, int64_t* left);
|
||||
/* Every request is one step: an embedding program's pass over the prompt, nothing generated.
|
||||
* Set at bring-up. */
|
||||
bool one_step() const { return embedding_; }
|
||||
bool parked() const { return parked_.load(std::memory_order_acquire); }
|
||||
/* While parked, the linear-state snapshot store's pinned host memory goes back to the host:
|
||||
* the park emptied the prefix cache, so the store holds no snapshot, and the next unpark pins
|
||||
* it again before paging in (4 GiB pins in about 0.3 s, far less than the host copies of
|
||||
* weights it makes room for would cost to read back from the drive). The bytes released; 0
|
||||
* when not parked, already released, or a snapshot is still held. From the fleet's thread. */
|
||||
int64_t release_host_spare();
|
||||
/* While parked: up to about `max_bytes` of the parked memory with no host copy comes into
|
||||
* host memory at its own addresses, so the next restore copies it over the link: chunks
|
||||
* whose copy is on the drive are read back, and the weights pool's chunks are filled from the
|
||||
* container, whole weights at a time. The bytes filled, or a negative status. From the fleet's
|
||||
* thread, with the model idle. */
|
||||
int64_t fill_host(int64_t max_bytes);
|
||||
/* Host memory a refill (a restore's or a host fill's) holds while it runs, at most: the
|
||||
* relayout pool's staged inputs (kRefillStaging), its workers' output buffers and the sweep's
|
||||
* pinned windows. The fleet keeps this much room for it. */
|
||||
static constexpr int64_t kRefillStaging = (int64_t)2 << 30;
|
||||
static constexpr int64_t kRefillHost = (int64_t)4 << 30;
|
||||
/* What release_host_spare gave back and unpark will pin again. */
|
||||
int64_t host_spare_released() const { return ck_released_.load(std::memory_order_acquire) ? ck_cap_ : 0; }
|
||||
/* Runs `fn` on the step loop between steps, with nothing of the engine's in flight on any rank
|
||||
* (every stream drained), and returns its result; for mapping changes under a serving engine.
|
||||
* RAD_E_STATE when the engine stops first. From any thread but the step loop's. */
|
||||
int run_quiet(const std::function<int()>& fn);
|
||||
/* The engine's owner id for the device layer (engine_owner): every thread it starts files its
|
||||
* allocations under it. */
|
||||
int owner() const { return owner_; }
|
||||
|
||||
/* ---- flex (docs/MULTIMODEL.md §6). What the cache and the expert slab hold on each card
|
||||
* beyond the claim, and giving it back: the step loop recalls the slab's loan first, then
|
||||
* takes the free top of the cache, the prefix cache's entries and (with `preempt`) the running
|
||||
* requests, which go back to the queue by recompute, and unbacks it. Blocks the calling thread
|
||||
* until the step loop has done it, at most `wait_ms`. The bytes given back on each card. */
|
||||
int64_t flex_bytes() const;
|
||||
/* Jobs running with no open request (a video, an async shape): the model is at work. */
|
||||
int64_t background_jobs() const { return background_jobs_.load(std::memory_order_acquire); }
|
||||
int64_t flex_release(int64_t bytes, bool preempt, int64_t wait_ms, bool kv = true);
|
||||
/* Expert flex (§6.7): the bytes on each card the expert slab holds past the claim, lent by the
|
||||
* fleet; they go first in flex_release, and with `kv` false they are all that goes. */
|
||||
int64_t expert_flex_bytes() const { return xflex_bytes_.load(std::memory_order_acquire); }
|
||||
/* What the slab could still grow by on each card while the engine is busy and the fleet had
|
||||
* no free memory for it; 0 when it is idle, at its ceiling or still filling what it has. */
|
||||
int64_t expert_flex_wanted() const { return xflex_want_.load(std::memory_order_acquire); }
|
||||
/* True once serve() has attached to its front (or listens): the model takes requests. */
|
||||
bool serving() const { return serving_.load(std::memory_order_acquire); }
|
||||
|
||||
/* --debug-graph and friends: print everything declare and plan learned, without serving. A
|
||||
* first-class mode rather than a verbose-flag side effect, so what runs is always visible. */
|
||||
int dump();
|
||||
@@ -95,6 +195,10 @@ public:
|
||||
* serving cards' power-management files (hardware_facts). */
|
||||
std::string diagnostics_json() const;
|
||||
bool startup_report_printed() const { return report_printed_; }
|
||||
/* The cards an engine may run on, as start() filters them (one architecture, discrete before
|
||||
* integrated); the fleet places models on them. */
|
||||
static int usable_cards(std::vector<int>* out);
|
||||
|
||||
/* --proceed-with-incompatible-configuration's banner (diag::unsupported_banner) on W lines;
|
||||
* main prints it before anything else, so it heads the log. */
|
||||
static void print_unsupported_banner();
|
||||
@@ -162,6 +266,13 @@ private:
|
||||
|
||||
RadModelMeta meta_{};
|
||||
LoadedPlugins plugins_;
|
||||
/* This engine's share of the process plugin set (plugin/registry.h, Sharing): its device facts,
|
||||
* selection table and kernel instances. Made by load_plugins; plugins_.registry points at it. */
|
||||
std::unique_ptr<Registry> reg_;
|
||||
/* The first of this engine's instance slots (RadBuildCtx::slot_base), held from load_plugins
|
||||
* to the destructor (rad_engine_claim); -1 while none is held. */
|
||||
int slot_base_ = -1;
|
||||
bool cards_claimed_ = false; /* rad_dev_cards_claim, for an engine of more than one rank */
|
||||
|
||||
/* RadModelMeta holds bare char*, so the strings behind its key/value table must outlive
|
||||
* every declare. */
|
||||
@@ -229,6 +340,11 @@ private:
|
||||
* 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); }
|
||||
/* What a table's or a stream's pin leaves free: the headroom, and in a fleet what the fleet
|
||||
* keeps (VramBroker::host_margin). */
|
||||
int64_t host_margin_bytes() const;
|
||||
/* Why a fleet's load put an embedding left to its default on the card; empty if it did not. */
|
||||
std::string emb_on_card_why_;
|
||||
/* 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
|
||||
@@ -264,6 +380,14 @@ private:
|
||||
* rank's planner in place of the container's activation profile. */
|
||||
std::vector<RadFileProfile> expert_profile_;
|
||||
int load_weights();
|
||||
/* After a page-in: every weight with a byte in `spans` (memory the page-in mapped back empty,
|
||||
* dev_page_refilled) is read from the container and laid out again at its current address,
|
||||
* through the load's sweep and relayout pool. */
|
||||
/* `before_writes`, when set, runs once before the refill's first write into the spans. */
|
||||
int refill_weights(const std::vector<PageSpan>& spans, const char* what = "restore",
|
||||
const std::function<int()>& before_writes = {});
|
||||
/* dev_page_in (or the live form with `left`) and the refill of what it mapped back empty. */
|
||||
int page_back_in(int64_t* left);
|
||||
int configure_kv();
|
||||
/* Resolves --checkpoint-slots auto for snapshots of `slot` bytes (`what` names their kind). */
|
||||
int size_checkpoint_store(int64_t slot, const char* what);
|
||||
@@ -324,6 +448,64 @@ private:
|
||||
/* The error the step loop ended on; RAD_OK while running or after a clean stop. Written once
|
||||
* by fail_loop(); read by the server watcher to stop HTTP and by serve() to return it. */
|
||||
std::atomic<int> loop_status_{RAD_OK};
|
||||
server::Front* front_ = nullptr;
|
||||
std::vector<std::string> front_aliases_;
|
||||
std::atomic<bool> stop_requested_{false};
|
||||
/* How long a stop lets responses already handed out finish before the server ends them. */
|
||||
std::atomic<int64_t> stop_drain_ms_{600000};
|
||||
VramBroker* broker_ = nullptr;
|
||||
std::unique_lock<std::mutex>* bringup_lk_ = nullptr; /* start()'s, while it runs */
|
||||
const int owner_;
|
||||
std::atomic<bool> parked_{false};
|
||||
/* The step loop's rest for a park: the fleet sets hold_req_, the loop answers with hold_ack_
|
||||
* once it is idle with nothing in flight and waits there until hold_req_ clears. */
|
||||
std::atomic<bool> hold_req_{false};
|
||||
std::atomic<bool> hold_ack_{false};
|
||||
/* hold_point's wait: woken when the hold clears (hold_release) or the engine stops
|
||||
* (wake_hold). */
|
||||
std::mutex hold_mu_;
|
||||
std::condition_variable hold_cv_;
|
||||
void hold_point(StallWatch* watch = nullptr);
|
||||
void hold_release();
|
||||
void wake_hold();
|
||||
int unpark_with(std::string* why, int64_t* left);
|
||||
void drain_streams();
|
||||
std::vector<int> rank_devices() const; /* each rank's card, in rank order */
|
||||
server::Server* srv_ = nullptr; /* run_server's, while it runs */
|
||||
std::atomic<int64_t> background_jobs_{0}; /* server::Deps::background */
|
||||
/* flex_release's handoff to the step loop (flex_service). */
|
||||
int64_t flex_floor_bytes_ = 0; /* rank 0's KV backing after the carve */
|
||||
std::mutex flex_mu_;
|
||||
std::condition_variable flex_cv_;
|
||||
std::atomic<bool> flex_pending_{false};
|
||||
int64_t flex_want_ = 0;
|
||||
bool flex_preempt_ = false;
|
||||
bool flex_kv_ = true; /* the cache's flex may go too */
|
||||
int64_t flex_got_ = -1;
|
||||
uint64_t flex_room_ns_ = 0;
|
||||
void flex_service();
|
||||
void flex_room_tick(uint64_t now_ns);
|
||||
/* Expert flex (§6.7). Each rank's slab borrows from its own reserved range (Rank::xflex), the
|
||||
* top `xflex_bytes_` of it backed; the ceiling is the loan that covers every slot carved there.
|
||||
* xflex_tick grows it on the step loop while the engine is busy, a GiB at a time once the
|
||||
* slab has filled what it holds; xflex_give recalls and unbacks it, between steps. */
|
||||
std::atomic<int64_t> xflex_bytes_{0};
|
||||
std::atomic<int64_t> xflex_want_{0};
|
||||
int64_t xflex_cap_ = 0;
|
||||
int64_t xflex_claimed_ = 0; /* the claim's expert bytes a card */
|
||||
uint64_t xflex_ns_ = 0, xflex_busy_ns_ = 0, xflex_retry_ns_ = 0;
|
||||
void xflex_tick(bool busy);
|
||||
int64_t xflex_give(int64_t bytes);
|
||||
int64_t xflex_settle();
|
||||
/* run_quiet's handoff to the step loop (quiet_service). */
|
||||
std::mutex quiet_mu_;
|
||||
std::condition_variable quiet_cv_;
|
||||
std::atomic<bool> quiet_pending_{false};
|
||||
const std::function<int()>* quiet_fn_ = nullptr;
|
||||
int quiet_rc_ = 0;
|
||||
bool quiet_done_ = false;
|
||||
void quiet_service();
|
||||
std::atomic<bool> serving_{false};
|
||||
int fail_loop(int st);
|
||||
|
||||
/* This step's scored rows (Request::token_scores): a logits row and the result it fills.
|
||||
@@ -594,6 +776,9 @@ private:
|
||||
* rank's shard of one snapshot (KVManager::set_checkpoint_store). Off the card because no
|
||||
* kernel reads a snapshot; it is only copied back into a sequence's state. */
|
||||
HostArena ck_store_;
|
||||
std::atomic<bool> ck_released_{ false }; /* release_host_spare closed it; unpark opens it */
|
||||
int64_t ck_slot_ = 0, ck_cap_ = 0;
|
||||
int repin_host_spare(std::string* why);
|
||||
int run_server();
|
||||
/* KL mode (core/kld.h), replacing run_server: submits the corpus documents as scoring
|
||||
* requests and hands every step's scored rows, copied to the host, to `kld_`. One pinned
|
||||
|
||||
+1386
-390
File diff suppressed because it is too large.
Load diff
@@ -51,9 +51,14 @@ int Engine::gen_loop() {
|
||||
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);
|
||||
quiet_service();
|
||||
const RadBatch* b = gen_->next(step);
|
||||
if (!b) {
|
||||
step_batch_.store(nullptr, std::memory_order_release);
|
||||
if (hold_req_.load(std::memory_order_acquire)) {
|
||||
hold_point();
|
||||
continue;
|
||||
}
|
||||
if (idle < 200) ++idle;
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(idle * 50));
|
||||
continue;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* engine_hostmem.cpp -- see engine_hostmem.h. */
|
||||
#include "engine_hostmem.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
|
||||
@@ -51,4 +52,37 @@ void cgroup_levels(const std::string& root, std::string path, bool v2,
|
||||
}
|
||||
}
|
||||
|
||||
void memory_cgroups(const std::function<bool(const std::string&, int64_t)>& visit) {
|
||||
std::ifstream f("/proc/self/cgroup");
|
||||
std::string line;
|
||||
bool go = true;
|
||||
while (go && std::getline(f, line)) {
|
||||
const size_t a = line.find(':'), b = a == std::string::npos ? a : line.find(':', a + 1);
|
||||
if (b == std::string::npos) continue;
|
||||
const std::string ctrl = line.substr(a + 1, b - a - 1);
|
||||
std::string path = line.substr(b + 1);
|
||||
const bool v2 = ctrl.empty();
|
||||
bool memory = v2;
|
||||
for (size_t i = 0; !memory && i < ctrl.size();) {
|
||||
const size_t j = std::min(ctrl.find(',', i), ctrl.size());
|
||||
memory = ctrl.compare(i, j - i, "memory") == 0;
|
||||
i = j + 1;
|
||||
}
|
||||
if (!memory) continue;
|
||||
const std::string root = v2 ? "/sys/fs/cgroup" : "/sys/fs/cgroup/memory";
|
||||
cgroup_levels(root, path, v2, [&](const std::string& dir, int64_t room) {
|
||||
return go = visit(dir, room);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
int64_t cgroup_least_room() {
|
||||
int64_t least = INT64_MAX;
|
||||
memory_cgroups([&](const std::string&, int64_t room) {
|
||||
least = std::min(least, room);
|
||||
return true;
|
||||
});
|
||||
return least;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -19,6 +19,16 @@ bool cgroup_room(const std::string& dir, bool v2, int64_t* room);
|
||||
void cgroup_levels(const std::string& root, std::string path, bool v2,
|
||||
const std::function<bool(const std::string& dir, int64_t room)>& visit);
|
||||
|
||||
/* 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"
|
||||
* (or a comma list naming memory) on v1; each level up to the visible root is a limit of its
|
||||
* own. */
|
||||
void memory_cgroups(const std::function<bool(const std::string& dir, int64_t room)>& visit);
|
||||
|
||||
/* The least room any of those levels leaves (cgroup_room), or INT64_MAX when none sets a limit:
|
||||
* a container's --memory, which the OOM killer enforces whatever MemAvailable says. */
|
||||
int64_t cgroup_least_room();
|
||||
|
||||
/* Whether `need` more bytes fit in host memory after `still` more this process will allocate
|
||||
* 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
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
#include "engine_priv.h"
|
||||
#include "lora/lora.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
@@ -36,7 +36,7 @@ int read_targets(const std::string& dir, std::set<std::string>* out, std::string
|
||||
const std::string path = dir + "/adapter_config.json";
|
||||
std::ifstream f(path);
|
||||
if (!f) { *err = "cannot read " + path; return RAD_E_NOTFOUND; }
|
||||
nlohmann::json j;
|
||||
Json j;
|
||||
try { f >> j; } catch (const std::exception& e) {
|
||||
*err = path + ": " + e.what();
|
||||
return RAD_E_INVAL;
|
||||
|
||||
@@ -72,6 +72,9 @@ struct Engine::Rank {
|
||||
/* Where the prefill stager's ring is at the span's shared level, from the arena's base; -1
|
||||
* without that level. */
|
||||
int64_t arena_low_off = -1;
|
||||
/* Expert flex (docs/MULTIMODEL.md §6.7): address space for the slab slots the fleet may lend,
|
||||
* one slot for every expert in the pinned pool, backed from the top as the loan grows. */
|
||||
VMem xflex;
|
||||
/* Prefill stager (core/place/stager.h): copies the next routed layer's pooled experts into the
|
||||
* top of this rank's arena while a full-plan step runs the layer before. */
|
||||
PrefillStager stager;
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/* fleet/broker.h -- how an engine asks the fleet for its part of the cards (docs/MULTIMODEL.md §6.3).
|
||||
*
|
||||
* An engine in a fleet of several models does not split a card by itself: the other models hold
|
||||
* part of it, and the fleet decides who leaves to make room. Once declare has told the engine what
|
||||
* it costs, the engine asks its broker for a claim between what it cannot start without and what it
|
||||
* could use at most; the broker makes room (evicting by the fleet's policy) and grants a claim, and
|
||||
* the engine splits that claim as a one-model process splits its card (Config::vram_claim).
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
struct VramAsk {
|
||||
std::vector<int> cards; /* the engine's cards, rank i on cards[i]; the claim is per card */
|
||||
int64_t need = 0; /* the fixed part: weights, arena, queues, one full-length context */
|
||||
int64_t want = 0; /* the most the engine can use: every expert, the cache's ceiling */
|
||||
/* The cache's terms, so a broker can price a token count: kv_fixed is state no context uses,
|
||||
* (kv_ceiling - kv_fixed) pages max_seqs x max_ctx tokens, and kv_one is the cache's part of
|
||||
* `need` (kv_fixed and the pages of one full-length context). */
|
||||
int64_t kv_fixed = 0;
|
||||
int64_t kv_ceiling = 0;
|
||||
int64_t kv_one = 0;
|
||||
int64_t max_tokens = 0; /* max_seqs x max_ctx */
|
||||
int64_t experts = 0; /* the whole expert plane, 0 for a dense model */
|
||||
int64_t expert_floor = 0; /* the experts the host pool cannot hold */
|
||||
};
|
||||
|
||||
class VramBroker {
|
||||
public:
|
||||
virtual ~VramBroker() = default;
|
||||
/* Grants a claim per card of at least `ask.need`, blocking until it is free on every card of
|
||||
* the ask. The claim is at most `want` unless the model's configuration fixes it. RAD_OK with
|
||||
* *grant set, or an error with *why naming what is in the way (models that may not leave, a
|
||||
* card too small). */
|
||||
virtual int grant(const VramAsk& ask, int64_t* grant, std::string* why) = 0;
|
||||
|
||||
/* Room for `bytes` of host memory the engine will pin beyond the pools the fleet already counted
|
||||
* (the tables placed in host memory), made and waited for as for a load's pools, and counted
|
||||
* from here until the load ends. False when it cannot be had, and nothing is counted. */
|
||||
virtual bool host_room(int64_t bytes) { (void)bytes; return true; }
|
||||
/* All that is counted for this load, about to be pinned, once more. It was there when counted,
|
||||
* and the load may have waited minutes for its VRAM since. False when it cannot be had: pinning
|
||||
* anyway gets the process killed by the kernel. */
|
||||
virtual bool host_pools_room() { return true; }
|
||||
/* Host memory this engine must leave free beside what it pins: the host's floor and what other
|
||||
* loads have counted on and not pinned yet. */
|
||||
virtual int64_t host_margin() { return 0; }
|
||||
|
||||
/* ---- flex (docs/MULTIMODEL.md §6). A granted engine's cache may grow past its claim into
|
||||
* memory no model holds, and gives it back when the fleet needs it. */
|
||||
/* For the engine being granted: the most tokens its cache may grow to, 0 for none (it stays at
|
||||
* its claim), -1 for its ceiling. */
|
||||
virtual int64_t flex_kv_max_tokens() { return 0; }
|
||||
/* May `bytes` more be backed on each of `cards` now? Never evicts and never blocks; refused
|
||||
* while the fleet is making room for a load. From an engine's step loop. */
|
||||
virtual bool flex_grow(const std::vector<int>& cards, int64_t bytes) {
|
||||
(void)cards; (void)bytes; return false;
|
||||
}
|
||||
/* After every flex_grow that said yes, once the engine has backed the bytes or given up: a load
|
||||
* or restore starting meanwhile waits for granted growth to land before it reads the cards'
|
||||
* free memory, or it would plan room that the growth then takes. */
|
||||
virtual void flex_done() {}
|
||||
/* The bytes a cache on `cards` could still grow by now, for admission (KVManager::set_flex_room). */
|
||||
virtual int64_t flex_room(const std::vector<int>& cards) { (void)cards; return 0; }
|
||||
/* For the engine being granted: the most VRAM its experts may take on a card, the claim's
|
||||
* share included, as its slab grows into memory no model holds (docs/MULTIMODEL.md §6.7); 0
|
||||
* for no growth, -1 for every expert it keeps in host memory. */
|
||||
virtual int64_t flex_experts_max_bytes() { return 0; }
|
||||
};
|
||||
|
||||
} // namespace rad
|
||||
@@ -0,0 +1,971 @@
|
||||
/* fleet/config.cpp -- reading the YAML file (fleet/config.h, docs/MULTIMODEL.md §4).
|
||||
*
|
||||
* The file is parsed into a tree with locations, anchors and merge keys resolved, then walked level
|
||||
* by level. Every scalar keeps its source text, so `temp: 1.0` reaches config_parse as "1.0" and is
|
||||
* judged by the same rules as the flag was. Errors name the file and line; the first one stops the
|
||||
* load, since a later error after a misread key would only mislead.
|
||||
*/
|
||||
#include "fleet/config.h"
|
||||
#include "util/json.h"
|
||||
|
||||
#include <ryml.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cerrno>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace rad::fleet {
|
||||
|
||||
namespace {
|
||||
|
||||
/* ------------------------------------------------------------------ levels */
|
||||
|
||||
/* Options that configure the process rather than a model. They travel in every engine's flag list
|
||||
* while one process holds one listener (§5.1), so each engine reads the same values. */
|
||||
const char* const kServerKeys[] = {
|
||||
"host", "port", "api-key", "api-key-env", "allow-host", "trusted-proxy", "http-threads",
|
||||
"read-timeout", "write-timeout", "keep-alive-timeout", "max-body-mib", "retry-after", "no-cors",
|
||||
"live", "radiance-home", "kernels", "download-dir", "proceed-with-incompatible-configuration",
|
||||
"debug-accept-reference-kernels",
|
||||
};
|
||||
|
||||
/* The memory level's options: the per-card pair (gpu-memory-mib, gpu-headroom-mib) and the host
|
||||
* headroom. Under memory: they apply to every model; a model that states either half of the card
|
||||
* pair itself replaces the memory level's pair, which is how models sharing a card divide it. */
|
||||
const char* const kMemoryFlagKeys[] = { "gpu-headroom-mib", "gpu-memory-mib", "host-headroom-mib" };
|
||||
|
||||
/* Options with no YAML key: the switches the YAML spells differently, and help. */
|
||||
struct Replaced { const char* flag; const char* instead; };
|
||||
const Replaced kReplaced[] = {
|
||||
{ "served-model-name", "the entry's name under models: is the model id; add more with aliases:" },
|
||||
{ "help", "run radiance --help for the key reference" },
|
||||
{ "v", "set server.log: debug" },
|
||||
{ "vv", "set server.log: trace" },
|
||||
};
|
||||
|
||||
/* Flags given more than once on a command line; a YAML sequence repeats them. */
|
||||
const char* const kRepeatable[] = { "lora", "allow-host", "trusted-proxy" };
|
||||
|
||||
/* The fleet's own keys on a model. `defaults:` may carry every one but aliases (read_model_keys). */
|
||||
const char* const kModelFleetKeys[] = { "aliases", "priority", "pin", "ttl", "flex", "park" };
|
||||
|
||||
const char* const kTopKeys[] = { "server", "cards", "memory", "scheduler", "defaults", "models", "groups" };
|
||||
|
||||
template <size_t N>
|
||||
bool in(const char* const (&set)[N], const std::string& k) {
|
||||
for (const char* s : set)
|
||||
if (k == s) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
std::vector<std::string> as_vector(const char* const (&set)[N]) {
|
||||
return std::vector<std::string>(std::begin(set), std::end(set));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ errors */
|
||||
|
||||
/* ryml reports through callbacks that must not return. A throw carries the message out to the
|
||||
* single catch in parse(); nothing else in this file throws. */
|
||||
struct YamlError : std::runtime_error {
|
||||
size_t line;
|
||||
YamlError(const std::string& m, size_t l) : std::runtime_error(m), line(l) {}
|
||||
};
|
||||
|
||||
[[noreturn]] void on_basic(ryml::csubstr msg, ryml::ErrorDataBasic const&, void*) {
|
||||
throw YamlError(std::string(msg.str, msg.len), ryml::npos);
|
||||
}
|
||||
[[noreturn]] void on_parse(ryml::csubstr msg, ryml::ErrorDataParse const& e, void*) {
|
||||
throw YamlError(std::string(msg.str, msg.len), e.ymlloc.line);
|
||||
}
|
||||
[[noreturn]] void on_visit(ryml::csubstr msg, ryml::ErrorDataVisit const&, void*) {
|
||||
throw YamlError(std::string(msg.str, msg.len), ryml::npos);
|
||||
}
|
||||
|
||||
std::string str(ryml::csubstr s) { return std::string(s.str, s.len); }
|
||||
|
||||
size_t edit_distance(const std::string& a, const std::string& b) {
|
||||
std::vector<size_t> row(b.size() + 1);
|
||||
for (size_t j = 0; j <= b.size(); ++j) row[j] = j;
|
||||
for (size_t i = 1; i <= a.size(); ++i) {
|
||||
size_t diag = row[0];
|
||||
row[0] = i;
|
||||
for (size_t j = 1; j <= b.size(); ++j) {
|
||||
const size_t up = row[j];
|
||||
row[j] = std::min({ row[j] + 1, row[j - 1] + 1, diag + (a[i - 1] != b[j - 1]) });
|
||||
diag = up;
|
||||
}
|
||||
}
|
||||
return row[b.size()];
|
||||
}
|
||||
|
||||
/* " (did you mean X?)" when a candidate is within a third of the key's length, else "". */
|
||||
std::string suggest(const std::string& key, const std::vector<std::string>& candidates) {
|
||||
std::string best;
|
||||
size_t best_d = SIZE_MAX;
|
||||
for (const std::string& c : candidates) {
|
||||
const size_t d = edit_distance(key, c);
|
||||
if (d < best_d) { best_d = d; best = c; }
|
||||
}
|
||||
if (best.empty() || best_d > std::max<size_t>(2, key.size() / 3)) return "";
|
||||
return " (did you mean " + best + "?)";
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the walk */
|
||||
|
||||
class Reader {
|
||||
public:
|
||||
Reader(const std::string& origin, ryml::Parser& parser, const ryml::Tree& tree)
|
||||
: origin_(origin), parser_(parser), tree_(tree) {
|
||||
size_t n = 0;
|
||||
const ConfigFlag* f = config_flags(&n);
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const char* name = f[i].name;
|
||||
while (*name == '-') ++name;
|
||||
flags_[name] = &f[i];
|
||||
}
|
||||
}
|
||||
|
||||
int run(FleetConfig* out);
|
||||
|
||||
private:
|
||||
using Node = ryml::ConstNodeRef;
|
||||
|
||||
/* A key's node, the key itself, and the YAML path it was read from, e.g. "models.qwen.tp".
|
||||
* The key is kept on its own because a model id may hold dots. */
|
||||
struct Item { Node node; std::string path; std::string key; };
|
||||
|
||||
const std::string& origin_;
|
||||
ryml::Parser& parser_;
|
||||
const ryml::Tree& tree_;
|
||||
std::map<std::string, const ConfigFlag*> flags_;
|
||||
|
||||
std::vector<std::string> shared_args_; /* server flags, in file order */
|
||||
std::vector<std::string> memory_args_; /* memory flags, in file order */
|
||||
std::map<std::string, std::string> shared_given_; /* flag (with dashes) -> YAML path */
|
||||
|
||||
std::string where(Node n) const {
|
||||
const ryml::Location loc = n.location(parser_);
|
||||
if (loc.line == ryml::npos) return origin_;
|
||||
return origin_ + ":" + std::to_string(loc.line + 1);
|
||||
}
|
||||
|
||||
int fail(Node n, const std::string& msg) const {
|
||||
RAD_ERR("%s: %s", where(n).c_str(), msg.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* The map's children in order, refusing a key given twice; YAML parsers keep both silently. */
|
||||
int children(Node map, const std::string& path, std::vector<Item>* out) const {
|
||||
if (!map.is_map()) return fail(map, (path.empty() ? std::string("the file") : path) + " must be a mapping of keys");
|
||||
std::set<std::string> seen;
|
||||
for (Node c : map.children()) {
|
||||
const std::string k = str(c.key());
|
||||
if (!seen.insert(k).second)
|
||||
return fail(c, (path.empty() ? k : path + "." + k) + " is given twice");
|
||||
out->push_back({ c, path.empty() ? k : path + "." + k, k });
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
bool scalar(Node n) const { return n.has_val() && !n.is_map() && !n.is_seq(); }
|
||||
bool null_val(Node n) const { return scalar(n) && !n.is_val_quoted() && (n.val_is_null() || n.val().empty()); }
|
||||
|
||||
int scalar_text(const Item& it, std::string* out) const {
|
||||
if (!scalar(it.node)) return fail(it.node, it.path + " takes a single value");
|
||||
if (null_val(it.node)) return fail(it.node, it.path + " needs a value");
|
||||
*out = str(it.node.val());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int boolean(const Item& it, bool* out) const {
|
||||
std::string v;
|
||||
if (int s = scalar_text(it, &v); s < 0) return s;
|
||||
if (v == "true" || v == "True" || v == "TRUE") { *out = true; return RAD_OK; }
|
||||
if (v == "false" || v == "False" || v == "FALSE") { *out = false; return RAD_OK; }
|
||||
return fail(it.node, it.path + " takes true or false, not '" + v + "'");
|
||||
}
|
||||
|
||||
int integer(const Item& it, int64_t lo, int64_t hi, int64_t* out) const {
|
||||
std::string v;
|
||||
if (int s = scalar_text(it, &v); s < 0) return s;
|
||||
char* end = nullptr;
|
||||
errno = 0;
|
||||
const long long n = std::strtoll(v.c_str(), &end, 10);
|
||||
if (v.empty() || *end || errno == ERANGE)
|
||||
return fail(it.node, it.path + " takes a whole number, not '" + v + "'");
|
||||
if (n < lo || n > hi)
|
||||
return fail(it.node, it.path + " must be in [" + std::to_string(lo) + ", " + std::to_string(hi) +
|
||||
"], not " + v);
|
||||
*out = n;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int number(const Item& it, double* out) const {
|
||||
std::string v;
|
||||
if (int s = scalar_text(it, &v); s < 0) return s;
|
||||
char* end = nullptr;
|
||||
errno = 0;
|
||||
const double d = std::strtod(v.c_str(), &end);
|
||||
if (v.empty() || *end || errno == ERANGE) return fail(it.node, it.path + " takes a number, not '" + v + "'");
|
||||
*out = d;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int duration(const Item& it, int64_t* out_ms) const {
|
||||
std::string v;
|
||||
if (int s = scalar_text(it, &v); s < 0) return s;
|
||||
if (!parse_duration_ms(v, out_ms))
|
||||
return fail(it.node, it.path + " takes a duration such as 250ms, 30s, 30m or 2h, not '" + v + "'");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A YAML value as JSON: mappings and sequences recursively, plain scalars typed the way YAML's
|
||||
* core schema types them (true/false/null/numbers), everything quoted as a string. */
|
||||
rad::Json to_json(Node n) const {
|
||||
if (n.is_map()) {
|
||||
rad::Json j = rad::Json::object();
|
||||
for (Node c : n.children()) j[str(c.key())] = to_json(c);
|
||||
return j;
|
||||
}
|
||||
if (n.is_seq()) {
|
||||
rad::Json j = rad::Json::array();
|
||||
for (Node c : n.children()) j.push_back(to_json(c));
|
||||
return j;
|
||||
}
|
||||
const std::string v = str(n.val());
|
||||
if (n.is_val_quoted()) return v;
|
||||
if (n.val_is_null() || v.empty() || v == "~" || v == "null") return nullptr;
|
||||
if (v == "true") return true;
|
||||
if (v == "false") return false;
|
||||
char* end = nullptr;
|
||||
errno = 0;
|
||||
const long long i = std::strtoll(v.c_str(), &end, 10);
|
||||
if (!*end && errno != ERANGE) return i;
|
||||
const double d = std::strtod(v.c_str(), &end);
|
||||
if (!*end && errno != ERANGE) return d;
|
||||
return v;
|
||||
}
|
||||
|
||||
/* `c`, an entry of a sequence value or a member of a mapping one, as flag text: the entry
|
||||
* itself, or KEY=VALUE. `what` names the children in the refusal. */
|
||||
int child_text(const Item& it, Node c, const char* what, std::string* out) const {
|
||||
if (!scalar(c) || null_val(c)) return fail(c, it.path + " " + what + " must be single values");
|
||||
*out = it.node.is_map() ? str(c.key()) + "=" + str(c.val()) : str(c.val());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One option key as flag arguments, appended to *out. The placeholder in the flag table says
|
||||
* how a structured value is spelled: LIST joins a sequence with commas, MAP joins a mapping as
|
||||
* KEY=VALUE pairs, JSON takes a mapping or sequence as JSON text, and repeatable flags repeat. */
|
||||
int flag_args(const Item& it, std::vector<std::string>* out) const {
|
||||
const ConfigFlag* f = flags_.at(it.key);
|
||||
const std::string flag = f->name;
|
||||
const std::string arg = f->arg ? f->arg : "";
|
||||
const bool structured = it.node.is_seq() || it.node.is_map();
|
||||
if (!f->arg) {
|
||||
bool on = false;
|
||||
if (int s = boolean(it, &on); s < 0) return s;
|
||||
if (on) out->push_back(flag);
|
||||
return RAD_OK;
|
||||
}
|
||||
if (in(kRepeatable, it.key) && structured) {
|
||||
for (Node c : it.node.children()) {
|
||||
std::string v;
|
||||
if (int s = child_text(it, c, "entries", &v); s < 0) return s;
|
||||
out->push_back(flag);
|
||||
out->push_back(v);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
std::string v;
|
||||
if (arg == "JSON" && structured) {
|
||||
v = to_json(it.node).dump();
|
||||
} else if ((arg == "LIST" && it.node.is_seq()) || (arg == "MAP" && it.node.is_map())) {
|
||||
for (Node c : it.node.children()) {
|
||||
std::string one;
|
||||
if (int s = child_text(it, c, arg == "MAP" ? "values" : "entries", &one); s < 0) return s;
|
||||
v += (v.empty() ? "" : ",") + one;
|
||||
}
|
||||
} else if (int s = scalar_text(it, &v); s < 0) {
|
||||
return s;
|
||||
}
|
||||
out->push_back(flag);
|
||||
out->push_back(v);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Where a key that is not valid here belongs, or why it does not exist. */
|
||||
std::string misplaced(const std::string& key, const std::string& level) const {
|
||||
for (const Replaced& r : kReplaced)
|
||||
if (key == r.flag) return key + " is not a key: " + r.instead;
|
||||
if (level != "server" && (in(kServerKeys, key) || key == "log")) return key + " belongs under server:";
|
||||
if (level != "memory" && level != "model" && in(kMemoryFlagKeys, key))
|
||||
return key + " belongs under memory: or a model";
|
||||
if (level != "memory" && (key == "host-mib" || key == "disk-tier"))
|
||||
return key + " belongs under memory:";
|
||||
if (level != "model" && flags_.count(key))
|
||||
return key + " is a per-model key; put it under the model or defaults:";
|
||||
return "";
|
||||
}
|
||||
|
||||
/* A key `level` does not take: where it belongs, else "PATH is not a NOUN key" with the
|
||||
* closest of the keys the level does take. */
|
||||
int refuse_key(const Item& it, const std::string& level, const std::string& noun,
|
||||
const std::vector<std::string>& valid) const {
|
||||
std::string m = misplaced(it.key, level);
|
||||
if (m.empty()) m = it.path + " is not a " + noun + " key" + suggest(it.key, valid);
|
||||
return fail(it.node, m);
|
||||
}
|
||||
|
||||
std::vector<std::string> model_key_names() const {
|
||||
std::vector<std::string> v;
|
||||
for (const auto& [k, f] : flags_)
|
||||
if (misplaced(k, "model").empty()) v.push_back(k);
|
||||
for (const char* k : kModelFleetKeys) v.push_back(k);
|
||||
return v;
|
||||
}
|
||||
|
||||
int read_server(const Item& sec, FleetConfig* out);
|
||||
int read_memory(const Item& sec, FleetConfig* out);
|
||||
int read_scheduler(const Item& sec, FleetConfig* out);
|
||||
int read_cards(const Item& sec, FleetConfig* out);
|
||||
int read_groups(const Item& sec, FleetConfig* out);
|
||||
int read_model_keys(const Item& sec, bool is_defaults, std::vector<Item>* out);
|
||||
int read_fleet_key(const Item& it, ModelEntry* e);
|
||||
int build_model(const std::string& name, Node at, const std::vector<Item>& keys, ModelEntry* e);
|
||||
};
|
||||
|
||||
int Reader::read_server(const Item& sec, FleetConfig* out) {
|
||||
std::vector<Item> items;
|
||||
if (int s = children(sec.node, sec.path, &items); s < 0) return s;
|
||||
for (const Item& it : items) {
|
||||
const std::string& k = it.key;
|
||||
if (k == "log") {
|
||||
std::string v;
|
||||
if (int s = scalar_text(it, &v); s < 0) return s;
|
||||
if (v == "info") out->log = Log::Info;
|
||||
else if (v == "debug") out->log = Log::Debug;
|
||||
else if (v == "trace") out->log = Log::Trace;
|
||||
else return fail(it.node, "server.log takes info, debug or trace, not '" + v + "'");
|
||||
out->log_set = true;
|
||||
continue;
|
||||
}
|
||||
if (!in(kServerKeys, k)) {
|
||||
std::vector<std::string> valid = as_vector(kServerKeys);
|
||||
valid.push_back("log");
|
||||
return refuse_key(it, "server", "server", valid);
|
||||
}
|
||||
if (int s = flag_args(it, &shared_args_); s < 0) return s;
|
||||
shared_given_[flags_.at(k)->name] = it.path;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Reader::read_memory(const Item& sec, FleetConfig* out) {
|
||||
std::vector<Item> items;
|
||||
if (int s = children(sec.node, sec.path, &items); s < 0) return s;
|
||||
for (const Item& it : items) {
|
||||
const std::string& k = it.key;
|
||||
if (k == "host-mib") {
|
||||
if (int s = integer(it, 1, INT64_MAX / (1 << 20), &out->host_mib); s < 0) return s;
|
||||
continue;
|
||||
}
|
||||
if (k == "disk-tier") {
|
||||
if (int s = scalar_text(it, &out->disk_tier); s < 0) return s;
|
||||
continue;
|
||||
}
|
||||
if (!in(kMemoryFlagKeys, k)) {
|
||||
std::vector<std::string> valid = as_vector(kMemoryFlagKeys);
|
||||
valid.push_back("host-mib");
|
||||
valid.push_back("disk-tier");
|
||||
return refuse_key(it, "memory", "memory", valid);
|
||||
}
|
||||
if (int s = flag_args(it, &memory_args_); s < 0) return s;
|
||||
shared_given_[flags_.at(k)->name] = it.path;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Reader::read_scheduler(const Item& sec, FleetConfig* out) {
|
||||
std::vector<Item> items;
|
||||
if (int s = children(sec.node, sec.path, &items); s < 0) return s;
|
||||
for (const Item& it : items) {
|
||||
const std::string& k = it.key;
|
||||
int s = RAD_OK;
|
||||
if (k == "load-timeout") s = duration(it, &out->load_timeout_ms);
|
||||
else if (k == "drain-timeout") s = duration(it, &out->drain_timeout_ms);
|
||||
else if (k == "keepalive") s = duration(it, &out->keepalive_ms);
|
||||
else if (k == "warm-up") s = boolean(it, &out->warm_up);
|
||||
else {
|
||||
return fail(it.node, "scheduler." + k + " is not a scheduler key" +
|
||||
suggest(k, { "load-timeout", "drain-timeout", "keepalive", "warm-up" }));
|
||||
}
|
||||
if (s < 0) return s;
|
||||
}
|
||||
if (out->keepalive_ms <= 0) return fail(sec.node, "scheduler.keepalive must be above zero");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Reader::read_cards(const Item& sec, FleetConfig* out) {
|
||||
if (scalar(sec.node) && str(sec.node.val()) == "all") return RAD_OK;
|
||||
if (!sec.node.is_seq() || sec.node.num_children() == 0)
|
||||
return fail(sec.node, "cards takes all or a list of card indices");
|
||||
std::set<int64_t> seen;
|
||||
for (Node c : sec.node.children()) {
|
||||
int64_t idx = 0;
|
||||
if (int s = integer({ c, sec.path, "cards" }, 0, 63, &idx); s < 0) return s;
|
||||
if (!seen.insert(idx).second) return fail(c, "card " + std::to_string(idx) + " is listed twice");
|
||||
out->cards.push_back((int)idx);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Reader::read_groups(const Item& sec, FleetConfig* out) {
|
||||
std::vector<Item> items;
|
||||
if (int s = children(sec.node, sec.path, &items); s < 0) return s;
|
||||
for (const Item& it : items) {
|
||||
std::vector<Item> kinds;
|
||||
if (int s = children(it.node, it.path, &kinds); s < 0) return s;
|
||||
if (kinds.size() != 1)
|
||||
return fail(it.node, it.path + " takes exactly one of together: or exclusive:");
|
||||
const Item& k = kinds[0];
|
||||
Group g;
|
||||
g.name = it.key;
|
||||
const std::string& kind = k.key;
|
||||
if (kind == "together") g.kind = Group::Kind::Together;
|
||||
else if (kind == "exclusive") g.kind = Group::Kind::Exclusive;
|
||||
else return fail(k.node, k.path + ": a group is together: or exclusive:" + suggest(kind, { "together", "exclusive" }));
|
||||
if (!k.node.is_seq() || k.node.num_children() < 2)
|
||||
return fail(k.node, k.path + " takes a list of at least two models");
|
||||
for (Node m : k.node.children()) {
|
||||
if (!scalar(m) || null_val(m)) return fail(m, k.path + " entries are model names");
|
||||
const std::string name = str(m.val());
|
||||
if (std::find(g.members.begin(), g.members.end(), name) != g.members.end())
|
||||
return fail(m, k.path + " lists " + name + " twice");
|
||||
g.members.push_back(name);
|
||||
}
|
||||
out->groups.push_back(std::move(g));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A model's (or the defaults') keys, checked against the levels; option values are read later. */
|
||||
int Reader::read_model_keys(const Item& sec, bool is_defaults, std::vector<Item>* out) {
|
||||
if (int s = children(sec.node, sec.path, out); s < 0) return s;
|
||||
for (const Item& it : *out) {
|
||||
const std::string& k = it.key;
|
||||
if (in(kModelFleetKeys, k)) {
|
||||
if (is_defaults && k == "aliases") return fail(it.node, "aliases name one model; they cannot be a default");
|
||||
continue;
|
||||
}
|
||||
std::string m = misplaced(k, "model");
|
||||
if (!m.empty()) return fail(it.node, m);
|
||||
if (!flags_.count(k)) return fail(it.node, it.path + " is not a key" + suggest(k, model_key_names()));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Reader::read_fleet_key(const Item& it, ModelEntry* e) {
|
||||
const std::string& k = it.key;
|
||||
if (k == "aliases") {
|
||||
std::vector<Node> names;
|
||||
if (scalar(it.node)) names.push_back(it.node);
|
||||
else if (it.node.is_seq()) for (Node c : it.node.children()) names.push_back(c);
|
||||
else return fail(it.node, it.path + " takes a name or a list of names");
|
||||
for (Node n : names) {
|
||||
if (!scalar(n) || null_val(n)) return fail(n, it.path + " entries are names");
|
||||
e->aliases.push_back(str(n.val()));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
if (k == "priority") {
|
||||
int64_t p = 0;
|
||||
if (int s = integer(it, -1000000, 1000000, &p); s < 0) return s;
|
||||
e->priority = (int)p;
|
||||
return RAD_OK;
|
||||
}
|
||||
if (k == "pin") return boolean(it, &e->pin);
|
||||
if (k == "ttl") return duration(it, &e->ttl_ms);
|
||||
if (k == "flex") {
|
||||
std::vector<Item> parts;
|
||||
if (int s = children(it.node, it.path, &parts); s < 0) return s;
|
||||
for (const Item& p : parts) {
|
||||
const std::string& pk = p.key;
|
||||
std::vector<Item> fields;
|
||||
if (pk != "kv" && pk != "experts")
|
||||
return fail(p.node, p.path + ": flex has kv: and experts:" + suggest(pk, { "kv", "experts" }));
|
||||
if (int s = children(p.node, p.path, &fields); s < 0) return s;
|
||||
for (const Item& f : fields) {
|
||||
const std::string& fk = f.key;
|
||||
int s = RAD_OK;
|
||||
if (pk == "kv" && fk == "min-tokens") s = integer(f, 1, INT64_MAX, &e->flex.kv_min_tokens);
|
||||
else if (pk == "kv" && fk == "max-tokens") s = integer(f, 1, INT64_MAX, &e->flex.kv_max_tokens);
|
||||
else if (pk == "kv" && fk == "weight") {
|
||||
if ((s = number(f, &e->flex.kv_weight)) == RAD_OK && !(e->flex.kv_weight > 0))
|
||||
return fail(f.node, f.path + " must be above zero");
|
||||
}
|
||||
else if (pk == "experts" && fk == "min-mib") s = integer(f, 0, INT64_MAX, &e->flex.experts_min_mib);
|
||||
else if (pk == "experts" && fk == "max-mib") s = integer(f, 0, INT64_MAX, &e->flex.experts_max_mib);
|
||||
else {
|
||||
const std::vector<std::string> c = pk == "kv"
|
||||
? std::vector<std::string>{ "min-tokens", "max-tokens", "weight" }
|
||||
: std::vector<std::string>{ "min-mib", "max-mib" };
|
||||
return fail(f.node, f.path + " is not a key" + suggest(fk, c));
|
||||
}
|
||||
if (s < 0) return s;
|
||||
}
|
||||
}
|
||||
if (e->flex.kv_min_tokens > 0 && e->flex.kv_max_tokens > 0 && e->flex.kv_min_tokens > e->flex.kv_max_tokens)
|
||||
return fail(it.node, it.path + ".kv: min-tokens is above max-tokens");
|
||||
if (e->flex.experts_min_mib >= 0 && e->flex.experts_max_mib > 0 && e->flex.experts_min_mib > e->flex.experts_max_mib)
|
||||
return fail(it.node, it.path + ".experts: min-mib is above max-mib");
|
||||
return RAD_OK;
|
||||
}
|
||||
if (k == "park") {
|
||||
std::vector<Item> fields;
|
||||
if (int s = children(it.node, it.path, &fields); s < 0) return s;
|
||||
for (const Item& f : fields) {
|
||||
const std::string& fk = f.key;
|
||||
std::string v;
|
||||
if (fk != "vram" && fk != "ram" && fk != "restore")
|
||||
return fail(f.node, f.path + ": park has vram:, ram: and restore:" +
|
||||
suggest(fk, { "vram", "ram", "restore" }));
|
||||
if (int s = scalar_text(f, &v); s < 0) return s;
|
||||
if (fk == "vram") {
|
||||
if (v == "none") e->park.vram = ParkSpec::Vram::None;
|
||||
else if (v == "statics") e->park.vram = ParkSpec::Vram::Statics;
|
||||
else {
|
||||
int64_t mib = 0;
|
||||
if (integer(f, 1, INT64_MAX, &mib) < 0)
|
||||
return fail(f.node, f.path + " takes none, statics or a size in MiB");
|
||||
e->park.vram = ParkSpec::Vram::Mib;
|
||||
e->park.vram_mib = mib;
|
||||
}
|
||||
} else if (fk == "restore") {
|
||||
if (v == "auto") e->park.restore = ParkSpec::Restore::Auto;
|
||||
else if (v == "full") e->park.restore = ParkSpec::Restore::Full;
|
||||
else if (v == "live") e->park.restore = ParkSpec::Restore::Live;
|
||||
else return fail(f.node, f.path + " takes auto, full or live, not '" + v + "'");
|
||||
} else {
|
||||
if (v == "required") e->park.ram = ParkSpec::Ram::Required;
|
||||
else if (v == "allowed") e->park.ram = ParkSpec::Ram::Allowed;
|
||||
else if (v == "never") e->park.ram = ParkSpec::Ram::Never;
|
||||
else return fail(f.node, f.path + " takes required, allowed or never, not '" + v + "'");
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* `keys` is the defaults with the model's own keys over them. */
|
||||
int Reader::build_model(const std::string& name, Node at, const std::vector<Item>& keys, ModelEntry* e) {
|
||||
e->name = name;
|
||||
std::vector<const Item*> options;
|
||||
for (const Item& it : keys) {
|
||||
if (!in(kModelFleetKeys, it.key)) options.push_back(&it);
|
||||
else if (int s = read_fleet_key(it, e); s < 0) return s;
|
||||
}
|
||||
std::sort(options.begin(), options.end(),
|
||||
[](const Item* a, const Item* b) { return a->key < b->key; });
|
||||
|
||||
/* A model stating either half of the card pair replaces the memory level's pair. */
|
||||
bool own_card = false;
|
||||
for (const Item* it : options) own_card |= it->key == "gpu-memory-mib" || it->key == "gpu-headroom-mib";
|
||||
std::vector<std::string> args = shared_args_;
|
||||
std::map<std::string, std::string> given = shared_given_;
|
||||
for (size_t i = 0; i < memory_args_.size();) {
|
||||
const std::string& f = memory_args_[i];
|
||||
const bool takes = flags_.at(f.substr(2))->arg != nullptr;
|
||||
const size_t n = takes ? 2 : 1;
|
||||
if (own_card && (f == "--gpu-memory-mib" || f == "--gpu-headroom-mib")) given.erase(f);
|
||||
else args.insert(args.end(), memory_args_.begin() + (long)i, memory_args_.begin() + (long)(i + n));
|
||||
i += n;
|
||||
}
|
||||
args.push_back("--served-model-name");
|
||||
args.push_back(name);
|
||||
given["--served-model-name"] = "models." + name;
|
||||
for (const Item* it : options) {
|
||||
if (int s = flag_args(*it, &args); s < 0) return s;
|
||||
given[flags_.at(it->key)->name] = it->path;
|
||||
}
|
||||
|
||||
std::vector<std::string> argv_store{ "radiance" };
|
||||
argv_store.insert(argv_store.end(), args.begin(), args.end());
|
||||
std::vector<char*> argv;
|
||||
for (std::string& a : argv_store) argv.push_back(a.data());
|
||||
argv.push_back(nullptr);
|
||||
Config cfg;
|
||||
if (config_parse((int)argv_store.size(), argv.data(), &cfg) != RAD_OK) {
|
||||
return fail(at, "models." + name + " refused by the line above (YAML keys are the options it names, "
|
||||
"without the leading --)");
|
||||
}
|
||||
/* config_parse records every option it read as given on the command line; they came from the
|
||||
* file, so each takes its YAML path. Options it filled from the environment keep that source. */
|
||||
for (auto& [flag, src] : cfg.given) {
|
||||
auto g = given.find(flag);
|
||||
if (g != given.end() && src == "command line") src = g->second;
|
||||
}
|
||||
e->args = std::move(args);
|
||||
e->cfg = std::move(cfg);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
bool valid_name(const std::string& n) {
|
||||
if (n.empty()) return false;
|
||||
for (unsigned char ch : n)
|
||||
if (ch == ':' || std::isspace(ch) || std::iscntrl(ch)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
int Reader::run(FleetConfig* out) {
|
||||
std::vector<Item> top;
|
||||
const Node root = tree_.crootref();
|
||||
if (root.is_stream() && root.num_children() != 1)
|
||||
return fail(root, "the file must hold exactly one YAML document");
|
||||
const Node doc = root.is_stream() ? root.first_child() : root;
|
||||
if (int s = children(doc, "", &top); s < 0) return s;
|
||||
|
||||
const Item* defaults = nullptr;
|
||||
const Item* models = nullptr;
|
||||
for (const Item& it : top) {
|
||||
const std::string& k = it.key;
|
||||
int s = RAD_OK;
|
||||
if (k == "server") s = read_server(it, out);
|
||||
else if (k == "memory") s = read_memory(it, out);
|
||||
else if (k == "scheduler") s = read_scheduler(it, out);
|
||||
else if (k == "cards") s = read_cards(it, out);
|
||||
else if (k == "groups") s = read_groups(it, out);
|
||||
else if (k == "defaults") defaults = ⁢
|
||||
else if (k == "models") models = ⁢
|
||||
else if (k.rfind("x-", 0) == 0) continue;
|
||||
else return refuse_key(it, "top", "top-level", as_vector(kTopKeys));
|
||||
if (s < 0) return s;
|
||||
}
|
||||
if (!models) return fail(doc, "no models: section; the file must name at least one model");
|
||||
|
||||
std::vector<Item> base;
|
||||
if (defaults)
|
||||
if (int s = read_model_keys(*defaults, true, &base); s < 0) return s;
|
||||
|
||||
std::vector<Item> entries;
|
||||
if (int s = children(models->node, models->path, &entries); s < 0) return s;
|
||||
if (entries.empty()) return fail(models->node, "models: names no model");
|
||||
|
||||
std::map<std::string, std::string> taken; /* name or alias -> the model it names */
|
||||
for (const Item& ent : entries) {
|
||||
const std::string& name = ent.key;
|
||||
if (!valid_name(name))
|
||||
return fail(ent.node, "'" + name + "' cannot be a model id: ids are non-empty and hold no ':' "
|
||||
"(reserved for base:adapter) and no whitespace");
|
||||
std::vector<Item> own;
|
||||
if (int s = read_model_keys(ent, false, &own); s < 0) return s;
|
||||
std::vector<Item> merged;
|
||||
for (const Item& d : base)
|
||||
if (std::none_of(own.begin(), own.end(), [&](const Item& o) { return o.key == d.key; }))
|
||||
merged.push_back(d);
|
||||
merged.insert(merged.end(), own.begin(), own.end());
|
||||
|
||||
ModelEntry e;
|
||||
if (int s = build_model(name, ent.node, merged, &e); s < 0) return s;
|
||||
std::vector<std::string> ids{ name };
|
||||
ids.insert(ids.end(), e.aliases.begin(), e.aliases.end());
|
||||
for (const std::string& n : ids) {
|
||||
if (!valid_name(n))
|
||||
return fail(ent.node, "models." + name + ": alias '" + n + "' holds ':' or whitespace");
|
||||
auto [it, fresh] = taken.emplace(n, name);
|
||||
if (!fresh)
|
||||
return fail(ent.node, "models." + name + ": '" + n + "' already names model " + it->second);
|
||||
}
|
||||
out->models.push_back(std::move(e));
|
||||
}
|
||||
|
||||
std::map<std::pair<std::string, std::string>, Group::Kind> pairs;
|
||||
for (const Group& g : out->groups) {
|
||||
for (const std::string& m : g.members)
|
||||
if (const ModelEntry* me = out->find(m); !me || me->name != m)
|
||||
return fail(doc, "groups." + g.name + " names '" + m + "', which is not a model id");
|
||||
for (size_t i = 0; i < g.members.size(); ++i)
|
||||
for (size_t j = i + 1; j < g.members.size(); ++j) {
|
||||
auto key = std::minmax(g.members[i], g.members[j]);
|
||||
auto [it, fresh] = pairs.emplace(key, g.kind);
|
||||
if (!fresh && it->second != g.kind)
|
||||
return fail(doc, "groups: " + key.first + " and " + key.second +
|
||||
" are in both a together and an exclusive group");
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
const ModelEntry* FleetConfig::find(const std::string& n) const {
|
||||
for (const ModelEntry& m : models) {
|
||||
if (m.name == n) return &m;
|
||||
for (const std::string& a : m.aliases)
|
||||
if (a == n) return &m;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::vector<std::string> level_keys(const std::string& level) {
|
||||
if (level == "server") return as_vector(kServerKeys);
|
||||
if (level == "memory") return as_vector(kMemoryFlagKeys);
|
||||
return {};
|
||||
}
|
||||
|
||||
bool parse_duration_ms(const std::string& s, int64_t* out_ms) {
|
||||
size_t i = 0;
|
||||
while (i < s.size() && std::isdigit((unsigned char)s[i])) ++i;
|
||||
if (i == 0 || i > 12) return false;
|
||||
const int64_t n = std::stoll(s.substr(0, i));
|
||||
const std::string unit = s.substr(i);
|
||||
int64_t mul = 0;
|
||||
if (unit == "ms") mul = 1;
|
||||
else if (unit == "s" || unit.empty()) mul = 1000;
|
||||
else if (unit == "m") mul = 60 * 1000;
|
||||
else if (unit == "h") mul = 3600 * 1000;
|
||||
else return false;
|
||||
*out_ms = n * mul;
|
||||
return true;
|
||||
}
|
||||
|
||||
int parse(const std::string& text, const std::string& origin, FleetConfig* out) {
|
||||
ryml::Callbacks cb;
|
||||
cb.set_error_basic(&on_basic).set_error_parse(&on_parse).set_error_visit(&on_visit);
|
||||
FleetConfig fc;
|
||||
fc.path = origin;
|
||||
try {
|
||||
ryml::EventHandlerTree handler(cb);
|
||||
ryml::Parser parser(&handler, ryml::ParserOptions().locations(true));
|
||||
ryml::Tree tree(cb);
|
||||
ryml::parse_in_arena(&parser, ryml::to_csubstr(origin), ryml::to_csubstr(text), &tree);
|
||||
/* Anchors, aliases and `<<` merge keys, so a file can share a block between models. */
|
||||
tree.resolve();
|
||||
if (tree.empty() || !tree.crootref().has_children()) {
|
||||
RAD_ERR("%s: the file is empty; it must name at least one model under models:", origin.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
Reader r(origin, parser, tree);
|
||||
if (int s = r.run(&fc); s < 0) return s;
|
||||
} catch (const YamlError& e) {
|
||||
if (e.line != ryml::npos) RAD_ERR("%s:%zu: %s", origin.c_str(), e.line + 1, e.what());
|
||||
else RAD_ERR("%s: %s", origin.c_str(), e.what());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
*out = std::move(fc);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int load(const std::string& path, FleetConfig* out) {
|
||||
std::ifstream f(path, std::ios::binary);
|
||||
if (!f) {
|
||||
RAD_ERR("%s: cannot read the configuration: %s", path.c_str(), std::strerror(errno));
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
std::ostringstream ss;
|
||||
ss << f.rdbuf();
|
||||
return parse(ss.str(), path, out);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the key reference */
|
||||
|
||||
namespace {
|
||||
|
||||
void print_keys(FILE* to, const std::vector<const ConfigFlag*>& flags, const char* indent) {
|
||||
for (const ConfigFlag* f : flags) {
|
||||
const char* name = f->name;
|
||||
while (*name == '-') ++name;
|
||||
char left[64];
|
||||
snprintf(left, sizeof left, "%s%s: %s", indent, name, f->arg ? f->arg : "true|false");
|
||||
std::string help;
|
||||
for (const char* p = f->help; *p; ++p) {
|
||||
help += *p;
|
||||
if (*p != '\n') continue;
|
||||
help.append(39, ' ');
|
||||
while (p[1] == ' ') ++p;
|
||||
}
|
||||
fprintf(to, "%-38s %s\n", left, help.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void print_reference(FILE* to) {
|
||||
size_t n = 0;
|
||||
const ConfigFlag* f = config_flags(&n);
|
||||
std::vector<const ConfigFlag*> server, memory, model;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const char* name = f[i].name;
|
||||
while (*name == '-') ++name;
|
||||
bool replaced = false;
|
||||
for (const Replaced& r : kReplaced) replaced |= !std::strcmp(name, r.flag);
|
||||
if (replaced) continue;
|
||||
if (in(kServerKeys, name)) server.push_back(&f[i]);
|
||||
else if (in(kMemoryFlagKeys, name)) memory.push_back(&f[i]);
|
||||
else model.push_back(&f[i]);
|
||||
}
|
||||
fprintf(to,
|
||||
"usage: radiance --config FILE [--check]\n"
|
||||
"\n"
|
||||
" --config FILE the YAML file naming every model this process serves (docs/MULTIMODEL.md)\n"
|
||||
" --check read and validate the file, print what it configures, serve nothing\n"
|
||||
"\n"
|
||||
"The file's levels, and the keys each takes:\n\n"
|
||||
"server:\n"
|
||||
" log: info|debug|trace the log level\n");
|
||||
print_keys(to, server, " ");
|
||||
fprintf(to,
|
||||
"\ncards: all | [N, ...] the cards models may use\n"
|
||||
"\nmemory:\n"
|
||||
" host-mib: N pinned host RAM the process may hold\n"
|
||||
" disk-tier: DIR the prefix-cache disk tier and park files\n");
|
||||
print_keys(to, memory, " ");
|
||||
fprintf(to,
|
||||
"\nscheduler:\n"
|
||||
" load-timeout: DURATION how long a request waits for its model (default 120s)\n"
|
||||
" drain-timeout: DURATION how long a model being evicted may finish requests (30s)\n"
|
||||
" keepalive: DURATION SSE comment interval while a request waits (10s)\n"
|
||||
" warm-up: true|false fill free VRAM, then host RAM, with models at start (true)\n"
|
||||
"\ndefaults: any model key, merged under every model\n"
|
||||
"\nmodels:\n"
|
||||
" NAME: the model id requests name\n"
|
||||
" aliases: [NAME, ...] more ids for this model\n"
|
||||
" priority: N higher keeps VRAM and takes flex from lower\n"
|
||||
" pin: true|false never leaves VRAM\n"
|
||||
" ttl: DURATION park after this long without requests\n"
|
||||
" flex: {kv: {min-tokens, max-tokens, weight}, experts: {min-mib, max-mib}}\n"
|
||||
" park: {vram: none|statics|MIB, ram: required|allowed|never, restore: auto|full|live}\n");
|
||||
print_keys(to, model, " ");
|
||||
fprintf(to,
|
||||
"\ngroups:\n"
|
||||
" NAME: {together: [A, B, ...]} loaded and parked together\n"
|
||||
" NAME: {exclusive: [A, B, ...]} never resident at the same time\n"
|
||||
"\nDurations are 250ms, 30s, 30m or 2h. Top-level keys starting with x- are ignored.\n");
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the migration hint */
|
||||
|
||||
namespace {
|
||||
|
||||
/* Plain when YAML would read it back as the same string, double-quoted otherwise. */
|
||||
std::string yaml_scalar(const std::string& v) {
|
||||
bool plain = !v.empty();
|
||||
for (unsigned char ch : v)
|
||||
if (!(std::isalnum(ch) || ch == '_' || ch == '.' || ch == '/' || ch == '-' || ch == '+' || ch == '='))
|
||||
plain = false;
|
||||
if (plain && (v[0] == '-' || v == "true" || v == "false" || v == "null")) plain = false;
|
||||
if (plain) return v;
|
||||
std::string q = "\"";
|
||||
/* A double-quoted scalar folds a raw line break into a space: control characters go escaped. */
|
||||
for (char ch : v) {
|
||||
if (ch == '\n') q += "\\n";
|
||||
else if (ch == '\t') q += "\\t";
|
||||
else if (ch == '\r') q += "\\r";
|
||||
else {
|
||||
if (ch == '"' || ch == '\\') q += '\\';
|
||||
q += ch;
|
||||
}
|
||||
}
|
||||
return q + "\"";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string yaml_from_args(int argc, char** argv) {
|
||||
size_t n = 0;
|
||||
const ConfigFlag* f = config_flags(&n);
|
||||
std::map<std::string, const ConfigFlag*> table;
|
||||
for (size_t i = 0; i < n; ++i) table[f[i].name] = &f[i];
|
||||
|
||||
struct Kv { std::string key; std::vector<std::string> vals; bool sw = false; bool json = false; };
|
||||
std::vector<Kv> server, memory, model;
|
||||
std::string name, log;
|
||||
auto put = [](std::vector<Kv>& to, const std::string& k, const std::string* v) {
|
||||
for (Kv& e : to)
|
||||
if (e.key == k) { if (v) e.vals.push_back(*v); return; }
|
||||
to.push_back({ k, v ? std::vector<std::string>{ *v } : std::vector<std::string>{}, v == nullptr });
|
||||
};
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string a = argv[i];
|
||||
if (a == "-v") { log = "debug"; continue; }
|
||||
if (a == "-vv") { log = "trace"; continue; }
|
||||
auto t = table.find(a);
|
||||
if (t == table.end()) {
|
||||
/* Not an option: written as a model key anyway, so loading the file refuses it by name
|
||||
* (with the closest key) instead of the setting vanishing. */
|
||||
if (a.size() > 2 && a.compare(0, 2, "--") == 0) {
|
||||
const bool has_val = i + 1 < argc && std::strncmp(argv[i + 1], "--", 2) != 0;
|
||||
const std::string v = has_val ? argv[++i] : std::string("true");
|
||||
put(model, a.substr(2), &v);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const std::string key = a.substr(2);
|
||||
std::string v;
|
||||
if (t->second->arg) {
|
||||
if (i + 1 >= argc) break;
|
||||
v = argv[++i];
|
||||
}
|
||||
if (key == "served-model-name") { name = v; continue; }
|
||||
std::vector<Kv>& to = in(kServerKeys, key) ? server : in(kMemoryFlagKeys, key) ? memory : model;
|
||||
put(to, key, t->second->arg ? &v : nullptr);
|
||||
/* JSON is YAML's flow style, so a JSON argument is written as it stands, unquoted. */
|
||||
if (t->second->arg && !std::strcmp(t->second->arg, "JSON")) {
|
||||
const rad::Json j = rad::Json::parse(v, nullptr, false);
|
||||
if (!j.is_discarded() && j.is_structured())
|
||||
for (Kv& e : to)
|
||||
if (e.key == key) e.json = true;
|
||||
}
|
||||
}
|
||||
if (name.empty()) {
|
||||
for (const Kv& e : model)
|
||||
if (e.key == "model" && !e.vals.empty()) {
|
||||
std::string m = e.vals[0];
|
||||
while (!m.empty() && m.back() == '/') m.pop_back();
|
||||
const size_t slash = m.rfind('/');
|
||||
if (slash != std::string::npos) m = m.substr(slash + 1);
|
||||
/* Only a container's extension goes: a checkpoint directory or repo name such as
|
||||
* Qwen3.8-27B-FP8 keeps its dots. */
|
||||
if (m.size() > 4 && m.compare(m.size() - 4, 4, ".rad") == 0) m.resize(m.size() - 4);
|
||||
name = m;
|
||||
}
|
||||
}
|
||||
if (!valid_name(name)) name = "default";
|
||||
|
||||
std::string y;
|
||||
auto emit = [&](const std::vector<Kv>& kvs, const char* indent) {
|
||||
for (const Kv& e : kvs) {
|
||||
if (e.sw) { y += std::string(indent) + e.key + ": true\n"; continue; }
|
||||
if (e.json && e.vals.size() == 1) {
|
||||
y += std::string(indent) + e.key + ": " + rad::Json::parse(e.vals[0]).dump() + "\n";
|
||||
continue;
|
||||
}
|
||||
if (e.vals.size() == 1) { y += std::string(indent) + e.key + ": " + yaml_scalar(e.vals[0]) + "\n"; continue; }
|
||||
y += std::string(indent) + e.key + ":\n";
|
||||
for (const std::string& v : e.vals) y += std::string(indent) + " - " + yaml_scalar(v) + "\n";
|
||||
}
|
||||
};
|
||||
if (!server.empty() || !log.empty()) {
|
||||
y += "server:\n";
|
||||
if (!log.empty()) y += " log: " + log + "\n";
|
||||
emit(server, " ");
|
||||
}
|
||||
if (!memory.empty()) {
|
||||
y += "memory:\n";
|
||||
emit(memory, " ");
|
||||
}
|
||||
y += "models:\n " + yaml_scalar(name) + ":\n";
|
||||
emit(model, " ");
|
||||
return y;
|
||||
}
|
||||
|
||||
} // namespace rad::fleet
|
||||
@@ -0,0 +1,141 @@
|
||||
/* fleet/config.h -- the YAML file that configures a radiance process (docs/MULTIMODEL.md §4).
|
||||
*
|
||||
* One file names every model the process serves and the settings they share. Each former command
|
||||
* line flag is a key with the same name and no leading dashes, at the level it belongs to:
|
||||
*
|
||||
* server: the listener, authentication, logging and plugin search path (§4.3)
|
||||
* cards: the cards models may use
|
||||
* memory: per-card VRAM headroom and the host budgets
|
||||
* scheduler: load and drain timeouts, the keepalive interval
|
||||
* defaults: per-model keys merged under every model
|
||||
* models: one entry per model, keyed by its id
|
||||
* groups: together / exclusive co-residency rules
|
||||
*
|
||||
* Top-level keys that start with `x-` are ignored, so a file can keep anchors there and merge them
|
||||
* into models with `<<: *name`.
|
||||
*
|
||||
* A model's keys are turned back into the flag list config_parse reads, so a key and its flag are
|
||||
* validated by the same code and cannot drift. The loader adds only what the flag table cannot
|
||||
* express: levels, the defaults merge, the fleet's own keys, and provenance (which YAML path set
|
||||
* each option, for the startup report).
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad::fleet {
|
||||
|
||||
/* A model's share of the card's flex pool above its fixed part (§6.3). -1 is "not set": the
|
||||
* floor defaults to one sequence at the model's context bound and the ceiling to everything the
|
||||
* card can lend. */
|
||||
struct FlexSpec {
|
||||
int64_t kv_min_tokens = -1;
|
||||
int64_t kv_max_tokens = -1;
|
||||
double kv_weight = 1.0;
|
||||
int64_t experts_min_mib = -1;
|
||||
int64_t experts_max_mib = -1;
|
||||
|
||||
bool operator==(const FlexSpec&) const = default;
|
||||
};
|
||||
|
||||
/* What a parked model keeps (§7.2). */
|
||||
struct ParkSpec {
|
||||
enum class Vram { None, Statics, Mib };
|
||||
enum class Ram { Required, Allowed, Never };
|
||||
/* How it comes back from host memory: every byte onto the card before it serves, or serving
|
||||
* at once with the rest read in place over the link while it moves (dev_page_in_live). Live
|
||||
* suits a model whose steps read a small part of what is parked (a tiered MoE's experts) or
|
||||
* that computes long per byte read; a dense model decoding reads all of it every step, so its
|
||||
* reads share the link with the move and both run slower (docs/MULTIMODEL.md §7.4). Auto is
|
||||
* Full, except that a one-step model (an embedding program) whose cards lack the room for all
|
||||
* of it serves at once with its weights read in place until free memory takes them (§7.5). */
|
||||
enum class Restore { Auto, Full, Live };
|
||||
Vram vram = Vram::None;
|
||||
int64_t vram_mib = 0; /* with Vram::Mib: the head of the first-use order kept */
|
||||
Ram ram = Ram::Allowed;
|
||||
Restore restore = Restore::Auto;
|
||||
|
||||
bool operator==(const ParkSpec&) const = default;
|
||||
};
|
||||
|
||||
struct ModelEntry {
|
||||
std::string name; /* the model id requests name; never contains ':' */
|
||||
std::vector<std::string> aliases;
|
||||
int priority = 0;
|
||||
bool pin = false;
|
||||
int64_t ttl_ms = 0; /* idle time before parking; 0 = never */
|
||||
FlexSpec flex;
|
||||
ParkSpec park;
|
||||
|
||||
/* The flag list `cfg` was parsed from, without the program name, in a fixed order: server
|
||||
* keys, then the model's own and inherited keys sorted by name. Two entries with equal args
|
||||
* configure identical engines, which is what hot reload compares (§10). */
|
||||
std::vector<std::string> args;
|
||||
Config cfg;
|
||||
};
|
||||
|
||||
struct Group {
|
||||
enum class Kind { Together, Exclusive };
|
||||
std::string name;
|
||||
Kind kind = Kind::Together;
|
||||
std::vector<std::string> members;
|
||||
};
|
||||
|
||||
struct FleetConfig {
|
||||
std::string path; /* the file read, for messages */
|
||||
|
||||
/* server.log: Info, Debug or Trace. Unset (`log_set` false), the level RADIANCE_LOG chose
|
||||
* stands. */
|
||||
Log log = Log::Info;
|
||||
bool log_set = false;
|
||||
|
||||
/* cards: empty means every card. */
|
||||
std::vector<int> cards;
|
||||
|
||||
/* memory: the per-card keys travel inside every model's flag list; these are the fleet's own. */
|
||||
int64_t host_mib = 0; /* 0 = not set */
|
||||
std::string disk_tier;
|
||||
|
||||
/* scheduler: */
|
||||
int64_t load_timeout_ms = 120000;
|
||||
int64_t drain_timeout_ms = 30000;
|
||||
int64_t keepalive_ms = 10000;
|
||||
/* Once the listener is open and nothing waits, unpinned models load one at a time into free
|
||||
* VRAM and park to host memory and the disk tier as later ones displace them, so a first
|
||||
* request finds its model parked rather than cold (docs/MULTIMODEL.md §8.6). */
|
||||
bool warm_up = true;
|
||||
|
||||
std::vector<ModelEntry> models;
|
||||
std::vector<Group> groups;
|
||||
|
||||
/* The model a name or alias resolves to, or null. */
|
||||
const ModelEntry* find(const std::string& name_or_alias) const;
|
||||
};
|
||||
|
||||
/* Read and validate `path`. RAD_OK, or RAD_E_INVAL after RAD_ERR lines that name the file, the
|
||||
* line and the key. Nothing is half-applied: on failure *out is left as it was. */
|
||||
int load(const std::string& path, FleetConfig* out);
|
||||
|
||||
/* The same from text already in memory; `origin` names it in messages. */
|
||||
int parse(const std::string& text, const std::string& origin, FleetConfig* out);
|
||||
|
||||
/* The YAML equivalent of a command line, for the message that refuses the removed flags: the
|
||||
* flags as one model named after the container, server and memory keys at their levels. A word
|
||||
* that is not an option is kept as a model key, so loading the result refuses it by name. */
|
||||
std::string yaml_from_args(int argc, char** argv);
|
||||
|
||||
/* The option keys a level holds ("server" or "memory"), without the fleet's own keys. */
|
||||
std::vector<std::string> level_keys(const std::string& level);
|
||||
|
||||
/* The key reference `radiance --help` prints: the levels, then every key with its argument and
|
||||
* help, grouped by level. */
|
||||
void print_reference(FILE* to);
|
||||
|
||||
/* Durations: "250ms", "30s", "30m", "2h"; a bare number is seconds. False on anything else. */
|
||||
bool parse_duration_ms(const std::string& s, int64_t* out_ms);
|
||||
|
||||
} // namespace rad::fleet
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,30 @@
|
||||
/* fleet/fleet.h -- the models of one configuration, served by one process (docs/MULTIMODEL.md).
|
||||
*
|
||||
* Every model the YAML names is known to the Front (server/front.h) from the start and loaded when
|
||||
* a request first needs it: the fleet's scheduler thread builds its Engine on cards it chooses,
|
||||
* making room by unloading models the policy lets go (fleet/policy.h). A model with an idle `ttl`
|
||||
* is unloaded after that long without requests; a pinned one is loaded at start and never leaves;
|
||||
* a one-model configuration loads its model at start, as a process of one model always has.
|
||||
*
|
||||
* Engines start one after another, since bring-up loads plugins and declares against process-wide
|
||||
* tables; they serve side by side. Unloading destroys the engine; its hardware queues stay with the
|
||||
* process for the next engine on that card (core/device/aql.cpp, g_spare) until the card is left
|
||||
* empty or a model needs their memory.
|
||||
*
|
||||
* Signals: SIGINT and SIGTERM drain and stop every model; SIGHUP re-reads the file (§10).
|
||||
*/
|
||||
#pragma once
|
||||
#include "fleet/config.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace rad::fleet {
|
||||
|
||||
/* Serve every model until SIGINT or SIGTERM. The process's exit code. */
|
||||
int run(FleetConfig& fc);
|
||||
|
||||
/* The keys this build reads but does not act on yet, as one message naming them by YAML path, or
|
||||
* "". A file setting them is refused rather than half-honoured. */
|
||||
std::string unsupported(const FleetConfig& fc);
|
||||
|
||||
} // namespace rad::fleet
|
||||
@@ -0,0 +1,179 @@
|
||||
/* fleet/policy.cpp -- card choice and eviction order (policy.h). */
|
||||
#include "fleet/policy.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
#include <tuple>
|
||||
|
||||
namespace rad::fleet {
|
||||
|
||||
int64_t Resident::gives(int card) const {
|
||||
for (size_t i = 0; i < cards.size(); ++i)
|
||||
if (cards[i] == card) return i < charges.size() ? charges[i] : charge;
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool leaves_before(const Resident& a, const Resident& b) {
|
||||
if (a.parked != b.parked) return !a.parked;
|
||||
if (a.priority != b.priority) return a.priority < b.priority;
|
||||
if (a.busy != b.busy) return !a.busy;
|
||||
const double sa = a.idle_s / std::max(a.restore_s, 0.05);
|
||||
const double sb = b.idle_s / std::max(b.restore_s, 0.05);
|
||||
if (sa != sb) return sa > sb;
|
||||
return a.id < b.id;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* Every ascending subset of `n` indices of size k, in lexicographic order. */
|
||||
void subsets(int n, int k, std::vector<std::vector<int>>* out) {
|
||||
if (k > n || k <= 0) return;
|
||||
std::vector<int> pick(k);
|
||||
for (int i = 0; i < k; ++i) pick[i] = i;
|
||||
for (;;) {
|
||||
out->push_back(pick);
|
||||
int i = k - 1;
|
||||
while (i >= 0 && pick[i] == n - k + i) --i;
|
||||
if (i < 0) return;
|
||||
++pick[i];
|
||||
for (int j = i + 1; j < k; ++j) pick[j] = pick[j - 1] + 1;
|
||||
}
|
||||
}
|
||||
|
||||
bool on(const Resident& r, int card) {
|
||||
return std::find(r.cards.begin(), r.cards.end(), card) != r.cards.end();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool plan_room(const std::vector<CardRoom>& cards, const std::vector<Resident>& residents, int tp,
|
||||
int64_t need, int priority, const std::vector<size_t>& forced,
|
||||
const std::vector<int>& prefer, const std::vector<int>* fixed, RoomPlan* out,
|
||||
std::string* why, const std::map<int, int64_t>* need_on) {
|
||||
auto need_of = [&](int card) {
|
||||
if (need_on)
|
||||
if (const auto it = need_on->find(card); it != need_on->end()) return it->second;
|
||||
return need;
|
||||
};
|
||||
if (tp <= 0 || tp > (int)cards.size()) {
|
||||
*why = "it needs " + std::to_string(tp) + " cards and " + std::to_string(cards.size()) +
|
||||
" are available";
|
||||
return false;
|
||||
}
|
||||
std::vector<const Resident*> order;
|
||||
for (const Resident& r : residents)
|
||||
if (!r.pin && !r.keep && r.priority <= priority) order.push_back(&r);
|
||||
std::sort(order.begin(), order.end(),
|
||||
[](const Resident* a, const Resident* b) { return leaves_before(*a, *b); });
|
||||
auto is_forced = [&](const Resident& r) {
|
||||
return std::find(forced.begin(), forced.end(), r.id) != forced.end();
|
||||
};
|
||||
|
||||
std::vector<std::vector<int>> sets;
|
||||
if (fixed) {
|
||||
std::vector<int> idx;
|
||||
for (int c : *fixed)
|
||||
for (size_t i = 0; i < cards.size(); ++i)
|
||||
if (cards[i].card == c) idx.push_back((int)i);
|
||||
if ((int)idx.size() != tp) {
|
||||
*why = "its cards are not all available";
|
||||
return false;
|
||||
}
|
||||
std::sort(idx.begin(), idx.end());
|
||||
sets.push_back(idx);
|
||||
} else {
|
||||
subsets((int)cards.size(), tp, &sets);
|
||||
}
|
||||
|
||||
bool found = false;
|
||||
std::tuple<int64_t, int, int, size_t> best{};
|
||||
int64_t short_best = INT64_MAX;
|
||||
for (size_t si = 0; si < sets.size(); ++si) {
|
||||
const std::vector<int>& set = sets[si];
|
||||
std::map<int, int64_t> room;
|
||||
for (int i : set) room[cards[(size_t)i].card] = cards[(size_t)i].free;
|
||||
std::vector<const Resident*> gone;
|
||||
auto take = [&](const Resident* r) {
|
||||
gone.push_back(r);
|
||||
for (int c : r->cards)
|
||||
if (room.count(c)) room[c] += r->gives(c);
|
||||
};
|
||||
for (const Resident& r : residents)
|
||||
if (is_forced(r)) take(&r);
|
||||
auto shortfall = [&] {
|
||||
int64_t s = 0;
|
||||
for (auto& [c, f] : room) s += std::max<int64_t>(need_of(c) - f, 0);
|
||||
return s;
|
||||
};
|
||||
for (const Resident* r : order) {
|
||||
if (shortfall() == 0) break;
|
||||
if (std::find(gone.begin(), gone.end(), r) != gone.end()) continue;
|
||||
bool helps = false;
|
||||
for (int c : r->cards)
|
||||
if (room.count(c) && room[c] < need_of(c)) helps = true;
|
||||
if (helps) take(r);
|
||||
}
|
||||
const int64_t sf = shortfall();
|
||||
if (sf > 0) {
|
||||
short_best = std::min(short_best, sf);
|
||||
continue;
|
||||
}
|
||||
int64_t displaced = 0;
|
||||
for (const Resident* r : gone)
|
||||
for (int c : r->cards) displaced += r->gives(c);
|
||||
int not_preferred = 0;
|
||||
for (int i : set)
|
||||
if (std::find(prefer.begin(), prefer.end(), cards[(size_t)i].card) == prefer.end())
|
||||
++not_preferred;
|
||||
/* Models that stay on the set's cards: fewer is better, so models spread over the cards
|
||||
* before they share one and each computes on a card of its own while it can. */
|
||||
int crowd = 0;
|
||||
for (const Resident& r : residents) {
|
||||
if (std::find(gone.begin(), gone.end(), &r) != gone.end()) continue;
|
||||
for (int i : set)
|
||||
if (on(r, cards[(size_t)i].card)) ++crowd;
|
||||
}
|
||||
const auto key = std::make_tuple(displaced, crowd, not_preferred, si);
|
||||
if (found && !(key < best)) continue;
|
||||
found = true;
|
||||
best = key;
|
||||
out->cards.clear();
|
||||
for (int i : set) out->cards.push_back(cards[(size_t)i].card);
|
||||
out->victims.clear();
|
||||
for (const Resident* r : gone) {
|
||||
if (r->members.empty()) out->victims.push_back(r->id);
|
||||
for (size_t m : r->members) out->victims.push_back(m);
|
||||
}
|
||||
out->displaced = displaced;
|
||||
}
|
||||
if (found) return true;
|
||||
|
||||
/* Name what stays in the way: every resident that may not leave for this one. */
|
||||
std::string blocking;
|
||||
for (const Resident& r : residents)
|
||||
if (r.pin || r.keep || r.priority > priority)
|
||||
blocking += (blocking.empty() ? "" : ", ") + std::to_string(r.id);
|
||||
*why = "short by " + std::to_string(short_best == INT64_MAX ? need : short_best) +
|
||||
" bytes even after every model allowed to leave has left";
|
||||
if (!blocking.empty()) *why += "; staying: #" + blocking;
|
||||
return false;
|
||||
}
|
||||
|
||||
int64_t flex_claim(int64_t need, int64_t want, int64_t kv_fixed, int64_t kv_ceiling,
|
||||
int64_t kv_one, int64_t max_tokens, int64_t experts, int64_t expert_floor,
|
||||
int64_t kv_min_tokens, int64_t experts_min_mib) {
|
||||
int64_t claim = need;
|
||||
if (kv_min_tokens > 0 && max_tokens > 0 && kv_ceiling > kv_fixed) {
|
||||
const int64_t t = std::min(kv_min_tokens, max_tokens);
|
||||
const int64_t kv = kv_fixed + (int64_t)((double)(kv_ceiling - kv_fixed) * (double)t /
|
||||
(double)max_tokens);
|
||||
claim += std::max<int64_t>(kv - kv_one, 0);
|
||||
}
|
||||
if (experts_min_mib > 0 && experts > expert_floor) {
|
||||
const int64_t e = std::min(experts_min_mib * ((int64_t)1 << 20), experts);
|
||||
claim += std::max<int64_t>(e - expert_floor, 0);
|
||||
}
|
||||
return std::max(need, std::min(claim, want));
|
||||
}
|
||||
|
||||
} // namespace rad::fleet
|
||||
@@ -0,0 +1,79 @@
|
||||
/* fleet/policy.h -- which cards a model loads on and who leaves to make room (docs/MULTIMODEL.md
|
||||
* §8.3, §8.4). Pure arithmetic on a snapshot, so the rules are tested without a card.
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad::fleet {
|
||||
|
||||
/* A card as the fleet sees it now: the bytes a model may still claim on it (the driver's free
|
||||
* reading less the headroom). */
|
||||
struct CardRoom {
|
||||
int card = 0;
|
||||
int64_t free = 0;
|
||||
};
|
||||
|
||||
/* A loaded model as a candidate to leave. */
|
||||
struct Resident {
|
||||
size_t id = 0;
|
||||
std::vector<int> cards;
|
||||
int64_t charge = 0; /* bytes it gives back on each of its cards when it leaves */
|
||||
int priority = 0;
|
||||
bool pin = false; /* never leaves */
|
||||
bool keep = false; /* may not leave for this load (a member of its together group) */
|
||||
bool busy = false; /* requests in flight or waiting */
|
||||
double idle_s = 0; /* since its last request */
|
||||
double restore_s = 1; /* how long it takes to come back */
|
||||
/* Parked already: it holds little VRAM and loses its host copy if it leaves, so it is the
|
||||
* last candidate whatever its priority. */
|
||||
bool parked = false;
|
||||
/* Bytes it gives back on each of `cards`, when they differ (a together group leaving as one,
|
||||
* whose members sit on different cards); empty takes `charge` on every card. */
|
||||
std::vector<int64_t> charges;
|
||||
/* The models that leave with it (a together group): Resident::id of each, `id` included.
|
||||
* Empty means `id` alone. */
|
||||
std::vector<size_t> members;
|
||||
|
||||
int64_t gives(int card) const;
|
||||
};
|
||||
|
||||
struct RoomPlan {
|
||||
std::vector<int> cards; /* the model's cards, ascending; rank i on cards[i] */
|
||||
std::vector<size_t> victims; /* Resident::id of every model that leaves, in eviction order;
|
||||
* a unit's members follow one another */
|
||||
int64_t displaced = 0; /* bytes the victims held, summed over their cards */
|
||||
};
|
||||
|
||||
/* The order models leave in: resident models before parked ones; then lower priority first; at
|
||||
* equal priority idle before busy; then the one that comes back cheapest relative to how long it
|
||||
* has been idle (idle_s / restore_s, highest first); then the lower id. True when `a` leaves
|
||||
* before `b`. */
|
||||
bool leaves_before(const Resident& a, const Resident& b);
|
||||
|
||||
/* Cards for a model of `tp` ranks that needs `need` bytes on each, and the models that leave so it
|
||||
* fits. Candidates to leave are the residents that are neither pinned nor kept, at the model's
|
||||
* `priority` or lower; `forced` leave whatever happens (the other members of an exclusive group).
|
||||
* Among the card sets that can be made to fit, the one displacing the fewest bytes wins, then the
|
||||
* one whose cards keep the fewest other models (models spread before they share a card), then the
|
||||
* one with most cards in `prefer` (where the model was before), then the lowest cards. With
|
||||
* `fixed` set only that card set is considered. A card named in `need_on` needs that many bytes
|
||||
* instead of `need`: a parked model's ranks can each have a different part still on their cards.
|
||||
*
|
||||
* True with *out filled, or false with *why naming what is in the way. */
|
||||
bool plan_room(const std::vector<CardRoom>& cards, const std::vector<Resident>& residents, int tp,
|
||||
int64_t need, int priority, const std::vector<size_t>& forced,
|
||||
const std::vector<int>& prefer, const std::vector<int>* fixed, RoomPlan* out,
|
||||
std::string* why, const std::map<int, int64_t>* need_on = nullptr);
|
||||
|
||||
/* The claim a model gets in a fleet of several (§6.3): its need plus what its flex floor asks for,
|
||||
* never above what it can use. `kv_min_tokens` and `experts_min_mib` are the YAML flex floors
|
||||
* (-1 unset). The cache's cost of T tokens is kv_fixed + (kv_ceiling - kv_fixed) * T / max_tokens. */
|
||||
int64_t flex_claim(int64_t need, int64_t want, int64_t kv_fixed, int64_t kv_ceiling,
|
||||
int64_t kv_one, int64_t max_tokens, int64_t experts, int64_t expert_floor,
|
||||
int64_t kv_min_tokens, int64_t experts_min_mib);
|
||||
|
||||
} // namespace rad::fleet
|
||||
+12
-12
@@ -3,7 +3,7 @@
|
||||
#include "ggml_planes.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
@@ -63,7 +63,7 @@ void MetaOwn::finish() {
|
||||
/* 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) {
|
||||
static bool join_scalars(const Json& v, std::string* s) {
|
||||
for (const auto& e : v) {
|
||||
if (e.is_array()) {
|
||||
if (!join_scalars(e, s)) return false;
|
||||
@@ -79,10 +79,10 @@ static bool join_scalars(const nlohmann::json& v, std::string* s) {
|
||||
return true;
|
||||
}
|
||||
|
||||
static void flatten_json(const nlohmann::json& j, const std::string& prefix, MetaOwn* out) {
|
||||
static void flatten_json(const 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();
|
||||
const 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 &&
|
||||
@@ -128,7 +128,7 @@ int meta_merge_config_json(const std::string& dir, const std::string& prefix, Me
|
||||
"-- and none of it is derivable from the target.", dir.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
nlohmann::json j;
|
||||
Json j;
|
||||
try { f >> j; }
|
||||
catch (const std::exception& e) { RAD_ERR("%s: %s", path.c_str(), e.what()); return RAD_E_FORMAT; }
|
||||
flatten_json(j, prefix, out);
|
||||
@@ -145,7 +145,7 @@ int meta_merge_generation_config(const std::string& dir, MetaOwn* out) {
|
||||
const std::string path = dir + "/generation_config.json";
|
||||
std::ifstream f(path);
|
||||
if (!f) return RAD_OK; /* optional */
|
||||
nlohmann::json j;
|
||||
Json j;
|
||||
try { f >> j; }
|
||||
catch (const std::exception& e) {
|
||||
RAD_WARN("%s: %s; no sampling defaults are carried", path.c_str(), e.what());
|
||||
@@ -180,7 +180,7 @@ int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out) {
|
||||
const std::string path = dir + "/" + f.file;
|
||||
std::ifstream in(path);
|
||||
if (!in) continue;
|
||||
nlohmann::json j;
|
||||
Json j;
|
||||
try { in >> j; }
|
||||
catch (const std::exception& e) {
|
||||
RAD_WARN("%s: %s; it is not carried", path.c_str(), e.what());
|
||||
@@ -199,7 +199,7 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
|
||||
"dimensions there; without it nothing can be sized.", dir.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
nlohmann::json j;
|
||||
Json j;
|
||||
try { f >> j; }
|
||||
catch (const std::exception& e) {
|
||||
RAD_ERR("%s: %s", path.c_str(), e.what());
|
||||
@@ -566,7 +566,7 @@ static int meta_merge_json_file(const std::string& path, const std::string& pref
|
||||
RAD_ERR("%s: cannot read it", path.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
nlohmann::json j;
|
||||
Json j;
|
||||
try { f >> j; }
|
||||
catch (const std::exception& e) { RAD_ERR("%s: %s", path.c_str(), e.what()); return RAD_E_FORMAT; }
|
||||
if (!j.is_object()) {
|
||||
@@ -1881,15 +1881,15 @@ struct LoraRule {
|
||||
};
|
||||
|
||||
/* Read the map file: {"strip": [...], "modules": {"<pat>": ["<t>", ...], ...}}. The module
|
||||
* order is preserved (an nlohmann object keeps insertion order), so the first rule whose
|
||||
* order is preserved (the DOM keeps insertion order), so the first rule whose
|
||||
* pattern matches a module wins. */
|
||||
static int lora_map_read(const std::string& file, std::vector<std::string>* strip,
|
||||
std::vector<LoraRule>* rules) {
|
||||
std::ifstream f(file);
|
||||
if (!f) { RAD_ERR("lora: --lora-map %s cannot be read", file.c_str()); return RAD_E_NOTFOUND; }
|
||||
nlohmann::ordered_json j;
|
||||
Json j;
|
||||
try {
|
||||
j = nlohmann::ordered_json::parse(f);
|
||||
j = Json::parse(f);
|
||||
} catch (const std::exception& e) {
|
||||
RAD_ERR("lora: --lora-map %s: %s", file.c_str(), e.what());
|
||||
return RAD_E_FORMAT;
|
||||
|
||||
+20
-5
@@ -711,6 +711,8 @@ int RadWriter::begin_append(const char* path, const RadFile& old) {
|
||||
fd_out_ = fd_spill_ = -1;
|
||||
return RAD_E_IO;
|
||||
}
|
||||
kept_expert_layers_.clear();
|
||||
new_expert_layers_.clear();
|
||||
append_ = true;
|
||||
began_ = true;
|
||||
return RAD_OK;
|
||||
@@ -722,6 +724,16 @@ int64_t RadWriter::add_existing(const Weight& w, const RadFile& old, const RadFi
|
||||
RAD_ERR("'%s': the container already holds a weight of this name", w.name.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (w.expert >= 0) {
|
||||
if (new_expert_layers_.count(w.layer)) {
|
||||
RAD_ERR("'%s' is layer %d's expert %d, kept where it is, and this run writes other "
|
||||
"experts of that layer past the end: a layer's experts sit at a fixed stride "
|
||||
"from each other, so a layer is kept whole or written whole.",
|
||||
w.name.c_str(), w.layer, w.expert);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
kept_expert_layers_.insert(w.layer);
|
||||
}
|
||||
/* Bytes and encoding are the old entry's; provenance and movement group are the caller's. */
|
||||
RadFileEntry n = e;
|
||||
n.name = intern(w.name);
|
||||
@@ -886,11 +898,14 @@ int64_t RadWriter::add_weight(const Weight& w) {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (append_ && w.expert >= 0) {
|
||||
RAD_ERR("'%s' is layer %d's expert %d, and a container extended in place cannot take a "
|
||||
"new expert: a layer's experts sit at a fixed stride from each other, and one "
|
||||
"written past the end joins no layer. Convert to a new file instead.",
|
||||
w.name.c_str(), w.layer, w.expert);
|
||||
return RAD_E_INVAL;
|
||||
if (kept_expert_layers_.count(w.layer)) {
|
||||
RAD_ERR("'%s' is layer %d's expert %d, and the container extended in place keeps "
|
||||
"experts of that layer: a layer's experts sit at a fixed stride from each "
|
||||
"other, and one written past the end joins no layer. Write the layer's whole "
|
||||
"table again, or convert to a new file.", w.name.c_str(), w.layer, w.expert);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
new_expert_layers_.insert(w.layer);
|
||||
}
|
||||
|
||||
/* Every entry starts on a movement-unit boundary (up to 4 KiB padding per matrix, tens of MB on
|
||||
|
||||
@@ -220,9 +220,12 @@ public:
|
||||
* afterwards the old tables are dead bytes. finish() leaves `<path>.pre-append` (the old
|
||||
* header and length) to restore it.
|
||||
*
|
||||
* New expert weights are refused: a layer's experts sit at a fixed stride and cannot be
|
||||
* extended. The caller must be the file's only user, since a process mapping it would see the
|
||||
* header change under it. */
|
||||
* A layer's experts sit at a fixed stride, so a layer whose experts are kept (add_existing)
|
||||
* takes no further one. A layer none of whose experts is kept takes its whole table, written
|
||||
* as in a new file: experts 0..n-1 in order, each one's slots in order -- a layer `old` holds
|
||||
* none of, or one whose old table the caller leaves behind as dead bytes. An old weight the
|
||||
* caller neither keeps nor writes again is dead bytes too. The caller must be the file's only
|
||||
* user, since a process mapping it would see the header change under it. */
|
||||
int begin_append(const char* path, const RadFile& old);
|
||||
/* A weight `old` already holds, recorded at the offsets it has there. Its encoding and planes
|
||||
* are the old entry's; its name, provenance and movement group are `w`'s. */
|
||||
@@ -288,6 +291,9 @@ private:
|
||||
uint64_t old_data_off_ = 0;
|
||||
RadFileHeader old_hdr_{};
|
||||
std::vector<uint8_t> dir_abs_;
|
||||
/* While extending in place: the layers an expert was kept in (add_existing) and the layers a
|
||||
* new expert was reserved in. A layer is in one of them only. */
|
||||
std::unordered_set<int32_t> kept_expert_layers_, new_expert_layers_;
|
||||
|
||||
std::string arch_, model_, quant_, recipe_, created_by_;
|
||||
|
||||
|
||||
@@ -405,7 +405,13 @@ int AudioDriver::admit_locked() {
|
||||
if (kv_->has_sequence(j.seq[b])) kv_->free_sequence(j.seq[b]);
|
||||
j.seq[b] = 0;
|
||||
}
|
||||
break;
|
||||
/* With nothing running to free blocks, waiting would never end. */
|
||||
bool running = false;
|
||||
for (const auto& o : jobs_) running = running || o->admitted;
|
||||
if (running) break;
|
||||
fail_locked(j, RAD_E_FULL, "the KV cache cannot hold this piece, and nothing is running "
|
||||
"that would free it; ask for a shorter piece");
|
||||
continue;
|
||||
}
|
||||
j.have_kv = true;
|
||||
j.lane = free_lanes_.back();
|
||||
|
||||
+8
-2
@@ -399,9 +399,15 @@ int Driver::admit_locked() {
|
||||
}
|
||||
if (j.failed) continue;
|
||||
if (!ok) {
|
||||
/* KV is short: release what this request took and wait. */
|
||||
/* KV is short: release what this request took and wait, unless nothing is running
|
||||
* that would free any. */
|
||||
release_kv_locked(j);
|
||||
break;
|
||||
bool running = false;
|
||||
for (const auto& o : jobs_) running = running || o->admitted;
|
||||
if (running) break;
|
||||
fail_locked(j, RAD_E_FULL, "the KV cache cannot hold this prompt, and nothing is running "
|
||||
"that would free it; try a shorter prompt");
|
||||
continue;
|
||||
}
|
||||
if (discrete()) {
|
||||
j.sigmas = schedule_discrete(decl_, table_, r.scheduler, r.steps);
|
||||
|
||||
+231
-104
@@ -3,7 +3,9 @@
|
||||
#include "shape.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
#include "util/rowpool.h"
|
||||
#include "util/simd.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
@@ -37,6 +39,10 @@ ShapeGenInfo shape_info(const RadShapeGenDecl& d, const std::string& name) {
|
||||
/* ================================================================== the picture */
|
||||
namespace {
|
||||
|
||||
/* The picture's passes below compute each output row from its own inputs only, in the same order
|
||||
* whichever thread runs it, so they spread over the row pool and stay bit-exact. */
|
||||
constexpr int kRowWidth = 8;
|
||||
|
||||
/* An 8-bit image, `ch` channels interleaved. */
|
||||
struct Img {
|
||||
int32_t w = 0, h = 0, ch = 0;
|
||||
@@ -74,13 +80,17 @@ void resize_area_down(const Img& s, int32_t dw, int32_t dh, Img* d) {
|
||||
const double sx = (double)s.w / dw, sy = (double)s.h / dh;
|
||||
const std::vector<AreaTap> xt = area_tab(s.w, dw, sx), yt = area_tab(s.h, dh, sy);
|
||||
const int32_t ch = s.ch;
|
||||
std::vector<float> row((size_t)dw * ch), acc((size_t)dw * ch);
|
||||
d->w = dw; d->h = dh; d->ch = ch;
|
||||
d->px.assign((size_t)dw * dh * ch, 0);
|
||||
size_t k = 0;
|
||||
for (int32_t dy = 0; dy < dh; ++dy) {
|
||||
std::fill(acc.begin(), acc.end(), 0.0f);
|
||||
for (; k < yt.size() && yt[k].di == dy; ++k) {
|
||||
/* Each destination row's first tap in yt, which lists them in row order. */
|
||||
std::vector<size_t> first((size_t)dh + 1, yt.size());
|
||||
for (size_t k = yt.size(); k-- > 0;) first[(size_t)yt[k].di] = k;
|
||||
for (int32_t dy = dh; dy-- > 0;) first[(size_t)dy] = std::min(first[(size_t)dy], first[(size_t)dy + 1]);
|
||||
row_pool_run(dh, kRowWidth, [&](int64_t dy) {
|
||||
thread_local std::vector<float> row, acc;
|
||||
row.assign((size_t)dw * ch, 0.0f);
|
||||
acc.assign((size_t)dw * ch, 0.0f);
|
||||
for (size_t k = first[(size_t)dy]; k < yt.size() && yt[k].di == dy; ++k) {
|
||||
std::fill(row.begin(), row.end(), 0.0f);
|
||||
const uint8_t* src = s.at(yt[k].si, 0);
|
||||
for (const AreaTap& t : xt)
|
||||
@@ -88,9 +98,9 @@ void resize_area_down(const Img& s, int32_t dw, int32_t dh, Img* d) {
|
||||
row[(size_t)t.di * ch + c] += src[(size_t)t.si * ch + c] * t.alpha;
|
||||
for (size_t i = 0; i < acc.size(); ++i) acc[i] += row[i] * yt[k].alpha;
|
||||
}
|
||||
uint8_t* dst = d->at(dy, 0);
|
||||
uint8_t* dst = d->at((int32_t)dy, 0);
|
||||
for (size_t i = 0; i < acc.size(); ++i) dst[i] = sat_u8(acc[i]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* cv::resize's fixed-point separable filter for 8-bit images: each tap's float coefficient
|
||||
@@ -140,31 +150,43 @@ Taps taps_cubic(int32_t ssize, int32_t dsize) {
|
||||
}
|
||||
|
||||
void resize_fixed(const Img& s, const Taps& tx, const Taps& ty, int32_t dw, int32_t dh, Img* d) {
|
||||
const int32_t ch = s.ch;
|
||||
/* Every source row through the horizontal taps, then each destination row from its rows. */
|
||||
std::vector<int32_t> hrow((size_t)s.h * dw * ch);
|
||||
for (int32_t y = 0; y < s.h; ++y)
|
||||
for (int32_t dx = 0; dx < dw; ++dx)
|
||||
const int32_t ch = s.ch, kx = tx.ksize, ky = ty.ksize;
|
||||
/* Every source row through the horizontal taps, then each destination row from its rows. The
|
||||
* clamped source offsets are worked out once a tap, so the loops below only multiply and add,
|
||||
* in the same order as one pixel at a time. */
|
||||
std::vector<int32_t> xo((size_t)dw * kx);
|
||||
for (int32_t dx = 0; dx < dw; ++dx)
|
||||
for (int32_t k = 0; k < kx; ++k)
|
||||
xo[(size_t)dx * kx + k] = std::clamp(tx.ofs[(size_t)dx] + k, 0, s.w - 1) * ch;
|
||||
const size_t rw = (size_t)dw * ch;
|
||||
std::vector<int32_t> hrow((size_t)s.h * rw);
|
||||
row_pool_run(s.h, kRowWidth, [&](int64_t y) {
|
||||
const uint8_t* src = s.at((int32_t)y, 0);
|
||||
int32_t* h = hrow.data() + (size_t)y * rw;
|
||||
for (int32_t dx = 0; dx < dw; ++dx) {
|
||||
const int32_t* o = xo.data() + (size_t)dx * kx;
|
||||
const int16_t* cf = tx.c.data() + (size_t)dx * kx;
|
||||
for (int32_t c = 0; c < ch; ++c) {
|
||||
int32_t sum = 0;
|
||||
for (int32_t k = 0; k < tx.ksize; ++k) {
|
||||
const int32_t sx = std::clamp(tx.ofs[(size_t)dx] + k, 0, s.w - 1);
|
||||
sum += s.at(y, sx)[c] * tx.c[(size_t)dx * tx.ksize + k];
|
||||
}
|
||||
hrow[((size_t)y * dw + dx) * ch + c] = sum;
|
||||
for (int32_t k = 0; k < kx; ++k) sum += src[o[k] + c] * cf[k];
|
||||
h[(size_t)dx * ch + c] = sum;
|
||||
}
|
||||
}
|
||||
});
|
||||
d->w = dw; d->h = dh; d->ch = ch;
|
||||
d->px.assign((size_t)dw * dh * ch, 0);
|
||||
for (int32_t dy = 0; dy < dh; ++dy)
|
||||
for (int32_t i = 0; i < dw * ch; ++i) {
|
||||
int64_t v = 0;
|
||||
for (int32_t k = 0; k < ty.ksize; ++k) {
|
||||
const int32_t sy = std::clamp(ty.ofs[(size_t)dy] + k, 0, s.h - 1);
|
||||
v += (int64_t)hrow[(size_t)sy * dw * ch + i] * ty.c[(size_t)dy * ty.ksize + k];
|
||||
}
|
||||
const int64_t r = (v + (1 << 21)) >> 22;
|
||||
d->px[(size_t)dy * dw * ch + i] = (uint8_t)std::clamp<int64_t>(r, 0, 255);
|
||||
row_pool_run(dh, kRowWidth, [&](int64_t dy) {
|
||||
thread_local std::vector<int64_t> acc;
|
||||
acc.assign(rw, 0);
|
||||
for (int32_t k = 0; k < ky; ++k) {
|
||||
const int32_t sy = std::clamp(ty.ofs[(size_t)dy] + k, 0, s.h - 1);
|
||||
const int32_t* h = hrow.data() + (size_t)sy * rw;
|
||||
simd::madd_i32_i64(acc.data(), h, ty.c[(size_t)dy * ky + k], rw);
|
||||
}
|
||||
uint8_t* out = d->px.data() + (size_t)dy * rw;
|
||||
for (size_t i = 0; i < rw; ++i)
|
||||
out[i] = (uint8_t)std::clamp<int64_t>((acc[i] + (1 << 21)) >> 22, 0, 255);
|
||||
});
|
||||
}
|
||||
|
||||
/* cv2.resize(src, (dw, dh), INTER_AREA). */
|
||||
@@ -219,13 +241,22 @@ int shape_picture(const ShapeGenInfo& g, const mm::FrameRGBA& rgba, std::vector<
|
||||
const int32_t H = rgba.h, W = rgba.w;
|
||||
if (H < 1 || W < 1 || rgba.rgba.size() != (size_t)H * W * 4) return no("the picture is empty");
|
||||
/* ---- ImageProcessorV2.recenter: the alpha's bounding box on a square of the longer side */
|
||||
/* Each row's first and last opaque column, then their extremes. */
|
||||
std::vector<int32_t> rx0((size_t)H), rx1((size_t)H);
|
||||
row_pool_run(H, kRowWidth, [&](int64_t y) {
|
||||
const uint8_t* r = rgba.rgba.data() + (size_t)y * W * 4;
|
||||
int32_t a = 0, b = W - 1;
|
||||
while (a < W && !r[(size_t)a * 4 + 3]) ++a;
|
||||
while (b > a && !r[(size_t)b * 4 + 3]) --b;
|
||||
rx0[(size_t)y] = a;
|
||||
rx1[(size_t)y] = a < W ? b : -1;
|
||||
});
|
||||
int32_t y0 = H, y1 = -1, x0 = W, x1 = -1;
|
||||
for (int32_t y = 0; y < H; ++y)
|
||||
for (int32_t x = 0; x < W; ++x)
|
||||
if (rgba.rgba[((size_t)y * W + x) * 4 + 3]) {
|
||||
y0 = std::min(y0, y); y1 = std::max(y1, y);
|
||||
x0 = std::min(x0, x); x1 = std::max(x1, x);
|
||||
}
|
||||
if (rx1[(size_t)y] >= 0) {
|
||||
y0 = std::min(y0, y); y1 = std::max(y1, y);
|
||||
x0 = std::min(x0, rx0[(size_t)y]); x1 = std::max(x1, rx1[(size_t)y]);
|
||||
}
|
||||
if (y1 < 0) return no("the picture is fully transparent: nothing to make a shape of");
|
||||
const int32_t h = y1 - y0, w = x1 - x0;
|
||||
if (h == 0 || w == 0)
|
||||
@@ -250,16 +281,17 @@ int shape_picture(const ShapeGenInfo& g, const mm::FrameRGBA& rgba, std::vector<
|
||||
Img sq;
|
||||
sq.w = size; sq.h = size; sq.ch = 3;
|
||||
sq.px.assign((size_t)size * size * 3, 255);
|
||||
for (int32_t y = 0; y < h2; ++y)
|
||||
row_pool_run(h2, kRowWidth, [&](int64_t y) {
|
||||
for (int32_t x = 0; x < w2; ++x) {
|
||||
const uint8_t* p = fit.at(y, x);
|
||||
const uint8_t* p = fit.at((int32_t)y, x);
|
||||
const float a = (float)p[3] / 255.0f;
|
||||
uint8_t* q = sq.at(oy + y, ox + x);
|
||||
uint8_t* q = sq.at(oy + (int32_t)y, ox + x);
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
const float v = (float)p[c] * a + 255.0f * (1.0f - a);
|
||||
q[c] = (uint8_t)std::clamp(v, 0.0f, 255.0f);
|
||||
}
|
||||
}
|
||||
});
|
||||
/* ---- the canvas, INTER_CUBIC */
|
||||
const int32_t C = (int32_t)g.canvas;
|
||||
Img can;
|
||||
@@ -268,16 +300,17 @@ int shape_picture(const ShapeGenInfo& g, const mm::FrameRGBA& rgba, std::vector<
|
||||
const int32_t E = (int32_t)g.enc_size, P = (int32_t)g.enc_patch, G = E / P;
|
||||
const AaTaps ta = aa_taps(C, E);
|
||||
std::vector<float> hor((size_t)C * E * 3), img((size_t)E * E * 3);
|
||||
for (int32_t y = 0; y < C; ++y)
|
||||
row_pool_run(C, kRowWidth, [&](int64_t y) {
|
||||
for (int32_t x = 0; x < E; ++x)
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
float s = 0.0f;
|
||||
const std::vector<float>& wt = ta.w[(size_t)x];
|
||||
for (size_t k = 0; k < wt.size(); ++k)
|
||||
s += wt[k] * ((float)can.at(y, ta.lo[(size_t)x] + (int32_t)k)[c] / 255.0f);
|
||||
s += wt[k] * ((float)can.at((int32_t)y, ta.lo[(size_t)x] + (int32_t)k)[c] / 255.0f);
|
||||
hor[((size_t)y * E + x) * 3 + c] = s;
|
||||
}
|
||||
for (int32_t y = 0; y < E; ++y)
|
||||
});
|
||||
row_pool_run(E, kRowWidth, [&](int64_t y) {
|
||||
for (int32_t x = 0; x < E; ++x)
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
float s = 0.0f;
|
||||
@@ -287,6 +320,7 @@ int shape_picture(const ShapeGenInfo& g, const mm::FrameRGBA& rgba, std::vector<
|
||||
img[((size_t)y * E + x) * 3 + c] =
|
||||
(float)((s - g.pix_mean[c]) / g.pix_std[c]);
|
||||
}
|
||||
});
|
||||
/* ---- patches, row-major; a patch's values (channel, row, column) */
|
||||
const int64_t pd = 3 * (int64_t)P * P;
|
||||
patches->assign((size_t)G * G * pd, 0.0f);
|
||||
@@ -332,13 +366,23 @@ namespace {
|
||||
/* A 3 x 3 x 3 dilation of an n^3 mask (zero outside), as separable maxima along each axis. */
|
||||
void dilate(std::vector<uint8_t>& m, int64_t n) {
|
||||
std::vector<uint8_t> t(m.size());
|
||||
/* One axis: each voxel ORs its two neighbours along it, where they exist. Along the
|
||||
* contiguous axis a line of n voxels at a time; along the others whole rows of `stride`
|
||||
* voxels, each with the rows either side of it. */
|
||||
auto pass = [&](const std::vector<uint8_t>& src, std::vector<uint8_t>& dst, int64_t stride) {
|
||||
for (int64_t p = 0; p < (int64_t)src.size(); ++p) {
|
||||
const int64_t c = (p / stride) % n;
|
||||
uint8_t v = src[(size_t)p];
|
||||
if (c > 0) v |= src[(size_t)(p - stride)];
|
||||
if (c + 1 < n) v |= src[(size_t)(p + stride)];
|
||||
dst[(size_t)p] = v;
|
||||
const uint8_t* s = src.data();
|
||||
uint8_t* d = dst.data();
|
||||
const int64_t total = (int64_t)src.size(), plane = n * stride;
|
||||
for (int64_t base = 0; base < total; base += plane) {
|
||||
if (stride == 1) {
|
||||
simd::or_adjacent_u8(d + base, s + base, (size_t)n);
|
||||
continue;
|
||||
}
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
const uint8_t* a = s + base + c * stride;
|
||||
simd::or3_u8(d + base + c * stride, a, c > 0 ? a - stride : nullptr,
|
||||
c + 1 < n ? a + stride : nullptr, (size_t)stride);
|
||||
}
|
||||
}
|
||||
};
|
||||
pass(m, t, 1);
|
||||
@@ -353,43 +397,85 @@ std::vector<uint32_t> shape_refine(const std::vector<float>& prev, int32_t rp, i
|
||||
double level, bool last) {
|
||||
const int64_t np = (int64_t)rp + 1, n = (int64_t)r + 1;
|
||||
std::vector<uint8_t> near((size_t)(np * np * np), 0);
|
||||
auto sgn = [](float v) { return (v > 0.0f) - (v < 0.0f); };
|
||||
const float lv = (float)level;
|
||||
for (int64_t i = 0; i < np; ++i)
|
||||
for (int64_t j = 0; j < np; ++j)
|
||||
for (int64_t k = 0; k < np; ++k) {
|
||||
const int64_t p = (i * np + j) * np + k;
|
||||
const float raw = prev[(size_t)p];
|
||||
if (std::isnan(raw)) continue;
|
||||
const float v = raw - lv;
|
||||
const int s = sgn(v);
|
||||
bool cross = std::fabs(v) < 0.95f;
|
||||
const int64_t nb[6][3] = { { i - 1, j, k }, { i + 1, j, k }, { i, j - 1, k },
|
||||
{ i, j + 1, k }, { i, j, k - 1 }, { i, j, k + 1 } };
|
||||
for (int q = 0; q < 6 && !cross; ++q) {
|
||||
const int64_t a = nb[q][0], b = nb[q][1], c = nb[q][2];
|
||||
/* Outside the grid the reference replicates the border, and a neighbour not
|
||||
* sampled stands in as the point itself: neither crosses. */
|
||||
if (a < 0 || a >= np || b < 0 || b >= np || c < 0 || c >= np) continue;
|
||||
const float u = prev[(size_t)((a * np + b) * np + c)];
|
||||
if (std::isnan(u)) continue;
|
||||
cross = sgn(u - lv) != s;
|
||||
/* A point is near the surface when it is within 0.95 of the level, or a neighbour along an
|
||||
* axis lies on the other side of it (neither a NaN, which is not sampled; past the grid's
|
||||
* edge the reference replicates the border, which never crosses). The sign of raw - lv is
|
||||
* the comparison of raw with lv, so each row's simd::level_bits_f32 bitmaps answer it 64
|
||||
* points at a time, three planes held at once. */
|
||||
const int64_t W = (np + 63) / 64, rowb = W * 4;
|
||||
std::vector<uint64_t> bits((size_t)(3 * np * rowb));
|
||||
auto plane = [&](int64_t i) { return bits.data() + (size_t)((i % 3) * np * rowb); };
|
||||
auto classify = [&](int64_t i) {
|
||||
uint64_t* pl = plane(i);
|
||||
for (int64_t j = 0; j < np; ++j) {
|
||||
uint64_t* row = pl + j * rowb;
|
||||
simd::level_bits_f32(&prev[(size_t)((i * np + j) * np)], (size_t)np, lv, 0.95f, row,
|
||||
row + W, row + 2 * W, row + 3 * W);
|
||||
}
|
||||
};
|
||||
auto diff = [&](const uint64_t* a, const uint64_t* b, int64_t w) { /* rows of four maps */
|
||||
return ((a[w] ^ b[w]) | (a[W + w] ^ b[W + w])) & ~b[2 * W + w];
|
||||
};
|
||||
/* Row maps moved one point along k: `up` holds point k - 1 at bit k, `dn` point k + 1. */
|
||||
std::vector<uint64_t> up((size_t)rowb), dn((size_t)rowb);
|
||||
if (np > 0) classify(0);
|
||||
for (int64_t i = 0; i < np; ++i) {
|
||||
if (i + 1 < np) classify(i + 1);
|
||||
for (int64_t j = 0; j < np; ++j) {
|
||||
const uint64_t* c = plane(i) + j * rowb;
|
||||
for (int m = 0; m < 3; ++m)
|
||||
for (int64_t w = 0; w < W; ++w) {
|
||||
const uint64_t* x = c + m * W;
|
||||
up[(size_t)(m * W + w)] = (x[w] << 1) | (w > 0 ? x[w - 1] >> 63 : 0);
|
||||
dn[(size_t)(m * W + w)] = (x[w] >> 1) | (w + 1 < W ? x[w + 1] << 63 : 0);
|
||||
}
|
||||
const uint64_t* nb[4] = { j > 0 ? c - rowb : nullptr, j + 1 < np ? c + rowb : nullptr,
|
||||
i > 0 ? plane(i - 1) + j * rowb : nullptr,
|
||||
i + 1 < np ? plane(i + 1) + j * rowb : nullptr };
|
||||
uint8_t* out = near.data() + (size_t)((i * np + j) * np);
|
||||
for (int64_t w = 0; w < W; ++w) {
|
||||
/* The row's points only; k - 1 exists from k = 1, k + 1 up to k = np - 2. */
|
||||
const int64_t k0 = w * 64, left = np - k0;
|
||||
const uint64_t inside = left >= 64 ? ~0ull : (1ull << left) - 1;
|
||||
const uint64_t has_dn = left > 64 ? ~0ull : (1ull << (left - 1)) - 1;
|
||||
uint64_t x = c[3 * W + w] | (diff(c, up.data(), w) & (w == 0 ? ~1ull : ~0ull)) |
|
||||
(diff(c, dn.data(), w) & has_dn);
|
||||
for (const uint64_t* o : nb) if (o) x |= diff(c, o, w);
|
||||
x &= inside & ~c[2 * W + w];
|
||||
while (x) {
|
||||
out[k0 + __builtin_ctzll(x)] = 1;
|
||||
x &= x - 1;
|
||||
}
|
||||
near[(size_t)p] = cross;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!last) dilate(near, np);
|
||||
std::vector<uint8_t> mark((size_t)(n * n * n), 0);
|
||||
auto up = [&](int64_t c) { return (c * r + rp / 2) / rp; };
|
||||
for (int64_t i = 0; i < np; ++i)
|
||||
for (int64_t j = 0; j < np; ++j)
|
||||
for (int64_t k = 0; k < np; ++k)
|
||||
if (near[(size_t)((i * np + j) * np + k)])
|
||||
mark[(size_t)((up(i) * n + up(j)) * n + up(k))] = 1;
|
||||
auto upi = [&](int64_t c) { return (c * r + rp / 2) / rp; };
|
||||
/* The masks are sparse: eight bytes looked at a time. */
|
||||
auto each_set = [](const std::vector<uint8_t>& m, auto&& fn) {
|
||||
const size_t sz = m.size();
|
||||
size_t p = 0;
|
||||
for (; p + 8 <= sz; p += 8) {
|
||||
uint64_t x;
|
||||
std::memcpy(&x, m.data() + p, 8);
|
||||
while (x) {
|
||||
const int b = __builtin_ctzll(x) >> 3;
|
||||
fn((int64_t)p + b);
|
||||
x &= ~(0xffull << (8 * b));
|
||||
}
|
||||
}
|
||||
for (; p < sz; ++p) if (m[p]) fn((int64_t)p);
|
||||
};
|
||||
each_set(near, [&](int64_t p) {
|
||||
const int64_t i = p / (np * np), j = p / np % np, k = p % np;
|
||||
mark[(size_t)((upi(i) * n + upi(j)) * n + upi(k))] = 1;
|
||||
});
|
||||
dilate(mark, n);
|
||||
if (last) dilate(mark, n);
|
||||
std::vector<uint32_t> pts;
|
||||
for (int64_t p = 0; p < (int64_t)mark.size(); ++p)
|
||||
if (mark[(size_t)p]) pts.push_back((uint32_t)p);
|
||||
each_set(mark, [&](int64_t p) { pts.push_back((uint32_t)p); });
|
||||
return pts;
|
||||
}
|
||||
|
||||
@@ -520,50 +606,91 @@ void shape_mesh(const std::vector<float>& field, int32_t r, double bounds, doubl
|
||||
const int64_t n = (int64_t)r + 1, nn = n * n;
|
||||
const float lv = (float)level;
|
||||
const double sc = 2.0 * bounds / (double)n;
|
||||
/* Each grid row's bitmaps (simd::level_bits_f32), for the two planes a slab of cubes lies
|
||||
* between: bit k of row j of plane p is grid point (i + p, j, k). */
|
||||
const int64_t W = (n + 63) / 64;
|
||||
std::vector<uint64_t> gt[2], nan[2], scratch((size_t)(2 * W));
|
||||
for (int p = 0; p < 2; ++p) { gt[p].assign((size_t)(n * W + 1), 0); nan[p].assign((size_t)(n * W + 1), 0); }
|
||||
auto classify = [&](int64_t i, int p) {
|
||||
for (int64_t j = 0; j < n; ++j)
|
||||
simd::level_bits_f32(&field[(size_t)((i * n + j) * n)], (size_t)n, lv, 0.0f,
|
||||
>[p][(size_t)(j * W)], scratch.data(), &nan[p][(size_t)(j * W)],
|
||||
scratch.data() + W);
|
||||
};
|
||||
/* An edge's vertex by its first grid point: the x edges between planes i and i + 1, and the
|
||||
* y and z edges of planes i and i + 1. */
|
||||
std::vector<int32_t> ex((size_t)nn), ey[2], ez[2];
|
||||
* y and z edges of planes i and i + 1. Vertex indices only grow, so a slot holds a vertex of
|
||||
* the current slab when it is at least the vertex count the slab started at (`v_now`; for
|
||||
* the edges of plane i, which the slab before also made, `v_last`): no slot is cleared. */
|
||||
std::vector<int32_t> ex((size_t)nn, -1), ey[2], ez[2];
|
||||
for (int p = 0; p < 2; ++p) { ey[p].assign((size_t)nn, -1); ez[p].assign((size_t)nn, -1); }
|
||||
auto value = [&](int64_t i, int64_t j, int64_t k) {
|
||||
return field[(size_t)((i * n + j) * n + k)];
|
||||
};
|
||||
/* Bits [w * 64, w * 64 + 64) of a row, moved down by one: bit k is the row's bit k + 1. */
|
||||
auto next = [&](const uint64_t* row, int64_t w) {
|
||||
return (row[w] >> 1) | (w + 1 < W ? row[w + 1] << 63 : 0);
|
||||
};
|
||||
if (n >= 2) classify(0, 1);
|
||||
int32_t v_last = 0;
|
||||
for (int64_t i = 0; i + 1 < n; ++i) {
|
||||
std::fill(ex.begin(), ex.end(), -1);
|
||||
std::swap(gt[0], gt[1]);
|
||||
std::swap(nan[0], nan[1]);
|
||||
classify(i + 1, 1);
|
||||
if (i > 0) {
|
||||
std::swap(ey[0], ey[1]);
|
||||
std::swap(ez[0], ez[1]);
|
||||
std::fill(ey[1].begin(), ey[1].end(), -1);
|
||||
std::fill(ez[1].begin(), ez[1].end(), -1);
|
||||
}
|
||||
for (int64_t j = 0; j + 1 < n; ++j)
|
||||
for (int64_t k = 0; k + 1 < n; ++k) {
|
||||
float v[8];
|
||||
bool skip = false;
|
||||
int m = 0;
|
||||
for (int c = 0; c < 8 && !skip; ++c) {
|
||||
v[c] = value(i + (c & 1), j + (c >> 1 & 1), k + (c >> 2 & 1));
|
||||
if (std::isnan(v[c])) skip = true;
|
||||
else if (v[c] > lv) m |= 1 << c;
|
||||
const int32_t v_now = (int32_t)(out->v.size() / 3);
|
||||
auto fresh = [&](int32_t at, int a, int64_t bi) {
|
||||
return at >= (a == 0 || bi == 1 ? v_now : v_last) && at >= 0;
|
||||
};
|
||||
for (int64_t j = 0; j + 1 < n; ++j) {
|
||||
const uint64_t* g[4] = { >[0][(size_t)(j * W)], >[1][(size_t)(j * W)],
|
||||
>[0][(size_t)((j + 1) * W)], >[1][(size_t)((j + 1) * W)] };
|
||||
const uint64_t* q[4] = { &nan[0][(size_t)(j * W)], &nan[1][(size_t)(j * W)],
|
||||
&nan[0][(size_t)((j + 1) * W)], &nan[1][(size_t)((j + 1) * W)] };
|
||||
for (int64_t w = 0; w < W; ++w) {
|
||||
/* Corner c of the cube at k: row c & 3 (i, j offsets), at k + (c >> 2). */
|
||||
uint64_t cb[8], any = 0, all = ~0ull, bad = 0;
|
||||
for (int c = 0; c < 4; ++c) {
|
||||
cb[c] = g[c][w];
|
||||
cb[c + 4] = next(g[c], w);
|
||||
bad |= q[c][w] | next(q[c], w);
|
||||
}
|
||||
if (skip || m == 0 || m == 255) continue;
|
||||
for (int t = 0; t < 30 && T.tri[m][t] >= 0; ++t) {
|
||||
const int e = T.tri[m][t];
|
||||
const int c0 = T.edge[e][0], c1 = T.edge[e][1], a = e / 4;
|
||||
const int64_t bi = c0 & 1, bj = c0 >> 1 & 1, bk = c0 >> 2 & 1;
|
||||
int32_t* slot = a == 0 ? &ex[(size_t)((j + bj) * n + k + bk)]
|
||||
: a == 1 ? &ey[bi][(size_t)(j * n + k + bk)]
|
||||
: &ez[bi][(size_t)((j + bj) * n + k)];
|
||||
if (*slot < 0) {
|
||||
const float t0 = v[c0], t1 = v[c1];
|
||||
const float f = t1 != t0 ? (lv - t0) / (t1 - t0) : 0.5f;
|
||||
float g[3] = { (float)(i + bi), (float)(j + bj), (float)(k + bk) };
|
||||
g[a] += f;
|
||||
*slot = (int32_t)(out->v.size() / 3);
|
||||
for (int d = 0; d < 3; ++d) out->v.push_back((float)(g[d] * sc - bounds));
|
||||
for (int c = 0; c < 8; ++c) { any |= cb[c]; all &= cb[c]; }
|
||||
/* Cubes start at k < n - 1. */
|
||||
const int64_t k0 = w * 64;
|
||||
uint64_t live = any & ~all & ~bad;
|
||||
if (n - 1 - k0 < 64) live &= (n - 1 - k0 > 0) ? (1ull << (n - 1 - k0)) - 1 : 0;
|
||||
while (live) {
|
||||
const int b = __builtin_ctzll(live);
|
||||
live &= live - 1;
|
||||
const int64_t k = k0 + b;
|
||||
int m = 0;
|
||||
for (int c = 0; c < 8; ++c) m |= (int)((cb[c] >> b) & 1u) << c;
|
||||
float v[8];
|
||||
for (int c = 0; c < 8; ++c) v[c] = value(i + (c & 1), j + (c >> 1 & 1), k + (c >> 2 & 1));
|
||||
for (int t = 0; t < 30 && T.tri[m][t] >= 0; ++t) {
|
||||
const int e = T.tri[m][t];
|
||||
const int c0 = T.edge[e][0], c1 = T.edge[e][1], a = e / 4;
|
||||
const int64_t bi = c0 & 1, bj = c0 >> 1 & 1, bk = c0 >> 2 & 1;
|
||||
int32_t* slot = a == 0 ? &ex[(size_t)((j + bj) * n + k + bk)]
|
||||
: a == 1 ? &ey[bi][(size_t)(j * n + k + bk)]
|
||||
: &ez[bi][(size_t)((j + bj) * n + k)];
|
||||
if (!fresh(*slot, a, bi)) {
|
||||
const float t0 = v[c0], t1 = v[c1];
|
||||
const float f = t1 != t0 ? (lv - t0) / (t1 - t0) : 0.5f;
|
||||
float gp[3] = { (float)(i + bi), (float)(j + bj), (float)(k + bk) };
|
||||
gp[a] += f;
|
||||
*slot = (int32_t)(out->v.size() / 3);
|
||||
for (int d = 0; d < 3; ++d) out->v.push_back((float)(gp[d] * sc - bounds));
|
||||
}
|
||||
out->f.push_back((uint32_t)*slot);
|
||||
}
|
||||
out->f.push_back((uint32_t)*slot);
|
||||
}
|
||||
}
|
||||
}
|
||||
v_last = v_now;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -610,7 +737,7 @@ std::string glb(const ShapeMesh& m) {
|
||||
put(bin, nrm.data(), vb);
|
||||
put(bin, m.f.data(), ib);
|
||||
while (bin.size() % 4) bin.push_back('\0');
|
||||
using nlohmann::json;
|
||||
using json = Json;
|
||||
json j;
|
||||
j["asset"] = { { "version", "2.0" }, { "generator", "radiance" } };
|
||||
j["scene"] = 0;
|
||||
|
||||
@@ -356,11 +356,27 @@ const RadBatch* ShapeDriver::build_query(Job& j, int step) {
|
||||
const int64_t n = std::min<int64_t>(decl_.max_query, j.n_pts - j.next);
|
||||
const int64_t side = (int64_t)j.levels[j.level] + 1;
|
||||
float* q = hptr<float>(R_QUERY);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t p = j.all ? j.next + i : (int64_t)j.pts[(size_t)(j.next + i)];
|
||||
q[3 * i] = j.axis[(size_t)(p / (side * side))];
|
||||
q[3 * i + 1] = j.axis[(size_t)(p / side % side)];
|
||||
q[3 * i + 2] = j.axis[(size_t)(p % side)];
|
||||
const float* ax = j.axis.data();
|
||||
if (j.all) {
|
||||
/* Consecutive points: the grid coordinates count up like an odometer, with no division
|
||||
* past the first point's. */
|
||||
int64_t z = j.next / (side * side), y = j.next / side % side, x = j.next % side;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
q[3 * i] = ax[z];
|
||||
q[3 * i + 1] = ax[y];
|
||||
q[3 * i + 2] = ax[x];
|
||||
if (++x == side) {
|
||||
x = 0;
|
||||
if (++y == side) { y = 0; ++z; }
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t p = (int64_t)j.pts[(size_t)(j.next + i)];
|
||||
q[3 * i] = ax[p / (side * side)];
|
||||
q[3 * i + 1] = ax[p / side % side];
|
||||
q[3 * i + 2] = ax[p % side];
|
||||
}
|
||||
}
|
||||
reg_[R_QUERY].used = n * 3 * 4;
|
||||
const int32_t qcu[2] = { 0, (int32_t)n };
|
||||
@@ -397,9 +413,11 @@ int ShapeDriver::done() {
|
||||
break;
|
||||
case RAD_GEN_PASS_SQUERY: {
|
||||
const int64_t n = pass_.n_query;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t p = j->all ? j->next + i : (int64_t)j->pts[(size_t)(j->next + i)];
|
||||
j->field[(size_t)p] = field_host_[i];
|
||||
if (j->all) {
|
||||
std::memcpy(j->field.data() + j->next, field_host_, (size_t)n * sizeof(float));
|
||||
} else {
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
j->field[(size_t)j->pts[(size_t)(j->next + i)]] = field_host_[i];
|
||||
}
|
||||
j->next += n;
|
||||
j->points += n;
|
||||
|
||||
+6
-6
@@ -3,7 +3,7 @@
|
||||
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
@@ -93,8 +93,8 @@ std::vector<GenFieldSource> gen_sampling_sources(const GenSampling& stated, cons
|
||||
}
|
||||
|
||||
bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampling* out) {
|
||||
nlohmann::json j;
|
||||
try { j = nlohmann::json::parse(json_text); }
|
||||
Json j;
|
||||
try { j = Json::parse(json_text); }
|
||||
catch (const std::exception& e) { RAD_WARN("%s: %s; ignoring it", src, e.what()); return false; }
|
||||
if (!j.is_object()) { RAD_WARN("%s: not a JSON object; ignoring it", src); return false; }
|
||||
|
||||
@@ -190,7 +190,7 @@ bool gen_sampling_from_file(const std::string& path, bool required, GenSampling*
|
||||
bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, GenSampling* out) {
|
||||
/* Rebuilt as JSON and passed to gen_sampling_parse, so container metadata and the original
|
||||
* file share one set of range checks and one reading of `do_sample`. */
|
||||
nlohmann::json j = nlohmann::json::object();
|
||||
Json j = Json::object();
|
||||
static const char* const kFields[] = { "do_sample", "temperature", "top_p", "min_p", "top_k",
|
||||
"no_repeat_ngram_size", "no_repeat_ngram_window_size",
|
||||
"no_repeat_ngram_whitelist", "suppress_tokens" };
|
||||
@@ -206,7 +206,7 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
|
||||
/* Not a number: the container's metadata is string-valued, and the whitelist is a
|
||||
* JSON array spelled as JSON text. */
|
||||
try {
|
||||
j[k] = nlohmann::json::parse(v);
|
||||
j[k] = Json::parse(v);
|
||||
} catch (const std::exception& e) {
|
||||
RAD_WARN("the container states generation.%s as \"%s\", which is not a JSON "
|
||||
"array of ids (%s); ignoring it", k, v, e.what());
|
||||
@@ -215,7 +215,7 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
|
||||
}
|
||||
if (std::strcmp(k, "suppress_tokens") == 0) {
|
||||
/* An array of scalars is flattened to a space-separated string (flatten_json). */
|
||||
nlohmann::json ids = nlohmann::json::array();
|
||||
Json ids = Json::array();
|
||||
char* p = const_cast<char*>(v);
|
||||
for (char* e = nullptr;; p = e) {
|
||||
const long long id = std::strtoll(p, &e, 10);
|
||||
|
||||
Loaded 100 of 696 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user