Archived
Merge upstream main (v1.12 -> v1.15.1, 408 commits) into the SYCL port
Conflicts from the old m2xfp branch take upstream's version. Two libxe2 fixes the merge needs:
- rad_plugin_abi_layout: the plugin now exports the ABI layout hash the loader checks.
- gemm_nt_q_w4a16: upstream 492d33c sends bf16 activations to the w4a16 GEMM (the separate cast
is gone); the fast kernel took only f16, so every call fell back to the exact path (decode
~2.5 tok/s). A bf16 activation is narrowed to f16 (round to nearest even) into a workspace first,
the dropped cast bit for bit; decode back to ~57 tok/s on one request.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
7580ec3d17
937 files changed
+285244
-8382
No files matched your search
@@ -6,4 +6,3 @@ compile_commands.json
|
||||
/sync-jarvis.sh
|
||||
__pycache__/
|
||||
.cache/
|
||||
/paper/
|
||||
@@ -0,0 +1,22 @@
|
||||
# Codeberg CI (Woodpecker): the full suite on a machine without ROCm -- the CPU-only build, the
|
||||
# same posture as `./build.sh --no-hip` -- on the current Ubuntu LTS. The LTS is chosen, not
|
||||
# assumed: the media codecs must be new enough for the FFmpeg >= 7 callback signatures the mp4
|
||||
# writer binds (24.04's 6.1 does not compile), and the card suites (`*_card`, LABELS "gpu") want
|
||||
# hardware this runner does not have, so the run is the host preset -- everything but gpu and oot.
|
||||
# vendor_sums runs here as everywhere: a changed lift that the vendor record does not carry fails
|
||||
# CI before it fails a user.
|
||||
when:
|
||||
- event: [push, pull_request, tag]
|
||||
|
||||
steps:
|
||||
test:
|
||||
image: ubuntu:26.04
|
||||
commands:
|
||||
- export DEBIAN_FRONTEND=noninteractive
|
||||
- apt-get update -qq
|
||||
- apt-get install -y -qq --no-install-recommends git cmake ninja-build g++ pkg-config jq
|
||||
ca-certificates libavformat-dev libavcodec-dev libavutil-dev libswscale-dev
|
||||
libswresample-dev
|
||||
- cmake -S . -B build -G Ninja -DRAD_WITH_HIP=OFF -DRAD_WITH_FFMPEG=AUTO
|
||||
- cmake --build build -j "$(nproc)"
|
||||
- ctest --preset host # everything but gpu and oot, in the configured build dir
|
||||
+19
-1
@@ -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.11.0 LANGUAGES C CXX)
|
||||
project(radiance VERSION 1.15.1 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
@@ -385,6 +385,21 @@ add_subdirectory(libquant)
|
||||
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr4d/CMakeLists.txt)
|
||||
add_subdirectory(libr4d)
|
||||
endif()
|
||||
# libr3d: the RDNA3 kernel library, same shape as libr4d and same guard -- device code needs a HIP
|
||||
# toolchain. It declares itself for `^gfx11` and returns without a target when the build's
|
||||
# RAD_GPU_TARGETS holds no RDNA3, so a gfx12-only build of this tree does not produce it. A card
|
||||
# with no kernel library of its own refuses device-only ops (docs/PLUGIN.md §10).
|
||||
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr3d/CMakeLists.txt)
|
||||
add_subdirectory(libr3d)
|
||||
endif()
|
||||
# libhalo: the Strix Halo (gfx1151) kernel library, built only when RAD_GPU_TARGETS names gfx1151.
|
||||
# On a gfx1151 it is preferred over libr3d, which also serves the chip: with no --kernels list the
|
||||
# loader takes libraries in file-name order (libhalo.so ahead of libr3d.so), the first library with
|
||||
# a row for an op supplies it, and libhalo declines every machine without a gfx1151
|
||||
# (rad_plugin_open), so other RDNA3 cards get libr3d alone.
|
||||
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libhalo/CMakeLists.txt)
|
||||
add_subdirectory(libhalo)
|
||||
endif()
|
||||
# libavx: the production host kernels (x86 SIMD, dispatched by CPU feature), built on every x86-64.
|
||||
# Not optional: host-placed ops need a kernel other than the oracle (rad_gate_reference_kernels
|
||||
# refuses libref), and a table too large for the card, such as the n-gram embedding's gather, runs
|
||||
@@ -393,6 +408,9 @@ if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$")
|
||||
add_subdirectory(libavx)
|
||||
endif()
|
||||
add_subdirectory(arch)
|
||||
# spechub: the linear-MTP coupling kernels (--draft-coupling). Built by default; without the flag
|
||||
# no op resolves to its rows.
|
||||
add_subdirectory(plugin/spechub)
|
||||
add_subdirectory(tools)
|
||||
if(RAD_BUILD_TESTS)
|
||||
enable_testing()
|
||||
|
||||
@@ -140,9 +140,12 @@ ARG JOBS=
|
||||
# libstdc++, which is also the runtime image's. gawk: tools/ops_doc_check.sh uses gensub, which
|
||||
# mawk lacks. libdav1d7, libwebp7 and libopenh264-7 are the runtime libraries of the ffmpeg stage's
|
||||
# AV1 decoder, WebP encoder and H.264 encoder; busybox-static goes into the runtime image.
|
||||
# libopenblas-dev: libquant's GPTQ factorises its Hessians through LAPACK where it finds OpenBLAS
|
||||
# (libquant/CMakeLists.txt); without it rad-convert's gptq rule runs single-threaded loops.
|
||||
RUN apt-get update \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 libopenh264-7 busybox-static \
|
||||
libopenblas-dev \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg
|
||||
|
||||
@@ -15,28 +15,50 @@ Written by Deadcode, with contributions from:
|
||||
adaptive draft window, the MoE prefill forms, the sorted operand's decode kernel, two K blocks a
|
||||
pass for up to 80 routed rows, --prefill-span, the towers' lookup tables counted once, and for
|
||||
Gemma 4 its assistant head as a drafter that reads the trunk's cache, bf16 checkpoints, the fused
|
||||
w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume, and the
|
||||
Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files
|
||||
w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume, the
|
||||
Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files, Gemma 4's E2B/E4B form (KV-shared
|
||||
layers, per-layer embeddings, clipped vision linears) with NVIDIA-Nemotron-3.5-Bolt-E4B, its audio
|
||||
encoder, its i8a8 linears and its KV heads replicated over ranks, 4-bit weights at decode heights
|
||||
through w4a16_asym, and the Ornith-1.5-122B compose files
|
||||
- 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
|
||||
- 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
|
||||
ISA instruments' VGPR granule, back-edge count and fail-closed parse, scored steps
|
||||
(rad_declare_scores, RadBatch::score_only), the gated prefill fold, the short-prompt split row and
|
||||
the rows forms of rmsnorm and rope, and LFM2's 8-bit trunk with the d1-3B recipe
|
||||
- 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
|
||||
wire, the diagnosis of the three-rank lossy-wire crash, cardclock.py, --busy-prefill-chunk, curl,
|
||||
jq and a CA bundle in the image with hfget.sh under its busybox, rad-export, --prefill-interleave,
|
||||
runtime LoRA adapters served beside the base model and picked per request, and the prefix cache's
|
||||
reserved snapshots held until their save lands
|
||||
reserved snapshots held until their save lands, --expert-stats, imatrix entries in llama.cpp's
|
||||
spelling, typed tool-call argument tags, a chat template refused at load when it cannot render,
|
||||
rad-chatparse --request, a draft head's routed experts in host memory (--draft-expert-placement
|
||||
host) and decode-hot residency (--expert-profile, --expert-pin-top), prefix hits over KV groups of
|
||||
different block sizes and a hybrid's window in the checkpoint slot, --prefix-resume exact,
|
||||
DeepSeek-V4.1-Flash's conversion from its release (the Engram tables, the fused imatrix, the
|
||||
UD-IQ1_S recipe and rad-convert --chat-template), a preempted prefill admitted only with its
|
||||
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
|
||||
- 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
|
||||
asymmetric GEMMs
|
||||
asymmetric GEMMs, and the int8 tiled GEMMs loading the weight a slab ahead
|
||||
- Perire: Gemma 4 26B-A4B with z-lab's DFlash drafter -- its plugin, its kernels in libr4d (the
|
||||
windowed paged attention, pair_argmax, the fused sandwich joins and expert_scale) and the host
|
||||
emulator that tests them, the prefill split into two slices with their all-reduces beside the
|
||||
compute, and the vocabulary-sharded draft head; Gemma 4 31B on four cards (its all-reduces fused
|
||||
with the junctions, overlapped with the compute and sent compressed, chained launches with block
|
||||
drafters), the embedding scale rounded as Hugging Face rounds it, and block drafters' drafts
|
||||
accepted on the card
|
||||
drafters), the embedding scale rounded as Hugging Face rounds it, block drafters' drafts
|
||||
accepted on the card, z-lab's DFlash drafter drafting on after a prefix-cache hit and the 31B's
|
||||
GPTQ calibration tap, and for speculation the MTP head's first draft read up to where it sits, no
|
||||
step queued behind one that ends its requests, a step's tokens streamed before the drafter's
|
||||
passes end, a block drafter's proposals verified as a tree, the 31B's block-16 DFlash2 tree with
|
||||
its short block under load, a block drafter's window carried in the window snapshot, and window
|
||||
snapshots from short prompts
|
||||
- redxherring: --model taking a Hugging Face repo id
|
||||
- Smellyyyy: the idea behind --prefill-interleave
|
||||
- gearwave00001: /v1/messages as Claude Code sends it
|
||||
@@ -44,12 +66,26 @@ Written by Deadcode, with contributions from:
|
||||
- sfjes: Gemma 4 31B dense -- its plugin, its two attention classes and their kernels, and prefix
|
||||
reuse that leaves a windowed group alone -- and --host-headroom-mib
|
||||
- zivius: LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of their Codeberg
|
||||
PR 50, and Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime
|
||||
PR 50, Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime, and Fish Audio drama-3 -- its
|
||||
plugin, its codec encoder and decoder, voice cloning from reference clips, and the torch.save
|
||||
reader
|
||||
- mici81: Gemma 3 dense (TranslateGemma 27B) -- its plugin, the windowed h128 attention, the
|
||||
sandwich junction's all-reduce and its DFlash2 drafter -- the fp8_v4 and k6_v4 KV caches, GPTQ's
|
||||
factorisations through LAPACK and a column-split linear's Hessian from per-rank parts,
|
||||
R4D_AR_MAX_BLOCKS for two engines on one set of cards, and added tokens decoded as HuggingFace
|
||||
decodes them
|
||||
R4D_AR_MAX_BLOCKS for two engines on one set of cards, added tokens decoded as HuggingFace decodes
|
||||
them, the MXFP4 GEMM rows for one to 64 rows and the tiled prefill GEMM's TN=4 form, the fp8 and
|
||||
int8 heads read once up to 128 rows, the pipelined prefill of one sequence on a second lane, Gemma
|
||||
3's junctions under a lossy wire, the block drafter's short block (--draft-short-from), the f16
|
||||
delta-net state cache, the two-rank all-reduce checking a peer's push has landed, the MXFP4 decode
|
||||
gate_up folded with its activation and fp8 quantiser, the head-256 split-KV decode attention,
|
||||
weight reads beside the decode all-reduces (--weight-prefetch), the head-256 prefill attention's
|
||||
KV split for small launches, the GUIDE's two engines on one pair, DFlash2's coupled acceptance at
|
||||
T > 0, the prefix cache's snapshot at a head prompts share, tip-only's snapshot a drafter window
|
||||
below the tip, Gemma 3's fused all-reduce junction on the lossy wire, the three-wave verify's
|
||||
split by depth, the delta net's out-projection read beside its decode recurrent update, the MXFP4
|
||||
feed-forward's gated fold up to 16 rows, the three-wave verify floor bounded by the batch's
|
||||
workgroups, the split-KV row sum read with fetch-inactive, KLATE again for the head-256 gqa6
|
||||
paged prefill, and the preempted-prefill gate past a KV group that holds no blocks
|
||||
- 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
|
||||
@@ -59,7 +95,11 @@ Written by Deadcode, with contributions from:
|
||||
exclusions, jinja's dotted integer index, GLM-5.3-Flash's kernels in libr4d and tool calls whose
|
||||
name the opener opens, GLM-5.3-Flash's vision tower and processor, its decode at a few rows and
|
||||
its DSA indexer split over the ranks, a host-tier restore that makes room as pressure does, KV
|
||||
groups every rank holds kept once a host slot, and the eight-rank two-shot in ring order
|
||||
groups every rank holds kept once a host slot, the eight-rank two-shot in ring order, the MLA
|
||||
row form (--tp-attn-split rows), DELETE /sessions, the dispatch stamps of a played pass with
|
||||
stampgaps.py, one n-gram table for engines on separate cards (--ngram-placement ram=DIR), GGUF
|
||||
Q8_0, Q4_K and Q6_K tensors imported as their planes, the dense integer rows at the group they
|
||||
compute, and the GDN conv kernels on an f32 weight
|
||||
- John McDonough: GLM-5.3-Flash -- its plugin, its blocks (mHC streams, KDA, the DSA indexer and
|
||||
sparse latent attention, f32-scaled FP8 and MXFP4 experts under sigmoid routing) and their
|
||||
reference and AVX ops -- a Quark export's block-FP8 layers, the signed QSA ranking, the
|
||||
@@ -68,11 +108,48 @@ Written by Deadcode, with contributions from:
|
||||
the bringup time in /stats, the acceptance tiles' live figures and statsdump's size-capped
|
||||
rotation
|
||||
- C_Tamas: control vectors, loaded when the deployment asks and applied as a per-layer residual
|
||||
projection
|
||||
projection, KV streaming for a context bigger than VRAM (--kv-resident), and the dashboard's
|
||||
request history, KV streaming traffic and one-unit KV meter
|
||||
- J-Nova: Unlimited-OCR, and Sage-A1.5 with its vision tower and its DFlash2 drafter
|
||||
- thekk1: the fp8 QK and PV legs of the h256 prefill attention (--attn-prefill-fp8)
|
||||
- lortht: Krea 2's rebalance of the text taps
|
||||
- lortht: Krea 2's rebalance of the text taps and its presets, MiniMax-H3's modulation rows, and
|
||||
keyframes carried through a latent upscale
|
||||
- Quackster: cards with a small PCI BAR, their kernel arguments kept in host memory
|
||||
- farcryjohn: periodic window snapshots that let an edited prompt reuse its prefix
|
||||
- gostar: snapshot-backed prefix KV kept across recomputes, and Tencent's Hy-Memory (HYV3) -- its
|
||||
BF16, FP8 and GGUF adapters, its KV scales, its native sectioned tool calls, and its W4 decode
|
||||
(the per-128 I4 expert packing, the one-row W4/W5 epilogue and the fused prologue and folds)
|
||||
- launch80_assets: tuning collectives as the exchange they serve at the served configuration, the
|
||||
per-layer embeddings' read-ahead queue and gather regimes, and the step loop's stall watch
|
||||
- hugypufy: M2XFP4 -- its quantiser, its GEMMs and its linears in the Qwen3.8 trunk and the DFlash2
|
||||
drafter -- and the ParoQuant M2XFP4 import
|
||||
- steki: Gemma 4 E2B's per-layer MLP width and the bf16 descriptor for Google's E2B/E4B
|
||||
directories, nomic-embed-text-v2-moe (the nomicbert plugin), its config key aliases and
|
||||
RAD_MAP_TRANSPOSE honouring src_index, an f32 source narrowed to a bf16 declaration at load, and
|
||||
the snapshot store's floor ahead of --host-headroom-mib
|
||||
- griffin-warrior: the kernel report's consistency checks and coverage header, collective selftest
|
||||
cases skipped without a peer path, the build's media capability in the diagnostics, and the
|
||||
GUIDE's ROCm SDK and ffmpeg notes
|
||||
- nickreese: GBNF bounded-repetition chains shared across identical operands
|
||||
- Dad_Vibes: hc_read's decode kernels as one grid, its tiled up-mix pipelined and its one-grid
|
||||
wait trapping past its deadline, and gemm_fp8a8's narrow form with its scales staged through LDS
|
||||
and its gated three-tile form at 8 waves
|
||||
- RikshaDriver: libr3d, the RDNA3 (gfx11) kernel library
|
||||
- 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
|
||||
name no vocabulary row refused, and the telemetry the HTTP thread reads made atomic
|
||||
- Brandon Bertelsen: Cloudflare's clef and clef-flash with their joint schema head on the card
|
||||
(seg_softmax_pool, a request's words for the plugin), Convai Innovations' Laya decision models,
|
||||
Mica on /v1/systemone, and Metaspace prepending only to text not already starting with its
|
||||
replacement
|
||||
- Gaspa79: NVIDIA's Nemotron 3.5 Embed 1B and 8B -- the nemotron35_embed plugin, its Pixtral
|
||||
tower and their CPU path -- and Nemotron 3.5 Rerank 8B on /rerank, with its BF16 masked mean
|
||||
(seg_mean_bf16_sum)
|
||||
- overchop: the file tier for large MoEs -- routing-aware reads of only the routed experts, the
|
||||
hot VRAM cache with its deposits and copyless relabels, and GLM-5.3-Flash's experts read
|
||||
file-direct under expert parallelism -- the stall watch counting drive reads as progress, and
|
||||
the DMA lane's lists fenced so a stalled read pointer no longer fills its ring
|
||||
|
||||
This product includes software from the following projects, each under the MIT License. The
|
||||
license text is in the file named beside each.
|
||||
@@ -84,6 +161,11 @@ license text is in the file named beside each.
|
||||
nlohmann/json Copyright (c) 2013-2025 Niels Lohmann vendor/nlohmann/LICENSE.MIT
|
||||
cpp-httplib Copyright (c) 2017 yhirose vendor/cpp-httplib/LICENSE
|
||||
|
||||
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).
|
||||
Its source and content checksum are recorded in tests/data/chat/hyv3/README.md.
|
||||
|
||||
core/server/systemone.cpp carries text from Liquid AI's d1 (prompt.py and api.py in the
|
||||
LiquidAI/d1-3B repository): the prompt it renders, its question blocks, the option codes and their
|
||||
fallback codebook and the answer spellings, unchanged, in code rewritten in C++. That text is Liquid
|
||||
@@ -98,3 +180,28 @@ Community License 1.0 -- data/vectors/LICENSE.qwen-community-1.0.txt -- which ca
|
||||
every copy of it, including its condition that a Model-as-a-Service or AI-work-assistant business
|
||||
needs a separate license from Qwen to use it commercially. radiance's Apache-2.0 grant covers the
|
||||
code that loads and applies the file; it does not cover the file or its directions.
|
||||
|
||||
core/server/clef.cpp carries clef's system prompt, and it and arch/common/rad_block_clef.h follow
|
||||
clef's released joint head (Cloudflare's clef and clef-flash, Hugging Face, Apache-2.0).
|
||||
core/server/laya.cpp is a rewrite of the laya package (github.com/NandhaKishorM/laya, Apache-2.0).
|
||||
core/server/mica.cpp carries Mica's system prompt and option labels and is a rewrite of its
|
||||
contract.py and native.py, and tests/data/golden/mica_contract_cases.json is its
|
||||
tests/fixtures/contract_cases.json (github.com/akivet/Mica, Apache-2.0).
|
||||
|
||||
Nemotron 3.5 input fixtures
|
||||
--------------------------
|
||||
|
||||
tests/data/chat/nemotron35/template.jinja and tokenizer-subset.json come from NVIDIA's
|
||||
Nemotron-3.5-Embed-8B-BF16 checkpoint, revision
|
||||
781e779ee4ca9c2d2a4f38321993556baeab49a1:
|
||||
https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16/tree/781e779ee4ca9c2d2a4f38321993556baeab49a1
|
||||
The checkpoint's governing license is OpenMDW-1.1, retained in
|
||||
tests/data/chat/nemotron35/LICENSE. The tokenizer fixture is a subset preserving source token
|
||||
IDs and the BPE entries needed by the test corpus; it is not the complete serving tokenizer.
|
||||
|
||||
tests/data/chat/nemotron35/rerank-template.jinja comes from NVIDIA's
|
||||
Nemotron-3.5-Rerank-8B-BF16 checkpoint, revision
|
||||
f88f8d9104726747791283ab156d2fcdb29e90a7:
|
||||
https://huggingface.co/nvidia/Nemotron-3.5-Rerank-8B-BF16/tree/f88f8d9104726747791283ab156d2fcdb29e90a7
|
||||
It is covered by the same retained OpenMDW-1.1 license.
|
||||
Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
||||
@@ -94,15 +94,26 @@ it (`-DRAD_XE2_MKL=OFF`, or `XE2_NO_MKL=1` at run time, keeps the hand-written p
|
||||
| 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` |
|
||||
| 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` |
|
||||
| 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` |
|
||||
| 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` |
|
||||
@@ -116,6 +127,7 @@ it (`-DRAD_XE2_MKL=OFF`, or `XE2_NO_MKL=1` at run time, keeps the hand-written p
|
||||
| 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` |
|
||||
@@ -123,6 +135,10 @@ it (`-DRAD_XE2_MKL=OFF`, or `XE2_NO_MKL=1` at run time, keeps the hand-written p
|
||||
| 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) | - |
|
||||
| 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) | — |
|
||||
|
||||
@@ -180,15 +196,21 @@ soundtrack from a prompt, 5 to 14 s, up to 1344x768. On two R9700s a 5.17 s clip
|
||||
about 68 s with FastH3 and 8.8 minutes at MiniMax-H3's 50 steps; both read about 39 GiB of pinned
|
||||
host memory. With LBH-123-AI's latent upscaler in the container, `"latent_upscale": 2` runs the first
|
||||
steps at half the size and refines at the full size: MiniMax-H3's clip then takes 3.4 minutes
|
||||
(docs/GUIDE.md §5.16). MiniMax-H3's license, which FastH3 carries, does not cover the EU, the UK,
|
||||
the Republic of Korea or the USA.
|
||||
(docs/GUIDE.md §5.16). A ComfyUI node, `integrations/comfyui/ComfyUI-Radiance-MiniMax`, renders
|
||||
through `/v1/videos` from a ComfyUI graph as a client of the server. MiniMax-H3's license, which
|
||||
FastH3 carries, does not cover the EU, the UK, the Republic of Korea or the USA.
|
||||
|
||||
MiniMax-Music3 and Breeze-TTS-2 answer `/v1/audio/speech`, whole or streamed as they are made: a song
|
||||
from lyrics and a description, 44.1 kHz stereo, made at about the speed it plays on two cards; and
|
||||
speech in a voice the request describes, made in 0.6 of its playing time on one card, its first
|
||||
streamed audio 0.21 s after the request. Breeze-TTS-2 also speaks text while it is being written,
|
||||
over the `/v1/audio/speech/stream` WebSocket; it is licensed for research and non-commercial use
|
||||
only.
|
||||
only. Fish Audio's drama-3 speaks a script whose speakers and direction are written in it
|
||||
(`<|speaker:1|>`, `[laughs]`), each speaker in the model's voice or one cloned from a reference
|
||||
clip and its transcript, at 0.3 of its playing time on two cards, its first streamed audio
|
||||
0.23 s after the request; under the Fish Audio Community License a service that lets others
|
||||
generate speech with it needs a licence from Fish Audio, and imitating a real person's voice needs
|
||||
their consent.
|
||||
|
||||
## Run with Docker
|
||||
|
||||
@@ -273,6 +295,7 @@ four-rank rows have no compose file. The other models' flags are in their compos
|
||||
| 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` |
|
||||
|
||||
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
|
||||
@@ -383,6 +406,7 @@ ctest --test-dir build -L oot # rebuilds every bundled plugin out o
|
||||
| [`docs/GUIDE.md`](docs/GUIDE.md) | installing, converting, serving, the HTTP API, operating a server |
|
||||
| [`docs/TOOLS.md`](docs/TOOLS.md) | every flag of every tool, and the recipe syntax |
|
||||
| [`docs/DOCKER.md`](docs/DOCKER.md) | the image and the compose files |
|
||||
| [`docs/PREPARING_YOUR_RIG.md`](docs/PREPARING_YOUR_RIG.md) | a two-R9700 machine from firmware setup to a serving model |
|
||||
| [`docs/PLUGIN.md`](docs/PLUGIN.md) | writing a kernel library, architecture or quantiser plugin, including one for another AMD card |
|
||||
| [`docs/ARCHITECTURES.md`](docs/ARCHITECTURES.md) | the supported model families and their geometry |
|
||||
| [`docs/TP3.md`](docs/TP3.md) | any world size: the attention world and uneven delta-net heads; three ranks |
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+25
-8
@@ -13,12 +13,15 @@ extern "C" {
|
||||
#endif
|
||||
|
||||
/* Bumped whenever anything a plugin compiles against changes shape: this header, rad_types.h,
|
||||
* rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h or rad_sample.h. Every
|
||||
* kind of plugin reports it, and a plugin that does not report exactly this version is refused at
|
||||
* load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a
|
||||
* change of shape: a plugin without it gets the default. rad_sycl.h is versioned on its own
|
||||
* (RAD_SYCL_STREAM_VERSION), since only SYCL kernel libraries read it. */
|
||||
#define RAD_ABI_VERSION 26u
|
||||
* rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h, rad_sample.h or
|
||||
* rad_spechub.h, a field appended to a struct included; the release that ships the change assigns
|
||||
* the number. Every kind of plugin reports it, and a plugin that does not report exactly this
|
||||
* 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.
|
||||
* rad_sycl.h is versioned on its own (RAD_SYCL_STREAM_VERSION), since only SYCL kernel libraries
|
||||
* read it. */
|
||||
#define RAD_ABI_VERSION 32u
|
||||
|
||||
/* ================================================================== plugin identity */
|
||||
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
|
||||
@@ -36,8 +39,10 @@ typedef struct RadPluginInfo {
|
||||
const char* build_target;
|
||||
} RadPluginInfo;
|
||||
|
||||
/* Every plugin exports these two. */
|
||||
/* Every plugin exports these three; rad_plugin_abi_layout is RAD_PLUGIN_ABI_LAYOUT_EXPORT
|
||||
* (rad_abi_layout.h). */
|
||||
uint32_t rad_plugin_abi_version(void);
|
||||
uint64_t rad_plugin_abi_layout(void);
|
||||
const RadPluginInfo* rad_plugin_info(void);
|
||||
|
||||
/* ================================================================== execution domain */
|
||||
@@ -550,9 +555,21 @@ typedef int (*RadKernelCollectiveFn)(int i);
|
||||
* - the engine refuses to serve a model with an op only a reference library implements, unless
|
||||
* given --debug-accept-reference-kernels;
|
||||
* - rad-kbench checks every other library against it.
|
||||
* Without the symbol, or with 0, it is an ordinary library. Symbol name: `rad_plugin_reference`. */
|
||||
* Without the symbol, or with 0, it is an ordinary library. Symbol name: `rad_plugin_reference`.
|
||||
*
|
||||
* It is a whole-library answer, because a library is usually one implementation of one thing. A
|
||||
* plugin that ships a device row AND the host oracle beside it is not: marking the library would
|
||||
* mark its device rows too, and the engine would refuse to serve an op that has a real kernel.
|
||||
* Such a plugin exports `rad_kernel_reference` below and leaves this one 0. */
|
||||
typedef int (*RadPluginReferenceFn)(void);
|
||||
|
||||
/* Optional, per row: nonzero says kernel `i` of rad_kernel_at is that row's reference
|
||||
* implementation. Overrides `rad_plugin_reference` for the rows it is exported for, so one
|
||||
* library can declare a device row (0) and its host oracle (1) side by side. A plugin that
|
||||
* exports neither leaves every row classified by `rad_plugin_reference`. Symbol name:
|
||||
* `rad_kernel_reference`. */
|
||||
typedef int (*RadKernelReferenceFn)(int i);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
/* rad_abi_layout.h -- the plugin ABI's layout fingerprint: a hash of the size of every struct abi/
|
||||
* exports and of the offset and size of each of its fields (rad_abi_layout_rows.h), as the
|
||||
* translation unit that includes this header sees them.
|
||||
*
|
||||
* RAD_ABI_VERSION names a layout, but two trees can give the same number to different layouts, and
|
||||
* a plugin built against one then reads the other's structs at the wrong offsets, with no error. A
|
||||
* plugin exports its own fingerprint (RAD_PLUGIN_ABI_LAYOUT_EXPORT, once in the plugin), and the
|
||||
* loader refuses one whose fingerprint differs from the engine's under the same version. C and C++.
|
||||
*/
|
||||
#ifndef RAD_ABI_LAYOUT_H
|
||||
#define RAD_ABI_LAYOUT_H
|
||||
|
||||
#include "rad_abi.h"
|
||||
#include "rad_builder.h"
|
||||
#include "rad_device.h"
|
||||
#include "rad_encoding.h"
|
||||
#include "rad_format.h"
|
||||
#include "rad_philox.h"
|
||||
#include "rad_planes.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "rad_quant.h"
|
||||
#include "rad_runtime.h"
|
||||
#include "rad_sample.h"
|
||||
#include "rad_spechub.h"
|
||||
#include "rad_sycl.h"
|
||||
#include "rad_types.h"
|
||||
#include "rad_yarn.h"
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* FNV-1a over the eight bytes of `v`, little end first. */
|
||||
static inline uint64_t rad_abi_layout_mix(uint64_t h, uint64_t v) {
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
h ^= (v >> (8 * i)) & 0xffu;
|
||||
h *= 0x100000001b3ull;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
/* The fingerprint of the abi/ headers this translation unit was compiled against. */
|
||||
static inline uint64_t rad_abi_layout(void) {
|
||||
uint64_t h = 0xcbf29ce484222325ull;
|
||||
h = rad_abi_layout_mix(h, RAD_ABI_VERSION);
|
||||
#define ABI_STRUCT(T) h = rad_abi_layout_mix(h, sizeof(T));
|
||||
#define ABI_FIELD(T, f) \
|
||||
h = rad_abi_layout_mix(h, offsetof(T, f)); \
|
||||
h = rad_abi_layout_mix(h, sizeof(((T*)0)->f));
|
||||
#include "rad_abi_layout_rows.h"
|
||||
#undef ABI_STRUCT
|
||||
#undef ABI_FIELD
|
||||
return h;
|
||||
}
|
||||
|
||||
/* The export the loader reads beside rad_plugin_abi_version: written once in a plugin, at file
|
||||
* scope. */
|
||||
#ifdef __cplusplus
|
||||
#define RAD_PLUGIN_ABI_LAYOUT_EXPORT \
|
||||
extern "C" uint64_t rad_plugin_abi_layout(void) { return rad_abi_layout(); }
|
||||
#else
|
||||
#define RAD_PLUGIN_ABI_LAYOUT_EXPORT \
|
||||
uint64_t rad_plugin_abi_layout(void) { return rad_abi_layout(); }
|
||||
#endif
|
||||
|
||||
#endif /* RAD_ABI_LAYOUT_H */
|
||||
@@ -1,6 +1,7 @@
|
||||
/* abi_layout_rows.h -- every struct abi/ exports and each of its top-level fields, as
|
||||
* ABI_STRUCT(type) and ABI_FIELD(type, field) lines; the includer defines both. abi_c_test.c and
|
||||
* abi_layout_test.cpp include it, so the C and C++ translation units list the same rows.
|
||||
/* rad_abi_layout_rows.h -- every struct abi/ exports and each of its top-level fields, as
|
||||
* ABI_STRUCT(type) and ABI_FIELD(type, field) lines; the includer defines both. rad_abi_layout.h
|
||||
* hashes them into the layout fingerprint every plugin exports, and tests/abi_c_test.c and
|
||||
* tests/abi_layout_test.cpp list them, so the C and C++ translation units see the same rows.
|
||||
*
|
||||
* A struct or field added to abi/ is added here too: abi_layout_test fails on a struct whose
|
||||
* listed fields do not account for its size. Included once per table, so it has no include guard.
|
||||
@@ -18,7 +19,13 @@ ABI_FIELD(RadArchProbe, gen_ctx)
|
||||
ABI_FIELD(RadArchProbe, gen_video)
|
||||
ABI_FIELD(RadArchProbe, kv_quant_ok)
|
||||
ABI_FIELD(RadArchProbe, chain_pays)
|
||||
ABI_FIELD(RadArchProbe, kv_stream_ok)
|
||||
ABI_FIELD(RadArchProbe, control_vector_ok)
|
||||
ABI_FIELD(RadArchProbe, tp_attn_rows_ok)
|
||||
ABI_FIELD(RadArchProbe, state_f16_ok)
|
||||
ABI_FIELD(RadArchProbe, tree_pays)
|
||||
ABI_FIELD(RadArchProbe, gen_max_pixels)
|
||||
ABI_FIELD(RadArchProbe, gen_max_refs)
|
||||
ABI_STRUCT(RadArgs)
|
||||
ABI_FIELD(RadArgs, t)
|
||||
ABI_FIELD(RadArgs, n_t)
|
||||
@@ -80,6 +87,12 @@ ABI_FIELD(RadBatch, vgen_b)
|
||||
ABI_FIELD(RadBatch, control_vector)
|
||||
ABI_FIELD(RadBatch, enc_seg_h)
|
||||
ABI_FIELD(RadBatch, enc_seg_w)
|
||||
ABI_FIELD(RadBatch, score_only)
|
||||
ABI_FIELD(RadBatch, n_plugin_words)
|
||||
ABI_FIELD(RadBatch, plugin_words)
|
||||
ABI_FIELD(RadBatch, plugin_cu)
|
||||
ABI_FIELD(RadBatch, plugin_words_h)
|
||||
ABI_FIELD(RadBatch, plugin_cu_h)
|
||||
ABI_STRUCT(RadBufDecl)
|
||||
ABI_FIELD(RadBufDecl, dtype)
|
||||
ABI_FIELD(RadBufDecl, rank)
|
||||
@@ -107,7 +120,20 @@ 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)
|
||||
ABI_FIELD(RadBuildCtx, tp_attn_rows)
|
||||
ABI_FIELD(RadBuildCtx, state_dtype)
|
||||
ABI_FIELD(RadBuildCtx, draft_coupling)
|
||||
ABI_FIELD(RadBuildCtx, weight_prefetch_off)
|
||||
ABI_FIELD(RadBuildCtx, draft_tree)
|
||||
ABI_FIELD(RadBuildCtx, calib_dir)
|
||||
ABI_FIELD(RadBuildCtx, calib_layer_lo)
|
||||
ABI_FIELD(RadBuildCtx, calib_layer_hi)
|
||||
ABI_FIELD(RadBuildCtx, calib_tokens)
|
||||
ABI_FIELD(RadBuildCtx, gen_max_pixels)
|
||||
ABI_FIELD(RadBuildCtx, gen_max_refs)
|
||||
ABI_STRUCT(RadAudioGenBatch)
|
||||
ABI_FIELD(RadAudioGenBatch, n_lane)
|
||||
ABI_FIELD(RadAudioGenBatch, lane)
|
||||
@@ -144,6 +170,16 @@ ABI_FIELD(RadAudioGenBatch, voc_latents)
|
||||
ABI_FIELD(RadAudioGenBatch, voc_left)
|
||||
ABI_FIELD(RadAudioGenBatch, voc_right)
|
||||
ABI_FIELD(RadAudioGenBatch, voc_frame0)
|
||||
ABI_FIELD(RadAudioGenBatch, prev_slot)
|
||||
ABI_FIELD(RadAudioGenBatch, prev_pos)
|
||||
ABI_FIELD(RadAudioGenBatch, prev_used)
|
||||
ABI_FIELD(RadAudioGenBatch, n_ref)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_samples)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_audio)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_cu)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_cu_h)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_frame)
|
||||
ABI_FIELD(RadAudioGenBatch, ref_frame_h)
|
||||
ABI_STRUCT(RadAudioGenDecl)
|
||||
ABI_FIELD(RadAudioGenDecl, name)
|
||||
ABI_FIELD(RadAudioGenDecl, tmpl)
|
||||
@@ -176,6 +212,14 @@ ABI_FIELD(RadAudioGenDecl, prompt_whole)
|
||||
ABI_FIELD(RadAudioGenDecl, first_frame)
|
||||
ABI_FIELD(RadAudioGenDecl, voc_chunk)
|
||||
ABI_FIELD(RadAudioGenDecl, voc_context)
|
||||
ABI_FIELD(RadAudioGenDecl, branches)
|
||||
ABI_FIELD(RadAudioGenDecl, input_special)
|
||||
ABI_FIELD(RadAudioGenDecl, tmpl_ref)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_item)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_rate)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_hop)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_max_samples)
|
||||
ABI_FIELD(RadAudioGenDecl, ref_max)
|
||||
ABI_STRUCT(RadControlVector)
|
||||
ABI_FIELD(RadControlVector, dir)
|
||||
ABI_FIELD(RadControlVector, scales)
|
||||
@@ -221,6 +265,7 @@ ABI_FIELD(RadChatFormat, object_string_open)
|
||||
ABI_FIELD(RadChatFormat, object_string_close)
|
||||
ABI_FIELD(RadChatFormat, object_bare_keys)
|
||||
ABI_FIELD(RadChatFormat, reasoning_anywhere)
|
||||
ABI_FIELD(RadChatFormat, arg_json_value_prefix)
|
||||
ABI_STRUCT(RadConstraint)
|
||||
ABI_FIELD(RadConstraint, key)
|
||||
ABI_FIELD(RadConstraint, op)
|
||||
@@ -237,6 +282,7 @@ ABI_FIELD(RadDeviceProps, vram_free)
|
||||
ABI_FIELD(RadDeviceProps, lds_bytes)
|
||||
ABI_FIELD(RadDeviceProps, supports_p2p)
|
||||
ABI_FIELD(RadDeviceProps, is_host_backend)
|
||||
ABI_FIELD(RadDeviceProps, unified)
|
||||
ABI_STRUCT(RadDrafterDecl)
|
||||
ABI_FIELD(RadDrafterDecl, name)
|
||||
ABI_FIELD(RadDrafterDecl, kind)
|
||||
@@ -453,6 +499,7 @@ ABI_FIELD(RadKVGroupBatch, state_index)
|
||||
ABI_FIELD(RadKVGroupBatch, state_index_pitch)
|
||||
ABI_FIELD(RadKVGroupBatch, block_size)
|
||||
ABI_FIELD(RadKVGroupBatch, max_blocks)
|
||||
ABI_FIELD(RadKVGroupBatch, stream)
|
||||
ABI_STRUCT(RadKVGroupDecl)
|
||||
ABI_FIELD(RadKVGroupDecl, kind)
|
||||
ABI_FIELD(RadKVGroupDecl, dtype)
|
||||
@@ -461,6 +508,16 @@ ABI_FIELD(RadKVGroupDecl, n_head_kv)
|
||||
ABI_FIELD(RadKVGroupDecl, head_dim)
|
||||
ABI_FIELD(RadKVGroupDecl, state_dim)
|
||||
ABI_FIELD(RadKVGroupDecl, conv_width)
|
||||
ABI_STRUCT(RadKVStream)
|
||||
ABI_FIELD(RadKVStream, host)
|
||||
ABI_FIELD(RadKVStream, res)
|
||||
ABI_FIELD(RadKVStream, slot_block)
|
||||
ABI_FIELD(RadKVStream, slot_state)
|
||||
ABI_FIELD(RadKVStream, ctl)
|
||||
ABI_FIELD(RadKVStream, block_bytes)
|
||||
ABI_FIELD(RadKVStream, host_layer_stride)
|
||||
ABI_FIELD(RadKVStream, slots)
|
||||
ABI_FIELD(RadKVStream, host_bytes)
|
||||
ABI_STRUCT(RadKernelInfo)
|
||||
ABI_FIELD(RadKernelInfo, name)
|
||||
ABI_FIELD(RadKernelInfo, op)
|
||||
@@ -688,6 +745,19 @@ ABI_FIELD(RadVideoGenBatch, image)
|
||||
ABI_FIELD(RadVideoGenBatch, has_image)
|
||||
ABI_FIELD(RadVideoGenBatch, guidance)
|
||||
ABI_FIELD(RadVideoGenBatch, decoder)
|
||||
ABI_FIELD(RadVideoGenBatch, sampler)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_pixels)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_frames)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_height)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_width)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_samples)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_n_samples)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_channels)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_geom_d)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_kind)
|
||||
ABI_FIELD(RadVideoGenBatch, enc_slot)
|
||||
ABI_FIELD(RadVideoGenBatch, ref_tab)
|
||||
ABI_FIELD(RadVideoGenBatch, mod_cu)
|
||||
ABI_STRUCT(RadVideoGenDecl)
|
||||
ABI_FIELD(RadVideoGenDecl, name)
|
||||
ABI_FIELD(RadVideoGenDecl, tmpl)
|
||||
@@ -750,6 +820,14 @@ ABI_FIELD(RadVideoGenDecl, duration_max)
|
||||
ABI_FIELD(RadVideoGenDecl, duration_dtype)
|
||||
ABI_FIELD(RadVideoGenDecl, decoders)
|
||||
ABI_FIELD(RadVideoGenDecl, decoder_max_area)
|
||||
ABI_FIELD(RadVideoGenDecl, max_ref_images)
|
||||
ABI_FIELD(RadVideoGenDecl, max_ref_videos)
|
||||
ABI_FIELD(RadVideoGenDecl, max_ref_audios)
|
||||
ABI_FIELD(RadVideoGenDecl, max_enc_frames)
|
||||
ABI_FIELD(RadVideoGenDecl, max_enc_side)
|
||||
ABI_FIELD(RadVideoGenDecl, max_enc_samples)
|
||||
ABI_FIELD(RadVideoGenDecl, enc_ratio)
|
||||
ABI_FIELD(RadVideoGenDecl, max_mod_cells)
|
||||
ABI_STRUCT(RadVideoGeom)
|
||||
ABI_FIELD(RadVideoGeom, n_text)
|
||||
ABI_FIELD(RadVideoGeom, frames)
|
||||
@@ -805,3 +883,18 @@ ABI_FIELD(RadYarn, factor)
|
||||
ABI_FIELD(RadYarn, low)
|
||||
ABI_FIELD(RadYarn, high)
|
||||
ABI_FIELD(RadYarn, magnitude)
|
||||
ABI_STRUCT(RadMtpCoupleDraw)
|
||||
ABI_FIELD(RadMtpCoupleDraw, seed)
|
||||
ABI_FIELD(RadMtpCoupleDraw, base)
|
||||
ABI_FIELD(RadMtpCoupleDraw, seq)
|
||||
ABI_FIELD(RadMtpCoupleDraw, card)
|
||||
ABI_FIELD(RadMtpCoupleDraw, mode)
|
||||
ABI_STRUCT(RadMtpCoupleState)
|
||||
ABI_FIELD(RadMtpCoupleState, draw)
|
||||
ABI_FIELD(RadMtpCoupleState, pos)
|
||||
ABI_FIELD(RadMtpCoupleState, status)
|
||||
ABI_FIELD(RadMtpCoupleState, round)
|
||||
ABI_FIELD(RadMtpCoupleState, x)
|
||||
ABI_FIELD(RadMtpCoupleState, count)
|
||||
ABI_FIELD(RadMtpCoupleState, ids)
|
||||
ABI_FIELD(RadMtpCoupleState, q)
|
||||
+311
-18
@@ -188,11 +188,20 @@ typedef struct RadBuildCtx {
|
||||
* 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 and a plugin built
|
||||
* against the older struct is unchanged. */
|
||||
* Zero-defaulted and in the padding after kv_quant, so no other field moves. */
|
||||
int attn_prefill_fp8;
|
||||
|
||||
/* ---- appended in ABI 26 (control vectors) */
|
||||
/* ---- 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
|
||||
* its `kv_resolve`'s ring depth. */
|
||||
int64_t kv_resident_blocks;
|
||||
/* RadArchProbe::kv_stream_ok. The streamed-only ops (`kv_store_streamed`, its folded form,
|
||||
* `kv_resolve`) are declared only when this is set and kv_resident_blocks asks for a ring;
|
||||
* otherwise rad_op_declared says no and the plugin takes its resident path. */
|
||||
int kv_stream_ok;
|
||||
|
||||
/* ---- appended in ABI 27 (control vectors) */
|
||||
/* A control vector loaded from a GGUF `controlvector` file found for this model, or null.
|
||||
*
|
||||
* The engine loads and validates it once, at bringup, and the plugin only reads it: the
|
||||
@@ -208,6 +217,84 @@ typedef struct RadBuildCtx {
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
const struct RadControlVector* cvec;
|
||||
|
||||
/* ---- appended in ABI 27 (row-split prefill attention) */
|
||||
/* 1 from --tp-attn-split rows: from the plugin's split threshold, a prefill-sized step under
|
||||
* tensor parallelism runs attention by rows, each rank all heads of its run of the step's
|
||||
* rows and an all_gather of the runs, instead of by heads. It is faster where the attention
|
||||
* dominates, costs the full-width projections on every rank, and is not bit-identical to the
|
||||
* head split. 0 (the zero-initialised default) is the head split. The engine sets it only
|
||||
* above one rank and only for a plugin whose probe sets RadArchProbe::tp_attn_rows_ok, and
|
||||
* refuses the flag otherwise.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int tp_attn_rows;
|
||||
|
||||
/* ---- appended in ABI 27 (recurrent state at f16) */
|
||||
/* RAD_F16 from --state-cache-dtype f16: the recurrent state caches (RAD_KV_LINEAR groups) are
|
||||
* stored at f16 instead of the plugin's f32, which halves the state pool, its checkpoints and
|
||||
* its traffic and changes the generated text. 0 (the zero-initialised default) is the
|
||||
* plugin's own width. The engine sets it only for a plugin whose probe has
|
||||
* RadArchProbe::state_f16_ok and refuses the flag otherwise.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
uint32_t state_dtype;
|
||||
|
||||
/* ---- appended in ABI 27 (draft coupling) */
|
||||
/* Nonzero from --draft-coupling on: a linear serial drafter samples each round's proposal from
|
||||
* its own shortlist law, or a block drafter's walk each position's (DFlash2), and declares the
|
||||
* planes and ops the coupled verify reads (abi/rad_spechub.h, docs/OPS.md `mtp_couple_propose`,
|
||||
* `dflash_couple_propose`). 0, the zero-initialised default,
|
||||
* declares the greedy drafter. A plugin that cannot couple returns RAD_E_UNSUPPORTED from
|
||||
* declare when it is set; the engine refuses a model whose program carries no coupled planes.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int draft_coupling;
|
||||
|
||||
/* ---- appended in ABI 28 (weight prefetch) */
|
||||
/* Nonzero from --weight-prefetch off: the plugin declares none of its weight prefetches, the
|
||||
* reads of a following GEMM's weight beside a collective (arch/common/rad_arch.h
|
||||
* prefetch_beside). An engine that shares its cards with another server sets it: where the
|
||||
* read goes on the second lane, the two servers hold more compute queues than a card has
|
||||
* slots, and the join from the first lane puts a queue switch into every decode step. 0, the
|
||||
* zero-initialised default, prefetches where the plugin does.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int weight_prefetch_off;
|
||||
|
||||
/* ---- appended in ABI 31 (tree verification) */
|
||||
/* Nonzero: grow the block drafter's proposals into a tree (rad_drafter_tree) where the plugin
|
||||
* can. The engine sets it where the plugin's probe said trees pay (RadArchProbe::tree_pays)
|
||||
* and the drafter decodes speculatively; 0 keeps the chain. A plugin that grows no trees
|
||||
* ignores it. 64-bit so it starts past the older
|
||||
* struct's tail padding, where a plugin built against it would read nothing.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int64_t draft_tree;
|
||||
|
||||
/* ---- appended in ABI 32 (calibration) */
|
||||
/* --calib-dir DIR: the deployment records calibration statistics (the second moment of each
|
||||
* linear's input, GPTQ's Hessian) into DIR; null records nothing. A plugin that keeps none
|
||||
* ignores it. `calib_layer_lo`..`calib_layer_hi` (--calib-layers, hi exclusive; both 0 for
|
||||
* every layer) bound the layers recorded in one run, so a model whose statistics do not fit
|
||||
* in memory at once is recorded in several runs over the same corpus. `calib_tokens` is the
|
||||
* corpus's token count under --calib-corpus: the plugin writes its files once it has seen
|
||||
* that many rows; 0 when the deployment drives no corpus.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
const char* calib_dir;
|
||||
int32_t calib_layer_lo;
|
||||
int32_t calib_layer_hi;
|
||||
int64_t calib_tokens;
|
||||
|
||||
/* ---- appended in ABI 32 (an image generator's bounds) */
|
||||
/* --image-gen-max-pixels: the largest image an image generator makes, in pixels; and
|
||||
* --image-gen-max-refs: the reference pictures a request at most. 0: the model's own. A
|
||||
* generator sizes its per-image and conditioning buffers for them and states them in its
|
||||
* RadGeneratorDecl (max_tokens, max_refs), which the core holds requests to; one that keeps
|
||||
* fixed buffers ignores them, and the core says so at startup. */
|
||||
int64_t gen_max_pixels;
|
||||
int64_t gen_max_refs;
|
||||
} RadBuildCtx;
|
||||
|
||||
/* ================================================================== control vectors */
|
||||
@@ -396,6 +483,10 @@ typedef struct RadKVGroupDecl {
|
||||
rad_kvgroup rad_decl_kv_group(RadBuilder* b, const char* name, const RadKVGroupDecl* d);
|
||||
/* Valid only after the op that reads this group has been declared. 0 before that. */
|
||||
int64_t rad_kv_block_size(RadBuilder* b, rad_kvgroup g);
|
||||
/* Bytes one block of one layer of a paged group occupies: its pool slot's pitch and its host
|
||||
* mirror row's. 0 for a group that is not paged, or before the block size is known. Additive
|
||||
* export. */
|
||||
int64_t rad_kv_layer_bytes(RadBuilder* b, rad_kvgroup g);
|
||||
|
||||
/* Bind a layer to a group, so the block manager knows how many state instances a sequence owns. */
|
||||
int rad_bind_layer_kv(RadBuilder* b, int layer, rad_kvgroup g);
|
||||
@@ -446,6 +537,17 @@ int rad_op_writes(RadBuilder* b, rad_op h, const rad_buf* bufs, int n);
|
||||
* A no-op for a PERSIST or DERIVED buffer, which is live everywhere already. */
|
||||
int rad_buf_concurrent(RadBuilder* b, rad_buf buf);
|
||||
|
||||
/* ---- appended in ABI 27 (the second lane's window) */
|
||||
/* The second lane's window: every op the architecture issues on lane 1 is declared between
|
||||
* rad_lane1_window_begin and rad_lane1_window_end. With a window a rad_buf_concurrent buffer is live
|
||||
* over the window and its own declared uses instead of the whole program, so buffers used only
|
||||
* outside the window (a drafter's, the heads') can share its bytes. The runtime holds the
|
||||
* architecture to it: an op issued on lane 1 outside the window fails the step by name, and an op
|
||||
* issued on lane 0 outside the window joins lane 1 first when lane 1 has work pending. Optional, one
|
||||
* window a program; call both at declare, in order. */
|
||||
int rad_lane1_window_begin(RadBuilder* b);
|
||||
int rad_lane1_window_end(RadBuilder* b);
|
||||
|
||||
/* An uneven shard: this rank's slice of a RAD_SHARD_ROW or RAD_SHARD_COL weight's split dimension
|
||||
* is [lo, hi) rather than an even 1/tp. Rows of each stacked row part for ROW, columns for COL, in
|
||||
* the container's unsharded units. The declared extent must already be `hi - lo` (per row part,
|
||||
@@ -483,9 +585,16 @@ int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g);
|
||||
* rank computes whole, an indexer's key cache every rank pools into); the engine moves bytes and
|
||||
* cannot know. RADIANCE_DEBUG_TIER_VERIFY checks the claim: each follower hashes what it would
|
||||
* have written and the leader compares. Paged groups only, and never a group this rank declared
|
||||
* zero. No effect at one rank. Additive export; RAD_ABI_VERSION does not move. */
|
||||
* zero. No effect at one rank, and none on a group that streams, whose host mirror is its tier.
|
||||
* Additive export. */
|
||||
int rad_kv_group_replicated(RadBuilder* b, rad_kvgroup g);
|
||||
|
||||
/* The group is read over its whole history every decode step (an indexer's block keys), so it
|
||||
* cannot stream. While a sibling group streams, its carve holds every sequence's full context
|
||||
* rather than the split's share, as the sibling's host mirror holds --max-num-seqs sequences.
|
||||
* Additive export. */
|
||||
int rad_kv_group_dense_read(RadBuilder* b, rad_kvgroup g);
|
||||
|
||||
#define RAD_BUFS(...) ((const rad_buf[]){ __VA_ARGS__ }), \
|
||||
(int)(sizeof((const rad_buf[]){ __VA_ARGS__ }) / sizeof(rad_buf))
|
||||
|
||||
@@ -522,7 +631,10 @@ typedef struct RadNameMap {
|
||||
|
||||
/* RAD_MAP_ROWS only: piece i is rows [src_index[i], src_index[i] + src_rows[i]) of the 2-D (or
|
||||
* higher, rows along dim 0) tensor src[i]; the pieces join along dim 0. RAD_MAP_COLS: columns
|
||||
* [src_index[0], src_index[0] + src_rows[0]) of src[0]'s last dimension. */
|
||||
* [src_index[0], src_index[0] + src_rows[0]) of src[0]'s last dimension. RAD_MAP_TRANSPOSE with
|
||||
* src_index[0] >= 0: rows [src_index[0] * src_rows[0], (src_index[0] + 1) * src_rows[0]) when
|
||||
* src[0] is rank 2 and src_rows[0] > 0 (a stack flattened over rows); otherwise src_index[0] is
|
||||
* the dim-0 sub-tensor of a higher-rank stack. */
|
||||
int64_t src_rows[8];
|
||||
} RadNameMap;
|
||||
|
||||
@@ -549,7 +661,9 @@ typedef struct RadNameMap {
|
||||
* columns it is fed.
|
||||
*
|
||||
* RAD_MAP_TRANSPOSE swaps the last two dimensions of src[0] in each leading slice, [.., a, b] to
|
||||
* [.., b, a]: a linear a checkpoint keeps as (in, out), where the GEMMs read (out, in).
|
||||
* [.., b, a]: a linear a checkpoint keeps as (in, out), where the GEMMs read (out, in). With
|
||||
* src_index[0], it first takes one expert's sub-tensor (see src_rows): a stacked expert table kept
|
||||
* [n_expert, in, out] or flattened [n_expert * in, out].
|
||||
*
|
||||
* RAD_MAP_EMA is an exponential-moving-average codebook as EnCodec-style quantisers keep it: src[0]
|
||||
* the embedding sums [bins, ...], src[1] the cluster usage [bins], and the codebook is each row
|
||||
@@ -581,6 +695,17 @@ int rad_decl_name_map(RadBuilder* b, const RadNameMap* m);
|
||||
* embedding-only or encoder-only plugin declares none. */
|
||||
int rad_declare_logits(RadBuilder* b, rad_buf logits);
|
||||
|
||||
/* Scored steps (RadBatch::score_only). A plugin whose lm_head is the bf16 table `table`
|
||||
* ([n_vocab, n_embd], e.g. a tied embedding, whatever encoding the head itself is read at) and
|
||||
* whose final-normed rows land in `hidden` ([rows, n_embd] bf16, row k the step's k-th sampled row,
|
||||
* as the lm_head reads them) declares both here. On a step where every sampled row is a scored row
|
||||
* the core sets RadBatch::score_only, the plugin issues everything but the lm_head, and the core
|
||||
* reads the hidden rows and the candidates' table rows back and takes the dot products on the host
|
||||
* in f64: the logits a scored request returns, at no head read on the card (half a gigabyte a step
|
||||
* at a 128K bf16 vocabulary). Optional; one rank only (the core ignores it at --tp > 1).
|
||||
* Additive export; RAD_ABI_VERSION does not move. */
|
||||
int rad_declare_scores(RadBuilder* b, rad_buf hidden, rad_weight table);
|
||||
|
||||
/* Which buffer holds this step's pooled vectors, what an embedding model returns instead of
|
||||
* logits. Row s is sequence s's whole input pooled into one vector, with whatever pooling the
|
||||
* model was trained with (a mean, the last token, a CLS row). The core reads rows [0, n_seq) back
|
||||
@@ -598,6 +723,11 @@ int rad_declare_logits(RadBuilder* b, rad_buf logits);
|
||||
* this or logits, never both. */
|
||||
int rad_declare_pooled(RadBuilder* b, rad_buf pooled);
|
||||
|
||||
/* The most integer words one request may hand the plugin (RadBatch::plugin_words), 0 for none.
|
||||
* The engine stages that many a sequence in the step batch and refuses a longer request before
|
||||
* it is admitted, so the plugin reads its words at the size it declared. Additive export. */
|
||||
int rad_declare_plugin_words(RadBuilder* b, int64_t max_words);
|
||||
|
||||
|
||||
/* ================================================================== the drafter */
|
||||
/* The plugin's draft head. The core drives the extra passes, and only the plugin knows what it
|
||||
@@ -626,7 +756,8 @@ typedef struct RadDrafterDecl {
|
||||
|
||||
/* Where a pass leaves its proposal. 0 = the sampler's token buffer. */
|
||||
rad_buf proposal;
|
||||
int64_t proposal_pitch; /* elements a row in `proposal`; 0 means 1 */
|
||||
int64_t proposal_pitch; /* elements a row in `proposal`; 0 means 1, and for a BLOCK
|
||||
* drafter `depth` (less is refused) */
|
||||
|
||||
/* BLOCK only. `mask_token` is the id every unfilled block position embeds; a block drafter
|
||||
* without one cannot run. `window` is the drafter's own sliding window over its own cache, 0
|
||||
@@ -678,6 +809,25 @@ int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d);
|
||||
* checkpoint was trained with is the plugin's to know. */
|
||||
int rad_drafter_shared_kv(RadBuilder* b, int pos_offset);
|
||||
|
||||
/* A block drafter whose one pass proposes a tree rather than a chain. Called once, after
|
||||
* rad_declare_drafter. `parents` is an i32 buffer at the proposal's pitch: row i's j-th entry is
|
||||
* the parent of the proposal's j-th token as a node index, 0 for the token the verify starts from
|
||||
* (the bonus token) and j' + 1 for the proposal's j'-th token, with every parent before its child.
|
||||
* Additive export; RAD_ABI_VERSION does not move.
|
||||
*
|
||||
* Each verify then runs the proposal as a tree in the same rows: node j at row j, rotated at the
|
||||
* committed end + its depth, its K and V stored at the committed end + j, and every trunk step
|
||||
* carries RadBatch::spec_parent, which the plugin hands its attention so a row sees, inside its
|
||||
* own block, only its ancestors. The acceptance follows the deepest root path the target agrees
|
||||
* with; the core then moves that path's K and V into place in every paged group. A proposal from
|
||||
* prompt lookup is verified as the chain-shaped tree.
|
||||
*
|
||||
* Requirements on the plugin: the trunk's attention honours spec_parent on every decode row; the
|
||||
* drafter's context pass stores K and V through the slot mapping only (it is staged per node, the
|
||||
* rejected ones at slot -1); and the step is issued ahead, behind which the block driver queues
|
||||
* the drafter's passes (the KL mode drafts nothing, so trees do not apply there). */
|
||||
int rad_drafter_tree(RadBuilder* b, rad_buf parents);
|
||||
|
||||
/* 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
|
||||
@@ -686,6 +836,20 @@ int rad_drafter_shared_kv(RadBuilder* b, int pos_offset);
|
||||
* that decision. Additive export; RAD_ABI_VERSION does not move. */
|
||||
int rad_chain_on(void);
|
||||
|
||||
/* A block drafter that also serves a shorter block: the plugin declared its query pass at `block`
|
||||
* rows a sequence as well as at RadDrafterDecl::block, with the same anchor convention, so the
|
||||
* core may stage a step's block at either. The short block proposes
|
||||
* `block - (RadDrafterDecl::block - depth)` tokens; a tree drafter's (rad_drafter_tree, declared
|
||||
* first) a tree of its own over the shorter pass, at most `block - 1` nodes, which needs only that
|
||||
* the short block be 2 rows or more. Called once, after rad_declare_drafter.
|
||||
*
|
||||
* The block is proposed whole, so its length is paid for by every drafting sequence whatever each
|
||||
* verifies: at one sequence a long block's extra drafts pay, at many its rows and its weaker first
|
||||
* positions cost more than they bring. The core picks per step (--draft-short-from; by default
|
||||
* a tree's from two decoding sequences on, a chain's never). */
|
||||
/* ---- appended in ABI 27 (a block drafter's short block) */
|
||||
int rad_drafter_short_block(RadBuilder* b, int64_t block);
|
||||
|
||||
/* ================================================================== the encoder */
|
||||
/* A media encoder the plugin runs on an encoder pass (RadBatch::enc). The core drives the pass and
|
||||
* reads its result, so the plugin declares it. A plugin that declares none serves text only, and
|
||||
@@ -997,7 +1161,8 @@ typedef struct RadAudioGenDecl {
|
||||
/* The prompt, as text the core tokenises: `{instructions}` is replaced by the request's
|
||||
* instructions (a piece's description, a voice's) and `{input}` by its input text (lyrics, the
|
||||
* words to speak), each first rewritten by the plugin's rad_arch_text_prepare when it exports
|
||||
* one. Special tokens are spelled as text. */
|
||||
* one. Special tokens are spelled as text. NULL for a model that takes no instructions, which
|
||||
* then declares `tmpl_plain` and has a request's instructions refused. */
|
||||
const char* tmpl;
|
||||
/* The unconditional branch is the conditional prompt with every token but the first
|
||||
* `neg_keep_head` and the last `neg_keep_tail` replaced by `neg_token`, so the two branches
|
||||
@@ -1058,6 +1223,36 @@ typedef struct RadAudioGenDecl {
|
||||
* latent: `lat_num` = `lat_den` = 1, `samples_per_latent` samples a frame. */
|
||||
int64_t voc_chunk;
|
||||
int64_t voc_context;
|
||||
|
||||
/* ---- appended in ABI 27 (one-branch speech over a hybrid model, references) */
|
||||
/* Sequences a request runs: 0 or 2, the conditional and unconditional branches above; 1, the
|
||||
* conditional one alone, for a model without guidance (no unconditional prompt is rendered,
|
||||
* a request's guidance must be 1, and every per-entry array of a PROMPT or FRAME pass has one
|
||||
* entry a lane, its `slot` the lane itself). The KV, the prompt's rows and a frame's rows then
|
||||
* cost half. */
|
||||
int32_t branches;
|
||||
/* Nonzero: the `{input}` slot is tokenised with its special tokens, which the template's own
|
||||
* text always is, so a caller can write the model's speaker tags. The plugin's
|
||||
* rad_arch_text_prepare then refuses the control tokens a caller must not write. */
|
||||
int32_t input_special;
|
||||
/* References (voice cloning): with `tmpl_ref`, a request may carry up to `ref_max` of them,
|
||||
* each a transcript and a clip of the voice saying it, which the plugin encodes into frames
|
||||
* in the request's PROMPT pass (whole prompts only: `prompt_whole`). `tmpl_ref` is the prompt
|
||||
* of a request with references, `{references}` each of them rendered from `ref_item` in turn
|
||||
* and `{input}` as in `tmpl_plain`. `ref_item` is one reference: `{index}` its number from 1,
|
||||
* `{text}` its transcript (rewritten by rad_arch_text_prepare as RAD_TEXT_REFERENCE) and
|
||||
* `{audio}` its frames, one prompt row each (RadAudioGenBatch::ref_frame); the text before
|
||||
* `{audio}` is tokenised as one segment with its special tokens (the transcript's own, which
|
||||
* prepare() has limited to those a caller may write), and so is the text after it. A clip is
|
||||
* mono f32 in [-1, 1] at `ref_rate`, right-padded with zeros to a whole number of `ref_hop`
|
||||
* samples, each `ref_hop` samples one frame; a request's clips hold at most `ref_max_samples`
|
||||
* samples together. NULL `tmpl_ref`: references are refused. */
|
||||
const char* tmpl_ref;
|
||||
const char* ref_item;
|
||||
int64_t ref_rate;
|
||||
int64_t ref_hop;
|
||||
int64_t ref_max_samples;
|
||||
int32_t ref_max;
|
||||
} RadAudioGenDecl;
|
||||
|
||||
int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d);
|
||||
@@ -1120,9 +1315,27 @@ int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d);
|
||||
* pass carries the geometry its latent has at that point: a step before the VUPSCALE pass is at
|
||||
* W' x H'. The schedule is the request's own, whatever size each evaluation runs at.
|
||||
*
|
||||
* Reference conditioning, for a plugin with the VAE encoders (`max_enc_side`, `max_enc_samples`,
|
||||
* below): before the prompt pass each of a request's reference media and keyframes is encoded,
|
||||
* one a pass, into the lane, where the steps read it. Nothing an encode makes is read back.
|
||||
*
|
||||
* RAD_GEN_PASS_VENCODE one picture or video, its frames in `enc_pixels` (RadVideoGenBatch),
|
||||
* through the video VAE's encoder.
|
||||
* RAD_GEN_PASS_AENCODE one soundtrack, its samples in `enc_samples`, through the audio VAE's
|
||||
* encoder.
|
||||
*
|
||||
* `enc_kind` (RAD_ENC_*, rad_runtime.h) and `enc_slot`, the media's 1-based number within its kind,
|
||||
* say where the latents go. A latent-upscaled request's keyframes, pinned on the grid its steps
|
||||
* run on, are encoded at W' x H' before the prompt pass, then again at W x H into the same slots
|
||||
* after the VUPSCALE pass and before the first evaluation at W x H. References, on their own grid,
|
||||
* are encoded once. The media's shape is the plugin's to accept: rad_arch_encode_geom
|
||||
* (below) refuses what the encoders cannot take, and the step's packed sequence with the encoded
|
||||
* media in it is the plugin's rad_arch_video_pack.
|
||||
*
|
||||
* A program declares exactly one of this, the other generators, logits or pooled vectors. */
|
||||
enum { RAD_GEN_PASS_VCOND = 8, RAD_GEN_PASS_VSTEP = 9, RAD_GEN_PASS_ADECODE = 10,
|
||||
RAD_GEN_PASS_VDECODE = 11, RAD_GEN_PASS_VUPSCALE = 12 };
|
||||
RAD_GEN_PASS_VDECODE = 11, RAD_GEN_PASS_VUPSCALE = 12,
|
||||
RAD_GEN_PASS_VENCODE = 13, RAD_GEN_PASS_AENCODE = 14 };
|
||||
|
||||
typedef struct RadVideoGenDecl {
|
||||
const char* name; /* "minimax-h3" -- the served model id and messages */
|
||||
@@ -1240,6 +1453,20 @@ typedef struct RadVideoGenDecl {
|
||||
* Null: one decoder. */
|
||||
const char* decoders;
|
||||
const int64_t* decoder_max_area;
|
||||
|
||||
/* ---- appended in ABI 31 (MiniMax-H3 reference conditioning, above) */
|
||||
/* The reference media a request may carry: pictures, videos (each with an optional soundtrack
|
||||
* of its own) and standalone soundtracks. 0 for none of a kind; a plugin that declares any
|
||||
* exports rad_arch_video_pack. */
|
||||
int64_t max_ref_images, max_ref_videos, max_ref_audios;
|
||||
/* What one encode pass carries: a video's frames after rad_arch_encode_geom pads them to whole
|
||||
* clips, a frame's longer side and a soundtrack's samples. `max_enc_side` 0: no video encoder,
|
||||
* `max_enc_samples` 0: no audio encoder. A picture's sides are multiples of `enc_ratio`. */
|
||||
int64_t max_enc_frames, max_enc_side, max_enc_samples;
|
||||
int32_t enc_ratio;
|
||||
/* The distinct modulations a step's groups may read (rad_arch_video_pack's `mod`, the highest
|
||||
* cell + 1); a request needing more is refused at submit. 0: no limit. */
|
||||
int32_t max_mod_cells;
|
||||
} RadVideoGenDecl;
|
||||
|
||||
int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d);
|
||||
@@ -1343,9 +1570,41 @@ typedef struct RadArchProbe {
|
||||
* then takes them. Zero keeps them off: 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
|
||||
* attention is sparse and block-addressed and it declares a streamed store and `kv_resolve`.
|
||||
* --kv-resident on an architecture that says 0 is turned off at startup, and nothing streamed
|
||||
* is declared (RadBuildCtx::kv_stream_ok). */
|
||||
int32_t kv_stream_ok;
|
||||
/* Nonzero when the plugin applies RadBuildCtx::cvec for this model. --control-vector is
|
||||
* refused at startup with the plugin named when this is 0. */
|
||||
int32_t control_vector_ok;
|
||||
|
||||
/* ---- appended in ABI 27 (row-split prefill attention) */
|
||||
/* Nonzero when the plugin serves RadBuildCtx::tp_attn_rows for this model. --tp-attn-split
|
||||
* rows is refused at startup with the plugin named when this is 0. */
|
||||
int32_t tp_attn_rows_ok;
|
||||
|
||||
/* ---- appended in ABI 27 (recurrent state at f16) */
|
||||
/* Nonzero when the plugin declares its recurrent state at f16 under RadBuildCtx::state_dtype
|
||||
* and its kernels read that width. --state-cache-dtype f16 is refused at startup with the
|
||||
* plugin named when this is 0. */
|
||||
int32_t state_f16_ok;
|
||||
|
||||
/* ---- appended in ABI 31 (tree verification) */
|
||||
/* Nonzero when this plugin can grow its block drafter's proposals into a tree
|
||||
* (rad_drafter_tree) and measured its speculative step faster with one. The core then asks for
|
||||
* a tree (RadBuildCtx::draft_tree) wherever that drafter decodes speculatively. Zero keeps the
|
||||
* chain: a plugin that never measured trees asks for none. 64-bit so it starts past the older
|
||||
* struct's tail padding, which a plugin built against it may copy over. */
|
||||
int64_t tree_pays;
|
||||
|
||||
/* ---- appended in ABI 32 (inputs: an image generator's bounds) */
|
||||
/* Set by the core before the call: --image-gen-max-pixels and --image-gen-max-refs, as
|
||||
* RadBuildCtx carries them to declare (0: the model's own). A generator's gen_rows and
|
||||
* gen_patches answer for them. */
|
||||
int64_t gen_max_pixels;
|
||||
int64_t gen_max_refs;
|
||||
} RadArchProbe;
|
||||
|
||||
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
|
||||
@@ -1363,6 +1622,12 @@ int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
|
||||
* arg_prefix ARG arg_name_suffix arg_value_prefix VALUE arg_value_suffix ...
|
||||
* call_end [call_close]
|
||||
*
|
||||
* An argument's tag may also say its value's type, with arg_json_value_prefix written in place of
|
||||
* arg_value_prefix before a JSON value. DeepSeek-V4.1's DSML, inside a section
|
||||
* "<|DSML| calls>" / "</|DSML| calls>", is "<|DSML| invoke name=\"" / "\">\n" / "</|DSML| invoke>",
|
||||
* arguments "<|DSML| parameter name=\"" / "\"" / " string=\"true\">" (or
|
||||
* " string=\"false\">") / "</|DSML| parameter>".
|
||||
*
|
||||
* Qwen3.8, for example, is "<think>\n" / "\n</think>\n\n", calls "<tool_call>\n" / "</tool_call>",
|
||||
* "<function=" / ">\n" / "</function>\n", arguments "<parameter=" / ">\n" / "" / "</parameter>\n".
|
||||
* Whitespace at the ends of a tag is optional when matching. Every string is NUL-terminated
|
||||
@@ -1412,14 +1677,13 @@ typedef struct RadChatFormat {
|
||||
const char* reasoning_open; /* "" when the model does not reason */
|
||||
const char* reasoning_close;
|
||||
/* Literals that end a reasoning block the model forgot to close, when a call starts there.
|
||||
* Each must be the call opener: `call_open`, or `name_prefix` when there is no call_open. */
|
||||
* Each must be a call opener (`call_open`, or `name_prefix` without one) or section_open. */
|
||||
const char* const* reasoning_breaks;
|
||||
uint32_t n_reasoning_breaks;
|
||||
uint32_t reasoning_in_prompt; /* RAD_CHAT_THINK_* */
|
||||
|
||||
/* Around all of a turn's calls, and between two calls beyond whitespace. The parser does not
|
||||
* read these yet, so a format that sets one is refused at startup by name; they are fields so
|
||||
* supporting them later does not change the struct. */
|
||||
/* Around the complete list of calls. section_open and section_close must be set together.
|
||||
* call_separator is additional text between calls beyond whitespace; it is not supported. */
|
||||
const char* section_open;
|
||||
const char* section_close;
|
||||
const char* call_separator;
|
||||
@@ -1464,6 +1728,12 @@ typedef struct RadChatFormat {
|
||||
* calls) and is read as reasoning there too, and a reasoning_close with no block open is not
|
||||
* part of the answer. Zero: only a block the reply starts with is reasoning. */
|
||||
uint32_t reasoning_anywhere;
|
||||
|
||||
/* Tagged arguments whose tag says the value's type: written in place of arg_value_prefix,
|
||||
* this opens a JSON value, and arg_value_prefix then opens a string. The tag the reply writes
|
||||
* decides how its value is read, whatever the schema says; the grammar writes the one the
|
||||
* schema calls for. NULL: the schema alone types a value. */
|
||||
const char* arg_json_value_prefix;
|
||||
} RadChatFormat;
|
||||
|
||||
/* Return the format, or NULL for "derive it from the chat template". Called once at startup. */
|
||||
@@ -1524,11 +1794,13 @@ const RadAudioFormat* rad_arch_audio_format(const RadModelMeta* meta);
|
||||
* as given. Training data has conventions a client does not know -- section tags on lines of
|
||||
* their own and lower case, no markdown in a description -- and only the plugin knows them.
|
||||
*
|
||||
* `field` is RAD_TEXT_*, `in` NUL-terminated UTF-8. Writes at most `cap` bytes, the NUL included,
|
||||
* and returns the length the whole result needs without its NUL (call again with more room when
|
||||
* it is >= cap), or a negative status for text the model cannot take. Called on HTTP threads, so
|
||||
* it keeps no state. */
|
||||
enum { RAD_TEXT_INSTRUCTIONS = 1, RAD_TEXT_INPUT = 2 };
|
||||
* `field` is RAD_TEXT_*, `in` NUL-terminated UTF-8: the instructions, the input, or a
|
||||
* reference's transcript (RadAudioGenDecl::ref_item's `{text}`). Writes at most `cap` bytes, the
|
||||
* NUL included, and returns the length the whole result needs without its NUL (call again with
|
||||
* more room when it is >= cap), or a negative status for text the model cannot take, with the
|
||||
* reason in `out` (NUL-terminated within `cap`) when it has one to give the caller. Called on
|
||||
* HTTP threads, so it keeps no state. */
|
||||
enum { RAD_TEXT_INSTRUCTIONS = 1, RAD_TEXT_INPUT = 2, RAD_TEXT_REFERENCE = 3 };
|
||||
int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap);
|
||||
|
||||
/* The layout of a video generator's passes (rad_declare_video_generator), which only the model
|
||||
@@ -1548,6 +1820,27 @@ typedef struct RadVideoGeom {
|
||||
enum { RAD_VPOS_STEP = 1, RAD_VPOS_DECODE = 2 };
|
||||
int64_t rad_arch_video_positions(int which, const RadVideoGeom* g, float* pos, int64_t cap);
|
||||
|
||||
/* The geometry of an encode pass (RAD_GEN_PASS_VENCODE, RAD_GEN_PASS_AENCODE): the int32s the
|
||||
* driver stages verbatim in RadVideoGenBatch::enc_geom_d for the plugin's kernels. `kind` is the
|
||||
* pass; `in` is {frames or samples, height, width, channels}, 0 where unused. With `out` null it
|
||||
* returns the count, with `out` it fills out[cap]; negative for media the encoders cannot take.
|
||||
* Entry 0 of an Aencode geometry is the samples padded to the encoder's hop, entry 23 of a Vencode
|
||||
* geometry the frames padded to whole clips and entry 24 its latent frames: the driver stages the
|
||||
* media padded to those lengths. A plugin with encoders exports it. Called on any thread. */
|
||||
int64_t rad_arch_encode_geom(int32_t kind, const int64_t* in, int32_t* out, int64_t cap);
|
||||
|
||||
/* The packed sequence of a step with reference media or keyframes in: `ref_tab` is
|
||||
* RadVideoGenBatch::ref_tab. Returns the sequence's rows, the rows RAD_VPOS_STEP would position, or
|
||||
* a negative status. `seg` receives the segment boundaries (seg[0] = 0, the last the rows) and
|
||||
* `mod` the boundaries of the modulation groups, then the cell each group reads (groups that read
|
||||
* the same modulation share a cell, numbered from 0); `*n_seg` and `*n_mod` are their capacities
|
||||
* in and their counts out, and a null array asks for the count alone. `pos` receives the rotary
|
||||
* positions, f32 [3, rows], when `cap_pos` holds 3 x rows. A plugin that declares reference media
|
||||
* exports it. Called on any thread. */
|
||||
int64_t rad_arch_video_pack(const RadVideoGeom* g, const int32_t* ref_tab, int32_t* seg,
|
||||
int32_t* n_seg, int32_t* mod, int32_t* n_mod, float* pos,
|
||||
int64_t cap_pos);
|
||||
|
||||
int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx);
|
||||
/* Forward declaration; the signature is in rad_runtime.h. */
|
||||
struct RadCtx;
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
/* rad_clef.h -- the words a clef request hands its head (RadBatch::plugin_words).
|
||||
*
|
||||
* clef's joint schema head (arch/common/rad_block_clef.h) reads more of a request than its
|
||||
* tokens: which prompt positions hold each question's instructions and each option's text, each
|
||||
* option's token ids (the lm_head rows it averages), and each question's type. The server lays
|
||||
* them out with the functions below, in the forms the head's kernels read (a cu_seqlens here, a
|
||||
* gather index there), and the engine carries them to the plugin as one range of int32 words.
|
||||
* Both sides include this header, so the layout is stated once.
|
||||
*
|
||||
* Plain C, like every abi/ header: the plugin is built apart from the engine.
|
||||
*/
|
||||
#ifndef RAD_CLEF_H
|
||||
#define RAD_CLEF_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* The bounds the head's buffers are declared at. A request past one is refused by the server. */
|
||||
enum {
|
||||
RAD_CLEF_MAX_QUESTIONS = 64,
|
||||
RAD_CLEF_MAX_OPTIONS = 512, /* every question's options together */
|
||||
RAD_CLEF_MAX_LEX = 8192, /* every option's tokens together */
|
||||
/* Prompt tokens. The head gathers every row of a prompt into buffers of its own, so this,
|
||||
* not the deployment's context, sizes them: at the model's own 262144 they would take
|
||||
* 4.5 GiB of the card for prompts that never pass a fifth of it. */
|
||||
RAD_CLEF_MAX_PROMPT = 32768
|
||||
};
|
||||
|
||||
/* The header: word 0 is the engine's (RadBatch::plugin_words), the rest the counts the layout is
|
||||
* computed from. */
|
||||
enum {
|
||||
RAD_CLEF_W_ROW = 0, /* the sequence's logits row this step, written by the engine */
|
||||
RAD_CLEF_W_N = 1, /* prompt tokens */
|
||||
RAD_CLEF_W_Q = 2, /* questions */
|
||||
RAD_CLEF_W_O = 3, /* options, every question together, in head order */
|
||||
RAD_CLEF_W_L = 4, /* option tokens, every option together */
|
||||
RAD_CLEF_W_S = 5, /* segments the prompt is cut into at every span's edges */
|
||||
RAD_CLEF_HDR = 8
|
||||
};
|
||||
|
||||
/* Where each array starts, in words from the range's start. Every array is int32. */
|
||||
typedef struct RadClefWords {
|
||||
int32_t n, q, o, l, s;
|
||||
int32_t seg_cu; /* [s + 1]: a partition of [0, n) with a boundary at every span's edges */
|
||||
int32_t q_seg; /* [q]: the segment holding each question's instructions */
|
||||
int32_t o_seg; /* [o]: the segment holding each option's text */
|
||||
int32_t o_q; /* [o]: each option's question */
|
||||
int32_t opt_cu; /* [q + 1]: each question's options, consecutive */
|
||||
int32_t type; /* [q]: 0 noul, 1 choice, 2 score */
|
||||
int32_t lex_cu; /* [o + 1]: each option's tokens in lex_ids, consecutive */
|
||||
int32_t lex_ids; /* [l]: the option tokens, as the prompt holds them */
|
||||
int32_t last; /* [1]: n - 1, the prompt's last position */
|
||||
int32_t cu_q; /* [2]: {0, q} */
|
||||
int32_t cu_o; /* [2]: {0, o} */
|
||||
int32_t cu_k; /* [2]: {0, n} */
|
||||
int32_t total; /* words in all */
|
||||
} RadClefWords;
|
||||
|
||||
static inline RadClefWords rad_clef_words_layout(int32_t n, int32_t q, int32_t o, int32_t l,
|
||||
int32_t s) {
|
||||
RadClefWords w;
|
||||
int32_t at = RAD_CLEF_HDR;
|
||||
w.n = n; w.q = q; w.o = o; w.l = l; w.s = s;
|
||||
w.seg_cu = at; at += s + 1;
|
||||
w.q_seg = at; at += q;
|
||||
w.o_seg = at; at += o;
|
||||
w.o_q = at; at += o;
|
||||
w.opt_cu = at; at += q + 1;
|
||||
w.type = at; at += q;
|
||||
w.lex_cu = at; at += o + 1;
|
||||
w.lex_ids = at; at += l;
|
||||
w.last = at; at += 1;
|
||||
w.cu_q = at; at += 2;
|
||||
w.cu_o = at; at += 2;
|
||||
w.cu_k = at; at += 2;
|
||||
w.total = at;
|
||||
return w;
|
||||
}
|
||||
|
||||
/* The layout a range of words carries, read off its header. */
|
||||
static inline RadClefWords rad_clef_words_read(const int32_t* words) {
|
||||
return rad_clef_words_layout(words[RAD_CLEF_W_N], words[RAD_CLEF_W_Q], words[RAD_CLEF_W_O],
|
||||
words[RAD_CLEF_W_L], words[RAD_CLEF_W_S]);
|
||||
}
|
||||
|
||||
/* The most words a request can carry within the bounds: what the head declares
|
||||
* (rad_declare_plugin_words). A span's two edges each cut the prompt, so the segments are at most
|
||||
* two a span plus one. */
|
||||
static inline int32_t rad_clef_max_words(void) {
|
||||
const int32_t spans = RAD_CLEF_MAX_QUESTIONS + RAD_CLEF_MAX_OPTIONS;
|
||||
return rad_clef_words_layout(0, RAD_CLEF_MAX_QUESTIONS, RAD_CLEF_MAX_OPTIONS,
|
||||
RAD_CLEF_MAX_LEX, 2 * spans + 1).total;
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* RAD_CLEF_H */
|
||||
@@ -36,12 +36,21 @@ typedef struct RadDeviceProps {
|
||||
int64_t lds_bytes; /* per-workgroup scratch, for occupancy arithmetic only */
|
||||
int supports_p2p;
|
||||
int is_host_backend; /* 1 when there is no accelerator behind this device */
|
||||
int unified; /* 1 when device memory is host memory (integrated graphics):
|
||||
* one address space and one RAM ledger -- the device pools and
|
||||
* the pinned host pools are charged against the same bytes,
|
||||
* KV tiers collapse to resident, and a copy whose source and
|
||||
* destination are the same address is a no-op */
|
||||
} RadDeviceProps;
|
||||
|
||||
int rad_dev_count(void);
|
||||
int rad_dev_set(int device);
|
||||
int rad_dev_props(int device, RadDeviceProps* out);
|
||||
int rad_dev_enable_peer(int self, int peer);
|
||||
/* 1 when the driver reports that `self` can reach `peer`'s memory, 0 when not, negative on a
|
||||
* device error. A tool that declares a multi-rank graph sets the device.p2p fact from it, as the
|
||||
* engine does (RAD_FACT_P2P). */
|
||||
int rad_dev_peer_access(int self, int peer);
|
||||
|
||||
void* rad_dev_alloc(int64_t bytes, int kind);
|
||||
void rad_dev_free(void* p, int kind);
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
/* rad_laya.h -- the words a Laya request hands its plugin (RadBatch::plugin_words), and the pooled
|
||||
* row the plugin answers in.
|
||||
*
|
||||
* Laya (arch/laya) reads one sequence a question, `[CLS] <type> question: <instructions> [SEP]
|
||||
* [MASK] opt0 [MASK] opt1 ... [SEP] <state> [SEP]`, and scores each option at its [MASK]. The
|
||||
* server builds the sequence (core/server/laya.cpp) and hands the plugin what the tokens do not
|
||||
* say: the question's type, which picks the head's type embedding, and where the markers are. The
|
||||
* plugin answers in the sequence's pooled row: one logit an option, in marker order.
|
||||
*
|
||||
* Plain C, like every abi/ header: the plugin is built apart from the engine.
|
||||
*/
|
||||
#ifndef RAD_LAYA_H
|
||||
#define RAD_LAYA_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
enum {
|
||||
/* Options a question, llama.cpp's bound for laya. The pooled row holds one logit an option. */
|
||||
RAD_LAYA_MAX_OPTIONS = 255,
|
||||
RAD_LAYA_POOLED = 256
|
||||
};
|
||||
|
||||
/* The question types in the order of the head's type embedding rows (laya's QTYPES). */
|
||||
enum { RAD_LAYA_CHOICE = 0, RAD_LAYA_SCORE = 1, RAD_LAYA_NOUL = 2 };
|
||||
|
||||
/* A sequence's words. Word 0 is the engine's (RadBatch::plugin_words). */
|
||||
enum {
|
||||
RAD_LAYA_W_ROW = 0, /* written by the engine */
|
||||
RAD_LAYA_W_N = 1, /* the sequence's tokens */
|
||||
RAD_LAYA_W_TYPE = 2, /* RAD_LAYA_CHOICE, RAD_LAYA_SCORE or RAD_LAYA_NOUL */
|
||||
RAD_LAYA_W_K = 3, /* options, so markers */
|
||||
RAD_LAYA_W_MARKERS = 4, /* [k]: each option's [MASK] position in the sequence, in order */
|
||||
RAD_LAYA_MAX_WORDS = RAD_LAYA_W_MARKERS + RAD_LAYA_MAX_OPTIONS
|
||||
};
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* RAD_LAYA_H */
|
||||
@@ -106,6 +106,15 @@ typedef struct RadQuantizerInfo {
|
||||
int rad_quant_count(void);
|
||||
const RadQuantizerInfo* rad_quant_at(int i);
|
||||
|
||||
/* Optional: the cards a quantiser may run on, as the HIP runtime numbers them (after
|
||||
* HIP_VISIBLE_DEVICES); none is the host alone, the state before any call. rad-convert calls it
|
||||
* once, after loading and before the first weight, with its --gpus list. A quantiser that uses a
|
||||
* card writes the same bytes it writes on the host, so a container does not depend on the machine
|
||||
* that converted it, and --reuse matches it either way. RAD_E_UNSUPPORTED: this build has no
|
||||
* device path; any other negative status refuses the list (a card that is not there). Symbol
|
||||
* name: `rad_quant_devices`. */
|
||||
typedef int (*RadQuantDevicesFn)(const int* ids, int n);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
+173
-10
@@ -22,6 +22,38 @@ typedef struct RadCtx RadCtx;
|
||||
* scheduler and the run phase the bounds without a device read. */
|
||||
enum { RAD_PHASE_PREFILL = 0, RAD_PHASE_DECODE = 1, RAD_PHASE_MIXED = 2 };
|
||||
|
||||
/* ================================================================== KV streaming */
|
||||
/* A streamed KV group keeps its whole context in pinned host memory and a ring of blocks on the
|
||||
* card (docs/KV-STREAMING.md). The step batch points every group that streams at this view, which
|
||||
* is fixed from bring-up (so a recorded pass replays a resolve); a resident group's is null.
|
||||
*
|
||||
* The mirror is laid out like the pool, layer by layer: layer l's row for block b is at
|
||||
* `host + l * host_layer_stride + b * block_bytes`. `res`, `slot_block`, `slot_state` and `ctl`
|
||||
* are device memory, read and rewritten by every resolve launch. */
|
||||
typedef struct RadKVStream {
|
||||
/* The mirror: pinned host memory a kernel reads over the link in place, every layer, zeroed at
|
||||
* bring-up. */
|
||||
uint8_t* host;
|
||||
/* Residency, one slice a layer: `res` is block -> ring slot or -1 (layer l at `res + l *
|
||||
* blocks`), `slot_block` is slot -> block or -1, `slot_state` is [slots, 2]: the epoch of a
|
||||
* slot's last use and its CLOCK reference bit. Per layer, because the resolve copies one
|
||||
* layer's bytes. */
|
||||
int32_t* res;
|
||||
int32_t* slot_block;
|
||||
int32_t* slot_state;
|
||||
/* The group's control block: epoch, clock hand, the last launch's miss count, the overflow
|
||||
* latch and cumulative counters (docs/OPS.md "kv_resolve"). */
|
||||
int32_t* ctl;
|
||||
/* Bytes one block of one layer occupies: the mirror's row pitch and the ring's slot pitch. */
|
||||
int64_t block_bytes;
|
||||
/* Bytes between one layer's mirror and the next. */
|
||||
int64_t host_layer_stride;
|
||||
/* The ring's depth in blocks; a selection names block ids over the whole context. */
|
||||
int64_t slots;
|
||||
/* The whole mirror's bytes, every layer. */
|
||||
int64_t host_bytes;
|
||||
} RadKVStream;
|
||||
|
||||
typedef struct RadKVGroupBatch {
|
||||
rad_kvgroup group;
|
||||
int32_t* slot_mapping; /* [n_tok] flat slot index per token, device */
|
||||
@@ -36,6 +68,8 @@ typedef struct RadKVGroupBatch {
|
||||
int64_t state_index_pitch;
|
||||
int64_t block_size;
|
||||
int64_t max_blocks;
|
||||
/* Null unless this group streams (RadKVStream). Trailing and zero-defaulted. */
|
||||
const RadKVStream* stream;
|
||||
} RadKVGroupBatch;
|
||||
|
||||
typedef struct RadBatch {
|
||||
@@ -85,7 +119,12 @@ typedef struct RadBatch {
|
||||
/* Speculative window (spec §10). n_spec == 0 for an ordinary decode step. */
|
||||
int n_spec; /* draft tokens per sequence this step */
|
||||
const int32_t* num_accepted; /* [n_seq] device, from the previous verify */
|
||||
const int32_t* spec_parent; /* [n_tok] device, tree layout; null for a linear chain */
|
||||
/* [n_tok] device; null for a linear chain. A tree verify (rad_drafter_tree): -2 marks an
|
||||
* ordinary causal row; any other entry is a node of its sequence's verify block and names its
|
||||
* parent by row within the sequence's rows (cu_seqlens), -1 for the block's first row, every
|
||||
* parent before its child. Inside its block such a row attends to itself and its ancestors
|
||||
* only (docs/OPS.md, attn_paged_tree). */
|
||||
const int32_t* spec_parent;
|
||||
|
||||
/* The draft pass. 0 is an ordinary step that runs the trunk; non-zero runs only the draft
|
||||
* head, and the sign gives the kind:
|
||||
@@ -135,9 +174,9 @@ typedef struct RadBatch {
|
||||
/* The longest query in each half. max_q_len over a mixed step is the prefill chunk's, and
|
||||
* banding the decode half with it would give eight rows a thousand-row GEMM's band.
|
||||
*
|
||||
* Only the decode value is currently read (by the GDN blocks). The prefill value is for a
|
||||
* block whose prefill path bands on a per-sequence query length; the GDN prefill ops band on
|
||||
* the step's total tokens, taken from their operands. */
|
||||
* The decode value is read by the GDN blocks and the fp8 gated attention's per-band issue
|
||||
* (rad_block_attn_gated_fp8.h), which also bands its prefill half on the prefill value; the
|
||||
* GDN prefill ops band on the step's total tokens, taken from their operands. */
|
||||
int32_t max_q_len_decode;
|
||||
int32_t max_q_len_prefill;
|
||||
|
||||
@@ -256,6 +295,36 @@ typedef struct RadBatch {
|
||||
* position tables per grid) reads them here; they live as long as the pass. */
|
||||
const int32_t* enc_seg_h;
|
||||
const int32_t* enc_seg_w;
|
||||
|
||||
/* ================================================ scored steps */
|
||||
|
||||
/* Non-zero when every row the sampler wants is a scored row (a /v1/systemone question: the raw
|
||||
* logits at a few candidate ids, the sampled token discarded) and the program declared where
|
||||
* the core finds the hidden rows and the head (rad_declare_scores). The plugin then skips its
|
||||
* lm_head and leaves `rad_declare_scores`' hidden buffer holding the gathered, final-normed
|
||||
* rows; the core computes the candidates' logits itself. Zero on every other step, and always
|
||||
* for a program that declared no scores. Appended; an older plugin never sees it set. */
|
||||
int32_t score_only;
|
||||
|
||||
/* ---- appended in ABI 32 (a request's words for the plugin) */
|
||||
/* Integer words a request hands the plugin whole (Request::plugin_words), for a head that
|
||||
* needs more of a request than its tokens: clef's joint schema head reads the prompt's
|
||||
* question and option spans and the option tokens (abi/rad_clef.h). Sequence s's words are
|
||||
* `plugin_words[plugin_cu[s] .. plugin_cu[s+1])`; a sequence with none has an empty range.
|
||||
* The engine writes the sequence's first sampled logits row of this step into word 0 of its
|
||||
* range, so the head can put its result beside that row's logits; the words after it are the
|
||||
* request's own. Carried only on the trunk step that samples a prompt's first token, so a
|
||||
* head runs once a request, when every prompt row has been computed.
|
||||
*
|
||||
* `plugin_words_h` and `plugin_cu_h` are the same words on the host, for a plugin that reads
|
||||
* counts before it issues; they live as long as the pass. All null, with `n_plugin_words`
|
||||
* 0, on a step no sequence of which carries words, and on every step of a program that
|
||||
* declared none (rad_declare_plugin_words). */
|
||||
int64_t n_plugin_words;
|
||||
const int32_t* plugin_words; /* [n_plugin_words] device */
|
||||
const int32_t* plugin_cu; /* [n_seq + 1] device */
|
||||
const int32_t* plugin_words_h;
|
||||
const int32_t* plugin_cu_h;
|
||||
} RadBatch;
|
||||
|
||||
/* What a generator pass carries beside the step batch's own fields, which keep their meanings:
|
||||
@@ -399,8 +468,13 @@ typedef struct RadGenBatch {
|
||||
|
||||
/* A request's conditioning options on a COND pass (RadGenBatch::cond_opts). */
|
||||
enum {
|
||||
RAD_GEN_COND_REBALANCE = 1 /* the conditioning at the plugin's fixed rebalance gains (the
|
||||
RAD_GEN_COND_REBALANCE = 1, /* the conditioning at the plugin's fixed rebalance gains (the
|
||||
* request field `rebalance`; Krea 2: its text taps) */
|
||||
/* which of the plugin's rebalance presets, beside RAD_GEN_COND_REBALANCE: 0 its default
|
||||
* gains, Krea 2: 1 balanced, 2 detail, 3 subtle (arch/krea2). A plugin declares these bits in
|
||||
* RadGeneratorDecl::cond_opts when it has presets. */
|
||||
RAD_GEN_COND_REBALANCE_PRESET = 0xff00,
|
||||
RAD_GEN_COND_REBALANCE_PRESET_SHIFT = 8
|
||||
};
|
||||
|
||||
/* An entry's flags on a DENOISE pass. */
|
||||
@@ -489,6 +563,30 @@ typedef struct RadAudioGenBatch {
|
||||
/* VOCODE with RadAudioGenDecl::voc_chunk: the lane's first frame the pass reads, counted
|
||||
* from the first kept frame. 64 bits so that it starts past the struct's ABI 18 end. */
|
||||
int64_t voc_frame0;
|
||||
|
||||
/* ---- appended in ABI 27 (a frame head at the previous row, references) */
|
||||
/* FRAME, one value per entry ([n_seq]): the row before the frame's own row -- the one whose
|
||||
* hidden state the frame is sampled from -- as its KV slot, its position, and the context
|
||||
* through it (position + 1). A model whose frame head attends at that row (Fish Audio
|
||||
* drama-3's codebook tower, layers bound to the language model's full-attention group) issues
|
||||
* those layers there, before the language model runs at the frame's own row. */
|
||||
const int32_t* prev_slot;
|
||||
const int32_t* prev_pos;
|
||||
const int32_t* prev_used;
|
||||
|
||||
/* PROMPT of a request with references (RadAudioGenDecl::tmpl_ref; n_ref 0 without): its
|
||||
* clips' samples end to end (`ref_samples` f32 on the device), the clips' bounds in samples
|
||||
* ([n_ref + 1], each a whole number of RadAudioGenDecl::ref_hop), and for every row of the
|
||||
* pass the frame of the clips it is or -1 for a token row ([n_tok]), frames counted over the
|
||||
* clips in order, frame f the samples [f ref_hop, (f + 1) ref_hop). A frame's row stages
|
||||
* token 0; the plugin embeds the frame there instead. */
|
||||
int64_t n_ref;
|
||||
int64_t ref_samples;
|
||||
const float* ref_audio;
|
||||
const int32_t* ref_cu;
|
||||
const int32_t* ref_cu_h;
|
||||
const int32_t* ref_frame;
|
||||
const int32_t* ref_frame_h;
|
||||
} RadAudioGenBatch;
|
||||
|
||||
/* A window entry's flags on a WINDOW pass. FIRST is RAD_GEN_F_FIRST's bit and the others are clear
|
||||
@@ -510,8 +608,11 @@ enum {
|
||||
* ADECODE no rows of the pass's own.
|
||||
* VDECODE `dec_rows` rows of the decoder's own (rad_arch_video_positions, RAD_VPOS_DECODE).
|
||||
* VUPSCALE no rows of the pass's own: the lane's video latent from `geom_from` to `geom`.
|
||||
* VENCODE no rows of the pass's own: a picture's or a video's frames in `enc_pixels`.
|
||||
* AENCODE no rows of the pass's own: a soundtrack's samples in `enc_samples`.
|
||||
*
|
||||
* Every pointer is device memory unless the name ends in _h. */
|
||||
|
||||
typedef struct RadVideoGenBatch {
|
||||
int32_t lane;
|
||||
RadVideoGeom geom; /* the request's geometry */
|
||||
@@ -520,9 +621,10 @@ typedef struct RadVideoGenBatch {
|
||||
/* The same lane, i32 [1], and 1 on a request's first step (0 otherwise), i32 [1]. */
|
||||
const int32_t* lane_d;
|
||||
const int32_t* first_d;
|
||||
/* i32 [4]: the packed sequence's segments, {0, n_text, n_text + audio rows, n_tok} -- text,
|
||||
* soundtrack, video -- and i32 [4] {0, video rows, 0, audio rows}, the bounds of the lane's two
|
||||
* latents counted from each one's first row. */
|
||||
/* i32: the packed sequence's segment boundaries, {0, n_text, n_text + audio rows, n_tok} --
|
||||
* text, soundtrack, video -- or rad_arch_video_pack's for a request with references; and i32
|
||||
* [4] {0, video rows, 0, audio rows}, the bounds of the lane's two latents counted from each
|
||||
* one's first row. */
|
||||
const int32_t* seg_cu;
|
||||
const int32_t* lat_cu;
|
||||
|
||||
@@ -533,7 +635,8 @@ typedef struct RadVideoGenBatch {
|
||||
|
||||
/* ---- VSTEP */
|
||||
int32_t step; /* from 0; the first draws the lane's noise */
|
||||
/* f32 [6]: the video's timestep, sigma and next sigma, then the soundtrack's. */
|
||||
/* f32 [16]: the video's timestep, sigma and next sigma, then the soundtrack's; from [6] the
|
||||
* res_multistep scalars of the video, then of the soundtrack (`sampler`, below). */
|
||||
const float* sched;
|
||||
const float* pos; /* f32 [3, n_tok]: RAD_VPOS_STEP */
|
||||
/* u32 [2, 2]: the video's noise seed and the soundtrack's, low word first (VSTEP, VUPSCALE and
|
||||
@@ -573,8 +676,55 @@ typedef struct RadVideoGenBatch {
|
||||
/* VDECODE: the decoder the request named (RadVideoGenDecl::decoders), its index; 0 the
|
||||
* default. */
|
||||
int32_t decoder;
|
||||
|
||||
/* ---- appended in ABI 31 (rad_builder.h, "Reference conditioning") */
|
||||
/* The sampler a VSTEP advances the latents with: RAD_SAMPLER_EULER, the first-order step on
|
||||
* sched[0..5], or RAD_SAMPLER_RES_MULTISTEP, the second-order one on the clean estimate
|
||||
* (k-diffusion's res_multistep at eta 0), which keeps the previous step's estimate. Its scalars
|
||||
* are sched[6..10] for the video and sched[11..15] for the soundtrack: sigma, r = next sigma /
|
||||
* sigma, the weights hb1 and hb2 of this step's estimate and the previous one, and the order,
|
||||
* 1 where there is no previous estimate on the same grid. */
|
||||
int32_t sampler;
|
||||
/* VENCODE: f32 [enc_frames, enc_height, enc_width, 3] RGB in 0..255, the frames padded to
|
||||
* whole clips by repeating the last (rad_arch_encode_geom's entry 23). AENCODE: f32
|
||||
* [enc_channels, enc_n_samples], each channel padded with zeros to the hop (entry 0). Both:
|
||||
* the pass's geometry as rad_arch_encode_geom gave it, i32 on the device, and the media's
|
||||
* kind (RAD_ENC_*, below) and its number within the kind from 1. */
|
||||
const float* enc_pixels;
|
||||
int32_t enc_frames, enc_height, enc_width;
|
||||
const float* enc_samples;
|
||||
int64_t enc_n_samples;
|
||||
int32_t enc_channels;
|
||||
const int32_t* enc_geom_d;
|
||||
int32_t enc_kind, enc_slot;
|
||||
/* VCOND and VSTEP of a request with reference media or keyframes: their table, host i32, null
|
||||
* without. [0] the references, [1] the keyframes, then 6 words a reference {kind, slot, latent
|
||||
* height, latent width, latent frames, soundtrack latents} in presentation order and 3 a
|
||||
* keyframe {frame, latent frames, soundtrack latents}, then the prompt's vision pads: a count
|
||||
* and {first token, tokens} of each picture's run. A reference's kind is RAD_VREF_PICTURE,
|
||||
* _AUDIO or _VIDEO; its slot is its encode pass's. */
|
||||
const int32_t* ref_tab;
|
||||
/* VSTEP: i32, rad_arch_video_pack's `mod`: the boundaries of the modulation groups, then the
|
||||
* cell each reads; `seg_cu` then holds the segment boundaries. A request without references
|
||||
* stages `seg_cu`'s four and no cells. */
|
||||
const int32_t* mod_cu;
|
||||
} RadVideoGenBatch;
|
||||
|
||||
enum { RAD_SAMPLER_EULER = 0, RAD_SAMPLER_RES_MULTISTEP = 1 };
|
||||
|
||||
/* RadVideoGenBatch::enc_kind: the media an encode pass carries, numbered from 1 within a kind. A
|
||||
* keyframe is 1 for the first frame and 2 for the last. */
|
||||
enum {
|
||||
RAD_ENC_IMAGE = 1, /* a reference picture; Vencode */
|
||||
RAD_ENC_VIDEO = 2, /* a reference video; Vencode */
|
||||
RAD_ENC_VAUDIO = 3, /* the soundtrack of reference video `enc_slot`; Aencode */
|
||||
RAD_ENC_AUDIO = 4, /* a standalone soundtrack; Aencode */
|
||||
RAD_ENC_KEYFRAME = 5 /* a first or last frame; Vencode */
|
||||
};
|
||||
|
||||
/* RadVideoGenBatch::ref_tab: a reference's kind. */
|
||||
enum { RAD_VREF_PICTURE = 0, RAD_VREF_AUDIO = 1, RAD_VREF_VIDEO = 2 };
|
||||
|
||||
/* RadVideoGenBatch::geom_d. The request's latent geometry, then a VDECODE pass's chunk: the latent
|
||||
* frames it reads (from latent frame `chunk_lat0`), its latent grid again so that (frames, h, w,
|
||||
* first, last) is one run, and the same chunk in patches. */
|
||||
@@ -681,7 +831,8 @@ int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n)
|
||||
* the all-reduce numbers its scratch slots per launch and the ranks must agree; a kernel with a
|
||||
* device-wide arrival counter must key it on the stream (libr4d's split-K GEMM does), or it may
|
||||
* not run here; and every buffer the second lane touches must be named to rad_buf_concurrent,
|
||||
* because the planner packs transients from one linear order. */
|
||||
* because the planner packs transients from one linear order (live for the whole program, or across
|
||||
* the second lane's window where the architecture declares one, abi/rad_builder.h). */
|
||||
int rad_lane(RadCtx* c, int lane);
|
||||
int rad_lane_join(RadCtx* c, int from, int to);
|
||||
|
||||
@@ -696,6 +847,18 @@ int rad_step_fail(RadCtx* c, const char* what);
|
||||
|
||||
/* ================================================================== run-phase queries */
|
||||
const RadBatch* rad_batch(RadCtx* c);
|
||||
/* The position of model layer `layer` among `group`'s bound layers, or -1 when this rank has no
|
||||
* pool for it or the group does not hold the layer: the lookup a RAD_KV operand makes, and the
|
||||
* index of the layer's host mirror row. Bound layers need not be contiguous. */
|
||||
int rad_kv_layer_index(RadCtx* c, rad_kvgroup group, int layer);
|
||||
/* Prefill staging of a streamed group (the ordering rule is in core/kvstream/stage.h).
|
||||
* rad_kv_stage_layer, before the layer's store: when the pass uses the one-layer stage view, make
|
||||
* the layer's mirror row whole in it (once a pass) and return 1, after which the caller reads
|
||||
* block ids directly and must not resolve; 0 when the group has no stage view.
|
||||
* rad_kv_stage_next, after every attention launch of the layer: start the next layer's copy. */
|
||||
int rad_kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb,
|
||||
int layer);
|
||||
int rad_kv_stage_next(RadCtx* c, rad_kvgroup group, int layer);
|
||||
int rad_rank(RadCtx* c);
|
||||
int rad_world_size(RadCtx* c);
|
||||
RadStream rad_stream(RadCtx* c);
|
||||
|
||||
@@ -0,0 +1,413 @@
|
||||
/* rad_spechub.h -- the speculative coupling (linear MTP and DFlash2's block walk): wire rows and
|
||||
* the shared arithmetic.
|
||||
*
|
||||
* The core writes these rows and a kernel plugin reads them, so their layout is ABI. The helpers
|
||||
* are header-only and stateless, so the host reference, the device kernel and the sampler share
|
||||
* one definition of the wire and of the arithmetic that turns it into a token.
|
||||
*
|
||||
* A row lives in a U32 plane whose base and row stride are eight-byte aligned, so a state can be
|
||||
* loaded whole on the device.
|
||||
*/
|
||||
#ifndef RAD_SPECHUB_H
|
||||
#define RAD_SPECHUB_H
|
||||
|
||||
#include <math.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* The verify reads a RadSampleParams row. */
|
||||
#include "rad_sample.h"
|
||||
|
||||
/* Linear MTP coupling (--draft-coupling on). One draw per drafting row, staged before the
|
||||
* serial passes; one state per (temporal round, row). `base` is the request's PRE-commit output
|
||||
* size, so (base, round) names one draft stream that no later step reuses. `card` is the step slot
|
||||
* the advance writes, checked against RadBatch::seq_ids. `mode` 1 samples x~Q; 0 keeps the greedy
|
||||
* proposal (temperature 0 or top_k 1). */
|
||||
typedef struct RadMtpCoupleDraw {
|
||||
uint64_t seed, base, seq;
|
||||
int32_t card;
|
||||
uint32_t mode;
|
||||
} RadMtpCoupleDraw;
|
||||
/* status 1: x sampled from the exact q[] stored here; 0: greedy proposal kept; -1: malformed
|
||||
* shortlist or row identity, greedy proposal kept. `pos` is the verify row's output position, bound
|
||||
* by the host after commit; the device writes 0. ids[count..7] = -1, q[count..7] = 0. */
|
||||
typedef struct RadMtpCoupleState {
|
||||
RadMtpCoupleDraw draw;
|
||||
uint64_t pos;
|
||||
int32_t status, round, x, count;
|
||||
int32_t ids[8];
|
||||
double q[8];
|
||||
} RadMtpCoupleState;
|
||||
#define RAD_MTP_COUPLE_DRAW_WORDS (sizeof(RadMtpCoupleDraw) / 4)
|
||||
#define RAD_MTP_COUPLE_STATE_WORDS (sizeof(RadMtpCoupleState) / 4)
|
||||
#define RAD_MTP_COUPLE_MAX_ROUNDS 8
|
||||
/* Draft stream of round r: seed ^ (KEY_DRAFT + r) at coordinate `base`. Acceptance and the
|
||||
* residual draw use RAD_SAMPLE_KEY_ACCEPT / RAD_SAMPLE_KEY_RESID at the verify position. */
|
||||
#define RAD_MTP_COUPLE_KEY_DRAFT 0x4d5450434f55504cull
|
||||
#ifdef __cplusplus
|
||||
static_assert(sizeof(RadMtpCoupleDraw) == 32, "MTP coupling draw wire");
|
||||
static_assert(sizeof(RadMtpCoupleState) == 152, "MTP coupling state wire");
|
||||
static_assert(offsetof(RadMtpCoupleState, q) % 8 == 0, "MTP coupling q alignment");
|
||||
#endif
|
||||
|
||||
/* ================================================================== the shared arithmetic
|
||||
*
|
||||
* Q is the FP64 softmax of an FP32 shortlist at temperature 1; P is the FP64 softmax of the
|
||||
* sampler's FP32 candidate logits; uniforms are 53-bit. A coupled row therefore realises the
|
||||
* filtered target law to FP64 rounding rather than sample_pick's FP32/24-bit law, and is not
|
||||
* seed-identical to the ordinary pick.
|
||||
*/
|
||||
#ifdef __cplusplus
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
#define RAD_SPECHUB_HD __host__ __device__
|
||||
#else
|
||||
#define RAD_SPECHUB_HD
|
||||
#endif
|
||||
|
||||
static inline RAD_SPECHUB_HD double rad_spechub_positive(double a) { return a > 0 ? a : 0; }
|
||||
static inline RAD_SPECHUB_HD bool rad_spechub_finite(double x) {
|
||||
return x == x && x <= 1.7976931348623157e308 && x >= -1.7976931348623157e308;
|
||||
}
|
||||
|
||||
/* A 53-bit uniform in [0, 1): splitmix64 over (seed ^ key, pos), top 53 bits scaled by 2^-53. */
|
||||
static inline RAD_SPECHUB_HD double rad_spechub_uniform(uint64_t seed, uint64_t pos, uint64_t key) {
|
||||
uint64_t z = (seed ^ key) * 0x9e3779b97f4a7c15ull + pos + 0x9e3779b97f4a7c15ull;
|
||||
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull;
|
||||
z = (z ^ (z >> 27)) * 0x94d049bb133111ebull;
|
||||
z ^= z >> 31;
|
||||
return (double)(z >> 11) * 0x1p-53;
|
||||
}
|
||||
|
||||
/* Is `s` a state the coupling's propose kernel could have written for a sampled row? The verifier
|
||||
* and the engine's bind check refuse a row by this rule, on the device and on the host. */
|
||||
static inline RAD_SPECHUB_HD bool rad_mtp_couple_state_valid(const RadMtpCoupleState& s,
|
||||
int64_t vocab) {
|
||||
if (s.status != 1 || s.draw.mode != 1 || s.count < 1 || s.count > 8 || s.round < 1 ||
|
||||
s.round > RAD_MTP_COUPLE_MAX_ROUNDS)
|
||||
return false;
|
||||
double sum = 0;
|
||||
bool has_x = false;
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
if (i >= s.count) {
|
||||
if (s.ids[i] != -1 || s.q[i] != 0) return false;
|
||||
continue;
|
||||
}
|
||||
if (s.ids[i] < 0 || s.ids[i] >= vocab || !rad_spechub_finite(s.q[i]) || !(s.q[i] > 0) ||
|
||||
s.q[i] > 1)
|
||||
return false;
|
||||
for (int j = 0; j < i; ++j)
|
||||
if (s.ids[j] == s.ids[i]) return false;
|
||||
sum += s.q[i];
|
||||
has_x |= s.ids[i] == s.x;
|
||||
}
|
||||
return has_x && (sum - 1) <= 1e-12 && (1 - sum) <= 1e-12;
|
||||
}
|
||||
|
||||
/* The verify position of coupled round r (1-based): the coordinate the engine's bind and the
|
||||
* sampler's row check must agree on.
|
||||
*
|
||||
* The sampler stages row k of a request at output position `n_out + k`, where `n_out` is the
|
||||
* request's committed output length when the step is built; round r is verified at row r - 1. The
|
||||
* acceptance and residual uniforms are drawn at this position.
|
||||
*
|
||||
* `n_out` is read from the request after the drafting step's commit. It is not rebuilt from the
|
||||
* draft's pre-commit `base` plus the accepted count: the two differ when the commit emits fewer
|
||||
* tokens than the card accepted (a max_tokens or context cut) or a step is carried. */
|
||||
static inline RAD_SPECHUB_HD uint64_t rad_mtp_couple_verify_pos(uint64_t n_out, int round) {
|
||||
return n_out + (round > 0 ? (uint64_t)(round - 1) : 0);
|
||||
}
|
||||
|
||||
/* Would the verify row for draft index `k` (0-based) of a request with committed output length
|
||||
* `n_out` take `c` as its coupled state? Same request and seed, the round this row's draft came
|
||||
* from, the position it samples, the very token it proposes, and a state the proposer could have
|
||||
* written. Anything else is a stale state from another step, and coupling against it would apply a
|
||||
* law this step never drew.
|
||||
*
|
||||
* Asked by the sampler's step build, against the state the engine bound. The engine's own bind
|
||||
* does not call it: it checks the readback against the card (draw, round, x, status) and writes
|
||||
* the position with rad_mtp_couple_verify_pos, the formula here that both sides must agree on. */
|
||||
static inline RAD_SPECHUB_HD bool rad_mtp_couple_binds(const RadMtpCoupleState& c, uint64_t seq,
|
||||
uint64_t seed, uint64_t n_out, int k,
|
||||
int32_t draft_x, int64_t vocab) {
|
||||
return c.status == 1 && c.draw.seq == seq && c.draw.seed == seed && c.round == k + 1 &&
|
||||
c.pos == rad_mtp_couple_verify_pos(n_out, k + 1) && c.x == draft_x &&
|
||||
rad_mtp_couple_state_valid(c, vocab);
|
||||
}
|
||||
|
||||
/* Build the stored Q from a shortlist of eight (id, score) slots.
|
||||
*
|
||||
* Holes (id < 0) and -inf scores carry no mass. An entry whose FP64 weight or normalized q
|
||||
* underflows to zero is dropped, so the stored q[] is exactly the law the draw walks. False on an
|
||||
* out-of-range id, NaN/+inf score, duplicate id or empty support (s->count = 0). */
|
||||
static inline RAD_SPECHUB_HD bool rad_mtp_couple_build_q(const int32_t* ids, const float* val,
|
||||
int64_t vocab, RadMtpCoupleState* s) {
|
||||
int32_t kid[8];
|
||||
float kv[8];
|
||||
int n = 0;
|
||||
s->count = 0;
|
||||
for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; }
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
if (ids[i] < 0) continue;
|
||||
if (ids[i] >= vocab || val[i] != val[i] || val[i] == INFINITY) return false;
|
||||
if (val[i] == -INFINITY) continue;
|
||||
for (int j = 0; j < n; ++j)
|
||||
if (kid[j] == ids[i]) return false;
|
||||
kid[n] = ids[i];
|
||||
kv[n++] = val[i];
|
||||
}
|
||||
if (!n) return false;
|
||||
float top = kv[0];
|
||||
for (int j = 1; j < n; ++j)
|
||||
if (kv[j] > top) top = kv[j];
|
||||
double w[8], sum = 0;
|
||||
for (int j = 0; j < n; ++j) { w[j] = ::exp((double)kv[j] - top); sum += w[j]; }
|
||||
for (int j = 0; j < n; ++j) {
|
||||
const double q = w[j] / sum;
|
||||
if (q > 0) { s->ids[s->count] = kid[j]; s->q[s->count++] = q; }
|
||||
}
|
||||
return s->count > 0;
|
||||
}
|
||||
|
||||
/* Inverse CDF over the stored q with a uniform in [0, 1); index into ids. */
|
||||
static inline RAD_SPECHUB_HD int rad_mtp_couple_pick(const RadMtpCoupleState& s, double u) {
|
||||
double total = 0;
|
||||
for (int i = 0; i < s.count; ++i) total += s.q[i];
|
||||
double c = u * total;
|
||||
for (int i = 0; i < s.count; ++i) { c -= s.q[i]; if (c < 0) return i; }
|
||||
return s.count - 1;
|
||||
}
|
||||
|
||||
/* Residual mass r(y) = max(0, P(y) - Q(y)) of one candidate. Q tokens use their P aggregated over
|
||||
* duplicate candidates, counted once at the first occurrence (`seen`). */
|
||||
static inline RAD_SPECHUB_HD double rad_mtp_couple_mass(const RadMtpCoupleState& s, const double* pq,
|
||||
int32_t id, float v, float top, double sum,
|
||||
unsigned* seen) {
|
||||
if (id < 0 || v == -INFINITY) return 0;
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
if (s.ids[k] == id) {
|
||||
if (*seen & (1u << k)) return 0;
|
||||
*seen |= 1u << k;
|
||||
return rad_spechub_positive(pq[k] - s.q[k]);
|
||||
}
|
||||
return ::exp((double)v - top) / sum;
|
||||
}
|
||||
|
||||
/* The maximal coupling of the target's law P (over the surviving candidates) with the draft's Q.
|
||||
* Writes the emitted token to *out and returns true, or returns false for an invalid or empty
|
||||
* target. u_accept and u_resid are independent uniforms in [0, 1).
|
||||
*
|
||||
* The draft x is kept when P dominates Q on every Q token or when u_accept * Q(x) < P(x); otherwise
|
||||
* the token is drawn from the residual (P - Q)+. The emitted token is distributed as P, and it
|
||||
* equals x with probability sum min(P, Q).
|
||||
*
|
||||
* If FP64 cancellation leaves the residual total R at 0 while some Q token has P < Q, P is sampled
|
||||
* directly in FP64 with u_resid. That branch depends on (P, Q) only, never on x or a uniform.
|
||||
*
|
||||
* R sums r over every candidate including x. The residual walk runs only when P(x) < Q(x), where
|
||||
* r(x) is exactly +0, so skipping x in the walk leaves its total equal to R bit for bit. */
|
||||
static inline RAD_SPECHUB_HD bool rad_mtp_couple_decide(const RadMtpCoupleState& s,
|
||||
const int32_t* ids, const float* val,
|
||||
int64_t n, int64_t vocab, double u_accept,
|
||||
double u_resid, int32_t* out) {
|
||||
float top = -INFINITY;
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0) continue;
|
||||
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
|
||||
if (val[j] > top) top = val[j];
|
||||
}
|
||||
if (top == -INFINITY) return false;
|
||||
double sum = 0, pq[8] = {};
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] < 0 || val[j] == -INFINITY) continue;
|
||||
const double w = ::exp((double)val[j] - top);
|
||||
sum += w;
|
||||
for (int k = 0; k < s.count; ++k)
|
||||
if (ids[j] == s.ids[k]) { pq[k] += w; break; }
|
||||
}
|
||||
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
|
||||
int ix = -1;
|
||||
bool dominated = true;
|
||||
for (int k = 0; k < s.count; ++k) {
|
||||
pq[k] /= sum;
|
||||
dominated = dominated && pq[k] >= s.q[k];
|
||||
if (s.ids[k] == s.x) ix = k;
|
||||
}
|
||||
if (ix < 0) return false; /* unreachable for a rad_mtp_couple_state_valid state */
|
||||
unsigned seen = 0;
|
||||
double resid = 0;
|
||||
for (int64_t j = 0; j < n; ++j)
|
||||
resid += rad_mtp_couple_mass(s, pq, ids[j], val[j], top, sum, &seen);
|
||||
if (!dominated && !(resid > 0 && rad_spechub_finite(resid))) {
|
||||
double c = u_resid * sum;
|
||||
int32_t last = -1;
|
||||
for (int64_t j = 0; j < n; ++j)
|
||||
if (ids[j] >= 0 && val[j] != -INFINITY) {
|
||||
const double w = ::exp((double)val[j] - top);
|
||||
if (w > 0) { last = ids[j]; c -= w; if (c < 0) { *out = last; return true; } }
|
||||
}
|
||||
*out = last;
|
||||
return true;
|
||||
}
|
||||
if (pq[ix] >= s.q[ix] || u_accept * s.q[ix] < pq[ix]) { *out = s.x; return true; }
|
||||
/* Rejected, so P(x) < Q(x): not dominated, resid > 0, and some y != x has mass > 0 below. */
|
||||
double c = u_resid * resid;
|
||||
int32_t last = -1;
|
||||
seen = 0;
|
||||
for (int64_t j = 0; j < n; ++j) {
|
||||
if (ids[j] == s.x) continue;
|
||||
const double m = rad_mtp_couple_mass(s, pq, ids[j], val[j], top, sum, &seen);
|
||||
if (m > 0) { last = ids[j]; c -= m; if (c < 0) { *out = last; return true; } }
|
||||
}
|
||||
*out = last;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* ================================================================== DFlash2's coupled walk
|
||||
*
|
||||
* The block drafter's counterpart of mtp_couple_propose (`dflash_couple_propose`). DFlash2 proposes
|
||||
* a block in one pass and `dflash_select` walks its candidate lattice greedily: at draft position l
|
||||
* every candidate c of that position scores
|
||||
*
|
||||
* score[l, c] = unary[l, c] + sum_r pred[pid][r] * hp[l][r] * succ[cand[l, c]][r]
|
||||
*
|
||||
* with pid the anchor at l = 0 and the walk's own previous token after it. The coupled walk scores
|
||||
* the same lattice but SAMPLES each position instead of taking its argmax:
|
||||
*
|
||||
* Q_l = the FP64 softmax of score[l, c] / q_temp over the eight best-scoring candidates whose
|
||||
* ids are in the vocabulary (rad_mtp_couple_build_q), x_l ~ Q_l at the draw's
|
||||
* (seed, base, KEY_DRAFT + l + 1), and pid = x_l for position l + 1.
|
||||
*
|
||||
* Q_l depends on the committed text (through the drafter's pass and the anchor) and on x_0..x_{l-1},
|
||||
* never on the target's verification, and it is stored exactly in the state row the verify reads,
|
||||
* which is all the maximal coupling needs to be exact (rad_mtp_couple_decide). The pairwise term is
|
||||
* what makes Q_l follow the walk's own earlier samples rather than the drafter's marginal.
|
||||
*
|
||||
* Bit-identical on host and device: each candidate's edge is RAD_DFLASH_EDGE_PARTS partial sums,
|
||||
* each a serial fmaf chain over a contiguous slice of the rank, added in order and then to the unary
|
||||
* score. The plugin builds with -ffp-contract=off, so nothing else is fused. */
|
||||
#define RAD_DFLASH_EDGE_PARTS 8
|
||||
#define RAD_DFLASH_COUPLE_MAX_K 32
|
||||
#define RAD_DFLASH_COUPLE_MAX_R 512
|
||||
|
||||
static inline RAD_SPECHUB_HD float rad_dflash_bf2f(uint16_t h) {
|
||||
union { uint32_t u; float f; } c;
|
||||
c.u = (uint32_t)h << 16;
|
||||
return c.f;
|
||||
}
|
||||
|
||||
/* Part `j` of one candidate's edge: a[r] * succ_row[r] over r in [j*R/P, (j+1)*R/P), fmaf in order.
|
||||
* `a` is the candidate-independent half, pred[pid][r] * hp[r] (or pred[pid][r] with no hp, 0 for a
|
||||
* predecessor outside the vocabulary). */
|
||||
static inline RAD_SPECHUB_HD float rad_dflash_edge_part(const float* a, const uint16_t* succ_row,
|
||||
int64_t R, int j) {
|
||||
const int64_t w = R / RAD_DFLASH_EDGE_PARTS;
|
||||
float acc = 0.0f;
|
||||
for (int64_t r = (int64_t)j * w; r < (int64_t)(j + 1) * w; ++r)
|
||||
acc = fmaf(a[r], rad_dflash_bf2f(succ_row[r]), acc);
|
||||
return acc;
|
||||
}
|
||||
|
||||
/* One position of the walk, given its K scores and ids (the ids as the candidate plane holds them).
|
||||
* Fills `*s` as mtp_couple_propose fills a round's state and returns the proposed token:
|
||||
*
|
||||
* mode 0 (a greedy request): status 0, x = `greedy_x`, the token dflash_select already wrote;
|
||||
* mode 1, its card's draw and a Q that builds: status 1, x ~ Q;
|
||||
* mode 1 otherwise: status -1, x = the walk's argmax (ties to the lower index, dflash_select's
|
||||
* rule over these scores), and the ordinary verify applies to it.
|
||||
*
|
||||
* The eight are taken in descending score, ties to the lower index, among candidates with an id
|
||||
* in [0, vocab); a NaN score is never taken (build_q would refuse it). */
|
||||
static inline RAD_SPECHUB_HD int32_t rad_dflash_couple_step(const float* sc, const int32_t* id,
|
||||
int K, float q_temp,
|
||||
const RadMtpCoupleDraw& d, bool card_ok,
|
||||
int round, int64_t vocab,
|
||||
int32_t greedy_x, RadMtpCoupleState* s) {
|
||||
s->draw = d;
|
||||
s->pos = 0;
|
||||
s->round = round;
|
||||
s->count = 0;
|
||||
for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; }
|
||||
if (d.mode != 1) {
|
||||
s->status = 0;
|
||||
s->x = greedy_x;
|
||||
return greedy_x;
|
||||
}
|
||||
s->status = -1;
|
||||
if (card_ok) {
|
||||
int32_t kid[8];
|
||||
float kv[8];
|
||||
unsigned taken = 0;
|
||||
int n = 0;
|
||||
for (; n < 8; ++n) {
|
||||
int best = -1;
|
||||
for (int c = 0; c < K; ++c) {
|
||||
if ((taken >> c) & 1u) continue;
|
||||
if (id[c] < 0 || id[c] >= vocab || sc[c] != sc[c]) continue;
|
||||
if (best < 0 || sc[c] > sc[best]) best = c;
|
||||
}
|
||||
if (best < 0) break;
|
||||
taken |= 1u << best;
|
||||
kid[n] = id[best];
|
||||
kv[n] = sc[best] / q_temp;
|
||||
}
|
||||
for (int i = n; i < 8; ++i) { kid[i] = -1; kv[i] = -INFINITY; }
|
||||
if (n > 0 && rad_mtp_couple_build_q(kid, kv, vocab, s)) {
|
||||
const double u = rad_spechub_uniform(d.seed, d.base,
|
||||
RAD_MTP_COUPLE_KEY_DRAFT + (uint64_t)round);
|
||||
s->x = s->ids[rad_mtp_couple_pick(*s, u)];
|
||||
s->status = 1;
|
||||
return s->x;
|
||||
}
|
||||
s->count = 0;
|
||||
for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; }
|
||||
}
|
||||
int best = 0;
|
||||
float bv = -INFINITY;
|
||||
for (int c = 0; c < K; ++c)
|
||||
if (sc[c] > bv) { bv = sc[c]; best = c; }
|
||||
s->x = id[best];
|
||||
return s->x;
|
||||
}
|
||||
|
||||
/* One sequence's whole walk on the host: the reference the device kernel is checked against, and
|
||||
* what the tests drive. `cand`/`unary` are `steps` rows at pitches `ld_cand`/`ld_unary`, `hp`
|
||||
* `steps` rows at `ld_hp` (null: ones), `tokens` the `steps` tokens dflash_select wrote (rewritten
|
||||
* for a sampled row), `state` round 1's row with `st_round` u32 words between rounds. K <= 32, R a
|
||||
* multiple of RAD_DFLASH_EDGE_PARTS and at most RAD_DFLASH_COUPLE_MAX_R (the plugin's validation).
|
||||
* `pred`/`succ` are [vocab, R]. */
|
||||
static inline void rad_dflash_couple_walk(const int32_t* cand, const float* unary, int64_t ld_cand,
|
||||
int64_t ld_unary, const uint16_t* hp, int64_t ld_hp,
|
||||
int32_t anchor, const uint16_t* pred,
|
||||
const uint16_t* succ, int K,
|
||||
int64_t R, int64_t vocab, int64_t steps, float q_temp,
|
||||
const RadMtpCoupleDraw& d, bool card_ok, int32_t* tokens,
|
||||
uint32_t* state, int64_t st_round) {
|
||||
float a[RAD_DFLASH_COUPLE_MAX_R], sc[RAD_DFLASH_COUPLE_MAX_K] = {};
|
||||
int32_t pid = anchor;
|
||||
for (int64_t l = 0; l < steps; ++l) {
|
||||
RadMtpCoupleState* s = reinterpret_cast<RadMtpCoupleState*>(state + l * st_round);
|
||||
const int32_t* id = cand + l * ld_cand;
|
||||
if (d.mode == 1) {
|
||||
const float* un = unary + l * ld_unary;
|
||||
const bool ok = pid >= 0 && pid < vocab;
|
||||
for (int64_t r = 0; r < R; ++r)
|
||||
a[r] = ok ? rad_dflash_bf2f(pred[(int64_t)pid * R + r]) *
|
||||
(hp ? rad_dflash_bf2f(hp[l * ld_hp + r]) : 1.0f)
|
||||
: 0.0f;
|
||||
for (int c = 0; c < K; ++c) {
|
||||
float acc = 0.0f;
|
||||
if (id[c] >= 0 && id[c] < vocab)
|
||||
for (int j = 0; j < RAD_DFLASH_EDGE_PARTS; ++j)
|
||||
acc += rad_dflash_edge_part(a, succ + (int64_t)id[c] * R, R, j);
|
||||
sc[c] = un[c] + acc;
|
||||
}
|
||||
}
|
||||
pid = rad_dflash_couple_step(sc, id, K, q_temp, d, card_ok, (int)l + 1, vocab, tokens[l], s);
|
||||
tokens[l] = pid;
|
||||
}
|
||||
}
|
||||
|
||||
#undef RAD_SPECHUB_HD
|
||||
#endif /* __cplusplus */
|
||||
#endif /* RAD_SPECHUB_H */
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/clef_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(clef_bf16 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(clef_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/clef_bf16.cpp)
|
||||
@@ -0,0 +1,67 @@
|
||||
/* clef_bf16 -- Cloudflare's clef and clef-flash decision models, bf16: the qwen35_bf16 trunk with
|
||||
* the joint schema head on the card (arch/common/rad_block_clef.h), served on /v1/systemone.
|
||||
*
|
||||
* This is arch/qwen35_bf16/qwen35_bf16.cpp built again under its own architecture id, as
|
||||
* qwen35_w8a8 is qwen35_fp8 built again: the trunk's declare and step are that file's, untouched,
|
||||
* and this file adds the head after them. A container selects it with `rad-convert --arch clef`,
|
||||
* so a plain qwen35 container never pays for the head and the qwen35 plugins carry no decision
|
||||
* code. The head needs `decision.type=clef` and the head's geometry in the container header,
|
||||
* which rad-convert writes from joint_head_config.json and joint_head.safetensors (--add).
|
||||
*/
|
||||
#define RAD_ARCH_NO_EXPORTS 1
|
||||
#include "../qwen35_bf16/qwen35_bf16.cpp"
|
||||
#undef RAD_ARCH_NO_EXPORTS
|
||||
|
||||
#include <arch/rad_block_clef.h>
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
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 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 (!ClefHead::present(meta)) {
|
||||
std::fprintf(stderr, "radiance: clef_bf16 serves a container converted with "
|
||||
"--set decision.type=clef and the head added (--add "
|
||||
"joint_head.safetensors); this one declares no decision model\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(qwen35_bf16::declare(b, meta, ctx));
|
||||
/* 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];
|
||||
/* 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];
|
||||
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);
|
||||
}
|
||||
|
||||
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)];
|
||||
/* 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);
|
||||
if (batch->n_out > 0) h.step_heads(c, batch, m.b_logits, m.w_lm_head);
|
||||
}
|
||||
|
||||
} /* namespace clef_bf16 */
|
||||
|
||||
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")
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/clef_fp8 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(clef_fp8 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(clef_fp8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/clef_fp8.cpp)
|
||||
@@ -0,0 +1,64 @@
|
||||
/* clef_fp8 -- Cloudflare's clef and clef-flash decision models, block fp8: the qwen35_fp8 trunk
|
||||
* with the joint schema head on the card (arch/common/rad_block_clef.h), served on
|
||||
* /v1/systemone.
|
||||
*
|
||||
* This is arch/qwen35_fp8/qwen35_fp8.cpp built again under its own namespace and architecture
|
||||
* id, as qwen35_w8a8 and qwen35moe_fp8 are: the trunk's declare, step and probe are that file's,
|
||||
* untouched, and this file adds the head after them. A container selects it with `rad-convert
|
||||
* --arch clef` and the fp8 recipe; the lm_head stays bf16, which the head reads.
|
||||
*/
|
||||
#define QWEN35_NS qwen35_clef_fp8
|
||||
#define QWEN35_ARCH_ID "clef"
|
||||
#define RAD_ARCH_NO_EXPORTS 1
|
||||
#include "../qwen35_fp8/qwen35_fp8.cpp"
|
||||
#undef RAD_ARCH_NO_EXPORTS
|
||||
|
||||
#include <arch/rad_block_clef.h>
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
namespace clef_fp8 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
static ClefHead g_head[MAX_RANKS];
|
||||
|
||||
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 (!ClefHead::present(meta)) {
|
||||
std::fprintf(stderr, "radiance: clef_fp8 serves a container converted with "
|
||||
"--set decision.type=clef and the head added (--add "
|
||||
"joint_head.safetensors); this one declares no decision model\n");
|
||||
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];
|
||||
/* 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];
|
||||
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);
|
||||
}
|
||||
|
||||
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)];
|
||||
/* 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);
|
||||
}
|
||||
|
||||
} /* namespace clef_fp8 */
|
||||
|
||||
RAD_ARCH_PROBE(qwen35_clef_fp8)
|
||||
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")
|
||||
+168
-6
@@ -15,6 +15,7 @@
|
||||
#include "rad_device.h"
|
||||
#include "rad_runtime.h"
|
||||
#include "rad_yarn.h"
|
||||
#include "rad_abi_layout.h"
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
@@ -513,12 +514,33 @@ inline int map_copy_alt(RadBuilder* b, const char* declared, const char* a, cons
|
||||
|
||||
/* One expert's slice of a stacked checkpoint tensor. GGUF stores a MoE layer's experts as one
|
||||
* ffn_gate_exps [.., n_expert], while placement moves one expert at a time and so needs one
|
||||
* declared weight per expert (spec §4.2). src_index carries the expert index explicitly. */
|
||||
inline int map_slice(RadBuilder* b, const char* declared, const char* src, int index) {
|
||||
* declared weight per expert (spec §4.2). src_index carries the expert index explicitly.
|
||||
*
|
||||
* `sub_rows` is for a stack flattened into the rows of a rank-2 tensor (Nomic's
|
||||
* experts.mlp.w1 is [n_expert * n_ff, n_embd]): it is the sub-tensor's row count, so the slice is
|
||||
* rows [index * sub_rows, (index + 1) * sub_rows). Left 0, a rank-3 stack takes index as its
|
||||
* dim-0 sub-tensor. */
|
||||
inline int map_slice(RadBuilder* b, const char* declared, const char* src, int index,
|
||||
int64_t sub_rows = 0) {
|
||||
RadNameMap m = map_base(declared, RAD_MAP_COPY);
|
||||
m.n_src = 1;
|
||||
m.src[0] = src;
|
||||
m.src_index[0]= index;
|
||||
m.src_rows[0] = sub_rows;
|
||||
return rad_decl_name_map(b, &m);
|
||||
}
|
||||
|
||||
/* One expert's slice of a stacked tensor, transposed: the per-expert table a grouped GEMM reads
|
||||
* when the checkpoint keeps it [in, out]. A rank-3 stack takes index as its dim-0 sub-tensor. A
|
||||
* rank-2 stack flattened over its rows takes `sub_rows` as the sub-tensor's row count, as
|
||||
* map_slice's. */
|
||||
inline int map_transpose_slice(RadBuilder* b, const char* declared, const char* src, int index,
|
||||
int64_t sub_rows = 0) {
|
||||
RadNameMap m = map_base(declared, RAD_MAP_TRANSPOSE);
|
||||
m.n_src = 1;
|
||||
m.src[0] = src;
|
||||
m.src_index[0]= index;
|
||||
m.src_rows[0] = sub_rows;
|
||||
return rad_decl_name_map(b, &m);
|
||||
}
|
||||
|
||||
@@ -617,7 +639,8 @@ inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
|
||||
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) RAD_ISSUE(c, op, RAD_W(w));
|
||||
rad_lane(c, 0);
|
||||
}
|
||||
/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. */
|
||||
/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. A plugin declares
|
||||
* none where the deployment turns the reads off (RadBuildCtx::weight_prefetch_off). */
|
||||
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) {
|
||||
if (!w || bytes <= 0 || !rad_op_declared(b, "prefetch")) return 0;
|
||||
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w));
|
||||
@@ -663,6 +686,9 @@ struct Geom {
|
||||
int64_t max_tok = 0;
|
||||
int64_t max_seqs = 0;
|
||||
int64_t max_ctx = 0;
|
||||
/* --kv-resident in tokens (RadBuildCtx::kv_resident_blocks), 0 when nothing streams: what
|
||||
* kv_resolve_declare states as the ring's depth. */
|
||||
int64_t kv_resident = 0;
|
||||
int max_spec = 0;
|
||||
/* Most rows the sampler can want in one step: one per sequence, or one per draft position per
|
||||
* sequence at a speculative verify. Bounds the logits buffer (at a 248K vocab, 63 MiB rather
|
||||
@@ -939,6 +965,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
g.max_tok = c->max_tok;
|
||||
g.max_seqs = c->max_seqs;
|
||||
g.max_ctx = c->max_ctx;
|
||||
g.kv_resident = c->kv_resident_blocks;
|
||||
g.max_spec = c->max_spec;
|
||||
g.max_logit_rows = c->max_seqs * (c->max_spec > 0 ? c->max_spec + 1 : 1);
|
||||
if (g.max_logit_rows > c->max_tok) g.max_logit_rows = c->max_tok;
|
||||
@@ -1059,6 +1086,95 @@ inline int64_t vocab_head_rows(const Geom& g) {
|
||||
* handle. */
|
||||
inline RadOperand kv_cache(rad_kvgroup group, int layer) { return RAD_KV(group, layer); }
|
||||
|
||||
/* One layer of a streamed group (RadKVStream): its rows of the host mirror and the ring's maps.
|
||||
* The mirror is layer-major over the group's bound layers in KVPoolBinding::layer_slot order, not
|
||||
* over model layers (Flash-Next's full-attention layers are every other layer, plus the MTP head),
|
||||
* so the row comes from rad_kv_layer_index. `host` is null when the group does not stream on this
|
||||
* rank or has no row for the layer. */
|
||||
struct KVStreamLayer {
|
||||
const RadKVStream* st = nullptr;
|
||||
const uint8_t* host = nullptr; /* [blocks, bbytes] mirror row */
|
||||
int32_t* res = nullptr; /* [blocks] block -> ring slot, -1 when absent */
|
||||
int32_t* slot_block = nullptr; /* [slots] ring slot -> block */
|
||||
int32_t* slot_state = nullptr; /* [slots, 2] */
|
||||
int64_t blocks = 0, bbytes = 0, slots = 0;
|
||||
};
|
||||
inline KVStreamLayer kv_stream_layer(RadCtx* c, rad_kvgroup group, int layer,
|
||||
const RadKVGroupBatch* kvb) {
|
||||
KVStreamLayer L;
|
||||
const RadKVStream* st = kvb ? kvb->stream : nullptr;
|
||||
if (!st || !st->host || st->block_bytes <= 0) return L;
|
||||
const int64_t li = rad_kv_layer_index(c, group, layer);
|
||||
if (li < 0) return L;
|
||||
L.st = st;
|
||||
L.bbytes = st->block_bytes;
|
||||
L.blocks = st->host_layer_stride / L.bbytes;
|
||||
L.slots = st->slots;
|
||||
L.host = st->host + li * st->host_layer_stride;
|
||||
L.res = st->res + li * L.blocks;
|
||||
L.slot_block = st->slot_block + li * L.slots;
|
||||
L.slot_state = st->slot_state + li * L.slots * 2;
|
||||
return L;
|
||||
}
|
||||
|
||||
/* The prefill stage of a streamed group (the ordering rule is in core/kvstream/stage.h):
|
||||
*
|
||||
* kv_stage_wait -- immediately before the layer's store: the copy from the mirror must land
|
||||
* before the store writes this chunk's newer bytes into the stage;
|
||||
* kv_stage_layer -- before the attention: true when the pass uses the stage, so the caller
|
||||
* reads block ids directly and must not resolve;
|
||||
* kv_stage_next -- after every attention launch of the layer: the next layer's copy starts
|
||||
* once the last read of the aliased stage is behind it.
|
||||
*
|
||||
* Both of the first two are rad_kv_stage_layer, which stages a layer once per pass. */
|
||||
inline bool kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb, int layer) {
|
||||
return rad_kv_stage_layer(c, group, kvb, layer) != 0;
|
||||
}
|
||||
inline bool kv_stage_wait(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb, int layer) {
|
||||
return rad_kv_stage_layer(c, group, kvb, layer) != 0;
|
||||
}
|
||||
inline void kv_stage_next(RadCtx* c, rad_kvgroup group, int layer) {
|
||||
(void)rad_kv_stage_next(c, group, layer);
|
||||
}
|
||||
|
||||
/* The `kv_resolve` a streamed group's block declares. None of its geometry is free:
|
||||
*
|
||||
* blocks the block-id space a selection can name: max_seqs sequences of the context;
|
||||
* slots the ring --kv-resident carves, in whole blocks, raised to one decode step's
|
||||
* selection (max_seqs x (1 + n_spec) x sel_pitch) as kvstream_ring raises it, and
|
||||
* at most `blocks`; the resolve is issued with the pool's depth, so declaring the
|
||||
* context would size its scratch for slots it cannot reach;
|
||||
* sel_pitch the selection row's pitch, which the attention declares its rows with
|
||||
* (`qsa_topk + 1` on the sparse path, the indexer's count on GLM).
|
||||
*
|
||||
* The kernel sizes its claim list from these (`M * sel_pitch`, r4d_kv_resolve.hip's
|
||||
* kv_claim_cap); ctl[12] reports the largest claim count a launch made, so a wrong declaration
|
||||
* shows in the engine's stream report. `sel` is read as well as written, so the arena keeps it
|
||||
* live from its producer to the attention. Returns 0 when the op is not declared or the group has
|
||||
* nothing to address. */
|
||||
inline rad_op kv_resolve_declare(RadBuilder* b, const Geom& g, rad_kvgroup kv, rad_buf sel,
|
||||
rad_buf nsel, int64_t sel_pitch) {
|
||||
if (!rad_op_declared(b, "kv_resolve") || !sel || !nsel || sel_pitch <= 0) return 0;
|
||||
const int64_t bs = rad_kv_block_size(b, kv);
|
||||
const int64_t bbytes = rad_kv_layer_bytes(b, kv);
|
||||
const int64_t blocks = bs > 0 ? g.max_seqs * ((g.max_ctx + bs - 1) / bs) : 0;
|
||||
if (bs <= 0 || bbytes <= 0 || blocks <= 0) return 0;
|
||||
const int64_t ring = g.kv_resident > 0 ? (g.kv_resident + bs - 1) / bs : 0;
|
||||
const int64_t step = g.max_seqs * (1 + (g.max_spec > 0 ? g.max_spec : 0)) * sel_pitch;
|
||||
const int64_t want = ring > 0 && step > ring ? step : ring;
|
||||
const int64_t slots = want > 0 && want < blocks ? want : blocks;
|
||||
const rad_op op = RAD_OP(b, "kv_resolve",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("blocks", blocks),
|
||||
RAD_INT("slots", slots), RAD_INT("sel_pitch", sel_pitch),
|
||||
RAD_INT("block_bytes", bbytes)),
|
||||
RAD_NOWEIGHTS);
|
||||
if (!op) return 0;
|
||||
const rad_buf rd[2] = { sel, nsel };
|
||||
rad_op_reads(b, op, rd, 2);
|
||||
rad_op_writes(b, op, &sel, 1);
|
||||
return op;
|
||||
}
|
||||
|
||||
/* ================================================================== step-sized operands */
|
||||
/* Every operand a step issues carries the step's row count, not the buffer's.
|
||||
*
|
||||
@@ -1097,6 +1213,17 @@ inline RadOperand bcol_at(rad_buf h, int64_t first_row, int64_t pitch,
|
||||
return o;
|
||||
}
|
||||
|
||||
/* Whether every logits row this step samples belongs to a sequence that carries words for the
|
||||
* plugin (RadBatch::plugin_words). A head that answers from those words then has no use for the
|
||||
* lm_head's row: it is sampled once and discarded. One row a sampled sequence; a speculative
|
||||
* step samples more and answers false. */
|
||||
inline bool plugin_words_cover_rows(const RadBatch* b) {
|
||||
if (b->n_out <= 0 || !b->plugin_cu_h) return false;
|
||||
int64_t n = 0;
|
||||
for (int64_t s = 0; s < b->n_seq; ++s) n += b->plugin_cu_h[s + 1] > b->plugin_cu_h[s] ? 1 : 0;
|
||||
return n == b->n_out;
|
||||
}
|
||||
|
||||
/* Rows [first, first + n), seen by the kernel as [n, pitch]; RadOperand::offset is in elements.
|
||||
*
|
||||
* Lets one op be issued in slices: an op whose widest kernel stops at M=64 (the delta net's
|
||||
@@ -1124,6 +1251,16 @@ inline RadOperand praw(const void* p, uint32_t dtype, int64_t rows) {
|
||||
return o;
|
||||
}
|
||||
|
||||
/* kv_resolve over `rows` selection rows (kv_resolve_declare): makes the blocks they name resident
|
||||
* in the ring and rewrites `sel` from block ids to ring slots. */
|
||||
inline void kv_resolve_issue(RadCtx* c, rad_op op, const KVStreamLayer& L, RadOperand sel,
|
||||
RadOperand nsel, rad_kvgroup group, int layer, int64_t rows) {
|
||||
RAD_ISSUE_N(c, op, rows, sel, nsel, praw(L.res, RAD_I32, L.blocks),
|
||||
praw(L.slot_block, RAD_I32, L.slots), praw2(L.slot_state, RAD_I32, L.slots, 2),
|
||||
praw(L.st->ctl, RAD_I32, 16), praw2(L.host, RAD_U8, L.blocks, L.bbytes),
|
||||
kv_cache(group, layer));
|
||||
}
|
||||
|
||||
/* Rotary positions of a pass, in the two forms consumers take.
|
||||
*
|
||||
* `rope_pos1`: one component per token, RadBatch::rope_pos's plane 0 if present, else
|
||||
@@ -1274,16 +1411,18 @@ inline int yarn_from(Geom& g, const RadModelMeta* meta, const char* prefix, int6
|
||||
}
|
||||
|
||||
/* `rope` declared for the geometry's rotary: M-RoPE's mode and sections when the model has them,
|
||||
* `mode` otherwise. */
|
||||
* `mode` otherwise. `op` names the row: "rope" (every caller), or "rope_rows" for a model that
|
||||
* wants the per-(token, pair) angles form at prefill row counts. */
|
||||
inline rad_op decl_rope(RadBuilder* b, const Geom& g, int64_t rows, int64_t head_dim,
|
||||
int64_t n_head, int64_t n_head_kv, int64_t rot, const char* mode) {
|
||||
int64_t n_head, int64_t n_head_kv, int64_t rot, const char* mode,
|
||||
const char* op = "rope") {
|
||||
const RadParam ps[] = { RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", g.rope_mc ? g.rope_mode : mode),
|
||||
RAD_INT("rotary_dim", rot), RAD_STR("sections", g.rope_sections) };
|
||||
const int n = (int)(sizeof ps / sizeof ps[0]) - (g.rope_mc ? 0 : 1);
|
||||
return decl_rotary(b, g, "rope", ps, n, nullptr, 0);
|
||||
return decl_rotary(b, g, op, ps, n, nullptr, 0);
|
||||
}
|
||||
|
||||
/* How many of this step's sequences are decode rows, and where their tokens end.
|
||||
@@ -1307,6 +1446,28 @@ inline const RadKVGroupBatch* kv_batch(const RadBatch* b, rad_kvgroup group) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* ================================================================== calibration in slices */
|
||||
/* The layers [lo, hi) of n a calibration taps: the environment variable `var` as "lo:hi", else
|
||||
* all of them. A large model's Grams do not fit beside its weights at once, so it is calibrated
|
||||
* in slices of layers, the corpus pushed through once a slice. */
|
||||
inline int calib_layers(const char* who, const char* var, int64_t n, int64_t* lo, int64_t* hi) {
|
||||
*lo = 0;
|
||||
*hi = n;
|
||||
const char* s = std::getenv(var);
|
||||
if (!s) return RAD_OK;
|
||||
long long l = 0, h = 0;
|
||||
int used = 0;
|
||||
if (std::sscanf(s, "%lld:%lld%n", &l, &h, &used) != 2 || s[used] != '\0' || l < 0 || h > n ||
|
||||
l >= h) {
|
||||
fprintf(stderr, "radiance: %s: %s '%s' is not lo:hi within 0:%lld\n", who, var, s,
|
||||
(long long)n);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
*lo = l;
|
||||
*hi = h;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== a block drafter */
|
||||
/* A drafter's Geom: the target's (n_embd, vocabulary, deployment bounds, rank, wire) with the
|
||||
* layer, head, feed-forward, norm and rotary geometry of the container's `draft.` config, split
|
||||
@@ -1396,6 +1557,7 @@ inline int drafter_kv_group(RadBuilder* b, Names& nm, const RadBuildCtx* ctx, Ge
|
||||
NS::step(c, batch); \
|
||||
} \
|
||||
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; } \
|
||||
extern "C" uint64_t rad_plugin_abi_layout(void) { return rad_abi_layout(); } \
|
||||
extern "C" const RadPluginInfo* rad_plugin_info(void) { \
|
||||
/* The plugin's name (rad_abi.h: "qwen3_dense_bf16"), not the architecture id: plugin \
|
||||
* names must be unique and one architecture can have several plugins. */ \
|
||||
|
||||
@@ -26,6 +26,14 @@
|
||||
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 */
|
||||
@@ -69,6 +77,7 @@ struct AttnGatedFP8 {
|
||||
* block table and context length: same op, same kernel, different list. `sel` is `topk + 1`
|
||||
* wide and the kernel takes its block-table pitch from the operand. */
|
||||
rad_buf qsa_sel = 0;
|
||||
rad_buf qsa_nsel = 0; /* [max_tok] i32, the valid entries of each `qsa_sel` row */
|
||||
rad_buf qsa_sequ = 0;
|
||||
/* Context length up to which dense attention gives the same result, `budget + ratio - 1`.
|
||||
* Below it every complete block is selected, the paths agree to the bit, and dense is cheaper
|
||||
@@ -110,10 +119,19 @@ struct AttnGatedFP8 {
|
||||
|
||||
rad_op op_fused = 0; /* qk_norm_rope_gate, if it resolves */
|
||||
rad_op op_fused_kv = 0; /* the same with kv_store folded in */
|
||||
/* The same with the streamed store folded in, issued instead when the batch hands this group a
|
||||
* stream (its mirror and map are the batch's). */
|
||||
rad_op op_fused_stream = 0;
|
||||
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 */
|
||||
/* 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;
|
||||
/* kv_resolve: this layer's selection made resident and rewritten as ring slots, issued before
|
||||
* each sparse launch. */
|
||||
rad_op op_resolve = 0;
|
||||
/* The output gate as `sigmoid` then `mul`: the bf16-linear form (Geom::w_bf16), and with fp8
|
||||
* linears the chain gate_quant_fp8 fuses, where it is not served. `gate` is the sigmoid's
|
||||
* output (the wire's with bf16 linears, the block's own otherwise) and `q_gate` the chain's
|
||||
@@ -143,6 +161,13 @@ struct AttnGatedFP8 {
|
||||
* by passes that only leave layer state behind, such as the MTP head's history pass over a
|
||||
* prompt chunk with no drafting row. */
|
||||
void store_kv(RadCtx* c, const RadBatch* batch) const;
|
||||
/* The layer's cache store, before its resolve and attention: `kv_store`, or for a streamed
|
||||
* group the stage wait and `kv_store_streamed`. */
|
||||
void store_cache(RadCtx* c, const RadKVGroupBatch* kvb, const int32_t* slot, int64_t T) const;
|
||||
/* A staged pass reads the pool at block-id identity, while the streamed store writes only
|
||||
* where the residency map names a ring slot (none before the group's first decode). This
|
||||
* stores the same bytes at identity, after the mirror writer. */
|
||||
void store_stage_identity(RadCtx* c, const int32_t* slot, int64_t T) const;
|
||||
|
||||
/* The block's tail, declared last by every rank: the all-reduce and the trailing add. */
|
||||
int declare_out(RadBuilder* b, bool add_out);
|
||||
@@ -157,6 +182,22 @@ struct AttnGatedFP8 {
|
||||
/* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
|
||||
int ar_overlap = 0;
|
||||
rad_op op_ar_ov = 0;
|
||||
|
||||
/* Whether step() with `own_ar` false runs the dense path a piece at a time over a caller's
|
||||
* normed pieces (ArPieces::in_ready): one prefill sequence in two pieces, each the chunk a
|
||||
* span of 1 makes, on the unfused prologue with one rotary component per token (every token's
|
||||
* components agree, so plane 0 of an M-RoPE batch's positions is each token's position) and
|
||||
* the gate quantised by gate_quant_fp8. A streamed group never takes it: the pieces path's
|
||||
* plain store never writes the host mirror. */
|
||||
bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
return pieces && pieces->in_ready && pieces->cu && pieces->cuts(T) &&
|
||||
T <= 2 * pieces->rows && !op_add && !op_fill && op_gq && !op_sig && !qsa_sel &&
|
||||
batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL &&
|
||||
!(T <= fused_rows) && batch->positions && !rope_mixed(batch) &&
|
||||
kvb && !kvb->stream && kvb->slot_mapping && kvb->block_table && kvb->seqused;
|
||||
}
|
||||
};
|
||||
|
||||
inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
@@ -311,11 +352,18 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
* ids: an aperture violation outside the cache. rad_op_reads rather than rw() because the list
|
||||
* depends on whether the layer has an indexer. */
|
||||
if (op_attn) {
|
||||
const rad_buf rd[3] = { w.q, qsa_sel, qsa_sequ };
|
||||
rad_op_reads(b, op_attn, rd, (qsa_sel && qsa_sequ) ? 3 : 1);
|
||||
const rad_buf rd[4] = { w.q, qsa_sel, qsa_sequ, qsa_nsel };
|
||||
rad_op_reads(b, op_attn, rd,
|
||||
(qsa_sel && qsa_sequ) ? (qsa_nsel ? 4 : 3) : 1);
|
||||
rad_op_writes(b, op_attn, &w.attn.x, 1);
|
||||
}
|
||||
|
||||
/* The resolve belongs here rather than in the indexer: it must follow this layer's store,
|
||||
* since a block copied in from the mirror has to carry this step's tokens. Its band is the
|
||||
* step's widest launch and its row `qsa_topk + 1` wide, as the attention declares. */
|
||||
if (qsa_sel && qsa_nsel)
|
||||
op_resolve = kv_resolve_declare(b, g, kv, qsa_sel, qsa_nsel, qsa_topk + 1);
|
||||
|
||||
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),
|
||||
@@ -324,6 +372,19 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
|
||||
/* 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"))
|
||||
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),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
|
||||
/* 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.
|
||||
@@ -340,6 +401,21 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
RAD_WEIGHTS(w_q_norm, w_k_norm)),
|
||||
{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"))
|
||||
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),
|
||||
RAD_INT("n_head_kv", g.n_head_kv), RAD_INT("rot", n_rot),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_F64("eps", g.eps),
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_INT("cs_f32", 1),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_WEIGHTS(w_q_norm, w_k_norm)),
|
||||
{w.qg, w.k, w.cos_sin, w.v}, {w.q, w.k});
|
||||
|
||||
/* Output gate, multiply and quantiser in one pass (`gate_quant_fp8`); at decode the dispatch
|
||||
* gaps between three small ops are comparable to the work. Each row is a (token, head) pair:
|
||||
* the gate is a fixed stride inside [q|gate], the attention output is contiguous, and the
|
||||
@@ -454,6 +530,34 @@ inline int AttnGatedFP8::declare_out(RadBuilder* b, bool add_out) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void AttnGatedFP8::store_stage_identity(RadCtx* c, const int32_t* slot, int64_t T) const {
|
||||
RAD_ISSUE_N(c, op_kv_store, T, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
|
||||
kv_cache(kv, layer));
|
||||
}
|
||||
|
||||
inline void AttnGatedFP8::store_cache(RadCtx* c, const RadKVGroupBatch* kvb,
|
||||
const int32_t* slot, int64_t T) const {
|
||||
if (!kvb || !kvb->stream) {
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
return;
|
||||
}
|
||||
/* A streamed group writes its host mirror, and the ring slot only where the block is resident
|
||||
* (docs/OPS.md "kv_store_streamed"). kv_store alone would treat a block id as a ring slot, so
|
||||
* a build without the streamed store fails the step. */
|
||||
const bool staged = kv_stage_wait(c, kv, kvb, layer);
|
||||
const KVStreamLayer L = kv_stream_layer(c, kv, layer, kvb);
|
||||
if (!op_kv_stream || !L.host || L.blocks <= 0) {
|
||||
rad_step_fail(c, "kv streaming: this layer's KV group streams but the build has no "
|
||||
"kv_store_streamed row to write its host mirror with");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE(c, op_kv_stream,
|
||||
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer),
|
||||
praw(L.res, RAD_I32, L.blocks), praw2(L.host, RAD_U8, L.blocks, L.bbytes));
|
||||
if (staged) store_stage_identity(c, slot, T);
|
||||
}
|
||||
|
||||
inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (!ext_in) nq_h.step(c, T);
|
||||
@@ -464,8 +568,7 @@ inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
|
||||
vp.step(c, w.h, w.v, T);
|
||||
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
|
||||
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
store_cache(c, kvb, slot, T);
|
||||
}
|
||||
|
||||
inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
@@ -477,6 +580,51 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
/* One prefill sequence in two pieces over the caller's normed input (takes_pieces): the
|
||||
* projections, prologue, cache store, attention, gate and out projection of the first piece,
|
||||
* then the second's, so the first piece's reduction runs beside all of the second piece's
|
||||
* work. Each piece is the chunk a span of 1 makes: its rows, its positions, its slots, and an
|
||||
* attention over its own query bounds (ArPieces::cu) that sees the cache up to its own end --
|
||||
* the first piece's position after its last row, the step's seqused for the second, which
|
||||
* reads the first piece's keys from the cache as a later chunk would. */
|
||||
if (!own_ar && takes_pieces(batch, pieces)) {
|
||||
const int64_t R = pieces->rows, hd = g.head_dim, qw = g.q_dim();
|
||||
const int64_t qgw = g.n_head * 2 * hd, kvw = g.n_head_kv * hd;
|
||||
const int64_t tpitch = kvb->block_table_pitch;
|
||||
for (int64_t p = 0; p < 2; ++p) {
|
||||
const int64_t r0 = p == 0 ? 0 : R;
|
||||
const int64_t n = p == 0 ? R : T - R;
|
||||
const int32_t* pos = (batch->rope_pos ? batch->rope_pos : batch->positions) + r0;
|
||||
qg.step(c, w.h, w.qg, T, r0, n);
|
||||
kp.step(c, w.h, w.k, T, r0, n);
|
||||
vp.step(c, w.h, w.v, T, r0, n);
|
||||
RAD_ISSUE_N(c, op_q_norm, n * g.n_head,
|
||||
bcol_at(w.qg, r0, qgw, 0, hd, n), RAD_W(w_q_norm),
|
||||
brow_slice(w.q, r0, n, qw));
|
||||
RAD_ISSUE_N(c, op_k_norm, n * g.n_head_kv,
|
||||
brow_slice(w.k, r0, n, kvw), RAD_W(w_k_norm),
|
||||
brow_slice(w.k, r0, n, kvw));
|
||||
RAD_ISSUE_N(c, op_rope_q, n, brow_slice(w.q, r0, n, qw), praw(pos, RAD_I32, n));
|
||||
RAD_ISSUE_N(c, op_rope_k, n, brow_slice(w.k, r0, n, kvw), praw(pos, RAD_I32, n));
|
||||
RAD_ISSUE_N(c, op_kv_store, n,
|
||||
brow_slice(w.k, r0, n, kvw), brow_slice(w.v, r0, n, kvw),
|
||||
praw(slot + r0, RAD_I32, n), kv_cache(kv, layer));
|
||||
RAD_ISSUE_N(c, op_attn, n,
|
||||
brows(w.q, T), kv_cache(kv, layer), praw2(table, RAD_I32, 1, tpitch),
|
||||
praw(p == 0 ? batch->positions + R : used, RAD_I32, 1),
|
||||
RAD_NONE, RAD_NONE, praw(pieces->cu + p, RAD_I32, 2),
|
||||
brows(w.attn.x, T));
|
||||
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.x, r0, n, qw));
|
||||
o.step(c, w.attn, w.h.x, T, r0, n);
|
||||
if (p == 0) pieces->hand(r0, n);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ext_in) nq_h.step(c, T);
|
||||
if (op_fill) {
|
||||
/* Attention-zero rank: zero output, then the reduce and the residual. */
|
||||
@@ -495,8 +643,24 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
* token, so a pass with media tokens (differing components) takes the unfused path with the
|
||||
* full [3, T] positions. */
|
||||
const bool fuse_ok = T <= fused_rows && !rope_mixed(batch);
|
||||
const bool fused_kv = op_fused_kv && fuse_ok;
|
||||
if (fused_kv) {
|
||||
/* A streamed group folds the streamed store into the prologue instead (op_fused_stream); one
|
||||
* whose layer has no mirror row leaves the store to store_cache, which fails the step. */
|
||||
const bool streamed = kvb && kvb->stream;
|
||||
const bool fused_kv = op_fused_kv && fuse_ok && !streamed;
|
||||
const KVStreamLayer L = streamed && op_fused_stream && fuse_ok
|
||||
? kv_stream_layer(c, kv, layer, kvb) : KVStreamLayer{};
|
||||
const bool folded_stream = L.host && L.blocks > 0;
|
||||
if (folded_stream) {
|
||||
/* The prologue is the store, so the stage copy must land before it (kv_stage_wait). */
|
||||
const bool staged = kv_stage_wait(c, kv, kvb, layer);
|
||||
RAD_ISSUE_N(c, op_fused_stream, T,
|
||||
brows(w.qg, T), brows(w.k, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
|
||||
RAD_W(w_q_norm), RAD_W(w_k_norm),
|
||||
brows(w.q, T), brows(w.k, T), RAD_NONE,
|
||||
brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer),
|
||||
praw(L.res, RAD_I32, L.blocks), praw2(L.host, RAD_U8, L.blocks, L.bbytes));
|
||||
if (staged) store_stage_identity(c, slot, T);
|
||||
} else if (fused_kv) {
|
||||
RAD_ISSUE_N(c, op_fused_kv, T,
|
||||
brows(w.qg, T), brows(w.k, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
|
||||
RAD_W(w_q_norm), RAD_W(w_k_norm),
|
||||
@@ -516,9 +680,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
|
||||
}
|
||||
|
||||
if (!fused_kv)
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
if (!fused_kv && !folded_stream) store_cache(c, kvb, slot, T);
|
||||
|
||||
/* Sparse attention issues one row per query. `attn_paged` indexes its block table and length
|
||||
* by row, and a row need not be a sequence, so T queries issued as T rows of q_len 1, each with
|
||||
@@ -532,9 +694,31 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
* `q_len` (rows = max_seqs * q_len_max * heads); more rows are refused as RAD_E_SCRATCH at
|
||||
* issue. Rows of q_len 1 up to the declared max_seqs always fit. */
|
||||
const int64_t reach = (int64_t)batch->max_ctx_len + batch->max_q_len;
|
||||
/* A pass on a streamed group's ring (a ring smaller than the id space, and not staged) must
|
||||
* take the sparse path: on the ring a block id is not a pool address, so the dense path would
|
||||
* read ring slots as pages. `T == n_seq` alone misses a verify pass, whose T is
|
||||
* n_seq x (1 + n_spec), on a context under qsa_exact_to. A ring that covers the context keeps
|
||||
* the dense path, where ids and slots coincide. */
|
||||
const RadKVStream* st = kvb ? kvb->stream : nullptr;
|
||||
const int64_t st_blocks =
|
||||
(st && st->block_bytes > 0) ? st->host_layer_stride / st->block_bytes : 0;
|
||||
const bool ring_addressed = st && st->slots > 0 && st_blocks > 0 && st->slots < st_blocks;
|
||||
const bool ring_bound = ring_addressed && !kv_stage_layer(c, kv, kvb, layer);
|
||||
const bool sparse = qsa_sel && qsa_sequ &&
|
||||
(T == batch->n_seq || qsa_exact_to <= 0 || reach > qsa_exact_to);
|
||||
(ring_bound || T == batch->n_seq || qsa_exact_to <= 0 ||
|
||||
reach > qsa_exact_to);
|
||||
const bool gated = sparse && op_attn_gq;
|
||||
/* A streamed group's selection, per launch: make the rows' blocks resident and rewrite `sel`
|
||||
* as ring slots, after this layer's store (a block copied in from the mirror must carry this
|
||||
* step's tokens) and before the attention. A pass on the stage view leaves `sel` as block ids
|
||||
* and never resolves, so a prefill cannot overflow the ring. */
|
||||
const KVStreamLayer res_l = op_resolve ? kv_stream_layer(c, kv, layer, kvb) : KVStreamLayer{};
|
||||
auto resolve_sel = [&](int64_t off, int64_t rows) {
|
||||
if (kv_stage_layer(c, kv, kvb, layer)) return;
|
||||
if (!res_l.host || res_l.blocks <= 0 || res_l.slots <= 0 || rows <= 0) return;
|
||||
kv_resolve_issue(c, op_resolve, res_l, brow_slice(qsa_sel, off, rows, qsa_topk + 1),
|
||||
brow_slice(qsa_nsel, off, rows, 1), kv, layer, rows);
|
||||
};
|
||||
/* A piece at a time where the caller takes the all-reduce that way (ArPieces). On the gated
|
||||
* sparse path every query row is its own (q_len 1) and the gate rides in the merge, so the
|
||||
* attention and out projection can finish a piece's rows and hand off its reduction while the
|
||||
@@ -547,6 +731,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
const int64_t pn = T - p0 < pieces->rows ? T - p0 : pieces->rows;
|
||||
for (int64_t off = p0; off < p0 + pn; off += chunk) {
|
||||
const int64_t rows = (p0 + pn - off) < chunk ? (p0 + pn - off) : chunk;
|
||||
resolve_sel(off, rows);
|
||||
RAD_ISSUE_N(c, op_attn_gq, 1,
|
||||
brow_slice(w.q, off, rows, qw),
|
||||
kv_cache(kv, layer),
|
||||
@@ -561,6 +746,8 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
o.step(c, w.attn, w.h.x, T, p0, pn);
|
||||
if (p0 + pn < T) pieces->hand(p0, pn);
|
||||
}
|
||||
/* Every attention launch of this layer is issued: start the next layer's stage copy. */
|
||||
if (kvb && kvb->stream) kv_stage_next(c, kv, layer);
|
||||
return;
|
||||
}
|
||||
if (gated) {
|
||||
@@ -568,6 +755,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
const int64_t qw = g.q_dim(), hd = g.head_dim;
|
||||
for (int64_t off = 0; off < T; off += chunk) {
|
||||
const int64_t rows = (T - off) < chunk ? (T - off) : chunk;
|
||||
resolve_sel(off, rows);
|
||||
RAD_ISSUE_N(c, op_attn_gq, 1,
|
||||
brow_slice(w.q, off, rows, qw),
|
||||
kv_cache(kv, layer),
|
||||
@@ -584,6 +772,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
const int64_t qw = g.q_dim();
|
||||
for (int64_t off = 0; off < T; off += chunk) {
|
||||
const int64_t rows = (T - off) < chunk ? (T - off) : chunk;
|
||||
resolve_sel(off, rows);
|
||||
RAD_ISSUE_N(c, op_attn, 1,
|
||||
brow_slice(w.q, off, rows, qw),
|
||||
kv_cache(kv, layer),
|
||||
@@ -592,18 +781,63 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
RAD_NONE, RAD_NONE, RAD_NONE,
|
||||
brow_slice(w.attn.x, off, rows, qw));
|
||||
}
|
||||
} else {
|
||||
/* Below qsa_exact_to the dense path reads block ids straight from the table and never
|
||||
* resolves, so a staged pass stages this layer here (a no-op without a stage view). A
|
||||
* ring-bound pass with no selection to resolve cannot be served at all. */
|
||||
if (ring_bound) {
|
||||
rad_step_fail(c, "kv streaming: a pass on the streamed group's ring has no selection "
|
||||
"to resolve, so its block ids are not pool addresses");
|
||||
} else if (kvb && kvb->stream) {
|
||||
(void)kv_stage_layer(c, kv, kvb, layer);
|
||||
}
|
||||
/* A mixed step issues its attention once per band, as the GDN blocks do: one launch at
|
||||
* the chunk's band would walk every decode sequence's whole context with one query-tiled
|
||||
* workgroup a KV head, the step's tail beside a long chunk. The decode half (sequences
|
||||
* [0, D), rows [0, DT)) is a prefix at its own band. The prefill half takes its
|
||||
* per-sequence arrays past the decode sequences and keeps q, out and cu at their absolute
|
||||
* rows, as the kernels index q and out by cu.
|
||||
*
|
||||
* The prefill half is issued at the op's top band, not at its own query length: a launch
|
||||
* over part of the step must be served by the query-tiled row, while a short chunk's band
|
||||
* (10 rows or fewer at gqa 6) is the split-KV decode row's, whose partials are sized at
|
||||
* declare for that band and would overflow the scratch. Kernels read exact lengths from
|
||||
* cu, so the loose band costs nothing. A chunk no longer than the verify blocks beside it
|
||||
* keeps one launch at their band: the whole step is decode-shaped then. */
|
||||
int64_t D = 0, DT = 0;
|
||||
batch_split(batch, &D, &DT);
|
||||
const int64_t pitch = kvb ? kvb->block_table_pitch : 0;
|
||||
const int32_t qp = batch->max_q_len_prefill > 0 ? batch->max_q_len_prefill
|
||||
: batch->max_q_len;
|
||||
if (batch->phase == RAD_PHASE_MIXED && D > 0 && D < batch->n_seq &&
|
||||
batch->max_q_len_decode > 0 && qp > batch->max_q_len_decode) {
|
||||
const int64_t P = batch->n_seq - D;
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len_decode,
|
||||
brows(w.q, DT), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, D, pitch), praw(used, RAD_I32, D),
|
||||
RAD_NONE, RAD_NONE, praw(batch->cu_seqlens, RAD_I32, D + 1),
|
||||
brows(w.attn.x, DT));
|
||||
RAD_ISSUE_N(c, op_attn, g.max_tok,
|
||||
brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table ? table + D * pitch : nullptr, RAD_I32, P, pitch),
|
||||
praw(used ? used + D : nullptr, RAD_I32, P),
|
||||
RAD_NONE, RAD_NONE, praw(batch->cu_seqlens + D, RAD_I32, P + 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),
|
||||
praw2(table, RAD_I32, batch->n_seq, pitch),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
/* cu_seqlens: the batch may be ragged (a prefill chunk beside decode rows). */
|
||||
/* cu_seqlens: verify rows may be of different lengths. */
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn.x, T));
|
||||
}
|
||||
}
|
||||
|
||||
/* Every attention launch of this layer is issued: start the next layer's stage copy, which
|
||||
* crosses the link under the out projection and the next layer's projections. */
|
||||
if (kvb && kvb->stream) kv_stage_next(c, kv, layer);
|
||||
if (gated) {
|
||||
/* the sparse attention gated and quantised in its merge */
|
||||
} else if (op_sig) {
|
||||
|
||||
@@ -0,0 +1,666 @@
|
||||
/* rad_block_clef.h -- clef's joint schema head, inside the backbone's plugin.
|
||||
*
|
||||
* Cloudflare's clef and clef-flash decide every question of a request jointly from the backbone's
|
||||
* final hidden state at EVERY prompt position (joint_schema_model.py, JointSchemaHead). This block
|
||||
* runs that head on the card, after the trunk, so /v1/systemone needs no second process:
|
||||
*
|
||||
* per token, every step hn = layernorm(h); hn is stored in a paged KV group of its own,
|
||||
* so a prefix hit keeps the rows the trunk did not recompute
|
||||
* per request, once every row of hn is gathered back out of the group's blocks, the
|
||||
* memory projection and the six cross-attention layers run over all
|
||||
* of them, the question and option spans are averaged, and the
|
||||
* routing, decoder layers and scorer give three numbers an option
|
||||
* (its lexical prior, its cosine and its residual) into the request's
|
||||
* logits row, where the server reads them (core/server/clef.cpp)
|
||||
*
|
||||
* The spans, the option tokens and the question types come as the request's words
|
||||
* (abi/rad_clef.h, RadBatch::plugin_words), laid out as the kernels read them. The head's own
|
||||
* tensors are the release's joint_head.safetensors, added to the container at convert, under their
|
||||
* own names. Every op here has a device kernel and a host reference, so the same block serves
|
||||
* the tiny CPU test and the card.
|
||||
*
|
||||
* Differences from the reference, all within bf16: the cosine and the prior are means of
|
||||
* products of RMS-normalised rows (an identity, with eps 1e-12 against torch's max(norm, 1e-12));
|
||||
* the routing softmax is formed in f32 (seg_softmax_pool). The learned scalars (prior_logit_scale,
|
||||
* joint_logit_scale, residual_gate) are applied by the server from the container header.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
#include <rad_clef.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct ClefHead {
|
||||
bool on = false;
|
||||
|
||||
int64_t E = 0; /* the backbone's hidden size: the head's input width */
|
||||
int64_t W = 0; /* the head's width */
|
||||
int64_t H = 0; /* heads */
|
||||
int64_t HD = 0; /* W / H */
|
||||
int64_t F = 0; /* feedforward */
|
||||
int64_t bs = 0; /* the cache's block size */
|
||||
int64_t nblk = 0; /* blocks a context holds at most */
|
||||
int64_t NM = 0; /* nblk * bs: rows a request holds at most */
|
||||
int64_t n_vocab = 0; /* this rank's logits width */
|
||||
int layer = 0; /* the group's bound layer index */
|
||||
double eps = 1e-5; /* torch.nn.LayerNorm's default */
|
||||
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
/* ---- weights */
|
||||
rad_weight hn_w = 0, hn_b = 0, w_mem = 0, w_q = 0, w_oq = 0, w_glob = 0, w_octx = 0,
|
||||
w_olex = 0, w_type = 0, osn_w = 0, osn_b = 0, fn_w = 0, fn_b = 0, on_w = 0,
|
||||
on_b = 0, rs1_w = 0, rs1_b = 0, rs2_w = 0, rs2_b = 0;
|
||||
struct Ev {
|
||||
rad_weight qn_w = 0, qn_b = 0, mn_w = 0, mn_b = 0, wq = 0, bq = 0, wk = 0, bk = 0, wv = 0,
|
||||
bv = 0, wo = 0, bo = 0, fn_w = 0, fn_b = 0, w1 = 0, b1 = 0, w2 = 0, b2 = 0;
|
||||
rad_op ln_q = 0, ln_m = 0, pq = 0, pk = 0, pv = 0, attn = 0, po = 0, ln_f = 0, f1 = 0,
|
||||
f2 = 0;
|
||||
};
|
||||
struct Dec {
|
||||
rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0, n3w = 0, n3b = 0, sa_w = 0, sa_b = 0,
|
||||
so_w = 0, so_b = 0, cq_w = 0, cq_b = 0, ck_w = 0, ck_b = 0, cv_w = 0, cv_b = 0,
|
||||
co_w = 0, co_b = 0, w1 = 0, b1 = 0, w2 = 0, b2 = 0;
|
||||
rad_op ln1 = 0, qkv = 0, sattn = 0, so = 0, ln2 = 0, pq = 0, pk = 0, pv = 0, cattn = 0,
|
||||
co = 0, ln3 = 0, f1 = 0, f2 = 0;
|
||||
};
|
||||
std::vector<Ev> ev;
|
||||
std::vector<Dec> dec;
|
||||
|
||||
/* ---- buffers */
|
||||
rad_buf b_hn = 0, b_all = 0, b_mem = 0, b_mn = 0, b_k = 0, b_v = 0, b_seg = 0, b_qv = 0,
|
||||
b_oc = 0, b_g = 0, b_lx = 0, b_lex = 0, b_x = 0, b_t1 = 0, b_t2 = 0, b_ff = 0,
|
||||
b_qq = 0, b_bf = 0, b_fr = 0, b_sc = 0, b_sum = 0, b_f = 0, b_fq = 0, b_f1 = 0,
|
||||
b_f2 = 0, b_gw = 0, b_fn = 0, b_on = 0, b_na = 0, b_nb = 0, b_an = 0, b_ln = 0,
|
||||
b_p = 0, b_neg1 = 0, b_d = 0, b_nd = 0, b_abs = 0, b_prod = 0, b_feat = 0, b_r = 0,
|
||||
b_out3 = 0;
|
||||
|
||||
/* ---- ops, one a use site: the arena plans from each op's read and write sets */
|
||||
rad_op op_hn = 0, op_store = 0, op_gather = 0, op_mem = 0, op_seg = 0, op_g_q = 0, op_g_o = 0,
|
||||
op_g_last = 0, op_lex = 0, op_lexmean = 0, op_octx = 0, op_olex = 0, op_add_x1 = 0,
|
||||
op_oq = 0, op_g_oq = 0, op_add_x2 = 0, op_qproj = 0, op_g_fr = 0, op_mul_sc = 0,
|
||||
op_score = 0, op_route = 0, op_ln_osn = 0, op_add_f1 = 0, op_glob = 0, op_add_fg = 0,
|
||||
op_type = 0, op_add_f2 = 0, op_ln_fn = 0, op_g_fr2 = 0, op_ln_on = 0, op_rms_a = 0,
|
||||
op_rms_b = 0, op_mul_cos = 0, op_mean_cos = 0, op_g_an = 0, op_add_an = 0,
|
||||
op_rms_an = 0, op_rms_lex = 0, op_mul_pri = 0, op_mean_pri = 0, op_neg1 = 0,
|
||||
op_nd = 0, op_d = 0, op_relu_d = 0, op_nd2 = 0, op_relu_nd = 0, op_abs = 0,
|
||||
op_prod = 0, op_cp_fr = 0, op_cp_on = 0, op_cp_prod = 0, op_cp_abs = 0, op_rs1 = 0,
|
||||
op_rs2 = 0, op_cast = 0;
|
||||
|
||||
static bool present(const RadModelMeta* meta) {
|
||||
const char* t = rad_meta_gets(meta, "decision.type", "");
|
||||
return t && !std::strcmp(t, "clef");
|
||||
}
|
||||
|
||||
/* Declared after the trunk's layers and lm_head: the trunk's cache block size is known then,
|
||||
* and the head's rows read the final norm's output `b_h` and write `b_logits`. */
|
||||
int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, Names& nm,
|
||||
const Geom& g, rad_buf b_h, rad_buf b_logits, rad_weight w_lm_head,
|
||||
rad_kvgroup kv_trunk, int bind_layer);
|
||||
|
||||
/* Every trunk step: the final norm's rows into the head's cache. */
|
||||
void step_tokens(RadCtx* c, const RadBatch* batch, rad_buf b_h);
|
||||
/* After the lm_head: the head over every sequence that carries words. */
|
||||
void step_heads(RadCtx* c, const RadBatch* batch, rad_buf b_logits, rad_weight w_lm_head);
|
||||
|
||||
private:
|
||||
const RadKVGroupBatch* group_of(const RadBatch* batch) const {
|
||||
for (int i = 0; i < batch->n_kv_groups; ++i)
|
||||
if (batch->kv[i].group == kv) return &batch->kv[i];
|
||||
return nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
inline int ClefHead::declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx,
|
||||
Names& nm, const Geom& g, rad_buf b_h, rad_buf b_logits,
|
||||
rad_weight w_lm_head, rad_kvgroup kv_trunk, int bind_layer) {
|
||||
(void)ctx;
|
||||
E = g.n_embd;
|
||||
W = rad_meta_geti(meta, "decision.clef.width", 0);
|
||||
H = rad_meta_geti(meta, "decision.clef.heads", 0);
|
||||
F = rad_meta_geti(meta, "decision.clef.feedforward", 0);
|
||||
const long long R = rad_meta_geti(meta, "decision.clef.routing_layers", 0);
|
||||
const long long D = rad_meta_geti(meta, "decision.clef.layers", 0);
|
||||
const long long hidden = rad_meta_geti(meta, "decision.clef.hidden_size", 0);
|
||||
if (W <= 0 || H <= 0 || F <= 0 || R <= 0 || D <= 0 || W % H || hidden != E) {
|
||||
std::fprintf(stderr, "radiance: clef: the container's decision.clef.* keys do not describe "
|
||||
"the head (hidden_size %lld against the backbone's %lld, width %lld, "
|
||||
"heads %lld, feedforward %lld, routing_layers %lld, layers %lld); "
|
||||
"rad-convert sets them from joint_head_config.json\n",
|
||||
hidden, (long long)E, (long long)W, (long long)H, (long long)F, R, D);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
HD = W / H;
|
||||
if (g.world != 1) {
|
||||
std::fprintf(stderr, "radiance: clef's head runs on one rank: its rows are replicated and "
|
||||
"the option tokens read the whole lm_head\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16) != RAD_BF16) {
|
||||
std::fprintf(stderr, "radiance: clef's head averages lm_head rows as bf16; this container's "
|
||||
"lm_head is quantised. Keep output.weight bf16 in the recipe\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (E % 2) return RAD_E_INVAL;
|
||||
bs = rad_kv_block_size(b, kv_trunk);
|
||||
if (bs <= 0) return RAD_E_STATE;
|
||||
/* Rows a request may hold: the context, or the head's own bound where that is less (the
|
||||
* server refuses a longer prompt before it is admitted). */
|
||||
const int64_t rows = g.max_ctx < RAD_CLEF_MAX_PROMPT ? g.max_ctx : RAD_CLEF_MAX_PROMPT;
|
||||
nblk = (rows + bs - 1) / bs;
|
||||
NM = nblk * bs;
|
||||
n_vocab = g.n_vocab;
|
||||
layer = bind_layer;
|
||||
const int64_t QM = RAD_CLEF_MAX_QUESTIONS, OM = RAD_CLEF_MAX_OPTIONS, LM = RAD_CLEF_MAX_LEX;
|
||||
const int64_t SM = 2 * (QM + OM) + 1;
|
||||
if (n_vocab < 3 * OM) {
|
||||
std::fprintf(stderr, "radiance: clef's head writes %lld values into a logits row of %lld\n",
|
||||
(long long)(3 * OM), (long long)n_vocab);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* ---- the cache: one FULL group, hn's two halves as a slot's K and V, so a block holds
|
||||
* bs rows of E in position order and a gather of a sequence's blocks is its rows. Bound past
|
||||
* the trunk, so the scheduler counts it as the head's; cached with the trunk's groups because
|
||||
* its block size is theirs (core/mem/prefix.cpp). */
|
||||
RadKVGroupDecl kd{};
|
||||
kd.kind = RAD_KV_FULL;
|
||||
kd.dtype = RAD_BF16;
|
||||
kd.n_head_kv = 1;
|
||||
kd.head_dim = E / 2;
|
||||
kv = rad_decl_kv_group(b, nm.f("clef.kv"), &kd);
|
||||
if (!kv) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, layer, kv));
|
||||
RAD_ARCH_TRY(rad_declare_plugin_words(b, rad_clef_max_words()));
|
||||
|
||||
/* ---- weights: the release's names, bf16, read once a request. */
|
||||
const int ACC = RAD_ACCESS_PER_REQUEST;
|
||||
auto bw = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp) -> rad_weight {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, grp_model());
|
||||
};
|
||||
/* A packed in_proj's third: rows [k W, (k+1) W) of the weight, and of the bias. */
|
||||
auto bw_rows = [&](const char* dn, const char* src, int k, int64_t cols) -> rad_weight {
|
||||
if (map_rows(b, dn, { { src, (int)(k * W), W } }) < 0) return 0;
|
||||
return cols ? decl_w(b, dn, RAD_BF16, { W, cols }, ACC, RAD_SHARD_NONE, grp_model())
|
||||
: decl_w(b, dn, RAD_BF16, { W }, ACC, RAD_SHARD_NONE, grp_model());
|
||||
};
|
||||
hn_w = bw(nm.f("clef.hidden_norm.weight"), nm.ckpt("hidden_norm.weight"), { E });
|
||||
hn_b = bw(nm.f("clef.hidden_norm.bias"), nm.ckpt("hidden_norm.bias"), { E });
|
||||
w_mem = bw(nm.f("clef.memory_projection.weight"), nm.ckpt("memory_projection.weight"), { W, E });
|
||||
w_q = bw(nm.f("clef.question_projection.weight"), nm.ckpt("question_projection.weight"), { W, E });
|
||||
w_oq = bw(nm.f("clef.option_question_projection.weight"), nm.ckpt("option_question_projection.weight"), { W, E });
|
||||
w_glob = bw(nm.f("clef.global_projection.weight"), nm.ckpt("global_projection.weight"), { W, E });
|
||||
w_octx = bw(nm.f("clef.option_context_projection.weight"), nm.ckpt("option_context_projection.weight"), { W, E });
|
||||
w_olex = bw(nm.f("clef.option_lexical_projection.weight"), nm.ckpt("option_lexical_projection.weight"), { W, E });
|
||||
w_type = bw(nm.f("clef.type_embedding.weight"), nm.ckpt("type_embedding.weight"), { 3, W });
|
||||
osn_w = bw(nm.f("clef.option_summary_norm.weight"), nm.ckpt("option_summary_norm.weight"), { W });
|
||||
osn_b = bw(nm.f("clef.option_summary_norm.bias"), nm.ckpt("option_summary_norm.bias"), { W });
|
||||
fn_w = bw(nm.f("clef.field_norm.weight"), nm.ckpt("field_norm.weight"), { W });
|
||||
fn_b = bw(nm.f("clef.field_norm.bias"), nm.ckpt("field_norm.bias"), { W });
|
||||
on_w = bw(nm.f("clef.option_norm.weight"), nm.ckpt("option_norm.weight"), { W });
|
||||
on_b = bw(nm.f("clef.option_norm.bias"), nm.ckpt("option_norm.bias"), { W });
|
||||
/* The scorer's first linear reads [field | option | field*option | |field-option|], one row
|
||||
* of 4 W an option, which the blocks below assemble in `feat`. */
|
||||
rs1_w = bw(nm.f("clef.residual_scorer.0.weight"), nm.ckpt("residual_scorer.0.weight"), { W, 4 * W });
|
||||
rs1_b = bw(nm.f("clef.residual_scorer.0.bias"), nm.ckpt("residual_scorer.0.bias"), { W });
|
||||
rs2_w = bw(nm.f("clef.residual_scorer.3.weight"), nm.ckpt("residual_scorer.3.weight"), { 1, W });
|
||||
rs2_b = bw(nm.f("clef.residual_scorer.3.bias"), nm.ckpt("residual_scorer.3.bias"), { 1 });
|
||||
if (!hn_w || !hn_b || !w_mem || !w_q || !w_oq || !w_glob || !w_octx || !w_olex || !w_type ||
|
||||
!osn_w || !osn_b || !fn_w || !fn_b || !on_w || !on_b || !rs1_w || !rs1_b || !rs2_w || !rs2_b)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
ev.assign((size_t)R, Ev{});
|
||||
for (int i = 0; i < (int)R; ++i) {
|
||||
Ev& e = ev[(size_t)i];
|
||||
const char* p = "evidence_layers";
|
||||
e.qn_w = bw(nm.f("clef.ev.%d.query_norm.weight", i), nm.ckpt("%s.%d.query_norm.weight", p, i), { W });
|
||||
e.qn_b = bw(nm.f("clef.ev.%d.query_norm.bias", i), nm.ckpt("%s.%d.query_norm.bias", p, i), { W });
|
||||
e.mn_w = bw(nm.f("clef.ev.%d.memory_norm.weight", i), nm.ckpt("%s.%d.memory_norm.weight", p, i), { W });
|
||||
e.mn_b = bw(nm.f("clef.ev.%d.memory_norm.bias", i), nm.ckpt("%s.%d.memory_norm.bias", p, i), { W });
|
||||
e.wq = bw_rows(nm.f("clef.ev.%d.q.weight", i), nm.ckpt("%s.%d.attention.in_proj_weight", p, i), 0, W);
|
||||
e.wk = bw_rows(nm.f("clef.ev.%d.k.weight", i), nm.ckpt("%s.%d.attention.in_proj_weight", p, i), 1, W);
|
||||
e.wv = bw_rows(nm.f("clef.ev.%d.v.weight", i), nm.ckpt("%s.%d.attention.in_proj_weight", p, i), 2, W);
|
||||
e.bq = bw_rows(nm.f("clef.ev.%d.q.bias", i), nm.ckpt("%s.%d.attention.in_proj_bias", p, i), 0, 0);
|
||||
e.bk = bw_rows(nm.f("clef.ev.%d.k.bias", i), nm.ckpt("%s.%d.attention.in_proj_bias", p, i), 1, 0);
|
||||
e.bv = bw_rows(nm.f("clef.ev.%d.v.bias", i), nm.ckpt("%s.%d.attention.in_proj_bias", p, i), 2, 0);
|
||||
e.wo = bw(nm.f("clef.ev.%d.o.weight", i), nm.ckpt("%s.%d.attention.out_proj.weight", p, i), { W, W });
|
||||
e.bo = bw(nm.f("clef.ev.%d.o.bias", i), nm.ckpt("%s.%d.attention.out_proj.bias", p, i), { W });
|
||||
e.fn_w = bw(nm.f("clef.ev.%d.ff_norm.weight", i), nm.ckpt("%s.%d.feedforward_norm.weight", p, i), { W });
|
||||
e.fn_b = bw(nm.f("clef.ev.%d.ff_norm.bias", i), nm.ckpt("%s.%d.feedforward_norm.bias", p, i), { W });
|
||||
e.w1 = bw(nm.f("clef.ev.%d.ff1.weight", i), nm.ckpt("%s.%d.feedforward.0.weight", p, i), { F, W });
|
||||
e.b1 = bw(nm.f("clef.ev.%d.ff1.bias", i), nm.ckpt("%s.%d.feedforward.0.bias", p, i), { F });
|
||||
e.w2 = bw(nm.f("clef.ev.%d.ff2.weight", i), nm.ckpt("%s.%d.feedforward.3.weight", p, i), { W, F });
|
||||
e.b2 = bw(nm.f("clef.ev.%d.ff2.bias", i), nm.ckpt("%s.%d.feedforward.3.bias", p, i), { W });
|
||||
if (!e.qn_w || !e.qn_b || !e.mn_w || !e.mn_b || !e.wq || !e.wk || !e.wv || !e.bq || !e.bk ||
|
||||
!e.bv || !e.wo || !e.bo || !e.fn_w || !e.fn_b || !e.w1 || !e.b1 || !e.w2 || !e.b2)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
dec.assign((size_t)D, Dec{});
|
||||
for (int i = 0; i < (int)D; ++i) {
|
||||
Dec& d = dec[(size_t)i];
|
||||
const char* p = "layers";
|
||||
d.n1w = bw(nm.f("clef.dec.%d.norm1.weight", i), nm.ckpt("%s.%d.norm1.weight", p, i), { W });
|
||||
d.n1b = bw(nm.f("clef.dec.%d.norm1.bias", i), nm.ckpt("%s.%d.norm1.bias", p, i), { W });
|
||||
d.n2w = bw(nm.f("clef.dec.%d.norm2.weight", i), nm.ckpt("%s.%d.norm2.weight", p, i), { W });
|
||||
d.n2b = bw(nm.f("clef.dec.%d.norm2.bias", i), nm.ckpt("%s.%d.norm2.bias", p, i), { W });
|
||||
d.n3w = bw(nm.f("clef.dec.%d.norm3.weight", i), nm.ckpt("%s.%d.norm3.weight", p, i), { W });
|
||||
d.n3b = bw(nm.f("clef.dec.%d.norm3.bias", i), nm.ckpt("%s.%d.norm3.bias", p, i), { W });
|
||||
/* Self-attention keeps its packed in_proj: one GEMM, then column slices. */
|
||||
d.sa_w = bw(nm.f("clef.dec.%d.sa.in.weight", i), nm.ckpt("%s.%d.self_attn.in_proj_weight", p, i), { 3 * W, W });
|
||||
d.sa_b = bw(nm.f("clef.dec.%d.sa.in.bias", i), nm.ckpt("%s.%d.self_attn.in_proj_bias", p, i), { 3 * W });
|
||||
d.so_w = bw(nm.f("clef.dec.%d.sa.o.weight", i), nm.ckpt("%s.%d.self_attn.out_proj.weight", p, i), { W, W });
|
||||
d.so_b = bw(nm.f("clef.dec.%d.sa.o.bias", i), nm.ckpt("%s.%d.self_attn.out_proj.bias", p, i), { W });
|
||||
d.cq_w = bw_rows(nm.f("clef.dec.%d.ca.q.weight", i), nm.ckpt("%s.%d.multihead_attn.in_proj_weight", p, i), 0, W);
|
||||
d.ck_w = bw_rows(nm.f("clef.dec.%d.ca.k.weight", i), nm.ckpt("%s.%d.multihead_attn.in_proj_weight", p, i), 1, W);
|
||||
d.cv_w = bw_rows(nm.f("clef.dec.%d.ca.v.weight", i), nm.ckpt("%s.%d.multihead_attn.in_proj_weight", p, i), 2, W);
|
||||
d.cq_b = bw_rows(nm.f("clef.dec.%d.ca.q.bias", i), nm.ckpt("%s.%d.multihead_attn.in_proj_bias", p, i), 0, 0);
|
||||
d.ck_b = bw_rows(nm.f("clef.dec.%d.ca.k.bias", i), nm.ckpt("%s.%d.multihead_attn.in_proj_bias", p, i), 1, 0);
|
||||
d.cv_b = bw_rows(nm.f("clef.dec.%d.ca.v.bias", i), nm.ckpt("%s.%d.multihead_attn.in_proj_bias", p, i), 2, 0);
|
||||
d.co_w = bw(nm.f("clef.dec.%d.ca.o.weight", i), nm.ckpt("%s.%d.multihead_attn.out_proj.weight", p, i), { W, W });
|
||||
d.co_b = bw(nm.f("clef.dec.%d.ca.o.bias", i), nm.ckpt("%s.%d.multihead_attn.out_proj.bias", p, i), { W });
|
||||
d.w1 = bw(nm.f("clef.dec.%d.ff1.weight", i), nm.ckpt("%s.%d.linear1.weight", p, i), { F, W });
|
||||
d.b1 = bw(nm.f("clef.dec.%d.ff1.bias", i), nm.ckpt("%s.%d.linear1.bias", p, i), { F });
|
||||
d.w2 = bw(nm.f("clef.dec.%d.ff2.weight", i), nm.ckpt("%s.%d.linear2.weight", p, i), { W, F });
|
||||
d.b2 = bw(nm.f("clef.dec.%d.ff2.bias", i), nm.ckpt("%s.%d.linear2.bias", p, i), { W });
|
||||
if (!d.n1w || !d.n1b || !d.n2w || !d.n2b || !d.n3w || !d.n3b || !d.sa_w || !d.sa_b ||
|
||||
!d.so_w || !d.so_b || !d.cq_w || !d.ck_w || !d.cv_w || !d.cq_b || !d.ck_b || !d.cv_b ||
|
||||
!d.co_w || !d.co_b || !d.w1 || !d.b1 || !d.w2 || !d.b2)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- buffers, bf16, at the bounds the words are refused past. */
|
||||
b_hn = decl_b(b, nm.f("clef.hn"), RAD_BF16, { g.max_tok, E });
|
||||
b_all = decl_b(b, nm.f("clef.all"), RAD_BF16, { NM, E });
|
||||
b_mem = decl_b(b, nm.f("clef.mem"), RAD_BF16, { NM, W });
|
||||
b_mn = decl_b(b, nm.f("clef.mn"), RAD_BF16, { NM, W });
|
||||
b_k = decl_b(b, nm.f("clef.k"), RAD_BF16, { NM, W });
|
||||
b_v = decl_b(b, nm.f("clef.v"), RAD_BF16, { NM, W });
|
||||
b_seg = decl_b(b, nm.f("clef.seg"), RAD_BF16, { SM, E });
|
||||
b_qv = decl_b(b, nm.f("clef.qv"), RAD_BF16, { QM, E });
|
||||
b_oc = decl_b(b, nm.f("clef.oc"), RAD_BF16, { OM, E });
|
||||
b_g = decl_b(b, nm.f("clef.g"), RAD_BF16, { 1, E });
|
||||
b_lx = decl_b(b, nm.f("clef.lx"), RAD_BF16, { LM, E });
|
||||
b_lex = decl_b(b, nm.f("clef.lex"), RAD_BF16, { OM, E });
|
||||
b_x = decl_b(b, nm.f("clef.x"), RAD_BF16, { OM, W });
|
||||
b_t1 = decl_b(b, nm.f("clef.t1"), RAD_BF16, { OM, W });
|
||||
b_t2 = decl_b(b, nm.f("clef.t2"), RAD_BF16, { OM, W });
|
||||
b_ff = decl_b(b, nm.f("clef.ff"), RAD_BF16, { OM, F });
|
||||
b_qq = decl_b(b, nm.f("clef.qq"), RAD_BF16, { QM, W });
|
||||
b_bf = decl_b(b, nm.f("clef.bf"), RAD_BF16, { QM, W });
|
||||
b_fr = decl_b(b, nm.f("clef.fr"), RAD_BF16, { OM, W });
|
||||
b_sc = decl_b(b, nm.f("clef.sc"), RAD_BF16, { OM, 1 });
|
||||
b_sum = decl_b(b, nm.f("clef.sum"), RAD_BF16, { QM, W });
|
||||
b_f = decl_b(b, nm.f("clef.f"), RAD_BF16, { QM, W });
|
||||
b_fq = decl_b(b, nm.f("clef.fq"), RAD_BF16, { QM, 3 * W });
|
||||
b_f1 = decl_b(b, nm.f("clef.f1"), RAD_BF16, { QM, W });
|
||||
b_f2 = decl_b(b, nm.f("clef.f2"), RAD_BF16, { QM, W });
|
||||
b_gw = decl_b(b, nm.f("clef.gw"), RAD_BF16, { 1, W });
|
||||
b_fn = decl_b(b, nm.f("clef.fn"), RAD_BF16, { QM, W });
|
||||
b_on = decl_b(b, nm.f("clef.on"), RAD_BF16, { OM, W });
|
||||
b_na = decl_b(b, nm.f("clef.na"), RAD_BF16, { OM, W });
|
||||
b_nb = decl_b(b, nm.f("clef.nb"), RAD_BF16, { OM, W });
|
||||
b_an = decl_b(b, nm.f("clef.an"), RAD_BF16, { OM, E });
|
||||
b_ln = decl_b(b, nm.f("clef.ln"), RAD_BF16, { OM, E });
|
||||
b_p = decl_b(b, nm.f("clef.p"), RAD_BF16, { OM, E });
|
||||
b_neg1 = decl_b(b, nm.f("clef.neg1"), RAD_BF16, { 1, W });
|
||||
b_d = decl_b(b, nm.f("clef.d"), RAD_BF16, { OM, W });
|
||||
b_nd = decl_b(b, nm.f("clef.nd"), RAD_BF16, { OM, W });
|
||||
b_abs = decl_b(b, nm.f("clef.abs"), RAD_BF16, { OM, W });
|
||||
b_prod = decl_b(b, nm.f("clef.prod"), RAD_BF16, { OM, W });
|
||||
b_feat = decl_b(b, nm.f("clef.feat"), RAD_BF16, { OM, 4 * W });
|
||||
b_r = decl_b(b, nm.f("clef.r"), RAD_BF16, { OM, W });
|
||||
b_out3 = decl_b(b, nm.f("clef.out3"), RAD_BF16, { 3 * OM, 1 });
|
||||
if (!b_hn || !b_all || !b_mem || !b_mn || !b_k || !b_v || !b_seg || !b_qv || !b_oc || !b_g ||
|
||||
!b_lx || !b_lex || !b_x || !b_t1 || !b_t2 || !b_ff || !b_qq || !b_bf || !b_fr || !b_sc ||
|
||||
!b_sum || !b_f || !b_fq || !b_f1 || !b_f2 || !b_gw || !b_fn || !b_on || !b_na || !b_nb ||
|
||||
!b_an || !b_ln || !b_p || !b_neg1 || !b_d || !b_nd || !b_abs || !b_prod || !b_feat || !b_r ||
|
||||
!b_out3)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* ---- ops. The lambdas state each kind once; the row bound is the op's band. */
|
||||
auto lnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_weight bias) {
|
||||
return RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) {
|
||||
return RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto gemmb = [&](int64_t rows, int64_t N, int64_t K, const char* act, rad_weight w,
|
||||
rad_weight bias) {
|
||||
return RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("act", act)),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto unary = [&](const char* op, int64_t rows, int64_t n) {
|
||||
return RAD_OP(b, op,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto gather = [&](int64_t rows, int64_t n) { return unary("gather_rows", rows, n); };
|
||||
auto cross = [&](int64_t rows) {
|
||||
return RAD_OP(b, "attn_cross",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", HD), RAD_INT("gqa", 1),
|
||||
RAD_INT("causal", 0), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)HD))),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto rmsp = [&](int64_t rows, int64_t n) {
|
||||
return RAD_OP(b, "rmsnorm_p",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", 1e-12),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
/* The mean of a row: a cosine from two RMS-normed rows, or with `mult` the dot product
|
||||
* scaled (mult = n / sqrt(W) gives options . field / sqrt(W)). */
|
||||
auto rowmean = [&](int64_t rows, int64_t n, double mult) {
|
||||
return RAD_OP(b, "pool_cols",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_INT("k", n),
|
||||
RAD_F64("mult", mult), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
|
||||
/* Every step: the final norm's rows into the cache. kv_store carries the block size and so is
|
||||
* the group's consumer (core/build/rad_builder.cpp, find_kv_consumer); its write is the pool. */
|
||||
op_hn = rw(b, lnorm(g.max_tok, E, hn_w, hn_b), { b_h }, { b_hn });
|
||||
op_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", E / 2),
|
||||
RAD_INT("n_head_kv", 1), RAD_INT("block_size", bs),
|
||||
RAD_STR("kv_dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_hn }, {});
|
||||
if (rad_kv_block_size(b, kv) != bs) {
|
||||
std::fprintf(stderr, "radiance: clef's cache took block size %lld, the trunk's is %lld\n",
|
||||
(long long)rad_kv_block_size(b, kv), (long long)bs);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
|
||||
/* Per request. A sequence's blocks are rows of bs * E: the gather reads the pool as
|
||||
* [n_blocks, bs * E] and writes `all` as [nblk, bs * E], which the ops below read as rows of E
|
||||
* (a contiguous buffer at another width, core/runtime and libr4d's r4d_rows_pitch). */
|
||||
op_gather = rw(b, gather(nblk, bs * E), {}, { b_all });
|
||||
op_mem = rw(b, gemm(NM, W, E, w_mem), { b_all }, { b_mem });
|
||||
op_seg = rw(b, unary("seg_mean", NM, E), { b_all }, { b_seg });
|
||||
op_g_q = rw(b, gather(QM, E), { b_seg }, { b_qv });
|
||||
op_g_o = rw(b, gather(OM, E), { b_seg }, { b_oc });
|
||||
op_g_last = rw(b, gather(1, E), { b_all }, { b_g });
|
||||
op_lex = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, LM), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(w_lm_head)),
|
||||
{}, { b_lx });
|
||||
op_lexmean = rw(b, unary("seg_mean", LM, E), { b_lx }, { b_lex });
|
||||
op_octx = rw(b, gemm(OM, W, E, w_octx), { b_oc }, { b_x });
|
||||
op_olex = rw(b, gemm(OM, W, E, w_olex), { b_lex }, { b_t1 });
|
||||
op_add_x1 = rw(b, unary("add", OM, W), { b_x, b_t1 }, { b_x });
|
||||
op_oq = rw(b, gemm(QM, W, E, w_oq), { b_qv }, { b_qq });
|
||||
op_g_oq = rw(b, gather(OM, W), { b_qq }, { b_t1 });
|
||||
op_add_x2 = rw(b, unary("add", OM, W), { b_x, b_t1 }, { b_x });
|
||||
for (Ev& e : ev) {
|
||||
e.ln_q = rw(b, lnorm(OM, W, e.qn_w, e.qn_b), { b_x }, { b_t1 });
|
||||
e.ln_m = rw(b, lnorm(NM, W, e.mn_w, e.mn_b), { b_mem }, { b_mn });
|
||||
e.pq = rw(b, gemmb(OM, W, W, "none", e.wq, e.bq), { b_t1 }, { b_t2 });
|
||||
e.pk = rw(b, gemmb(NM, W, W, "none", e.wk, e.bk), { b_mn }, { b_k });
|
||||
e.pv = rw(b, gemmb(NM, W, W, "none", e.wv, e.bv), { b_mn }, { b_v });
|
||||
e.attn = rw(b, cross(OM), { b_t2, b_k, b_v }, { b_t1 });
|
||||
e.po = rw(b, gemmb(OM, W, W, "none", e.wo, e.bo), { b_t1, b_x }, { b_x });
|
||||
e.ln_f = rw(b, lnorm(OM, W, e.fn_w, e.fn_b), { b_x }, { b_t1 });
|
||||
e.f1 = rw(b, gemmb(OM, F, W, "gelu", e.w1, e.b1), { b_t1 }, { b_ff });
|
||||
e.f2 = rw(b, gemmb(OM, W, F, "none", e.w2, e.b2), { b_ff, b_x }, { b_x });
|
||||
}
|
||||
op_qproj = rw(b, gemm(QM, W, E, w_q), { b_qv }, { b_bf });
|
||||
op_g_fr = rw(b, gather(OM, W), { b_bf }, { b_fr });
|
||||
op_mul_sc = rw(b, unary("mul", OM, W), { b_x, b_fr }, { b_t1 });
|
||||
op_score = rw(b, rowmean(OM, W, (double)W / std::sqrt((double)W)), { b_t1 }, { b_sc });
|
||||
op_route = rw(b, unary("seg_softmax_pool", OM, W), { b_sc, b_x }, { b_sum });
|
||||
op_ln_osn = rw(b, lnorm(QM, W, osn_w, osn_b), { b_sum }, { b_f1 });
|
||||
op_add_f1 = rw(b, unary("add", QM, W), { b_bf, b_f1 }, { b_f });
|
||||
op_glob = rw(b, gemm(1, W, E, w_glob), { b_g }, { b_gw });
|
||||
op_add_fg = rw(b, unary("add", QM, W), { b_f, b_gw }, { b_f });
|
||||
op_type = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, QM), RAD_INT("n_embd", W),
|
||||
RAD_INT("n_vocab", 3), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", 0)),
|
||||
RAD_WEIGHTS(w_type)),
|
||||
{}, { b_f1 });
|
||||
op_add_f2 = rw(b, unary("add", QM, W), { b_f, b_f1 }, { b_f });
|
||||
for (Dec& d : dec) {
|
||||
d.ln1 = rw(b, lnorm(QM, W, d.n1w, d.n1b), { b_f }, { b_f1 });
|
||||
d.qkv = rw(b, gemmb(QM, 3 * W, W, "none", d.sa_w, d.sa_b), { b_f1 }, { b_fq });
|
||||
d.sattn = rw(b, RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, QM), RAD_INT("head_dim", HD),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)HD)),
|
||||
RAD_INT("max_seqlen", QM)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_fq }, { b_f1 });
|
||||
d.so = rw(b, gemmb(QM, W, W, "none", d.so_w, d.so_b), { b_f1, b_f }, { b_f });
|
||||
d.ln2 = rw(b, lnorm(QM, W, d.n2w, d.n2b), { b_f }, { b_f1 });
|
||||
d.pq = rw(b, gemmb(QM, W, W, "none", d.cq_w, d.cq_b), { b_f1 }, { b_f2 });
|
||||
d.pk = rw(b, gemmb(NM, W, W, "none", d.ck_w, d.ck_b), { b_mem }, { b_k });
|
||||
d.pv = rw(b, gemmb(NM, W, W, "none", d.cv_w, d.cv_b), { b_mem }, { b_v });
|
||||
d.cattn = rw(b, cross(QM), { b_f2, b_k, b_v }, { b_f1 });
|
||||
d.co = rw(b, gemmb(QM, W, W, "none", d.co_w, d.co_b), { b_f1, b_f }, { b_f });
|
||||
d.ln3 = rw(b, lnorm(QM, W, d.n3w, d.n3b), { b_f }, { b_f1 });
|
||||
d.f1 = rw(b, gemmb(QM, F, W, "gelu", d.w1, d.b1), { b_f1 }, { b_ff });
|
||||
d.f2 = rw(b, gemmb(QM, W, F, "none", d.w2, d.b2), { b_ff, b_f }, { b_f });
|
||||
}
|
||||
op_ln_fn = rw(b, lnorm(QM, W, fn_w, fn_b), { b_f }, { b_fn });
|
||||
/* The scorer, an option at a time against its question's field. */
|
||||
op_g_fr2 = rw(b, gather(OM, W), { b_fn }, { b_fr });
|
||||
op_ln_on = rw(b, lnorm(OM, W, on_w, on_b), { b_x }, { b_on });
|
||||
op_rms_a = rw(b, rmsp(OM, W), { b_fr }, { b_na });
|
||||
op_rms_b = rw(b, rmsp(OM, W), { b_on }, { b_nb });
|
||||
op_mul_cos = rw(b, unary("mul", OM, W), { b_na, b_nb }, { b_t1 });
|
||||
op_mean_cos = rw(b, rowmean(OM, W, 1.0), { b_t1 }, { b_out3 });
|
||||
op_g_an = rw(b, gather(OM, E), { b_qv }, { b_an });
|
||||
op_add_an = rw(b, unary("add", OM, E), { b_an, b_g }, { b_an });
|
||||
op_rms_an = rw(b, rmsp(OM, E), { b_an }, { b_p });
|
||||
op_rms_lex = rw(b, rmsp(OM, E), { b_lex }, { b_ln });
|
||||
op_mul_pri = rw(b, unary("mul", OM, E), { b_p, b_ln }, { b_an });
|
||||
op_mean_pri = rw(b, rowmean(OM, E, 1.0), { b_an }, { b_out3 });
|
||||
op_neg1 = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", W),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("value", -1.0)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { b_neg1 });
|
||||
op_nd = rw(b, unary("mul", OM, W), { b_on, b_neg1 }, { b_nd });
|
||||
op_d = rw(b, unary("add", OM, W), { b_fr, b_nd }, { b_d });
|
||||
op_relu_d = rw(b, unary("relu", OM, W), { b_d }, { b_abs });
|
||||
op_nd2 = rw(b, unary("mul", OM, W), { b_d, b_neg1 }, { b_nd });
|
||||
op_relu_nd = rw(b, unary("relu", OM, W), { b_nd }, { b_nd });
|
||||
op_abs = rw(b, unary("add", OM, W), { b_abs, b_nd }, { b_abs });
|
||||
op_prod = rw(b, unary("mul", OM, W), { b_fr, b_on }, { b_prod });
|
||||
/* The four feature blocks side by side in `feat`: the field rows are gathered straight into
|
||||
* the first, the other three copied in (cast at one dtype is the copy op), so the scorer's
|
||||
* first linear is one GEMM over 4 W, rounded once as the reference rounds it. */
|
||||
auto copy = [&]() {
|
||||
return RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, OM), RAD_INT("n", W), RAD_STR("from", "bf16"),
|
||||
RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
op_cp_fr = rw(b, copy(), { b_fr }, { b_feat });
|
||||
op_cp_on = rw(b, copy(), { b_on }, { b_feat });
|
||||
op_cp_prod = rw(b, copy(), { b_prod }, { b_feat });
|
||||
op_cp_abs = rw(b, copy(), { b_abs }, { b_feat });
|
||||
op_rs1 = rw(b, gemmb(OM, W, 4 * W, "gelu", rs1_w, rs1_b), { b_feat }, { b_r });
|
||||
op_rs2 = rw(b, gemmb(OM, 1, W, "none", rs2_w, rs2_b), { b_r }, { b_out3 });
|
||||
op_cast = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 3 * OM),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_out3 }, { b_logits });
|
||||
|
||||
rad_note(b, "clef's joint schema head on the card: width %lld, %lld heads of %lld, "
|
||||
"feedforward %lld, %lld routing + %lld decoder layers; hn cached as a FULL group "
|
||||
"of block %lld (%lld rows a context); at most %d questions, %d options, %d option "
|
||||
"tokens a request; three values an option into the logits row",
|
||||
(long long)W, (long long)H, (long long)HD, (long long)F, R, D, (long long)bs,
|
||||
(long long)NM, (int)QM, (int)OM, (int)LM);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void ClefHead::step_tokens(RadCtx* c, const RadBatch* batch, rad_buf b_h) {
|
||||
if (!on || batch->n_tok <= 0) return;
|
||||
const RadKVGroupBatch* kb = group_of(batch);
|
||||
if (!kb) { rad_step_fail(c, "clef: the head's cache group is not in the step batch"); return; }
|
||||
const int64_t T = batch->n_tok;
|
||||
RAD_ISSUE_N(c, op_hn, T, brows(b_h, T), RAD_W(hn_w), RAD_W(hn_b), brows(b_hn, T));
|
||||
RAD_ISSUE_N(c, op_store, T, bcol(b_hn, 0, E / 2, T), bcol(b_hn, E / 2, E / 2, T),
|
||||
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
|
||||
}
|
||||
|
||||
inline void ClefHead::step_heads(RadCtx* c, const RadBatch* batch, rad_buf b_logits,
|
||||
rad_weight w_lm_head) {
|
||||
if (!on || !batch->plugin_cu_h || !batch->plugin_words_h) return;
|
||||
const RadKVGroupBatch* kb = group_of(batch);
|
||||
if (!kb) { rad_step_fail(c, "clef: the head's cache group is not in the step batch"); return; }
|
||||
const int64_t QM = RAD_CLEF_MAX_QUESTIONS, OM = RAD_CLEF_MAX_OPTIONS, LM = RAD_CLEF_MAX_LEX;
|
||||
const int64_t SM = 2 * (QM + OM) + 1;
|
||||
for (int64_t s = 0; s < batch->n_seq; ++s) {
|
||||
const int32_t w0 = batch->plugin_cu_h[s], w1 = batch->plugin_cu_h[s + 1];
|
||||
if (w1 <= w0) continue;
|
||||
if (w1 - w0 < RAD_CLEF_HDR) { rad_step_fail(c, "clef: a request's words have no header"); return; }
|
||||
const int32_t* hw = batch->plugin_words_h + w0;
|
||||
const int32_t* dw = batch->plugin_words + w0;
|
||||
const RadClefWords L = rad_clef_words_read(hw);
|
||||
const int64_t N = L.n, Q = L.q, O = L.o, Lx = L.l, S = L.s;
|
||||
const int32_t row = hw[RAD_CLEF_W_ROW];
|
||||
const int64_t nb = (N + bs - 1) / bs;
|
||||
if (w1 - w0 < L.total || N < 1 || N > NM || Q < 1 || Q > QM || O < 1 || O > OM ||
|
||||
Lx < 1 || Lx > LM || S < 1 || S > SM || row < 0 || row >= batch->n_out ||
|
||||
nb > kb->max_blocks) {
|
||||
rad_step_fail(c, "clef: a request's words are out of the head's bounds");
|
||||
return;
|
||||
}
|
||||
auto dev = [&](int32_t off, int64_t n) { return praw(dw + off, RAD_I32, n); };
|
||||
auto out3 = [&](int64_t at, int64_t rows) { return bcol_at(b_out3, at, 1, 0, 1, rows); };
|
||||
const int32_t* bt = kb->block_table + s * kb->block_table_pitch;
|
||||
|
||||
/* Every row of hn, from the sequence's blocks. */
|
||||
RAD_ISSUE_N(c, op_gather, nb, kv_cache(kv, layer), praw(bt, RAD_I32, nb),
|
||||
brows(b_all, nb * bs));
|
||||
RAD_ISSUE_N(c, op_mem, N, brows(b_all, N), RAD_W(w_mem), brows(b_mem, N));
|
||||
/* The question, option and global vectors. */
|
||||
RAD_ISSUE_N(c, op_seg, N, brows(b_all, N), dev(L.seg_cu, S + 1), brows(b_seg, S));
|
||||
RAD_ISSUE_N(c, op_g_q, Q, brows(b_seg, S), dev(L.q_seg, Q), brows(b_qv, Q));
|
||||
RAD_ISSUE_N(c, op_g_o, O, brows(b_seg, S), dev(L.o_seg, O), brows(b_oc, O));
|
||||
RAD_ISSUE_N(c, op_g_last, 1, brows(b_all, N), dev(L.last, 1), brows(b_g, 1));
|
||||
RAD_ISSUE_N(c, op_lex, Lx, dev(L.lex_ids, Lx), RAD_W(w_lm_head), brows(b_lx, Lx));
|
||||
RAD_ISSUE_N(c, op_lexmean, Lx, brows(b_lx, Lx), dev(L.lex_cu, O + 1), brows(b_lex, O));
|
||||
/* Option queries, then the evidence layers over the memory. */
|
||||
RAD_ISSUE_N(c, op_octx, O, brows(b_oc, O), RAD_W(w_octx), brows(b_x, O));
|
||||
RAD_ISSUE_N(c, op_olex, O, brows(b_lex, O), RAD_W(w_olex), brows(b_t1, O));
|
||||
RAD_ISSUE_N(c, op_add_x1, O, brows(b_x, O), brows(b_t1, O), brows(b_x, O));
|
||||
RAD_ISSUE_N(c, op_oq, Q, brows(b_qv, Q), RAD_W(w_oq), brows(b_qq, Q));
|
||||
RAD_ISSUE_N(c, op_g_oq, O, brows(b_qq, Q), dev(L.o_q, O), brows(b_t1, O));
|
||||
RAD_ISSUE_N(c, op_add_x2, O, brows(b_x, O), brows(b_t1, O), brows(b_x, O));
|
||||
for (const Ev& e : ev) {
|
||||
RAD_ISSUE_N(c, e.ln_q, O, brows(b_x, O), RAD_W(e.qn_w), RAD_W(e.qn_b), brows(b_t1, O));
|
||||
RAD_ISSUE_N(c, e.ln_m, N, brows(b_mem, N), RAD_W(e.mn_w), RAD_W(e.mn_b), brows(b_mn, N));
|
||||
RAD_ISSUE_N(c, e.pq, O, brows(b_t1, O), RAD_W(e.wq), RAD_W(e.bq), RAD_NONE, brows(b_t2, O));
|
||||
RAD_ISSUE_N(c, e.pk, N, brows(b_mn, N), RAD_W(e.wk), RAD_W(e.bk), RAD_NONE, brows(b_k, N));
|
||||
RAD_ISSUE_N(c, e.pv, N, brows(b_mn, N), RAD_W(e.wv), RAD_W(e.bv), RAD_NONE, brows(b_v, N));
|
||||
RAD_ISSUE_N(c, e.attn, O, brows(b_t2, O), brows(b_k, N), brows(b_v, N),
|
||||
dev(L.cu_o, 2), dev(L.cu_k, 2), brows(b_t1, O));
|
||||
RAD_ISSUE_N(c, e.po, O, brows(b_t1, O), RAD_W(e.wo), RAD_W(e.bo), brows(b_x, O), brows(b_x, O));
|
||||
RAD_ISSUE_N(c, e.ln_f, O, brows(b_x, O), RAD_W(e.fn_w), RAD_W(e.fn_b), brows(b_t1, O));
|
||||
RAD_ISSUE_N(c, e.f1, O, brows(b_t1, O), RAD_W(e.w1), RAD_W(e.b1), RAD_NONE, brows(b_ff, O));
|
||||
RAD_ISSUE_N(c, e.f2, O, brows(b_ff, O), RAD_W(e.w2), RAD_W(e.b2), brows(b_x, O), brows(b_x, O));
|
||||
}
|
||||
/* Base fields, each question's routing over its options, and the field vectors. */
|
||||
RAD_ISSUE_N(c, op_qproj, Q, brows(b_qv, Q), RAD_W(w_q), brows(b_bf, Q));
|
||||
RAD_ISSUE_N(c, op_g_fr, O, brows(b_bf, Q), dev(L.o_q, O), brows(b_fr, O));
|
||||
RAD_ISSUE_N(c, op_mul_sc, O, brows(b_x, O), brows(b_fr, O), brows(b_t1, O));
|
||||
RAD_ISSUE_N(c, op_score, O, brows(b_t1, O), brows(b_sc, O));
|
||||
RAD_ISSUE_N(c, op_route, O, brows(b_sc, O), brows(b_x, O), dev(L.opt_cu, Q + 1), brows(b_sum, Q));
|
||||
RAD_ISSUE_N(c, op_ln_osn, Q, brows(b_sum, Q), RAD_W(osn_w), RAD_W(osn_b), brows(b_f1, Q));
|
||||
RAD_ISSUE_N(c, op_add_f1, Q, brows(b_bf, Q), brows(b_f1, Q), brows(b_f, Q));
|
||||
RAD_ISSUE_N(c, op_glob, 1, brows(b_g, 1), RAD_W(w_glob), brows(b_gw, 1));
|
||||
RAD_ISSUE_N(c, op_add_fg, Q, brows(b_f, Q), brows(b_gw, 1), brows(b_f, Q));
|
||||
RAD_ISSUE_N(c, op_type, Q, dev(L.type, Q), RAD_W(w_type), brows(b_f1, Q));
|
||||
RAD_ISSUE_N(c, op_add_f2, Q, brows(b_f, Q), brows(b_f1, Q), brows(b_f, Q));
|
||||
for (const Dec& d : dec) {
|
||||
RAD_ISSUE_N(c, d.ln1, Q, brows(b_f, Q), RAD_W(d.n1w), RAD_W(d.n1b), brows(b_f1, Q));
|
||||
RAD_ISSUE_N(c, d.qkv, Q, brows(b_f1, Q), RAD_W(d.sa_w), RAD_W(d.sa_b), RAD_NONE, brows(b_fq, Q));
|
||||
RAD_ISSUE_N(c, d.sattn, Q, bcol(b_fq, 0, W, Q), bcol(b_fq, W, W, Q),
|
||||
bcol(b_fq, 2 * W, W, Q), dev(L.cu_q, 2), brows(b_f1, Q));
|
||||
RAD_ISSUE_N(c, d.so, Q, brows(b_f1, Q), RAD_W(d.so_w), RAD_W(d.so_b), brows(b_f, Q), brows(b_f, Q));
|
||||
RAD_ISSUE_N(c, d.ln2, Q, brows(b_f, Q), RAD_W(d.n2w), RAD_W(d.n2b), brows(b_f1, Q));
|
||||
RAD_ISSUE_N(c, d.pq, Q, brows(b_f1, Q), RAD_W(d.cq_w), RAD_W(d.cq_b), RAD_NONE, brows(b_f2, Q));
|
||||
RAD_ISSUE_N(c, d.pk, N, brows(b_mem, N), RAD_W(d.ck_w), RAD_W(d.ck_b), RAD_NONE, brows(b_k, N));
|
||||
RAD_ISSUE_N(c, d.pv, N, brows(b_mem, N), RAD_W(d.cv_w), RAD_W(d.cv_b), RAD_NONE, brows(b_v, N));
|
||||
RAD_ISSUE_N(c, d.cattn, Q, brows(b_f2, Q), brows(b_k, N), brows(b_v, N),
|
||||
dev(L.cu_q, 2), dev(L.cu_k, 2), brows(b_f1, Q));
|
||||
RAD_ISSUE_N(c, d.co, Q, brows(b_f1, Q), RAD_W(d.co_w), RAD_W(d.co_b), brows(b_f, Q), brows(b_f, Q));
|
||||
RAD_ISSUE_N(c, d.ln3, Q, brows(b_f, Q), RAD_W(d.n3w), RAD_W(d.n3b), brows(b_f1, Q));
|
||||
RAD_ISSUE_N(c, d.f1, Q, brows(b_f1, Q), RAD_W(d.w1), RAD_W(d.b1), RAD_NONE, brows(b_ff, Q));
|
||||
RAD_ISSUE_N(c, d.f2, Q, brows(b_ff, Q), RAD_W(d.w2), RAD_W(d.b2), brows(b_f, Q), brows(b_f, Q));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_ln_fn, Q, brows(b_f, Q), RAD_W(fn_w), RAD_W(fn_b), brows(b_fn, Q));
|
||||
/* The scorer: the cosine, the lexical prior and the residual, one value an option, into
|
||||
* out3's three stretches (prior | cosine | residual). */
|
||||
RAD_ISSUE_N(c, op_g_fr2, O, brows(b_fn, Q), dev(L.o_q, O), brows(b_fr, O));
|
||||
RAD_ISSUE_N(c, op_ln_on, O, brows(b_x, O), RAD_W(on_w), RAD_W(on_b), brows(b_on, O));
|
||||
RAD_ISSUE_N(c, op_rms_a, O, brows(b_fr, O), brows(b_na, O));
|
||||
RAD_ISSUE_N(c, op_rms_b, O, brows(b_on, O), brows(b_nb, O));
|
||||
RAD_ISSUE_N(c, op_mul_cos, O, brows(b_na, O), brows(b_nb, O), brows(b_t1, O));
|
||||
RAD_ISSUE_N(c, op_mean_cos, O, brows(b_t1, O), out3(OM, O));
|
||||
RAD_ISSUE_N(c, op_g_an, O, brows(b_qv, Q), dev(L.o_q, O), brows(b_an, O));
|
||||
RAD_ISSUE_N(c, op_add_an, O, brows(b_an, O), brows(b_g, 1), brows(b_an, O));
|
||||
RAD_ISSUE_N(c, op_rms_an, O, brows(b_an, O), brows(b_p, O));
|
||||
RAD_ISSUE_N(c, op_rms_lex, O, brows(b_lex, O), brows(b_ln, O));
|
||||
RAD_ISSUE_N(c, op_mul_pri, O, brows(b_p, O), brows(b_ln, O), brows(b_an, O));
|
||||
RAD_ISSUE_N(c, op_mean_pri, O, brows(b_an, O), out3(0, O));
|
||||
RAD_ISSUE_N(c, op_neg1, 1, brows(b_neg1, 1));
|
||||
RAD_ISSUE_N(c, op_nd, O, brows(b_on, O), brows(b_neg1, 1), brows(b_nd, O));
|
||||
RAD_ISSUE_N(c, op_d, O, brows(b_fr, O), brows(b_nd, O), brows(b_d, O));
|
||||
RAD_ISSUE_N(c, op_relu_d, O, brows(b_d, O), brows(b_abs, O));
|
||||
RAD_ISSUE_N(c, op_nd2, O, brows(b_d, O), brows(b_neg1, 1), brows(b_nd, O));
|
||||
RAD_ISSUE_N(c, op_relu_nd, O, brows(b_nd, O), brows(b_nd, O));
|
||||
RAD_ISSUE_N(c, op_abs, O, brows(b_abs, O), brows(b_nd, O), brows(b_abs, O));
|
||||
RAD_ISSUE_N(c, op_prod, O, brows(b_fr, O), brows(b_on, O), brows(b_prod, O));
|
||||
/* [field | option | field*option | |field-option|], then the scorer. The field rows go
|
||||
* in again (a copy into the first block) so every block arrives the same way. */
|
||||
RAD_ISSUE_N(c, op_cp_fr, O, brows(b_fr, O), bcol(b_feat, 0, W, O));
|
||||
RAD_ISSUE_N(c, op_cp_on, O, brows(b_on, O), bcol(b_feat, W, W, O));
|
||||
RAD_ISSUE_N(c, op_cp_prod, O, brows(b_prod, O), bcol(b_feat, 2 * W, W, O));
|
||||
RAD_ISSUE_N(c, op_cp_abs, O, brows(b_abs, O), bcol(b_feat, 3 * W, W, O));
|
||||
RAD_ISSUE_N(c, op_rs1, O, brows(b_feat, O), RAD_W(rs1_w), RAD_W(rs1_b), RAD_NONE, brows(b_r, O));
|
||||
RAD_ISSUE_N(c, op_rs2, O, brows(b_r, O), RAD_W(rs2_w), RAD_W(rs2_b), RAD_NONE, out3(2 * OM, O));
|
||||
/* The three stretches, as f32, into the request's logits row (one row of 3 OM). */
|
||||
RAD_ISSUE_N(c, op_cast, 1, brows(b_out3, 3 * OM),
|
||||
bcol_at(b_logits, row, n_vocab, 0, 3 * OM, 1));
|
||||
}
|
||||
}
|
||||
|
||||
/* The zero logits rows a trunk leaves when it skips its lm_head for rows a decision head answers
|
||||
* (the qwen35 plugins' `op_logits_fill`): declared here, by the plugin that wants the skip, so a
|
||||
* trunk serving a plain container declares the same graph as before. */
|
||||
inline rad_op clef_logits_fill(RadBuilder* b, Names& nm, const Geom& g, rad_buf b_logits) {
|
||||
return rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_vocab),
|
||||
RAD_STR("dtype", "f32"), RAD_F64("value", 0.0)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { b_logits });
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
@@ -98,6 +98,7 @@
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_spechub.h" /* RAD_MTP_COUPLE_*: the coupling wire (--draft-coupling) */
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
@@ -122,6 +123,16 @@ struct Dflash2 {
|
||||
int64_t group = 16;
|
||||
int64_t sel_rank = 256; /* the codebooks' width */
|
||||
int64_t sel_topk = 16; /* candidates kept per position */
|
||||
/* Propose a tree of `steps()` nodes instead of the selector's one path (`dflash_tree`,
|
||||
* rad_drafter_tree): best-first over the candidate lattice by path probability, each
|
||||
* edge's probability the softmax of its scores over the K candidates divided by
|
||||
* `tree_temp`. False: the greedy walk. */
|
||||
bool tree = false;
|
||||
double tree_temp = 1.0;
|
||||
/* A tree's draft nodes a step, 0 for `steps()`. More than the block drafts is a wider tree
|
||||
* over the same lattice (its depth is still at most `steps()`); the proposal buffers, the
|
||||
* drafter's declared depth and the verify are this wide. */
|
||||
int64_t tree_nodes = 0;
|
||||
int64_t window = 0; /* sliding attention width, 0 for none */
|
||||
int causal = 0;
|
||||
/* The target's embedding scale, applied to the query block as the drafter was trained
|
||||
@@ -130,7 +141,19 @@ struct Dflash2 {
|
||||
/* Bytes of the next GEMM's weight read into the cache beside each all-reduce of the query
|
||||
* pass (prefetch_beside, rad_arch.h); 0 reads none. */
|
||||
int64_t prefetch = 0;
|
||||
|
||||
/* Also declare the short block's query pass (kShortBlock rows, or `short_rows`) for
|
||||
* --draft-short-from; an architecture that does not call rad_drafter_short_block leaves
|
||||
* it off and its graph as it was. A tree's selector at that block grows a tree of its own
|
||||
* over the shorter pass, `short_rows - 1` nodes or fewer. */
|
||||
int short_block = 0;
|
||||
/* --draft-coupling: the temperature of the draft law Q the coupled walk samples from
|
||||
* (dflash_couple_propose's `q_temp`). Any value keeps the output exact; it only moves
|
||||
* acceptance, sum min(P, Q). */
|
||||
double q_temp = 1.0;
|
||||
int64_t short_rows = 0;
|
||||
int64_t steps() const { return block - 1; }
|
||||
int64_t nodes() const { return tree && tree_nodes > 0 ? tree_nodes : steps(); }
|
||||
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
|
||||
/* The kernel projection emits [2, taps, NG] per token (prepare's set, then finish's);
|
||||
* `dflash_conv` reads a slice of it at the full row pitch. */
|
||||
@@ -185,6 +208,11 @@ struct Dflash2 {
|
||||
rad_buf dpair = 0; /* [srows, sel_topk, 2] f32 */
|
||||
rad_buf dgath = 0; /* [srows, world * sel_topk, 2] f32 */
|
||||
rad_buf tokens = 0; /* [max_seqs, steps] i32 the draft; the engine reads it by name */
|
||||
/* --draft-coupling: [max_seqs, DRAW_WORDS] draws the engine stages, and [steps, max_seqs,
|
||||
* STATE_WORDS] states it reads back (abi/rad_spechub.h). Both or neither. */
|
||||
rad_buf couple_draws = 0, couple_state = 0;
|
||||
/* [max_seqs, steps] i32 a tree's parents (Config::tree, rad_drafter_tree); 0 otherwise */
|
||||
rad_buf parents = 0;
|
||||
};
|
||||
|
||||
/* Whether the 2-bit draft head is vocab-sharded (rad_arch.h: vocab_head_sharded), so whoever
|
||||
@@ -260,6 +288,11 @@ struct Dflash2 {
|
||||
rad_op op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
|
||||
rad_op op_gug[MAX_LAYERS] = {}; /* the gate_up|silu|quant fold; 0 when nothing serves it */
|
||||
rad_op op_aconv[MAX_LAYERS] = {}, op_fconv[MAX_LAYERS] = {};
|
||||
/* The short block's (block_lo rows a sequence): the convolutions mask at the block's first row
|
||||
* and the selector strides by it, so each has an op of its own; every other op is per row. */
|
||||
rad_op op_aconv_lo[MAX_LAYERS] = {}, op_fconv_lo[MAX_LAYERS] = {}, op_sel_lo = 0;
|
||||
int64_t block_lo = 0;
|
||||
int64_t sel_lo_nodes = 0; /* a tree's nodes at the short block (op_sel_lo) */
|
||||
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
|
||||
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
|
||||
/* The residual add folded into the norm after it (add_rmsnorm), issued in place of op_add and
|
||||
@@ -287,6 +320,12 @@ struct Dflash2 {
|
||||
static constexpr int64_t kRerankR = 32;
|
||||
int64_t top_w = 0; /* the coarse top-K's width: kRerankR or sel_topk */
|
||||
rad_op op_hp = 0, op_sel = 0;
|
||||
/* --draft-coupling: the sampled walk after the greedy one (dflash_couple_propose), for the
|
||||
* drafter's block and its short one. 0 when the coupling is off. */
|
||||
rad_op op_couple = 0, op_couple_lo = 0;
|
||||
/* The short block: kShortBlock rows (depth 3, the window that pays at many sequences), when
|
||||
* the drafter's own block is longer (rad_drafter_short_block). */
|
||||
static constexpr int64_t kShortBlock = 4;
|
||||
|
||||
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,
|
||||
@@ -695,7 +734,29 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* layers. Planned from those alone, its range would end before the coefficients' begins and
|
||||
* the plan could lay one over the other. Read by the last convolution as well, it is live
|
||||
* wherever the coefficients are. */
|
||||
{
|
||||
const int64_t rows = cfg.short_rows > 0 ? cfg.short_rows : kShortBlock;
|
||||
block_lo = cfg.short_block && rows >= 2 && cfg.block > rows ? rows : 0;
|
||||
}
|
||||
for (int64_t l = 0; block_lo && l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_aconv_lo[i] = rw(b, RAD_OP(b, "dflash_conv",
|
||||
RAD_PARAMS(RAD_RANGE("T", 1, qrows), RAD_INT("hidden_size", g.n_embd),
|
||||
RAD_INT("taps", cfg.taps), RAD_INT("group_size", cfg.group),
|
||||
RAD_INT("NG", NG), RAD_INT("block_size", block_lo),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_acb[i])),
|
||||
{w.h, w.coef}, {w.h2});
|
||||
op_fconv_lo[i] = rw(b, RAD_OP(b, "dflash_conv",
|
||||
RAD_PARAMS(RAD_RANGE("T", 1, qrows), RAD_INT("hidden_size", g.n_embd),
|
||||
RAD_INT("taps", cfg.taps), RAD_INT("group_size", cfg.group),
|
||||
RAD_INT("NG", NG), RAD_INT("block_size", block_lo),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_fcb[i])),
|
||||
{w.h, w.coef}, {w.h2});
|
||||
}
|
||||
if (rad_op_reads(b, op_fconv[g.n_layer - 1], &w.attn, 1) < 0) return RAD_E_INVAL;
|
||||
if (block_lo && rad_op_reads(b, op_fconv_lo[g.n_layer - 1], &w.attn, 1) < 0) return RAD_E_INVAL;
|
||||
op_qrope = rope(qrows, g.n_head, w.q);
|
||||
op_krope = rope(qrows, g.n_head_kv, w.k);
|
||||
op_store = rw(b, RAD_OP(b, "kv_store",
|
||||
@@ -901,14 +962,101 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_WEIGHTS(w_selp)),
|
||||
{w.sel_h}, {w.hp});
|
||||
/* `anchor_stride` is `block`: the operand is the step's token_ids, `block` per sequence with
|
||||
* the anchor first. */
|
||||
op_sel = rw(b, RAD_OP(b, "dflash_select",
|
||||
* the anchor first.
|
||||
*
|
||||
* A tree (Config::tree): `dflash_tree` grows `steps` nodes best-first over the same lattice
|
||||
* and the same edge scores, writing each node's parent beside its token. Where no library
|
||||
* serves it the block falls back to the chain and says so; the caller reads `cfg.tree` after
|
||||
* declare to decide whether to tell the core (rad_drafter_tree). --draft-coupling samples one
|
||||
* path per sequence, so a coupled drafter proposes the chain. */
|
||||
if (cfg.tree && (w.couple_draws || w.couple_state)) {
|
||||
rad_note(b, "DFlash2: --draft-coupling samples a chain; the drafter proposes no tree");
|
||||
cfg.tree = false;
|
||||
}
|
||||
if (cfg.tree) {
|
||||
op_sel = RAD_OP(b, "dflash_tree",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", cfg.block),
|
||||
RAD_INT("nodes", cfg.nodes()), RAD_F64("temp", cfg.tree_temp),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_pred, w_succ));
|
||||
if (op_sel && rad_op_resolved(b, op_sel)) {
|
||||
rw(b, op_sel, {w.cand, w.unary, w.hp}, {w.tokens, w.parents});
|
||||
} else {
|
||||
rad_note(b, "DFlash2: no library serves dflash_tree here; the drafter proposes its "
|
||||
"selector's chain");
|
||||
cfg.tree = false;
|
||||
op_sel = 0;
|
||||
}
|
||||
}
|
||||
if (!cfg.tree) op_sel = rw(b, RAD_OP(b, "dflash_select",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", cfg.block), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_pred, w_succ)),
|
||||
{w.cand, w.unary, w.hp}, {w.tokens});
|
||||
if (block_lo && cfg.tree) {
|
||||
/* A tree over the short block's own lattice (the pass attends across its block, so it is
|
||||
* not the full pass's prefix): as many nodes as the block drafts, or the tree's own count
|
||||
* where that is fewer. */
|
||||
sel_lo_nodes = std::min<int64_t>(cfg.nodes(), block_lo - 1);
|
||||
op_sel_lo = RAD_OP(b, "dflash_tree",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", block_lo - 1),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", block_lo),
|
||||
RAD_INT("nodes", sel_lo_nodes), RAD_F64("temp", cfg.tree_temp),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_pred, w_succ));
|
||||
if (op_sel_lo && rad_op_resolved(b, op_sel_lo)) {
|
||||
rw(b, op_sel_lo, {w.cand, w.unary, w.hp}, {w.tokens, w.parents});
|
||||
} else {
|
||||
rad_note(b, "DFlash2: no library serves dflash_tree at the short block; the tree keeps "
|
||||
"its own block under load");
|
||||
op_sel_lo = 0;
|
||||
block_lo = 0;
|
||||
sel_lo_nodes = 0;
|
||||
}
|
||||
} else if (block_lo)
|
||||
op_sel_lo = rw(b, RAD_OP(b, "dflash_select",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", block_lo - 1),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", block_lo), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_pred, w_succ)),
|
||||
{w.cand, w.unary, w.hp}, {w.tokens});
|
||||
|
||||
/* --draft-coupling: the walk again, sampled (abi/rad_spechub.h, rad_dflash_couple_step), over
|
||||
* the same lattice right after the greedy walk. A greedy request's row keeps the selector's
|
||||
* tokens; a sampled one gets x ~ Q at every position and the Q it was drawn from, which the
|
||||
* engine reads back and binds to the verify. The tokens stay global ids, so the engine's take
|
||||
* (ADV_BTAKE) is unchanged. */
|
||||
if (w.couple_draws || w.couple_state) {
|
||||
if (!w.couple_draws || !w.couple_state || cfg.steps() > RAD_MTP_COUPLE_MAX_ROUNDS ||
|
||||
cfg.sel_topk > RAD_DFLASH_COUPLE_MAX_K)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
auto couple = [&](int64_t steps, int64_t stride) {
|
||||
return rw(b, RAD_OP(b, "dflash_couple_propose",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", steps),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", stride),
|
||||
RAD_INT("max_rounds", cfg.steps()),
|
||||
RAD_F64("q_temp", cfg.q_temp)),
|
||||
RAD_WEIGHTS(w_pred, w_succ)),
|
||||
{w.cand, w.unary, w.hp, w.couple_draws, w.tokens},
|
||||
{w.tokens, w.couple_state});
|
||||
};
|
||||
op_couple = couple(cfg.steps(), cfg.block);
|
||||
if (!op_couple) return RAD_E_INVAL;
|
||||
if (block_lo) {
|
||||
op_couple_lo = couple(block_lo - 1, block_lo);
|
||||
if (!op_couple_lo) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
/* The reads beside the all-reduces, after every weight they read is declared. */
|
||||
if (op_ar && cfg.prefetch > 0)
|
||||
@@ -983,6 +1131,17 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t NG = cfg.ng(g.n_embd);
|
||||
const int64_t half = cfg.taps * NG; /* prepare's coefficients, then finish's */
|
||||
|
||||
/* The block this pass was staged at: every drafting sequence carries the same number of rows,
|
||||
* the drafter's own block or its short one (rad_drafter_short_block). */
|
||||
const int64_t blk = batch->n_seq > 0 && T % batch->n_seq == 0 ? T / batch->n_seq : 0;
|
||||
const bool lo = block_lo > 0 && blk == block_lo;
|
||||
if (!lo && blk != cfg.block) {
|
||||
rad_step_fail(c, "dflash2: a query pass staged at a block this drafter has no ops for");
|
||||
return;
|
||||
}
|
||||
const rad_op* aconv = lo ? op_aconv_lo : op_aconv;
|
||||
const rad_op* fconv = lo ? op_fconv_lo : op_fconv;
|
||||
|
||||
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T));
|
||||
if (op_embed_ar)
|
||||
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE);
|
||||
@@ -1005,7 +1164,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
/* ---- attention, wrapped in the two halves of one convolution */
|
||||
norm(op_anorm[i], op_aan[i], w_anorm[i]);
|
||||
RAD_ISSUE_N(c, op_acoef[i], T, brows(w.h, T), RAD_W(w_acp[i]), brows(w.coef, T));
|
||||
RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
|
||||
RAD_ISSUE_N(c, aconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
|
||||
wrow_slice(w_acb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
|
||||
RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T));
|
||||
@@ -1044,14 +1203,14 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
* replicated norm, so either order gives the same result; reducing first keeps x's
|
||||
* update agreed across ranks. */
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
RAD_ISSUE_N(c, aconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
wrow_slice(w_acb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
add_pending = true;
|
||||
|
||||
/* ---- the feed-forward, wrapped in the other convolution */
|
||||
norm(op_fnorm[i], op_afn[i], w_fnorm[i]);
|
||||
RAD_ISSUE_N(c, op_fcoef[i], T, brows(w.h, T), RAD_W(w_fcp[i]), brows(w.coef, T));
|
||||
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
|
||||
RAD_ISSUE_N(c, fconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
|
||||
wrow_slice(w_fcb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T));
|
||||
if (op_gug[i] && T <= gated_rows) {
|
||||
@@ -1068,7 +1227,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
|
||||
for (int j = 0; j < 2; ++j) prefetch_beside(c, op_pff[i][j], pff_w[i][j], T);
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
RAD_ISSUE_N(c, fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
wrow_slice(w_fcb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
add_pending = true;
|
||||
}
|
||||
@@ -1107,10 +1266,26 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
}
|
||||
|
||||
RAD_ISSUE_N(c, op_hp, S, brows(w.sel_h, S), RAD_W(w_selp), brows(w.hp, S));
|
||||
RAD_ISSUE_N(c, op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
|
||||
/* A tree's outputs as views exactly its nodes wide, at the buffers' row pitch: at the short
|
||||
* block it grows fewer nodes than a row holds, and the proposals are read at the full pitch. */
|
||||
const int64_t nn = lo ? sel_lo_nodes : cfg.nodes();
|
||||
if (cfg.tree)
|
||||
RAD_ISSUE_N(c, lo ? op_sel_lo : op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
|
||||
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
|
||||
bcol(w.tokens, 0, nn, batch->n_seq), bcol(w.parents, 0, nn, batch->n_seq));
|
||||
else
|
||||
RAD_ISSUE_N(c, lo ? op_sel_lo : op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
|
||||
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
|
||||
brows(w.tokens, batch->n_seq));
|
||||
if (op_couple)
|
||||
RAD_ISSUE_N(c, lo ? op_couple_lo : op_couple, batch->n_seq,
|
||||
bcol(w.cand, 0, cfg.sel_topk, S), bcol(w.unary, 0, cfg.sel_topk, S),
|
||||
brows(w.hp, S), praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred),
|
||||
RAD_W(w_succ), praw(batch->seq_ids, RAD_I32, batch->n_seq),
|
||||
brows(w.couple_draws, batch->n_seq), brows(w.tokens, batch->n_seq),
|
||||
RAD_B(w.couple_state));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
|
||||
@@ -109,6 +109,11 @@ struct GdnFP8 {
|
||||
rad_weight w_norm = 0, w_ab = 0, w_conv = 0;
|
||||
/* The input was normed and quantised by the caller; this block declares no norm. */
|
||||
bool ext_in = false;
|
||||
/* Set by the architecture before declare: the a|b projection runs on the second lane beside the
|
||||
* in-projection at decode and verify sizes. Not where lane 1 carries collectives, which the
|
||||
* projection would queue behind. Its concurrent buffers cost memory (at Qwen3.8-27B TP2: +70
|
||||
* MiB arena and +33 MiB queues a card) for about +1 % at one stream. */
|
||||
bool ab_lane = false;
|
||||
rad_weight w_a_log = 0, w_dt_bias = 0, w_out_norm = 0;
|
||||
LinearFP8 in{}, out{};
|
||||
NormQuantFP8 nq_h{};
|
||||
@@ -122,6 +127,11 @@ struct GdnFP8 {
|
||||
* the widest decode window the fold serves. */
|
||||
rad_op op_cr = 0;
|
||||
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. */
|
||||
rad_op op_pf_out = 0;
|
||||
int64_t pf_out_rows = 0, pf_out_seqs = 0;
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
/* The next block absorbs this block's closing all-reduce (see rad_block_attn_gated_fp8.h). */
|
||||
bool ar_out = false;
|
||||
@@ -139,6 +149,13 @@ struct GdnFP8 {
|
||||
* trailing add, which would read the delta before the reduction. */
|
||||
void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
|
||||
ArPieces* pieces = nullptr) const;
|
||||
/* Whether step() with `own_ar` false runs the whole block a piece at a time over `pieces`
|
||||
* (its piece path), asked by a caller that must know before it commits to a schedule. */
|
||||
bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const {
|
||||
return pieces && pieces->cu && pieces->cuts(batch->n_tok) &&
|
||||
batch->n_tok <= 2 * pieces->rows && (ext_in || pieces->in_ready) && !op_add &&
|
||||
batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL;
|
||||
}
|
||||
/* Whether a step of T rows issues the all-reduce itself, asked by a caller before taking it
|
||||
* over; and that all-reduce over rows [r0, r0 + rows) of the output. */
|
||||
bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
|
||||
@@ -264,6 +281,10 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", ab_dim),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_ab)), {w.h.x}, {w.ab});
|
||||
if (ab_lane) {
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, w.h.x));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, w.ab));
|
||||
}
|
||||
|
||||
/* ---- the chunked path. As in the bf16 block, except `a` and `b_gate` are views of `ab`. */
|
||||
op_conv_prep = rw(b, RAD_OP(b, "gdn_conv_prep",
|
||||
@@ -389,10 +410,10 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
* piece the chunk a span of 1 makes (the projection over its rows; the convolution, solve and
|
||||
* scan over its bounds, with the state handed on through the cache; the gated norm, quantiser
|
||||
* and out projection), so the first piece's reduction runs beside all of the second piece's
|
||||
* work. The second piece reads the history the first left in the convolution slot: a spanned
|
||||
* step is past the prompt's first interval, so its context length is never zero. */
|
||||
if (!own_ar && pieces && pieces->cu && pieces->cuts(T) && T <= 2 * pieces->rows && ext_in &&
|
||||
!op_add && S == 1 && batch->phase == RAD_PHASE_PREFILL) {
|
||||
* work. The second piece reads the history the first left in the convolution slot, so each
|
||||
* piece passes its own context length, its first row's position: the step's would tell the
|
||||
* second piece of a prompt's first chunk that it has none. */
|
||||
if (!own_ar && takes_pieces(batch, pieces)) {
|
||||
const int64_t in_w = conv_dim + v_dim;
|
||||
for (int64_t p = 0; p < 2; ++p) {
|
||||
const int64_t r0 = p * pieces->rows;
|
||||
@@ -405,7 +426,7 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
bcol(w.in.x, 0, conv_dim, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log),
|
||||
RAD_W(w_dt_bias), kv_cache(kv_conv, layer), praw(cu, RAD_I32, 2),
|
||||
bcol(w.ab, 0, H, T), bcol(w.ab, H, H, T),
|
||||
praw(cv_idx, RAD_I32, 1), praw(batch->ctx_lens, RAD_I32, 1),
|
||||
praw(cv_idx, RAD_I32, 1), praw(batch->positions + r0, RAD_I32, 1),
|
||||
brows(w.q, T), brows(w.k, T), brows(w.v, T),
|
||||
brows(w.gdec, T), brows(w.beta, T));
|
||||
RAD_ISSUE_N(c, op_kkt, n,
|
||||
@@ -429,8 +450,19 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
}
|
||||
|
||||
if (!ext_in) nq_h.step(c, T);
|
||||
/* 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) {
|
||||
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);
|
||||
rad_lane_join(c, 1, 0);
|
||||
} else {
|
||||
in.step(c, w.h, w.in.x, T);
|
||||
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
|
||||
}
|
||||
|
||||
/* Each path runs over its own run of sequences. The step is sorted decode-first: decode rows
|
||||
* are sequences [0, D) with tokens [0, DT), prefill chunks are [D, S) with the rest. A pure
|
||||
@@ -454,6 +486,14 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
const int64_t PT = T - DT;
|
||||
const int64_t in_w = conv_dim + v_dim; /* w.in.x's declared row width */
|
||||
|
||||
/* 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). */
|
||||
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)
|
||||
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,
|
||||
bcol(w.in.x, 0, conv_dim, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer),
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
/* rad_block_gemma4_audio.h -- Gemma 4's audio encoder (USM conformer), shared by the plugins whose
|
||||
* checkpoints carry it: EmbeddingGemma 2 (embgemma2) and Gemma 4 E2B/E4B (gemma4_bf16).
|
||||
*
|
||||
* a frame is 128 log-mel bins (the processor's), four frames an output row
|
||||
* subsampling: two 3x3 stride-2 convolutions over (time, frequency) -- 1 -> 128 -> 32 channels,
|
||||
* each input masked to the clip's real frames first, each followed by a channel LayerNorm (no
|
||||
* bias) and a ReLU -- then 32 x 32 features a row through a 1024 linear
|
||||
* 12 conformer blocks: a feed-forward at half weight, local attention (11 frames back, a
|
||||
* relative-position term, a softplus per-dimension query scale, a softcap of 50), a gated
|
||||
* depthwise causal convolution, a second half-weight feed-forward, a norm; their linears are
|
||||
* clipped: input and output clamped to bounds the checkpoint stores
|
||||
* 1024 -> 1536 with a bias, then the multimodal embedder: an RMS norm with no gain, 1536 -> the
|
||||
* text model's width.
|
||||
*
|
||||
* The blocks' clamps at +-1e10 ("gradient clipping") are omitted: they are ten orders of magnitude
|
||||
* beyond the activations' range and change nothing. One clip is one segment; a pass carries up to
|
||||
* RadBuildCtx::max_audio_frames frames. */
|
||||
#ifndef RAD_BLOCK_GEMMA4_AUDIO_H
|
||||
#define RAD_BLOCK_GEMMA4_AUDIO_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct Gemma4Audio {
|
||||
/* A clipped linear: the weight and its four bounds. */
|
||||
struct Clip {
|
||||
rad_weight w = 0, in_lo = 0, in_hi = 0, out_lo = 0, out_hi = 0;
|
||||
rad_op op_in = 0, op_mm = 0, op_out = 0;
|
||||
};
|
||||
struct FF {
|
||||
rad_weight pre = 0, post = 0;
|
||||
Clip l1, l2;
|
||||
rad_op op_pre = 0, op_act = 0, op_post = 0, op_add = 0;
|
||||
};
|
||||
struct Layer {
|
||||
FF ff1, ff2;
|
||||
rad_weight n_pre_attn = 0, n_post_attn = 0, n_out = 0, w_rel = 0, pds = 0;
|
||||
Clip q, k, v, post;
|
||||
rad_weight lc_pre = 0, lc_dw = 0, lc_norm = 0;
|
||||
Clip lc_start, lc_end;
|
||||
rad_op op_npa = 0, op_rel = 0, op_attn = 0, op_npo = 0, op_add_attn = 0;
|
||||
rad_op op_lc_pre = 0, op_glu = 0, op_dw = 0, op_lc_norm = 0, op_lc_act = 0, op_lc_add = 0;
|
||||
rad_op op_out = 0;
|
||||
};
|
||||
bool on = false;
|
||||
int64_t P = 0, R = 0, H = 0, heads = 0, hd = 0, ffw = 0, n_embd = 0, out_dims = 0;
|
||||
int64_t c0 = 0, c1 = 0, nmel = 0, merge = 4, left = 0, chunk = 0, n_rel = 0;
|
||||
double eps = 1e-6, softcap = 0;
|
||||
rad_weight w_c0 = 0, w_c1 = 0, w_n0 = 0, w_n1 = 0, w_in = 0, w_out = 0, b_outw = 0, w_emb = 0;
|
||||
rad_op op_c0 = 0, op_n0 = 0, op_r0 = 0, op_c1 = 0, op_n1 = 0, op_r1 = 0, op_in = 0;
|
||||
rad_op op_relpos = 0, op_outp = 0, op_en = 0, op_emb = 0;
|
||||
rad_buf b_s0 = 0, b_s1 = 0, b_x = 0, b_h = 0, b_hc = 0, b_f = 0, b_q = 0, b_k = 0, b_v = 0;
|
||||
rad_buf b_att = 0, b_o = 0, b_g = 0, b_u = 0, b_relpos = 0, b_relk = 0, b_o2 = 0, b_on = 0;
|
||||
rad_buf b_out = 0;
|
||||
std::vector<Layer> L;
|
||||
|
||||
/* A feature-extractor key: preprocessor_config.json's (`preprocessor.`), else
|
||||
* processor_config.json's `feature_extractor` object (`processor.feature_extractor.`). */
|
||||
static int64_t fe_i(const RadModelMeta* m, const char* k, int64_t d) {
|
||||
char a[96], b[128];
|
||||
std::snprintf(a, sizeof a, "preprocessor.%s", k);
|
||||
std::snprintf(b, sizeof b, "processor.feature_extractor.%s", k);
|
||||
return rad_meta_geti(m, a, rad_meta_geti(m, b, d));
|
||||
}
|
||||
|
||||
static bool present(const RadModelMeta* m) {
|
||||
const char* t = rad_meta_gets(m, "audio_config.model_type", "");
|
||||
return t && !std::strcmp(t, "gemma4_audio");
|
||||
}
|
||||
/* The longest clip in frames: 30 s at the extractor's 10 ms hop, rounded up to whole rows. */
|
||||
static int64_t frames_for(const RadModelMeta* m) {
|
||||
const int64_t rate = fe_i(m, "sampling_rate", 16000);
|
||||
const int64_t fl = fe_i(m, "frame_length", 320);
|
||||
const int64_t hop = fe_i(m, "hop_length", 160);
|
||||
if (rate <= 0 || hop <= 0) return 0;
|
||||
const int64_t n = 30 * rate;
|
||||
const int64_t real = (n + fl / 2 - fl - 1) / hop + 1;
|
||||
return (real + 3) / 4 * 4;
|
||||
}
|
||||
|
||||
/* `pre` is the checkpoint prefix of the encoder and its embedder ("model." for Gemma 4's
|
||||
* conditional-generation checkpoints, "" for EmbeddingGemma 2); `who` names the plugin in
|
||||
* refusals. The encoder's layers take weight groups from `first_group`. */
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group, const char* pre, const char* who) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK;
|
||||
const char* A = "audio_config";
|
||||
auto gi = [&](const char* k, int64_t d) {
|
||||
char key[96];
|
||||
std::snprintf(key, sizeof key, "%s.%s", A, k);
|
||||
return rad_meta_geti(m, key, d);
|
||||
};
|
||||
auto gf = [&](const char* k, double d) {
|
||||
char key[96];
|
||||
std::snprintf(key, sizeof key, "%s.%s", A, k);
|
||||
return rad_meta_getf(m, key, d);
|
||||
};
|
||||
H = gi("hidden_size", 0);
|
||||
heads = gi("num_attention_heads", 0);
|
||||
out_dims = gi("output_proj_dims", 0);
|
||||
chunk = gi("attention_chunk_size", 0);
|
||||
/* transformers masks a key unless 0 <= q - k < attention_context_left - 1, so the
|
||||
* furthest key back is context_left - 2 frames: 11 for this checkpoint, the query and
|
||||
* eleven before it. */
|
||||
left = gi("attention_context_left", 0) - 2;
|
||||
softcap = gf("attention_logit_cap", 0.0);
|
||||
eps = gf("rms_norm_eps", 1e-6);
|
||||
const int64_t depth = gi("num_hidden_layers", 0);
|
||||
const int64_t kconv = gi("conv_kernel_size", 0);
|
||||
const int64_t right = gi("attention_context_right", 0);
|
||||
const double resw = gf("residual_weight", 0.0);
|
||||
const char* act = rad_meta_gets(m, "audio_config.hidden_act", "");
|
||||
const char* chs = rad_meta_gets(m, "audio_config.subsampling_conv_channels", "");
|
||||
nmel = fe_i(m, "feature_size", 0);
|
||||
if (std::sscanf(chs ? chs : "", "%lld %lld", (long long*)&c0, (long long*)&c1) != 2)
|
||||
c0 = c1 = 0;
|
||||
hd = heads > 0 ? H / heads : 0;
|
||||
ffw = 4 * H;
|
||||
n_rel = left + 1;
|
||||
if (H <= 0 || heads <= 0 || hd * heads != H || out_dims <= 0 || depth <= 0 || kconv <= 0 ||
|
||||
chunk <= 0 || left < 0 || right != 0 || !(softcap > 0) || resw != 0.5 ||
|
||||
std::strcmp(act ? act : "", "silu") || c0 <= 0 || c1 <= 0 || nmel != 128 ||
|
||||
(nmel / 4) * c1 != H) {
|
||||
fprintf(stderr, "radiance: %s: the container's audio_config is not the "
|
||||
"conformer this plugin serves (hidden %lld, heads %lld, output %lld, "
|
||||
"layers %lld, conv %lld, left %lld right %lld, residual %g, act %s, "
|
||||
"subsampling %lld/%lld over %lld bins)\n", who, (long long)H,
|
||||
(long long)heads, (long long)out_dims, (long long)depth, (long long)kconv,
|
||||
(long long)left, (long long)right, resw, act ? act : "", (long long)c0,
|
||||
(long long)c1, (long long)nmel);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
n_embd = model_embd;
|
||||
P = ctx->max_audio_frames;
|
||||
if (P % merge) return RAD_E_SHAPE;
|
||||
R = P / merge;
|
||||
const int AC = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
|
||||
char T[64];
|
||||
std::snprintf(T, sizeof T, "%saudio_tower", pre);
|
||||
|
||||
/* ---- weights */
|
||||
auto w = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
|
||||
RadWeightGroup g) -> rad_weight {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, RAD_BF16, shp, AC, N, g);
|
||||
};
|
||||
auto clip = [&](Clip& c, const char* dn, const char* src, int64_t out, int64_t in,
|
||||
RadWeightGroup g) {
|
||||
char d1[160], s1[200];
|
||||
std::snprintf(d1, sizeof d1, "%s.w", dn); std::snprintf(s1, sizeof s1, "%s.linear.weight", src);
|
||||
c.w = w(nm.f("%s", d1), nm.ckpt("%s", s1), {out, in}, g);
|
||||
const char* bn[4] = { "input_min", "input_max", "output_min", "output_max" };
|
||||
rad_weight* dst[4] = { &c.in_lo, &c.in_hi, &c.out_lo, &c.out_hi };
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
std::snprintf(d1, sizeof d1, "%s.%s", dn, bn[i]);
|
||||
std::snprintf(s1, sizeof s1, "%s.%s", src, bn[i]);
|
||||
*dst[i] = w(nm.f("%s", d1), nm.ckpt("%s", s1), {1}, g);
|
||||
}
|
||||
};
|
||||
w_c0 = w(nm.f("a.sscp.c0"), nm.ckpt("%s.subsample_conv_projection.layer0.conv.weight", T), {c0, 1, 3, 3}, grp_model());
|
||||
w_n0 = w(nm.f("a.sscp.n0"), nm.ckpt("%s.subsample_conv_projection.layer0.norm.weight", T), {c0}, grp_model());
|
||||
w_c1 = w(nm.f("a.sscp.c1"), nm.ckpt("%s.subsample_conv_projection.layer1.conv.weight", T), {c1, c0, 3, 3}, grp_model());
|
||||
w_n1 = w(nm.f("a.sscp.n1"), nm.ckpt("%s.subsample_conv_projection.layer1.norm.weight", T), {c1}, grp_model());
|
||||
w_in = w(nm.f("a.sscp.proj"), nm.ckpt("%s.subsample_conv_projection.input_proj_linear.weight", T), {H, H}, grp_model());
|
||||
w_out = w(nm.f("a.out.w"), nm.ckpt("%s.output_proj.weight", T), {out_dims, H}, grp_model());
|
||||
b_outw = w(nm.f("a.out.b"), nm.ckpt("%s.output_proj.bias", T), {out_dims}, grp_model());
|
||||
w_emb = w(nm.f("a.embed"), nm.ckpt("%sembed_audio.embedding_projection.weight", pre), {n_embd, out_dims}, grp_model());
|
||||
L.assign((size_t)depth, Layer{});
|
||||
for (int64_t i = 0; i < depth; ++i) {
|
||||
Layer& l = L[(size_t)i];
|
||||
const long long li = (long long)i;
|
||||
const RadWeightGroup g = grp_layer(first_group + (int)i);
|
||||
char d[96], s[160];
|
||||
auto D = [&](const char* x) { std::snprintf(d, sizeof d, "a.blk.%lld.%s", li, x); return nm.f("%s", d); };
|
||||
auto S = [&](const char* x) { std::snprintf(s, sizeof s, "%s.layers.%lld.%s", T, li, x); return nm.ckpt("%s", s); };
|
||||
for (int f = 0; f < 2; ++f) {
|
||||
FF& ff = f ? l.ff2 : l.ff1;
|
||||
const char* fn = f ? "feed_forward2" : "feed_forward1";
|
||||
char px[64]; std::snprintf(px, sizeof px, "%s.pre_layer_norm.weight", fn);
|
||||
ff.pre = w(D(px), S(px), {H}, g);
|
||||
std::snprintf(px, sizeof px, "%s.post_layer_norm.weight", fn);
|
||||
ff.post = w(D(px), S(px), {H}, g);
|
||||
char dn[96], sn[160];
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.%s.l1", li, fn);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.%s.ffw_layer_1", T, li, fn);
|
||||
clip(ff.l1, dn, sn, ffw, H, g);
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.%s.l2", li, fn);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.%s.ffw_layer_2", T, li, fn);
|
||||
clip(ff.l2, dn, sn, H, ffw, g);
|
||||
}
|
||||
l.n_pre_attn = w(D("norm_pre_attn"), S("norm_pre_attn.weight"), {H}, g);
|
||||
l.n_post_attn = w(D("norm_post_attn"), S("norm_post_attn.weight"), {H}, g);
|
||||
l.n_out = w(D("norm_out"), S("norm_out.weight"), {H}, g);
|
||||
l.w_rel = w(D("rel_k"), S("self_attn.relative_k_proj.weight"), {H, H}, g);
|
||||
l.pds = w(D("per_dim_scale"), S("self_attn.per_dim_scale"), {hd}, g);
|
||||
const char* qn[4] = { "q_proj", "k_proj", "v_proj", "post" };
|
||||
Clip* qc[4] = { &l.q, &l.k, &l.v, &l.post };
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
char dn[96], sn[160];
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.attn.%s", li, qn[j]);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.self_attn.%s", T, li, qn[j]);
|
||||
clip(*qc[j], dn, sn, H, H, g);
|
||||
}
|
||||
l.lc_pre = w(D("lconv.pre"), S("lconv1d.pre_layer_norm.weight"), {H}, g);
|
||||
l.lc_dw = w(D("lconv.dw"), S("lconv1d.depthwise_conv1d.weight"), {H, 1, kconv}, g);
|
||||
l.lc_norm = w(D("lconv.norm"), S("lconv1d.conv_norm.weight"), {H}, g);
|
||||
{
|
||||
char dn[96], sn[160];
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.lconv.start", li);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.lconv1d.linear_start", T, li);
|
||||
clip(l.lc_start, dn, sn, 2 * H, H, g);
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.lconv.end", li);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.lconv1d.linear_end", T, li);
|
||||
clip(l.lc_end, dn, sn, H, H, g);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- activations: the subsampler's planes at their own widths, the blocks' at R rows */
|
||||
b_s0 = decl_b(b, nm.f("a.s0"), RAD_BF16, {P / 2, (nmel / 2) * c0});
|
||||
b_s1 = decl_b(b, nm.f("a.s1"), RAD_BF16, {R, (nmel / 4) * c1});
|
||||
b_x = decl_b(b, nm.f("a.x"), RAD_BF16, {R, H});
|
||||
b_h = decl_b(b, nm.f("a.h"), RAD_BF16, {R, H});
|
||||
b_hc = decl_b(b, nm.f("a.hc"), RAD_BF16, {R, H});
|
||||
b_f = decl_b(b, nm.f("a.f"), RAD_BF16, {R, ffw});
|
||||
b_q = decl_b(b, nm.f("a.q"), RAD_BF16, {R, H});
|
||||
b_k = decl_b(b, nm.f("a.k"), RAD_BF16, {R, H});
|
||||
b_v = decl_b(b, nm.f("a.v"), RAD_BF16, {R, H});
|
||||
b_att = decl_b(b, nm.f("a.att"), RAD_BF16, {R, H});
|
||||
b_o = decl_b(b, nm.f("a.o"), RAD_BF16, {R, H});
|
||||
b_g = decl_b(b, nm.f("a.g"), RAD_BF16, {R, 2 * H});
|
||||
b_u = decl_b(b, nm.f("a.u"), RAD_BF16, {R, H});
|
||||
b_relpos = decl_b(b, nm.f("a.relpos"), RAD_BF16, {n_rel, H});
|
||||
b_relk = decl_b(b, nm.f("a.relk"), RAD_BF16, {n_rel, H});
|
||||
b_o2 = decl_b(b, nm.f("a.o2"), RAD_BF16, {R, out_dims});
|
||||
b_on = decl_b(b, nm.f("a.on"), RAD_BF16, {R, out_dims});
|
||||
b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {R, n_embd});
|
||||
|
||||
auto gemm = [&](int64_t rows, int64_t Nn, int64_t K, rad_weight wt) {
|
||||
return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn),
|
||||
RAD_INT("K", K), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
auto rms = [&](int64_t rows, int64_t n, rad_weight wt, double mult) {
|
||||
if (!wt)
|
||||
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("mult", mult)),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
auto clamp = [&](int64_t rows, int64_t n, rad_weight lo, rad_weight hi) {
|
||||
return RAD_OP(b, "clamp", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(lo, hi));
|
||||
};
|
||||
auto unary = [&](const char* op, int64_t rows, int64_t n) {
|
||||
return RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto add = [&](int64_t rows, int64_t n) { return unary("add", rows, n); };
|
||||
auto lnorm = [&](int64_t rows, int64_t n, rad_weight g) {
|
||||
return RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(g));
|
||||
};
|
||||
auto conv = [&](int64_t rows, int64_t width, int64_t ci, int64_t co, int64_t cu_div,
|
||||
int64_t vstride, rad_weight wt) {
|
||||
return RAD_OP(b, "conv2d", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("width", width),
|
||||
RAD_INT("cin", ci), RAD_INT("cout", co),
|
||||
RAD_INT("kh", 3), RAD_INT("kw", 3),
|
||||
RAD_INT("stride", 2), RAD_INT("pad", 1),
|
||||
RAD_INT("cu_div", cu_div),
|
||||
RAD_INT("valid_stride", vstride),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
/* A clipped linear over rows of `in` into `out`: the input clamp writes a copy (the input
|
||||
* feeds several projections, each with its own bounds), the output clamp is in place. The
|
||||
* copy is a whole [R, n_in] buffer, since a GEMM's input must be contiguous. */
|
||||
auto clipped = [&](Clip& c, int64_t n_out, int64_t n_in, rad_buf in, rad_buf tmp,
|
||||
rad_buf out) {
|
||||
c.op_in = rw(b, clamp(R, n_in, c.in_lo, c.in_hi), {in}, {tmp});
|
||||
c.op_mm = rw(b, gemm(R, n_out, n_in, c.w), {tmp}, {out});
|
||||
c.op_out = rw(b, clamp(R, n_out, c.out_lo, c.out_hi), {out}, {out});
|
||||
};
|
||||
|
||||
op_c0 = rw(b, conv(P, nmel, 1, c0, 1, 1, w_c0), {}, {b_s0});
|
||||
op_n0 = rw(b, lnorm(P / 2 * (nmel / 2), c0, w_n0), {b_s0}, {b_s0});
|
||||
op_r0 = rw(b, unary("relu", P / 2 * (nmel / 2), c0), {b_s0}, {b_s0});
|
||||
op_c1 = rw(b, conv(P / 2, nmel / 2, c0, c1, 2, 2, w_c1), {b_s0}, {b_s1});
|
||||
op_n1 = rw(b, lnorm(R * (nmel / 4), c1, w_n1), {b_s1}, {b_s1});
|
||||
op_r1 = rw(b, unary("relu", R * (nmel / 4), c1), {b_s1}, {b_s1});
|
||||
op_in = rw(b, gemm(R, H, H, w_in), {b_s1}, {b_x});
|
||||
op_relpos = rw(b, RAD_OP(b, "rel_sinusoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, n_rel), RAD_INT("n", H),
|
||||
RAD_F64("max_timescale", 10000.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {b_relpos});
|
||||
for (Layer& l : L) {
|
||||
auto ffw_block = [&](FF& ff) {
|
||||
ff.op_pre = rw(b, rms(R, H, ff.pre, 1.0), {b_x}, {b_h});
|
||||
clipped(ff.l1, ffw, H, b_h, b_hc, b_f);
|
||||
ff.op_act = rw(b, unary("silu", R, ffw), {b_f}, {b_f});
|
||||
/* the activation's only reader is this linear, so its clamp is in place */
|
||||
clipped(ff.l2, H, ffw, b_f, b_f, b_o);
|
||||
ff.op_post = rw(b, rms(R, H, ff.post, 0.5), {b_o}, {b_o});
|
||||
ff.op_add = rw(b, add(R, H), {b_x, b_o}, {b_x});
|
||||
};
|
||||
ffw_block(l.ff1);
|
||||
l.op_npa = rw(b, rms(R, H, l.n_pre_attn, 1.0), {b_x}, {b_h});
|
||||
clipped(l.q, H, H, b_h, b_hc, b_q);
|
||||
clipped(l.k, H, H, b_h, b_hc, b_k);
|
||||
clipped(l.v, H, H, b_h, b_hc, b_v);
|
||||
l.op_rel = rw(b, gemm(n_rel, H, H, l.w_rel), {b_relpos}, {b_relk});
|
||||
l.op_attn = rw(b, RAD_OP(b, "attn_local_rel",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd),
|
||||
RAD_INT("n_head", heads), RAD_INT("left", left),
|
||||
RAD_INT("right", 0), RAD_F64("softcap", softcap),
|
||||
RAD_INT("cu_div", merge), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(l.pds)),
|
||||
{b_q, b_k, b_v, b_relk}, {b_att});
|
||||
clipped(l.post, H, H, b_att, b_hc, b_o);
|
||||
l.op_npo = rw(b, rms(R, H, l.n_post_attn, 1.0), {b_o}, {b_o});
|
||||
l.op_add_attn = rw(b, add(R, H), {b_x, b_o}, {b_x});
|
||||
l.op_lc_pre = rw(b, rms(R, H, l.lc_pre, 1.0), {b_x}, {b_h});
|
||||
clipped(l.lc_start, 2 * H, H, b_h, b_hc, b_g);
|
||||
/* GLU: the first half times the sigmoid of the second. */
|
||||
l.op_glu = rw(b, RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
|
||||
RAD_STR("act", "sigmoid"), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_g}, {b_u});
|
||||
l.op_dw = rw(b, RAD_OP(b, "conv1d_dw",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
|
||||
RAD_INT("k", kconv), RAD_INT("cu_div", merge),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(l.lc_dw)),
|
||||
{b_u}, {b_o});
|
||||
l.op_lc_norm = rw(b, rms(R, H, l.lc_norm, 1.0), {b_o}, {b_o});
|
||||
l.op_lc_act = rw(b, unary("silu", R, H), {b_o}, {b_o});
|
||||
clipped(l.lc_end, H, H, b_o, b_hc, b_u);
|
||||
l.op_lc_add = rw(b, add(R, H), {b_x, b_u}, {b_x});
|
||||
ffw_block(l.ff2);
|
||||
l.op_out = rw(b, rms(R, H, l.n_out, 1.0), {b_x}, {b_x});
|
||||
}
|
||||
op_outp = rw(b, RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("N", out_dims),
|
||||
RAD_INT("K", H), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("act", "none")),
|
||||
RAD_WEIGHTS(w_out, b_outw)),
|
||||
{b_x}, {b_o2});
|
||||
op_en = rw(b, rms(R, out_dims, 0, 1.0), {b_o2}, {b_on});
|
||||
op_emb = rw(b, gemm(R, n_embd, out_dims, w_emb), {b_on}, {b_out});
|
||||
|
||||
RadEncoderDecl e{};
|
||||
e.name = "audio";
|
||||
e.modalities = RAD_MM_AUDIO;
|
||||
e.patch_dim = nmel;
|
||||
e.merge = merge;
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "audio encoder: %lld conformer blocks of %lld (%lld heads x %lld), "
|
||||
"subsampling %lld/%lld channels, local attention %lld back; %lld frames a "
|
||||
"pass -> %lld rows of %lld", (long long)depth, (long long)H, (long long)heads,
|
||||
(long long)hd, (long long)c0, (long long)c1, (long long)left, (long long)P,
|
||||
(long long)R, (long long)n_embd);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
|
||||
if (!on || Pn <= 0 || Pn > P || Pn % merge || S <= 0) {
|
||||
rad_step_fail(c, "an audio pass this program's audio encoder cannot serve: none "
|
||||
"declared, more frames than it was declared for, or not whole rows");
|
||||
return;
|
||||
}
|
||||
const int64_t Rn = Pn / merge;
|
||||
const int32_t* crd = batch->enc_coord;
|
||||
const RadOperand frames = praw2(batch->enc_pixels, RAD_BF16, Pn, nmel);
|
||||
const RadOperand valid = praw(crd + Pn, RAD_I32, Pn);
|
||||
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
|
||||
auto clipped = [&](const Clip& cl, rad_buf in, int64_t n_in, rad_buf tmp, rad_buf out,
|
||||
int64_t n_out) {
|
||||
RAD_ISSUE_N(c, cl.op_in, Rn, bcol(in, 0, n_in, Rn), RAD_W(cl.in_lo), RAD_W(cl.in_hi),
|
||||
bcol(tmp, 0, n_in, Rn));
|
||||
RAD_ISSUE_N(c, cl.op_mm, Rn, bcol(tmp, 0, n_in, Rn), RAD_W(cl.w), bcol(out, 0, n_out, Rn));
|
||||
RAD_ISSUE_N(c, cl.op_out, Rn, bcol(out, 0, n_out, Rn), RAD_W(cl.out_lo), RAD_W(cl.out_hi),
|
||||
bcol(out, 0, n_out, Rn));
|
||||
};
|
||||
|
||||
RAD_ISSUE_N(c, op_c0, Pn, frames, RAD_W(w_c0), cu, valid, brows(b_s0, Pn / 2), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_n0, Pn / 2 * (nmel / 2), brows(b_s0, Pn / 2), RAD_W(w_n0), RAD_NONE,
|
||||
brows(b_s0, Pn / 2));
|
||||
RAD_ISSUE_N(c, op_r0, Pn / 2 * (nmel / 2), brows(b_s0, Pn / 2), brows(b_s0, Pn / 2));
|
||||
RAD_ISSUE_N(c, op_c1, Pn / 2, brows(b_s0, Pn / 2), RAD_W(w_c1), cu, valid, brows(b_s1, Rn),
|
||||
RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_n1, Rn * (nmel / 4), brows(b_s1, Rn), RAD_W(w_n1), RAD_NONE,
|
||||
brows(b_s1, Rn));
|
||||
RAD_ISSUE_N(c, op_r1, Rn * (nmel / 4), brows(b_s1, Rn), brows(b_s1, Rn));
|
||||
RAD_ISSUE_N(c, op_in, Rn, brows(b_s1, Rn), RAD_W(w_in), brows(b_x, Rn));
|
||||
RAD_ISSUE_N(c, op_relpos, n_rel, brows(b_relpos, n_rel));
|
||||
for (const Layer& l : L) {
|
||||
auto ffw_block = [&](const FF& ff) {
|
||||
RAD_ISSUE_N(c, ff.op_pre, Rn, brows(b_x, Rn), RAD_W(ff.pre), brows(b_h, Rn));
|
||||
clipped(ff.l1, b_h, H, b_hc, b_f, ffw);
|
||||
RAD_ISSUE_N(c, ff.op_act, Rn, brows(b_f, Rn), brows(b_f, Rn));
|
||||
clipped(ff.l2, b_f, ffw, b_f, b_o, H);
|
||||
RAD_ISSUE_N(c, ff.op_post, Rn, brows(b_o, Rn), RAD_W(ff.post), brows(b_o, Rn));
|
||||
RAD_ISSUE_N(c, ff.op_add, Rn, brows(b_x, Rn), brows(b_o, Rn), brows(b_x, Rn));
|
||||
};
|
||||
ffw_block(l.ff1);
|
||||
RAD_ISSUE_N(c, l.op_npa, Rn, brows(b_x, Rn), RAD_W(l.n_pre_attn), brows(b_h, Rn));
|
||||
clipped(l.q, b_h, H, b_hc, b_q, H);
|
||||
clipped(l.k, b_h, H, b_hc, b_k, H);
|
||||
clipped(l.v, b_h, H, b_hc, b_v, H);
|
||||
RAD_ISSUE_N(c, l.op_rel, n_rel, brows(b_relpos, n_rel), RAD_W(l.w_rel),
|
||||
brows(b_relk, n_rel));
|
||||
RAD_ISSUE_N(c, l.op_attn, Rn, brows(b_q, Rn), brows(b_k, Rn), brows(b_v, Rn),
|
||||
brows(b_relk, n_rel), RAD_W(l.pds), cu, brows(b_att, Rn));
|
||||
clipped(l.post, b_att, H, b_hc, b_o, H);
|
||||
RAD_ISSUE_N(c, l.op_npo, Rn, brows(b_o, Rn), RAD_W(l.n_post_attn), brows(b_o, Rn));
|
||||
RAD_ISSUE_N(c, l.op_add_attn, Rn, brows(b_x, Rn), brows(b_o, Rn), brows(b_x, Rn));
|
||||
RAD_ISSUE_N(c, l.op_lc_pre, Rn, brows(b_x, Rn), RAD_W(l.lc_pre), brows(b_h, Rn));
|
||||
clipped(l.lc_start, b_h, H, b_hc, b_g, 2 * H);
|
||||
RAD_ISSUE_N(c, l.op_glu, Rn, bcol(b_g, H, H, Rn), bcol(b_g, 0, H, Rn), brows(b_u, Rn));
|
||||
RAD_ISSUE_N(c, l.op_dw, Rn, brows(b_u, Rn), RAD_W(l.lc_dw), cu, brows(b_o, Rn),
|
||||
RAD_NONE);
|
||||
RAD_ISSUE_N(c, l.op_lc_norm, Rn, brows(b_o, Rn), RAD_W(l.lc_norm), brows(b_o, Rn));
|
||||
RAD_ISSUE_N(c, l.op_lc_act, Rn, brows(b_o, Rn), brows(b_o, Rn));
|
||||
clipped(l.lc_end, b_o, H, b_hc, b_u, H);
|
||||
RAD_ISSUE_N(c, l.op_lc_add, Rn, brows(b_x, Rn), brows(b_u, Rn), brows(b_x, Rn));
|
||||
ffw_block(l.ff2);
|
||||
RAD_ISSUE_N(c, l.op_out, Rn, brows(b_x, Rn), RAD_W(l.n_out), brows(b_x, Rn));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_outp, Rn, brows(b_x, Rn), RAD_W(w_out), RAD_W(b_outw), RAD_NONE,
|
||||
brows(b_o2, Rn));
|
||||
RAD_ISSUE_N(c, op_en, Rn, brows(b_o2, Rn), RAD_NONE, brows(b_on, Rn));
|
||||
RAD_ISSUE_N(c, op_emb, Rn, brows(b_on, Rn), RAD_W(w_emb), brows(b_out, Rn));
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif
|
||||
@@ -19,6 +19,15 @@
|
||||
* replace the image's placeholder embeddings (which the text model scales by sqrt(n_embd); the
|
||||
* image rows are not scaled).
|
||||
*
|
||||
* Clipped linears (vision_config.use_clipped_linears, Gemma 4 E2B/E4B): every projection clamps its
|
||||
* input and its output to bounds the checkpoint stores (`<proj>.input_min/max`, `output_min/max`;
|
||||
* transformers' Gemma4ClippableLinear). The tower keeps its fused q|k|v and gate|up GEMMs, so it
|
||||
* takes the input bounds of q_proj (and of gate_proj) for the fused input, q_proj's output bounds for
|
||||
* q's columns, k_proj's for k's and v's, and gate_proj's output bounds for gate|up. That is exact
|
||||
* where the fused parts share their bounds, as NVIDIA's E4B does in all 16 layers (k and v share the
|
||||
* input bounds of q and their output bounds, up shares gate's). The bound weights are one bf16
|
||||
* element each, read by `clamp`.
|
||||
*
|
||||
* One encoder pass carries RadBuildCtx::max_enc_patches patches over any number of segments (an
|
||||
* image, or one frame of a video). Every rank runs the whole tower (engine_mm.cpp), so its weights
|
||||
* are replicated (RAD_SHARD_NONE) and each rank writes the rows into its own copy of the embedding
|
||||
@@ -41,8 +50,12 @@ struct Gemma4Vision {
|
||||
rad_weight pre_ff = 0, gate_up = 0, down = 0, post_ff = 0;
|
||||
rad_op op_in = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_o = 0, op_pa = 0, op_add1 = 0;
|
||||
rad_op op_pf = 0, op_gu = 0, op_act = 0, op_down = 0, op_pff = 0, op_add2 = 0;
|
||||
/* clipped linears: the bounds (lo, hi) of the nine clamps, and the clamps */
|
||||
enum { C_QKV_IN, C_Q_OUT, C_KV_OUT, C_O_IN, C_O_OUT, C_GU_IN, C_GU_OUT, C_DN_IN, C_DN_OUT, C_N };
|
||||
rad_weight lo[C_N] = {}, hi[C_N] = {};
|
||||
rad_op op_c[C_N] = {};
|
||||
};
|
||||
bool on = false, standardize = false;
|
||||
bool on = false, standardize = false, clip = false;
|
||||
int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0;
|
||||
int64_t npos = 0, n_embd = 0;
|
||||
rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0, w_sbias = 0, w_sscale = 0;
|
||||
@@ -88,15 +101,14 @@ struct Gemma4Vision {
|
||||
(long long)pool, (long long)depth);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Clipped linears (their bounds are buffers the vision checkpoint states as infinite) and
|
||||
* any rotary or activation other than the 2-D one and gelu-tanh are refused by name. */
|
||||
if (rad_meta_geti(m, "vision_config.use_clipped_linears", 0) ||
|
||||
(std::strcmp(rt, "default") && std::strcmp(rt, "axial")) ||
|
||||
/* Any rotary or activation other than the 2-D one and gelu-tanh is refused by name. */
|
||||
if ((std::strcmp(rt, "default") && std::strcmp(rt, "axial")) ||
|
||||
std::strcmp(act, "gelu_pytorch_tanh")) {
|
||||
fprintf(stderr, "radiance: %s: this vision tower uses clipped linears, a '%s' rotary or "
|
||||
"a '%s' activation, which it does not serve\n", who, rt, act);
|
||||
fprintf(stderr, "radiance: %s: this vision tower uses a '%s' rotary or a '%s' "
|
||||
"activation, which it does not serve\n", who, rt, act);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
clip = rad_meta_geti(m, "vision_config.use_clipped_linears", 0) != 0;
|
||||
n_embd = model_embd;
|
||||
patch_dim = 3 * patch * patch;
|
||||
const int64_t kk = pool * pool;
|
||||
@@ -154,6 +166,27 @@ struct Gemma4Vision {
|
||||
l.gate_up = decl_w(b, nm.f("v.blk.%lld.gate_up", li), RAD_BF16, {2 * ff, width}, A, N, g);
|
||||
l.down = decl_w(b, nm.f("v.blk.%lld.down", li), RAD_BF16, {width, ff}, A, N, g);
|
||||
l.post_ff = decl_w(b, nm.f("v.blk.%lld.post_ff", li), RAD_BF16, {width}, A, N, g);
|
||||
if (clip) {
|
||||
/* clamp k -> the checkpoint projection whose bound it takes, and which bound */
|
||||
static const char* const proj[Layer::C_N] = {
|
||||
"self_attn.q_proj", "self_attn.q_proj", "self_attn.k_proj", "self_attn.o_proj",
|
||||
"self_attn.o_proj", "mlp.gate_proj", "mlp.gate_proj", "mlp.down_proj",
|
||||
"mlp.down_proj" };
|
||||
static const bool in_side[Layer::C_N] = { true, false, false, true, false, true,
|
||||
false, true, false };
|
||||
for (int k = 0; k < Layer::C_N; ++k) {
|
||||
const char* side = in_side[k] ? "input" : "output";
|
||||
const char* lo_n = nm.f("v.blk.%lld.clip%d.lo", li, k);
|
||||
const char* hi_n = nm.f("v.blk.%lld.clip%d.hi", li, k);
|
||||
RAD_ARCH_TRY(map_copy(b, lo_n, nm.ckpt("%s.encoder.layers.%lld.%s.%s_min", V, li,
|
||||
proj[k], side)));
|
||||
RAD_ARCH_TRY(map_copy(b, hi_n, nm.ckpt("%s.encoder.layers.%lld.%s.%s_max", V, li,
|
||||
proj[k], side)));
|
||||
l.lo[k] = decl_w(b, lo_n, RAD_BF16, {1}, A, N, g);
|
||||
l.hi[k] = decl_w(b, hi_n, RAD_BF16, {1}, A, N, g);
|
||||
if (!l.lo[k] || !l.hi[k]) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width});
|
||||
@@ -198,6 +231,11 @@ struct Gemma4Vision {
|
||||
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto clamp = [&](int64_t n, rad_weight lo, rad_weight hi) {
|
||||
return RAD_OP(b, "clamp", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(lo, hi));
|
||||
};
|
||||
auto gain = [&](rad_weight w) {
|
||||
return RAD_OP(b, "mul_weight", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("scalar", 0)),
|
||||
@@ -212,6 +250,19 @@ struct Gemma4Vision {
|
||||
char sec[48];
|
||||
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(hd / 4), (long long)(hd / 4));
|
||||
for (Layer& l : L) {
|
||||
/* the clamps, each in place on the one buffer its linear reads or writes (each of those
|
||||
* is read by that linear alone, or by what follows it) */
|
||||
if (clip) {
|
||||
using C = Layer;
|
||||
const struct { int k; int64_t n; rad_buf buf; } cl[C::C_N] = {
|
||||
{ C::C_QKV_IN, width, b_h }, { C::C_Q_OUT, width, b_qkv },
|
||||
{ C::C_KV_OUT, 2 * width, b_qkv }, { C::C_O_IN, width, b_att },
|
||||
{ C::C_O_OUT, width, b_o }, { C::C_GU_IN, width, b_h },
|
||||
{ C::C_GU_OUT, 2 * ff, b_gu }, { C::C_DN_IN, ff, b_ff },
|
||||
{ C::C_DN_OUT, width, b_o } };
|
||||
for (const auto& e : cl)
|
||||
l.op_c[e.k] = rw(b, clamp(e.n, l.lo[e.k], l.hi[e.k]), {e.buf}, {e.buf});
|
||||
}
|
||||
l.op_in = rw(b, rms(P, l.in_norm), {b_x}, {b_h});
|
||||
l.op_qkv = rw(b, gemm(P, 3 * width, width, l.qkv), {b_h}, {b_qkv});
|
||||
l.op_qk = rw(b, RAD_OP(b, "qk_norm_rope",
|
||||
@@ -272,10 +323,11 @@ struct Gemma4Vision {
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
|
||||
"pooled %lldx%lld%s; %lld patches a pass -> %lld rows of %lld",
|
||||
"pooled %lldx%lld%s%s; %lld patches a pass -> %lld rows of %lld",
|
||||
(long long)depth, (long long)width, (long long)heads, (long long)hd, (long long)ff,
|
||||
(long long)patch, (long long)pool, (long long)pool,
|
||||
standardize ? ", standardised" : "", (long long)P, (long long)R,
|
||||
standardize ? ", standardised" : "", clip ? ", clipped linears" : "",
|
||||
(long long)P, (long long)R,
|
||||
(long long)n_embd);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
@@ -299,20 +351,33 @@ struct Gemma4Vision {
|
||||
RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn));
|
||||
RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn));
|
||||
RAD_ISSUE_N(c, op_add, Pn, brows(b_x, Pn), brows(b_px, Pn), brows(b_x, Pn));
|
||||
/* a clamp of operand `x` in place, when the tower clips */
|
||||
auto cl = [&](const Layer& l, int k, RadOperand x) {
|
||||
if (clip) RAD_ISSUE_N(c, l.op_c[k], Pn, x, RAD_W(l.lo[k]), RAD_W(l.hi[k]), x);
|
||||
};
|
||||
for (const Layer& l : L) {
|
||||
RAD_ISSUE_N(c, l.op_in, Pn, brows(b_x, Pn), RAD_W(l.in_norm), brows(b_h, Pn));
|
||||
cl(l, Layer::C_QKV_IN, brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.op_qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv), brows(b_qkv, Pn));
|
||||
cl(l, Layer::C_Q_OUT, bcol(b_qkv, 0, width, Pn));
|
||||
cl(l, Layer::C_KV_OUT, bcol(b_qkv, width, 2 * width, Pn));
|
||||
RAD_ISSUE_N(c, l.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm));
|
||||
RAD_ISSUE_N(c, l.op_attn, Pn, bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
|
||||
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
|
||||
cl(l, Layer::C_O_IN, brows(b_att, Pn));
|
||||
RAD_ISSUE_N(c, l.op_o, Pn, brows(b_att, Pn), RAD_W(l.o), brows(b_o, Pn));
|
||||
cl(l, Layer::C_O_OUT, brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_pa, Pn, brows(b_o, Pn), RAD_W(l.post_attn), brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_add1, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, l.op_pf, Pn, brows(b_x, Pn), RAD_W(l.pre_ff), brows(b_h, Pn));
|
||||
cl(l, Layer::C_GU_IN, brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gate_up), brows(b_gu, Pn));
|
||||
cl(l, Layer::C_GU_OUT, brows(b_gu, Pn));
|
||||
RAD_ISSUE_N(c, l.op_act, Pn, bcol(b_gu, 0, ff, Pn), bcol(b_gu, ff, ff, Pn),
|
||||
brows(b_ff, Pn));
|
||||
cl(l, Layer::C_DN_IN, brows(b_ff, Pn));
|
||||
RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down), brows(b_o, Pn));
|
||||
cl(l, Layer::C_DN_OUT, brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_pff, Pn, brows(b_o, Pn), RAD_W(l.post_ff), brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_add2, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
|
||||
}
|
||||
|
||||
@@ -90,6 +90,9 @@ struct DsaCache {
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = 17;
|
||||
*index_group = rad_decl_kv_group(b, nm.f("kv_dsa_index"), &d);
|
||||
/* dsa_score reads this group over the whole history every step, so it stays resident and
|
||||
* holds every sequence's context while a sibling streams (kvstream/carve.cpp). */
|
||||
RAD_ARCH_TRY(rad_kv_group_dense_read(b, *index_group));
|
||||
}
|
||||
index = *index_group;
|
||||
if (!index) return RAD_E_INVAL;
|
||||
|
||||
@@ -3,14 +3,23 @@
|
||||
* complete heads shard as rows of the shared K/V weight. prepare() exposes the normalized q latent
|
||||
* for the indexer; finish() consumes the indexer's selection. The caller owns the mHC residual.
|
||||
*
|
||||
* Under tensor parallelism the 64 heads split over the ranks (GlmTp::heads): the rows of q_b and
|
||||
* kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent cache are
|
||||
* replicated. */
|
||||
* Under tensor parallelism the head form splits the 64 heads over the ranks (GlmTp::heads): the
|
||||
* rows of q_b and kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent
|
||||
* cache are replicated. From GlmTp::kSplitRows a prefill-sized step takes the row form instead
|
||||
* (Wire::rows, Form::rows): each rank runs its run of the step's rows (GlmTp::run_of) through q_b,
|
||||
* absorption, attention, expansion and the output projection with all 64 heads, then an
|
||||
* all_gather lays the runs out as the whole step. The latent cache and the selection are whole on
|
||||
* every rank already, so the split needs no other exchange. The gather moves half the bytes of
|
||||
* the head form's all-reduce, and the attention loads each key once for all 64 heads of a row.
|
||||
* The price is the three projections at full width on every rank (126 MB a layer); RowsWire::q
|
||||
* unset declares neither them nor the form. */
|
||||
#ifndef RAD_BLOCK_GLM_MLA_H
|
||||
#define RAD_BLOCK_GLM_MLA_H
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_glm_tp.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
@@ -20,6 +29,9 @@ struct MlaLatent {
|
||||
};
|
||||
struct Wire {
|
||||
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0;
|
||||
/* qsa_select's entry count (selected_count), one int a row: the streamed resolve's `nsel`.
|
||||
* Never `length`, which is a token count. */
|
||||
rad_buf nsel = 0;
|
||||
};
|
||||
Geom g{};
|
||||
Config c{};
|
||||
@@ -88,11 +100,28 @@ struct MlaLatent {
|
||||
};
|
||||
|
||||
struct GlmMla {
|
||||
/* How a prefill-sized step under tensor parallelism runs: `heads` keeps the head form at every
|
||||
* step size and spares the full-width weights' VRAM; `rows` is the row form. The plugin
|
||||
* chooses (RadBuildCtx::tp_attn_rows); the block takes the choice through whether it is given
|
||||
* RowsWire buffers. */
|
||||
enum class Form { heads, rows };
|
||||
/* The row form's buffers, `rows_for(max_tok)` rows each. `out` (Wire::out) must hold
|
||||
* world * rows_for(T) rows, since every rank's run is gathered at full length. */
|
||||
struct RowsWire {
|
||||
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0;
|
||||
ActFP8 attn{};
|
||||
};
|
||||
struct Wire {
|
||||
ActFP8 input{}, q_low{}, attn{};
|
||||
rad_buf q_raw = 0, kv_raw = 0, latent = 0, out = 0;
|
||||
MlaLatent::Wire core{};
|
||||
RowsWire rows{};
|
||||
};
|
||||
/* The gathered row of the row form: 4096 bf16, so a run is ceil(T / world) rows. */
|
||||
static constexpr int64_t kOutRowBytes = 4096 * 2;
|
||||
static int64_t rows_for(int64_t T, int world) {
|
||||
return GlmTp::run_rows(T, world, kOutRowBytes);
|
||||
}
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
@@ -102,7 +131,11 @@ struct GlmMla {
|
||||
QuantFP8 attn_quant{};
|
||||
MlaLatent core{};
|
||||
rad_weight q_gain = 0, kv_gain = 0;
|
||||
rad_op op_kv_norm = 0, op_store = 0, op_ar = 0;
|
||||
rad_op op_kv_norm = 0, op_store = 0, op_store_stream = 0, op_resolve = 0, op_ar = 0;
|
||||
LinearFP8 rows_q_b{}, rows_output{};
|
||||
QuantFP8 rows_quant{};
|
||||
rad_weight rows_kv_b = 0;
|
||||
rad_op op_rows_absorb = 0, op_rows_attn = 0, op_rows_expand = 0, op_rows_gather = 0;
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
const char* prefix, rad_kvgroup group, bool reduce = true,
|
||||
bool defer_finish = false) {
|
||||
@@ -159,8 +192,84 @@ struct GlmMla {
|
||||
RAD_ARCH_TRY(output.declare(b, nm, g, nm.f("blk.%d.attn_output", layer), 4096,
|
||||
GlmTp::mla_width(g.world), RAD_SHARD_COL, grp_layer(layer),
|
||||
{ nm.ckpt("%s.o_proj.weight", prefix) }, w.attn, w.out));
|
||||
/* The streamed store: kv_store's operands plus the residency map and the layer's mirror row,
|
||||
* added at issue (prepare). */
|
||||
if (rad_op_declared(b, "kv_store_streamed") && rad_kv_block_size(b, kv) == 4)
|
||||
op_store_stream = rw(b,
|
||||
RAD_OP(b, "kv_store_streamed",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("head_dim", 256), RAD_INT("n_head_kv", 1),
|
||||
RAD_INT("block_size", 4),
|
||||
RAD_STR("kv_dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.latent }, {});
|
||||
/* Issued in finish, after this layer's indexer selects and before the attention reads
|
||||
* `selected`. `sel_pitch` is the row pitch MlaLatent declares its attention with. */
|
||||
op_resolve = kv_resolve_declare(b, g, kv, w.core.selected, w.core.nsel, core.c.blocks);
|
||||
if (reduce) op_ar = GlmTp::reduce(b, g, w.out);
|
||||
return op_store && (!(reduce && g.world > 1) || op_ar) ? RAD_OK : RAD_E_INVAL;
|
||||
if (!op_store || ((reduce && g.world > 1) && !op_ar)) return RAD_E_INVAL;
|
||||
return reduce ? declare_rows(b, nm, prefix) : RAD_OK;
|
||||
}
|
||||
/* Declared whatever the step size, as every TP split here is: arena levels declare again at a
|
||||
* smaller max_tok and must get the same graph. The gather's message bound is the all-reduce's,
|
||||
* so both share one exchange instance and its scratch. */
|
||||
int declare_rows(RadBuilder* b, Names& nm, const char* prefix) {
|
||||
const auto& r = w.rows;
|
||||
if (!r.q || g.world < 2) return RAD_OK;
|
||||
if (!r.q_latent || !r.attn_latent || !r.out || !r.attn.x || r.attn.x == r.q) return RAD_E_INVAL;
|
||||
const int64_t R = rows_for(g.max_tok, g.world);
|
||||
const auto wg = grp_layer(layer);
|
||||
/* Whole views of the head form's container entries: one stored weight each, whose
|
||||
* encoding (block fp8 at f32 scales, the decoded bf16 kv_b) the views inherit. */
|
||||
rows_q_b.stored = nm.f("blk.%d.attn_q_b.weight", layer);
|
||||
RAD_ARCH_TRY(rows_q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b_rows", layer), 16384, 1536,
|
||||
RAD_SHARD_NONE, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) },
|
||||
w.q_low, r.q, R));
|
||||
rows_kv_b = decl_view(b, nm.f("blk.%d.attn_kv_b_rows.weight", layer),
|
||||
nm.f("blk.%d.attn_kv_b.weight", layer), nullptr, RAD_BF16,
|
||||
{ 64 * 2 * 256, 512 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
|
||||
if (!rows_kv_b) return RAD_E_INVAL;
|
||||
auto project = [&](const char* mode, rad_buf in, rad_buf out) {
|
||||
return rw(b,
|
||||
RAD_OP(b, "mla_project",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("heads", 64),
|
||||
RAD_INT("head_dim", 256), RAD_INT("latent_dim", 512),
|
||||
RAD_STR("mode", mode), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(rows_kv_b)),
|
||||
{ in }, { out });
|
||||
};
|
||||
op_rows_absorb = project("absorb", r.q, r.q_latent);
|
||||
op_rows_attn =
|
||||
rw(b,
|
||||
RAD_OP(b, "mla_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("latent_dim", 512),
|
||||
RAD_INT("heads", 64), RAD_INT("blocks", core.c.blocks),
|
||||
RAD_INT("block_size", 4), RAD_F64("scale", 1.0 / std::sqrt(256.0)),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ r.q_latent, w.core.selected, w.core.length }, { r.attn_latent });
|
||||
op_rows_expand = project("expand", r.attn_latent, r.attn.x);
|
||||
RAD_ARCH_TRY(rows_quant.declare(b, g, r.attn, 16384));
|
||||
rows_output.stored = nm.f("blk.%d.attn_output.weight", layer);
|
||||
RAD_ARCH_TRY(rows_output.declare(b, nm, g, nm.f("blk.%d.attn_output_rows", layer), 4096,
|
||||
16384, RAD_SHARD_NONE, wg,
|
||||
{ nm.ckpt("%s.o_proj.weight", prefix) }, r.attn, r.out,
|
||||
R));
|
||||
op_rows_gather = rw(b,
|
||||
RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", 4096, g.max_tok * 4096),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ r.out }, { w.out });
|
||||
return op_rows_absorb && op_rows_attn && op_rows_expand && op_rows_gather ? RAD_OK
|
||||
: RAD_E_INVAL;
|
||||
}
|
||||
/* From the TP split threshold, and while the last rank's run is not empty (always at that
|
||||
* threshold for up to 8 ranks); the same answer on every rank, as the gather needs. */
|
||||
bool rows_take(int64_t T) const {
|
||||
return op_rows_gather && GlmTp::splits(T, g.world) &&
|
||||
(g.world - 1) * rows_for(T, g.world) < T;
|
||||
}
|
||||
void prepare(RadCtx* ctx, const RadBatch* batch) const {
|
||||
const auto* kb = kv_batch(batch, kv);
|
||||
@@ -173,17 +282,78 @@ struct GlmMla {
|
||||
kv_a.step(ctx, w.input, w.kv_raw, T);
|
||||
q_norm.step(ctx, T);
|
||||
RAD_ISSUE_N(ctx, op_kv_norm, T, brows(w.kv_raw, T), RAD_W(kv_gain), brows(w.latent, T));
|
||||
q_b.step(ctx, w.q_low, w.core.q, T);
|
||||
/* The row form splits the query projection into finish_rows (per rank), so q_b runs here
|
||||
* only in the head form; the latent store below is full length either way. */
|
||||
if (!rows_take(T)) q_b.step(ctx, w.q_low, w.core.q, T);
|
||||
if (!kb->stream) {
|
||||
RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T),
|
||||
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
|
||||
return;
|
||||
}
|
||||
/* A streamed group writes its host mirror, and the ring slot only where the block is
|
||||
* resident; the stage wait goes immediately before the store (core/kvstream/stage.h). A
|
||||
* staged pass also stores at block-id identity, which is how the stage view is read. */
|
||||
const bool staged = kv_stage_wait(ctx, kv, kb, layer);
|
||||
const KVStreamLayer L = kv_stream_layer(ctx, kv, layer, kb);
|
||||
if (!op_store_stream || !L.host || L.blocks <= 0) {
|
||||
rad_step_fail(ctx, "GLM MLA: this layer's KV group streams but the build has no "
|
||||
"kv_store_streamed row to write its host mirror with");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(ctx, op_store_stream, T, bcol(w.latent, 0, 256, T),
|
||||
bcol(w.latent, 256, 256, T), praw(kb->slot_mapping, RAD_I32, T),
|
||||
kv_cache(kv, layer), praw(L.res, RAD_I32, L.blocks),
|
||||
praw2(L.host, RAD_U8, L.blocks, L.bbytes));
|
||||
if (staged)
|
||||
RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T),
|
||||
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
|
||||
}
|
||||
void finish(RadCtx* ctx, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const auto* kb = kv_batch(batch, kv);
|
||||
/* A streamed group's selection is resolved here, after this layer's indexer wrote fresh
|
||||
* block ids into the one `selected` buffer every layer shares and before either form of
|
||||
* the attention reads it. A pass on the stage view reads block ids and never resolves. */
|
||||
if (kb && kb->stream && !kv_stage_layer(ctx, kv, kb, layer) && T > 0) {
|
||||
const KVStreamLayer L = kv_stream_layer(ctx, kv, layer, kb);
|
||||
if (!op_resolve || !w.core.nsel || !L.host || L.blocks <= 0 || L.slots <= 0) {
|
||||
rad_step_fail(ctx, "GLM MLA: this layer's KV group streams but the build has no "
|
||||
"kv_resolve for its selection");
|
||||
return;
|
||||
}
|
||||
/* The count is qsa_select's entry count, never `length` (a token count). */
|
||||
kv_resolve_issue(ctx, op_resolve, L, brow_slice(w.core.selected, 0, T, core.c.blocks),
|
||||
brow_slice(w.core.nsel, 0, T, 1), kv, layer, T);
|
||||
}
|
||||
if (rows_take(T)) {
|
||||
finish_rows(ctx, T);
|
||||
} else {
|
||||
core.step(ctx, T);
|
||||
attn_quant.step(ctx, T);
|
||||
output.step(ctx, w.attn, w.out, T);
|
||||
if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE);
|
||||
}
|
||||
/* After every attention launch of this layer (core/kvstream/stage.h). */
|
||||
if (kb && kb->stream) kv_stage_next(ctx, kv, layer);
|
||||
}
|
||||
/* This rank's rows [first, first + n) end to end; the last rank's run may be short, and the
|
||||
* gather sends its unwritten tail rows, which land past T. */
|
||||
void finish_rows(RadCtx* ctx, int64_t T) const {
|
||||
const auto& r = w.rows;
|
||||
const GlmTp::Run run = GlmTp::run_of(T, g.world, g.rank, kOutRowBytes);
|
||||
const int64_t first = run.first, n = run.rows;
|
||||
rows_q_b.step(ctx, w.q_low, r.q, T, first, n, 0);
|
||||
RAD_ISSUE_N(ctx, op_rows_absorb, n, brows(r.q, n), RAD_W(rows_kv_b), brows(r.q_latent, n));
|
||||
RAD_ISSUE_N(ctx, op_rows_attn, n, brows(r.q_latent, n), kv_cache(kv, layer),
|
||||
brow_slice(w.core.selected, first, n, core.c.blocks),
|
||||
brow_slice(w.core.length, first, n, 1), brows(r.attn_latent, n));
|
||||
RAD_ISSUE_N(ctx, op_rows_expand, n, brows(r.attn_latent, n), RAD_W(rows_kv_b),
|
||||
brows(r.attn.x, n));
|
||||
rows_quant.step(ctx, n);
|
||||
rows_output.step(ctx, r.attn, r.out, n);
|
||||
RAD_ISSUE_N(ctx, op_rows_gather, run.run * 4096, brows(r.out, run.run),
|
||||
brows(w.out, g.world * run.run));
|
||||
}
|
||||
};
|
||||
}
|
||||
} // namespace rad::arch
|
||||
|
||||
@@ -52,9 +52,9 @@ struct MlpFP8 {
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
/* gate_up with the gate and quantiser in its epilogue, so the [M, 2*n_ff] bf16 product is
|
||||
* never written (unfused, the extra launch and second pass are a sizeable decode cost).
|
||||
* Declared beside the pair, not instead of it: the fold is the narrow tile's epilogue and
|
||||
* serves M <= 64, so prefill chunks take the pair. Byte-identical, as r4d_selftest and
|
||||
* ref_test check. */
|
||||
* Declared beside the pair, not instead of it: the narrow fold serves M <= 64, so prefill
|
||||
* chunks take the pair -- unless the model asked for `wide_fold`, whose row serves every M.
|
||||
* Byte-identical, as r4d_selftest and ref_test check. */
|
||||
rad_op op_gated = 0;
|
||||
int64_t gated_rows = 0;
|
||||
/* The next block absorbs this block's closing all-reduce, so this one must not issue it.
|
||||
@@ -67,19 +67,37 @@ struct MlpFP8 {
|
||||
/* `fold`: a predecessor's delta is still in `w.h.x` and this norm does its residual add
|
||||
* (false for the first block of a chain). `add_out`: issue the trailing add here. See
|
||||
* rad_fp8.h. */
|
||||
/* `wide_fold`: declare the gated fold over the whole prompt (gemm_nt_q_gated_wide, whose row
|
||||
* serves every M) rather than the narrow row's 64-row band. Set by a model that runs whole
|
||||
* prompts through the fold; every other caller keeps the band and the pair past it. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
const Src& src, bool fold = false, bool add_out = true,
|
||||
int ar_in = kArNone, bool ar_out_ = false, double swiglu_limit = 0);
|
||||
int ar_in = kArNone, bool ar_out_ = false, double swiglu_limit = 0,
|
||||
bool wide_fold = false);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
/* The block over the first `T` rows of its buffers (see MoeFP8::step_rows). */
|
||||
void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); }
|
||||
/* One row slice of the whole block; `rows <= 0` means the rest of the step. */
|
||||
void slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
|
||||
/* The slice in its parts, for a caller that runs the norm and the tail elsewhere (qwen35_fp8's
|
||||
* pipelined prefill puts both on the second lane): the projections from the normed input to
|
||||
* the delta in `w.h.x`, then the all-reduce and add this block issues itself. */
|
||||
void body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
|
||||
void tail(RadCtx* c, int64_t r0, int64_t rows) const;
|
||||
/* The block's all-reduce over rows [r0, r0 + rows) of the output, at `overlap` where declared
|
||||
* (a caller that runs it beside other work). */
|
||||
void issue_ar(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
RAD_ISSUE_N(c, op_ar_ov ? op_ar_ov : op_ar, rows * g.n_embd,
|
||||
brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
|
||||
}
|
||||
/* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
|
||||
int ar_overlap = 0;
|
||||
rad_op op_ar_ov = 0;
|
||||
};
|
||||
|
||||
inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
const Src& src, bool fold, bool add_out,
|
||||
int ar_in, bool ar_out_, double swiglu_limit) {
|
||||
int ar_in, bool ar_out_, double swiglu_limit, bool wide_fold) {
|
||||
g = geom; w = wire; layer = l;
|
||||
ar_out = ar_out_;
|
||||
|
||||
@@ -105,17 +123,26 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
down.reads_x && !(w.ffn.q8_fed && down.probed_i8), false,
|
||||
swiglu_limit));
|
||||
|
||||
/* The fold (decl_gated_fold), an fp8a8 tile, so bf16, f32-scaled, MXFP4, rotated 5-bit, 4-bit
|
||||
* and int8 gate_up weights take the pair, and so does a clamped (swiglu_limit) product.
|
||||
* Declared over int8 codes, only a host kernel would take it, and that would pin the layer's
|
||||
* weights to the host. */
|
||||
if (swiglu_limit <= 0 && !gate_up.bf16 && !gate_up.f32_scale && !gate_up.mx &&
|
||||
!gate_up.m2x && !gate_up.paro5 && !gate_up.w4 && !gate_up.i8)
|
||||
/* The fold: decl_gated_fold (an fp8a8 tile) for block-fp8 weights, decl_gated_fold_mx for plain
|
||||
* MXFP4 at one to 16 rows (eight where K is short). Other gate_up encodings (M2XFP4 included),
|
||||
* and a clamped (swiglu_limit) product, take the pair. Over int8 codes only a host kernel would
|
||||
* take it, which would pin the layer's weights to the host. */
|
||||
const bool fold_ok = swiglu_limit <= 0 && !gate_up.f32_scale;
|
||||
if (fold_ok && !gate_up.bf16 && !gate_up.mx && !gate_up.m2x && !gate_up.paro5 && !gate_up.w4 &&
|
||||
!gate_up.i8)
|
||||
op_gated = decl_gated_fold(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
|
||||
{ w.h.q, w.h.s },
|
||||
gq_ffn.want_x
|
||||
? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s, w.ffn.x }
|
||||
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s },
|
||||
&gated_rows, wide_fold);
|
||||
else if (fold_ok && gate_up.mx && !gate_up.paro)
|
||||
op_gated = decl_gated_fold_mx(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
|
||||
gate_up.wref, { w.h.q, w.h.s },
|
||||
gq_ffn.want_x
|
||||
? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s,
|
||||
w.ffn.x }
|
||||
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s },
|
||||
&gated_rows);
|
||||
RAD_ARCH_TRY(down.declare(b, nm, g, down_base,
|
||||
g.n_embd, g.n_ff, RAD_SHARD_COL, grp_layer(l),
|
||||
@@ -129,6 +156,17 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
/* The same collective for a caller that runs it beside other work (issue_ar): at `overlap` 1
|
||||
* it gets the rows that hold fewer CUs while waiting on the link. */
|
||||
if (g.world > 1 && ar_overlap > 0)
|
||||
op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes),
|
||||
RAD_INT("overlap", ar_overlap)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
|
||||
/* Only when the next block's norm will not add (rad_fp8.h: NormQuantFP8). */
|
||||
if (add_out)
|
||||
@@ -149,7 +187,18 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (rows <= 0) rows = T - r0;
|
||||
nq_h.step(c, T, r0, rows);
|
||||
if (op_gated && rows <= gated_rows) {
|
||||
body(c, T, r0, rows);
|
||||
tail(c, r0, rows);
|
||||
}
|
||||
|
||||
inline void MlpFP8::body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (op_gated && rows <= gated_rows && gate_up.mx) {
|
||||
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd),
|
||||
brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
|
||||
RAD_W(gate_up.ws), RAD_W(gate_up.wref), brow_slice(w.ffn.q, r0, rows, g.n_ff),
|
||||
brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK),
|
||||
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
|
||||
} else if (op_gated && rows <= gated_rows) {
|
||||
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd),
|
||||
brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
|
||||
RAD_W(gate_up.ws), brow_slice(w.ffn.q, r0, rows, g.n_ff),
|
||||
@@ -160,6 +209,9 @@ inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const
|
||||
gq_ffn.step(c, w.gate_up, T, r0, rows);
|
||||
}
|
||||
down.step(c, w.ffn, w.h.x, T, r0, rows);
|
||||
}
|
||||
|
||||
inline void MlpFP8::tail(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
if (op_ar && !(ar_out && ar_fused_ok(g, rows)))
|
||||
RAD_ISSUE_N(c, op_ar, rows * g.n_embd, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
|
||||
if (op_add)
|
||||
|
||||
+136
-42
@@ -189,6 +189,13 @@ struct MoeFP8 {
|
||||
int swiglu_quant = 0;
|
||||
/* A shared arm without its sigmoid gate: the gate plane is filled with 1. */
|
||||
int shared_ungated = 0;
|
||||
/* At TP1 the caller may fill the ungated arm's ones plane once for the whole step,
|
||||
* rather than each layer/pass filling the same plane again. */
|
||||
int shared_one_external = 0;
|
||||
/* Add the already-rounded routed and shared BF16 outputs in FP32, then round to BF16.
|
||||
* At TP1 the ungated gather preserves both roundings; TP>1 reduces each arm separately
|
||||
* before combining, so its gather cannot fold the shared output. */
|
||||
int shared_fp32_combine = 0;
|
||||
/* 4-bit experts (`i4*bf16[1x128]`) rather than E4M3 (`fp8_e4m3*bf16[128x128]`); for
|
||||
* Qwen3.8-Flash-Next this decides whether the model fits two cards (see the `moe_gemm_w4a8`
|
||||
* registry row). It is the stored encoding: probe() reads it from the first expert's
|
||||
@@ -278,7 +285,7 @@ struct MoeFP8 {
|
||||
ActFP8 eff{}; /* [rows * top_k, n_ff_exp] */
|
||||
rad_buf edn = 0; /* [rows * top_k, n_embd] bf16, in sorted order */
|
||||
/* back in token order, and the shared expert, one row per token */
|
||||
rad_buf moe = 0; /* [max_tok, n_embd] bf16 */
|
||||
rad_buf moe = 0; /* [max_tok, n_embd] bf16; separate routed output if needed */
|
||||
rad_buf sgu = 0; /* [max_tok, 2 * n_ff_shared] bf16 */
|
||||
ActFP8 sff{}; /* [max_tok, n_ff_shared] */
|
||||
rad_buf sout = 0; /* [max_tok, n_embd] bf16 */
|
||||
@@ -306,6 +313,13 @@ struct MoeFP8 {
|
||||
* already fused gate rows first, as this block wants. */
|
||||
const char* experts_gate_up = nullptr;
|
||||
const char* experts_down = nullptr;
|
||||
/* Some GGUF writers retain gate and up as separate stacked tensors. These three fields
|
||||
* describe that layout; each expert's gate/up slices are fused at conversion. */
|
||||
const char* experts_gate = nullptr;
|
||||
const char* experts_up = nullptr;
|
||||
const char* shared_mlp_gate = nullptr;
|
||||
const char* shared_mlp_up = nullptr;
|
||||
const char* shared_mlp_down = nullptr;
|
||||
const char* shared_gate = nullptr; /* mlp.shared_expert_gate.weight, [1, n_embd] */
|
||||
};
|
||||
|
||||
@@ -413,6 +427,8 @@ struct MoeFP8 {
|
||||
mutable bool calib_dne_failed = false;
|
||||
void calib_experts_pass(RadCtx* c_, int64_t slots) const;
|
||||
rad_op op_sgate = 0;
|
||||
rad_op op_combine = 0; /* BF16 inputs, FP32 addition, one BF16 rounding */
|
||||
rad_op op_moe_ar = 0, op_shared_ar = 0;
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
bool ar_out = false;
|
||||
/* Which wires the consumer of this block's all-reduce takes. Set before declare; see
|
||||
@@ -530,21 +546,30 @@ inline int moe_expert_sources(RadBuilder* b, Names& nm, const char* tag, const c
|
||||
|
||||
/* The gate_up and down name maps of one expert: a dim-0 slice of the stacked tensors, or the
|
||||
* checkpoint's per-expert gate and up joined along rows. `gate_up` false maps down alone. */
|
||||
inline int moe_map_gate_up(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw,
|
||||
long long ge) {
|
||||
if (src.experts_gate_up) return map_slice(b, guw, src.experts_gate_up, (int)ge);
|
||||
if (src.experts_gate && src.experts_up)
|
||||
return map_slice_concat(b, guw, {src.experts_gate, src.experts_up}, (int)ge);
|
||||
return map_concat(b, guw, {nm.ckpt("%s.%lld.gate_proj.weight", src.experts, ge),
|
||||
nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge)});
|
||||
}
|
||||
|
||||
inline int moe_map_expert(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw,
|
||||
const char* dnw, long long ge, bool gate_up) {
|
||||
if (src.experts_gate_up) {
|
||||
/* The slice index is global: the checkpoint holds every expert. */
|
||||
if (gate_up) RAD_ARCH_TRY(map_slice(b, guw, src.experts_gate_up, (int)ge));
|
||||
if (gate_up) RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge));
|
||||
if (src.experts_gate_up || src.experts_gate)
|
||||
return map_slice(b, dnw, src.experts_down, (int)ge);
|
||||
}
|
||||
const char* gate = nm.ckpt("%s.%lld.gate_proj.weight", src.experts, ge);
|
||||
const char* up = nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge);
|
||||
if (gate_up) RAD_ARCH_TRY(map_concat(b, guw, { gate, up }));
|
||||
return map_copy(b, dnw, nm.ckpt("%s.%lld.down_proj.weight", src.experts, ge));
|
||||
}
|
||||
|
||||
inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config* cfg) {
|
||||
if (!cfg || (!src.experts && !src.experts_gate_up)) return RAD_E_INVAL;
|
||||
if (!cfg || (!src.experts && !src.experts_gate_up && !src.experts_gate)) return RAD_E_INVAL;
|
||||
const bool split_stack = src.experts_gate || src.experts_up;
|
||||
if ((src.experts_gate_up && split_stack) ||
|
||||
(split_stack && (!src.experts_gate || !src.experts_up || !src.experts_down ||
|
||||
src.experts)) ||
|
||||
(src.experts_gate_up && (!src.experts_down || src.experts))) return RAD_E_INVAL;
|
||||
/* The caller names the expert in model numbering (the first this rank owns under expert
|
||||
* parallelism); declare() skips the ones mapped here.
|
||||
*
|
||||
@@ -559,9 +584,7 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
|
||||
int f = 0;
|
||||
for (long long ge = g0; ge < gn && ge <= g0 + kMaxProtected; ++ge) {
|
||||
const char* guw = nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, ge);
|
||||
if (src.experts_gate_up) RAD_ARCH_TRY(map_slice(b, guw, src.experts_gate_up, (int)ge));
|
||||
else RAD_ARCH_TRY(map_concat(b, guw, { nm.ckpt("%s.%lld.gate_proj.weight", src.experts, ge),
|
||||
nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge) }));
|
||||
RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge));
|
||||
cfg->probed_count = ge - g0 + 1;
|
||||
RadEncoding e{};
|
||||
f = 0;
|
||||
@@ -604,8 +627,18 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
if (c.rows <= 0) c.rows = g.max_tok;
|
||||
/* A rank whose slice of the shared arm is empty (see Config) declares no arm, and the
|
||||
* all-reduce carries the others' share. */
|
||||
const bool shared = c.n_ff_shared > 0 && src.shared;
|
||||
const bool split_shared = src.shared_mlp_gate || src.shared_mlp_up || src.shared_mlp_down;
|
||||
if (split_shared && (!src.shared_mlp_gate || !src.shared_mlp_up || !src.shared_mlp_down ||
|
||||
src.shared)) return RAD_E_INVAL;
|
||||
const bool shared = c.n_ff_shared > 0 && (src.shared || src.shared_mlp_gate);
|
||||
if (shared && c.shared_ungated && src.shared_gate) return RAD_E_INVAL;
|
||||
if (c.shared_one_external && (!shared || !c.shared_ungated || !w.sgate || g.world != 1))
|
||||
return RAD_E_INVAL;
|
||||
if (c.shared_fp32_combine && (!shared || !w.moe || std::strcmp(g.dtype, "bf16"))) {
|
||||
fprintf(stderr, "radiance: layer %d requests an FP32 shared/routed combine without its "
|
||||
"BF16 shared arm and routed output\n", l);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Whether `w.sgate` is excluded from buffer sharing; set with the shared arm and required by
|
||||
* the fused router's gate write (see there). */
|
||||
bool sgate_concurrent = false;
|
||||
@@ -793,12 +826,16 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
{w.logits}, {w.ids, w.ew, w.sorted, w.eoff, w.ecnt});
|
||||
}
|
||||
|
||||
/* Exactly one of a prefix or the two stacked tensors. */
|
||||
const bool stacked = src.experts_gate_up != nullptr;
|
||||
if (stacked != (src.experts_down != nullptr) || (stacked == (src.experts != nullptr))) {
|
||||
fprintf(stderr, "radiance: a routed feed-forward takes EITHER an `experts` prefix or "
|
||||
"both stacked tensors; got prefix %s, gate_up %s, down %s\n",
|
||||
/* Exactly one of a per-expert prefix, fused stacked gate_up, or separate stacked gate/up. */
|
||||
const bool split_stack = src.experts_gate || src.experts_up;
|
||||
const bool stacked = src.experts_gate_up || split_stack;
|
||||
if ((src.experts_gate_up && split_stack) ||
|
||||
(split_stack && (!src.experts_gate || !src.experts_up)) ||
|
||||
stacked != (src.experts_down != nullptr) || (stacked == (src.experts != nullptr))) {
|
||||
fprintf(stderr, "radiance: a routed feed-forward needs a per-expert prefix or complete "
|
||||
"stacked expert tensors; prefix %s, gate_up %s, gate %s, up %s, down %s\n",
|
||||
src.experts ? "yes" : "no", src.experts_gate_up ? "yes" : "no",
|
||||
src.experts_gate ? "yes" : "no", src.experts_up ? "yes" : "no",
|
||||
src.experts_down ? "yes" : "no");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
@@ -1287,12 +1324,15 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
if (!b_gram_dne || !op_gram_dne) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* The gather folds the shared arm in, so `w.moe` is never written; `scale_rows` plus a
|
||||
* separate gather would be two dispatches per layer and a 160 KiB round trip. */
|
||||
gfold = shared;
|
||||
/* The gather rounds the routed sum to BF16 before adding the rounded shared product.
|
||||
* At TP1 a unity gate therefore preserves HYV3's FP32 combine exactly. TP>1 must first
|
||||
* reduce each arm independently, and cannot combine them inside the local gather. */
|
||||
const bool separate_fp32_combine = shared && c.shared_fp32_combine &&
|
||||
(g.world > 1 || !c.shared_ungated);
|
||||
gfold = shared && !separate_fp32_combine;
|
||||
for (int form = scatter_inv ? 0 : 1; form < 2 && !op_gather; ++form) {
|
||||
rad_buf grd[5] = { w.edn, w.ew, form ? w.sorted : w.inv, w.sout, w.sgate };
|
||||
rad_buf gwr[1] = { w.h.x };
|
||||
rad_buf gwr[1] = { separate_fp32_combine ? w.moe : w.h.x };
|
||||
op_gather = RAD_OP(b, form ? "moe_gather" : "moe_gather_inv",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("top_k", c.top_k), RAD_STR("dtype", g.dtype),
|
||||
@@ -1314,8 +1354,16 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
/* Probe the down projection first: what it reads (codes, or the bf16 plane for a plain
|
||||
* weight) decides what the gate writes. */
|
||||
const char* down_base = nm.f("blk.%d.ffn_down_shexp", l);
|
||||
RAD_ARCH_TRY(sh_down.probe(b, nm, g, down_base,
|
||||
{ nm.ckpt("%s.down_proj.weight", src.shared) }));
|
||||
const char* shared_down = src.shared_mlp_down
|
||||
? src.shared_mlp_down
|
||||
: nm.ckpt("%s.down_proj.weight", src.shared);
|
||||
const char* shared_gate = src.shared_mlp_gate
|
||||
? src.shared_mlp_gate
|
||||
: nm.ckpt("%s.gate_proj.weight", src.shared);
|
||||
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 }));
|
||||
/* 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()) {
|
||||
@@ -1335,8 +1383,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
* gate/up row parts stay, as a property of the stacked checkpoint tensor. */
|
||||
RAD_ARCH_TRY(sh_gate_up.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up_shexp", l),
|
||||
2 * c.n_ff_shared, g.n_embd, RAD_SHARD_ROW, grp_layer(l),
|
||||
{ nm.ckpt("%s.gate_proj.weight", src.shared),
|
||||
nm.ckpt("%s.up_proj.weight", src.shared) },
|
||||
{ shared_gate, shared_up },
|
||||
w.h, w.sgu, c.rows,
|
||||
{ c.n_ff_shared, c.n_ff_shared },
|
||||
c.shared_lo, c.shared_hi));
|
||||
@@ -1347,7 +1394,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
c.swiglu_limit));
|
||||
RAD_ARCH_TRY(sh_down.declare(b, nm, g, down_base,
|
||||
g.n_embd, c.n_ff_shared, RAD_SHARD_COL, grp_layer(l),
|
||||
{ nm.ckpt("%s.down_proj.weight", src.shared) },
|
||||
{ shared_down },
|
||||
w.sff, w.sout, c.rows, {},
|
||||
c.shared_lo, c.shared_hi));
|
||||
/* The shared gate, replicated like the router so every rank computes the same gate. One
|
||||
@@ -1371,6 +1418,18 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
}
|
||||
}
|
||||
|
||||
if (separate_fp32_combine) {
|
||||
/* BF16 add widens both inputs to FP32, adds, then rounds once to BF16: the same bytes as
|
||||
* cast + cast + F32 add + cast. The routed gather's BF16 rounding and the separate TP
|
||||
* reductions stay; a local gather cannot fold those reductions. */
|
||||
op_combine = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.moe, w.sout}, {w.h.x});
|
||||
if (!op_combine) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- The router GEMM and `router_topk_scatter` as one op, plus the shared gate when the
|
||||
* layer has one; up to the pair's row bound and the skinny GEMM's decode band. Unresolved, the
|
||||
* separate ops run. Declared here, after the gate weight, because it names both weights;
|
||||
@@ -1426,7 +1485,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
} else {
|
||||
sigmoid_scatter_rows = (int64_t)c.rows * c.top_k <= kMoeSortRows
|
||||
? c.rows : kMoeSortRows / c.top_k;
|
||||
const bool gate = op_sgate != 0 && c.shared_ungated;
|
||||
const bool gate = op_sgate != 0 && c.shared_ungated && !c.shared_fp32_combine;
|
||||
if (gate && !sgate_concurrent) {
|
||||
fprintf(stderr, "radiance: layer %d: the fused selection writes the shared gate "
|
||||
"ahead of its declared writer, which needs `sgate` out of the "
|
||||
@@ -1456,14 +1515,25 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
}
|
||||
}
|
||||
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
if (g.world > 1) {
|
||||
const auto all_reduce = [&](const char* dtype, rad_buf buffer) {
|
||||
return rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_STR("dtype", dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
{buffer}, {buffer});
|
||||
};
|
||||
if (separate_fp32_combine) {
|
||||
/* Each arm is a tensor-parallel partial. Reduce the BF16 arm outputs independently,
|
||||
* then perform HYV3's shared+routed addition in F32 before the final BF16 cast. */
|
||||
op_moe_ar = all_reduce(g.dtype, w.moe);
|
||||
op_shared_ar = all_reduce(g.dtype, w.sout);
|
||||
} else {
|
||||
op_ar = all_reduce(g.dtype, w.h.x);
|
||||
}
|
||||
}
|
||||
/* The same collective for a caller that runs it beside other work (issue_ar, a pipelined
|
||||
* prefill): at `overlap` 1 it gets the rows that hold fewer CUs while waiting on the link. */
|
||||
if (g.world > 1 && ar_overlap > 0)
|
||||
@@ -1512,12 +1582,16 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
* buffers are step-tall, so the pass offset applies as in an MlpFP8 slice. */
|
||||
inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows,
|
||||
bool gate_done) const {
|
||||
/* `gate_done`: the fused router already wrote this pass's gate. */
|
||||
if (!gate_done && c.shared_ungated)
|
||||
/* `gate_done`: the fused router already wrote this pass's gate. A separate FP32 combine
|
||||
* reads no ones plane. At TP1 an ungated folded gather does, unless the caller prepared the
|
||||
* whole step's ones plane once (shared_one_external). */
|
||||
if (!gate_done && c.shared_ungated) {
|
||||
if (gfold && !c.shared_one_external)
|
||||
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.sgate, r0, rows, 1));
|
||||
else if (!gate_done)
|
||||
} else if (!gate_done) {
|
||||
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_sgate),
|
||||
brow_slice(w.sgate, r0, rows, 1));
|
||||
}
|
||||
sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows);
|
||||
}
|
||||
|
||||
@@ -1547,10 +1621,13 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
* (rad_expert_prefetch). A failure only loses the prediction. */
|
||||
if (xp_next && xp_next->xp.n_parts > 0)
|
||||
(void)rad_expert_prefetch(c_, &xp_next->xp, w.h.x, r0, rows, g.n_embd);
|
||||
/* Write the routing counts straight into the core's row for this layer when it keeps one, so
|
||||
* the report in step() needs no copy (otherwise a dependent blit per routed layer). */
|
||||
int32_t* const counts = rad_route_counts(c_, layer, ne);
|
||||
const RadOperand ecnt = counts ? praw(counts, RAD_I32, ne) : brows(w.ecnt, ne);
|
||||
/* Bind the block's own ecnt buffer, never the core's raw routing row: a raw-pointer operand
|
||||
* does not survive the step tape's replay (the decode path re-issues ops from the tape), so
|
||||
* 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 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;
|
||||
@@ -1717,11 +1794,21 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
|
||||
/* The gather last, since with the fold it reads the shared arm (`sout`, `sgate`); it writes
|
||||
* the block's delta into `h.x`. */
|
||||
if (!gather_taken(g, T, gather_out_rows, gather_out_rows6))
|
||||
if (op_combine || !gather_taken(g, T, gather_out_rows, gather_out_rows6))
|
||||
RAD_ISSUE_N(c_, op_gather, rows, brows(w.edn, rows * k), brow_slice(w.ew, r0, rows, k),
|
||||
brows(gather_inv ? w.inv : w.sorted, rows * k),
|
||||
gfold ? brow_slice(w.sout, r0, rows, g.n_embd) : RAD_NONE,
|
||||
gfold ? brow_slice(w.sgate, r0, rows, 1) : RAD_NONE,
|
||||
brow_slice(op_combine ? w.moe : w.h.x, r0, rows, g.n_embd));
|
||||
if (op_moe_ar)
|
||||
RAD_ISSUE_N(c_, op_moe_ar, rows * g.n_embd,
|
||||
brow_slice(w.moe, r0, rows, g.n_embd), RAD_NONE);
|
||||
if (op_shared_ar)
|
||||
RAD_ISSUE_N(c_, op_shared_ar, rows * g.n_embd,
|
||||
brow_slice(w.sout, r0, rows, g.n_embd), RAD_NONE);
|
||||
if (op_combine)
|
||||
RAD_ISSUE_N(c_, op_combine, rows, brow_slice(w.moe, r0, rows, g.n_embd),
|
||||
brow_slice(w.sout, r0, rows, g.n_embd),
|
||||
brow_slice(w.h.x, r0, rows, g.n_embd));
|
||||
|
||||
/* A write that takes the all-reduce does it once for the whole step, deciding on T, so this
|
||||
@@ -1800,12 +1887,19 @@ inline void MoeFP8::route_report(RadCtx* c_) const {
|
||||
* `expert_w` stays null: RadRouting declares it `const float*` but these weights are bf16
|
||||
* (f32 under the sigmoid router). Nothing in the core reads it (the heat engine uses
|
||||
* `expert_count`). */
|
||||
/* The router kernel writes the block's own ecnt buffer (w.ecnt) every pass, so report THAT
|
||||
* pointer: a consumer reading it stream-ordered (the file stager's trigger runs after this
|
||||
* layer's router on the same stream) sees this pass's counts. Reporting rad_route_counts'
|
||||
* row instead names a buffer the router never writes; the pointer then equals the report's
|
||||
* 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. */
|
||||
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;
|
||||
const int32_t* const counts = rad_route_counts(c_, layer, c.n_expert);
|
||||
r.expert_count = counts ? counts : (const int32_t*)rad_buf_ptr(c_, w.ecnt);
|
||||
r.expert_count = (const int32_t*)rad_buf_ptr(c_, w.ecnt);
|
||||
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;
|
||||
|
||||
@@ -73,6 +73,7 @@
|
||||
#include "rad_block_hc.h"
|
||||
#include "rad_block_moe_fp8.h"
|
||||
#include "rad_block_mtp_fp8.h" /* mtp_draft_head_q2(): one reading of the 2-bit head */
|
||||
#include "rad_spechub.h" /* RAD_MTP_COUPLE_*: the coupling wire */
|
||||
#include "rad_qsa.h"
|
||||
#include "rad_block_vit.h"
|
||||
|
||||
@@ -108,6 +109,9 @@ struct MtpHcBlock {
|
||||
/* Vocab-parallel pairs, declared only when the head is sharded: (int32 id, f32 value)
|
||||
* pairs stored as f32, this rank's top-R and the all-gathered world * R. */
|
||||
rad_buf dpair = 0, dgath = 0;
|
||||
/* --draft-coupling: [max_seqs] draws and [depth, max_seqs] states, both PERSIST across
|
||||
* the serial passes (round 1 resets the logical stream, not the plane). */
|
||||
rad_buf couple_draws = 0, couple_state = 0;
|
||||
AttnGatedFP8::Wire attn{};
|
||||
MoeFP8::Wire mlp{};
|
||||
QsaIndexer::Wire qsa{};
|
||||
@@ -158,6 +162,9 @@ struct MtpHcBlock {
|
||||
rad_op op_dsel = 0, op_dback = 0;
|
||||
rad_op op_logits = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0, op_drerank = 0;
|
||||
rad_op op_dgather = 0, op_dmerge = 0;
|
||||
/* --draft-coupling: one op a round. The ABI freezes `round` as a parameter, so a round
|
||||
* cannot be an operand and each gets its own declared op. */
|
||||
rad_op op_couple[RAD_MTP_COUPLE_MAX_ROUNDS] = {};
|
||||
|
||||
/* rad_arch.h's vocab-head rule, asked through the block by whoever sizes `dlog` and the pair
|
||||
* planes. */
|
||||
@@ -422,6 +429,25 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
if (!op_dgather || !op_dmerge) return RAD_E_INVAL;
|
||||
}
|
||||
if (!op_dquant || !op_dlogits || !op_dtopk) return RAD_E_INVAL;
|
||||
/* The coupled proposal: one op a round, after the final rerank/merge, over the shortlist
|
||||
* whose column 0 is the proposal. Linear chains only: x is a token, while a tree reads
|
||||
* column 0 as a parent index. The engine refuses other drafters; this check keeps a
|
||||
* mismatched declaration from writing tokens into a tree plane. */
|
||||
if (w.couple_draws || w.couple_state) {
|
||||
if (!w.couple_draws || !w.couple_state || depth < 1 ||
|
||||
depth > RAD_MTP_COUPLE_MAX_ROUNDS || !op_drerank || (g.world > 1 && !op_dmerge))
|
||||
return RAD_E_UNSUPPORTED;
|
||||
for (int round = 1; round <= depth; ++round) {
|
||||
op_couple[round - 1] = rw(b, RAD_OP(b, "mtp_couple_propose",
|
||||
/* The whole vocabulary: `row_topk` reports global ids and the merge keeps
|
||||
* them, while `g.n_vocab` is this rank's shard. */
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("round", round), RAD_INT("max_rounds", depth)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.didx, w.dval, w.couple_draws }, { w.didx, w.couple_state });
|
||||
if (!op_couple[round - 1]) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Keep the carry `hin` live through the head's last op: it is written before the mixer and
|
||||
* lm_head run, and the planner could otherwise give its bytes to them (silently lowering
|
||||
@@ -429,6 +455,7 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
{
|
||||
rad_op last = op_logits;
|
||||
if (q2) last = op_dmerge ? op_dmerge : op_drerank ? op_drerank : op_dtopk;
|
||||
if (op_couple[0]) last = op_couple[depth - 1];
|
||||
if (rad_op_reads(b, last, &w.hin, 1) < 0) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
@@ -524,6 +551,19 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_ISSUE_N(c, op_drerank, L, brows(w.hout, L), RAD_W(w_lm), brows(w.didx, L),
|
||||
brows(w.didx, L), brows(w.dval, L), RAD_NONE);
|
||||
}
|
||||
/* After the final reranked shortlist: column 0 is what ADV_TAKE reads, and a sampled row
|
||||
* replaces it with its x. Round 1 runs in the history pass (r < 0), later rounds in their
|
||||
* own passes. */
|
||||
if (op_couple[0]) {
|
||||
const int round = r < 0 ? 1 : r;
|
||||
if (round < 1 || round > depth) {
|
||||
rad_step_fail(c, "MTP coupled round exceeds the declared draft depth");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, op_couple[round - 1], L, brows(w.didx, L), brows(w.dval, L),
|
||||
praw(batch->seq_ids, RAD_I32, batch->n_seq),
|
||||
brows(w.couple_draws, L), RAD_B(w.couple_state));
|
||||
}
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_logits, L, brows(w.hout, L), RAD_W(w_lm), brows(w.logits, L));
|
||||
}
|
||||
|
||||
@@ -106,10 +106,16 @@ struct PleLayer {
|
||||
rad_op op_gate = 0, op_conv = 0, op_add = 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
|
||||
* prompt, whose rows the gather's reader thread prefetches. Clamped to what `b_ids` holds, so
|
||||
* a larger offer only shortens the queue. */
|
||||
static constexpr int64_t kAheadChunks = 2;
|
||||
/* The prompt that follows the step, bounded by what `b_ids` holds after the step's rows. */
|
||||
int64_t ahead_rows(const RadBatch* batch) const {
|
||||
const int64_t a = batch->n_ahead;
|
||||
return a <= 0 ? 0 : (a < g.max_tok ? a : g.max_tok);
|
||||
if (a <= 0) return 0;
|
||||
const int64_t cap = kAheadChunks * g.max_tok;
|
||||
return a < cap ? a : cap;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg, int layer,
|
||||
@@ -172,7 +178,8 @@ 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); the gather takes them as two operands. The name map
|
||||
* recipe (data/recipes/qwen4exp-w4.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. */
|
||||
const char* tn = nm.f("blk.%d.ple_ngram.weight", layer);
|
||||
@@ -275,10 +282,11 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
* follows declared order, where the two ops are adjacent, so a transient could be overwritten
|
||||
* in between. */
|
||||
{
|
||||
/* Twice the step's rows: the step's ids, then those of the prompt that follows
|
||||
* (RadBatch::n_ahead), which the gather's reader prefetches while the step runs. */
|
||||
/* The step's rows, then kAheadChunks further steps of the following prompt
|
||||
* (RadBatch::n_ahead) for the reader to prefetch. */
|
||||
RadBufDecl d{};
|
||||
d.dtype = RAD_I32; d.rank = 2; d.shape[0] = 2 * g.max_tok; d.shape[1] = c.heads;
|
||||
d.dtype = RAD_I32; d.rank = 2;
|
||||
d.shape[0] = (1 + kAheadChunks) * g.max_tok; d.shape[1] = c.heads;
|
||||
d.kind = RAD_BUF_PERSIST; d.domain = RAD_DOMAIN_HOST;
|
||||
b_ids = rad_decl_buffer(b, nm.f("ple_ids"), &d);
|
||||
|
||||
|
||||
@@ -78,16 +78,33 @@ struct VisionTower {
|
||||
return rad_meta_geti(m, "vision_config.depth", 0) > 0;
|
||||
}
|
||||
|
||||
/* With `gate_weights`, a checkpoint or container without the tower's weights declares nothing
|
||||
* and leaves `on` false, for a model whose config names a tower its weights may not have. */
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group, bool deepstack = false);
|
||||
int64_t model_embd, int first_group, bool deepstack = false,
|
||||
bool gate_weights = false);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx,
|
||||
Names& nm, int64_t model_embd, int first_group, bool deepstack) {
|
||||
Names& nm, int64_t model_embd, int first_group, bool deepstack,
|
||||
bool gate_weights) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
|
||||
|
||||
/* Whether the stem is there: its map first, then its encoding, which convert answers from the
|
||||
* checkpoint and load from the container alike. A map left behind is inert. */
|
||||
if (gate_weights) {
|
||||
if (map_copy(b, nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight")) < 0)
|
||||
return RAD_E_INVAL;
|
||||
RadEncoding enc;
|
||||
if (rad_weight_encoding(b, nm.f("v.patch.weight"), &enc, nullptr, nullptr) != RAD_OK) {
|
||||
std::fprintf(stderr, "radiance: vision_config names a tower the checkpoint does not "
|
||||
"ship; declaring without it\n");
|
||||
return RAD_OK;
|
||||
}
|
||||
}
|
||||
|
||||
depth = rad_meta_geti(m, "vision_config.depth", 0);
|
||||
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
|
||||
heads = rad_meta_geti(m, "vision_config.num_heads", 0);
|
||||
@@ -173,7 +190,11 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, g);
|
||||
};
|
||||
w_patch = bw(nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight"),
|
||||
/* Mapped above with `gate_weights`. */
|
||||
w_patch = gate_weights
|
||||
? decl_w(b, nm.f("v.patch.weight"), RAD_BF16, { width, patch_dim },
|
||||
RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_model())
|
||||
: bw(nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight"),
|
||||
RAD_BF16, { width, patch_dim }, grp_model());
|
||||
b_patch = bw(nm.f("v.patch.bias"), nm.ckpt("model.visual.patch_embed.proj.bias"),
|
||||
RAD_BF16, { width }, grp_model());
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
/* rad_calib_full.h -- the whole Hessian of each linear's input in a dense bf16 trunk, under tensor
|
||||
* parallelism, recorded over a --calib-corpus run into --calib-dir (RadBuildCtx::calib_*).
|
||||
*
|
||||
* GPTQ needs H = sum over tokens of x x^T for the whole input x of a linear. A linear split by its
|
||||
* input columns across ranks (o_proj, the delta net's out_proj, down_proj) sees only its rank's
|
||||
* columns, and a Gram of those is one diagonal block of H: the products across ranks are never
|
||||
* formed on any card. So each such input is gathered to its whole width first (`all_gather`,
|
||||
* row-interleaved: rank r's columns land at r * width / world), and the Gram is taken of the whole
|
||||
* row. An input every rank holds whole (a norm's output) is read where it is.
|
||||
*
|
||||
* One rank records each layer (layer % world), so the Gram work and the host memory split
|
||||
* evenly. Its f32 scratch receives one step's sum for one input (`gram_accum` with `upper` 1: H is
|
||||
* symmetric and only k2 >= k1 is kept), whose upper triangle is copied to a pinned square and which
|
||||
* is zeroed for the next input, all in stream order. A worker thread waits on the copy's event and adds the square to a
|
||||
* host accumulator holding the upper triangle packed row by row (k(k+1)/2 f32), while the rank goes
|
||||
* on issuing the step: two squares alternate, so the rank waits only when the adds fall two Grams
|
||||
* behind. Syncing and adding on the rank's own thread instead left the card idle for every add, 16
|
||||
* of 1.2 GB a step on each rank of Qwen3.8-27B, and the ranks wait on each other at every
|
||||
* all-reduce. The host holds every recorded input of the rank: 786 MB a layer at Qwen3.8-27B,
|
||||
* which is what --calib-layers bounds. A step's sum is f32 over at most a step's
|
||||
* rows, and the host adds a few thousand of them; the consumer damps H by a percent of its trace,
|
||||
* far above that rounding.
|
||||
*
|
||||
* Files, written once the plugin has seen RadBuildCtx::calib_tokens rows (the whole corpus): one
|
||||
* safetensors file per input, <dir>/<stem>.safetensors, holding `hessian_upper`, f32
|
||||
* [k * (k + 1) / 2], row i's entries k2 = i .. k-1 after row i-1's, and metadata naming `k`, the
|
||||
* rows summed and the checkpoint linears that read the input. H is the raw sum; divide by `rows`
|
||||
* for the mean second moment. */
|
||||
#pragma once
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <condition_variable>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace rad::arch {
|
||||
|
||||
struct CalibFull {
|
||||
struct Site {
|
||||
std::string stem; /* the file's name, without .safetensors */
|
||||
std::string linears; /* the checkpoint linears that read this input, comma-separated */
|
||||
rad_buf local = 0; /* this rank's part of the input (the whole input when replicated) */
|
||||
int64_t K = 0; /* the whole input's width */
|
||||
int64_t k_local = 0; /* this rank's columns; K when replicated */
|
||||
rad_op op_gather = 0; /* the columns of every rank into `gathered`; 0 when replicated */
|
||||
rad_op op_gram = 0; /* declared on the owner only */
|
||||
bool owner = false;
|
||||
std::vector<float> tri; /* the owner's accumulator, upper triangle packed */
|
||||
};
|
||||
|
||||
bool on = false;
|
||||
const char* dir = nullptr;
|
||||
int rank = 0, world = 1;
|
||||
int64_t lo = 0, hi = 0; /* layers recorded */
|
||||
long long target = 0, seen = 0;
|
||||
bool written = false;
|
||||
rad_buf gathered = 0; /* [max_tok, widest split input] bf16 */
|
||||
int64_t gather_w = 0;
|
||||
rad_buf scratch = 0; /* [kmax, kmax] f32 on a rank that owns any input */
|
||||
int64_t kmax = 0;
|
||||
std::vector<Site> sites;
|
||||
|
||||
/* The host side of the taps (see the file comment). Created at the first tap and released once
|
||||
* the files are written; a run that ends before then leaks it, since its worker may still wait
|
||||
* on a card that is being torn down. */
|
||||
struct Async {
|
||||
std::mutex mu;
|
||||
std::condition_variable cv;
|
||||
std::thread worker;
|
||||
float* square[2] = { nullptr, nullptr }; /* pinned, kmax * kmax f32 */
|
||||
RadEvent copied[2] = { nullptr, nullptr };
|
||||
int site[2] = { -1, -1 }; /* the site square s holds; -1 when free */
|
||||
std::deque<int> queue; /* squares copied and not yet added */
|
||||
int next = 0;
|
||||
bool stop = false, failed = false;
|
||||
};
|
||||
Async* async = nullptr;
|
||||
|
||||
/* Whether this run records layer l. */
|
||||
bool records(int64_t l) const { return on && l >= lo && l < hi; }
|
||||
int owner_of(int64_t l) const { return (int)(l % world); }
|
||||
|
||||
/* From the build context: nothing unless --calib-dir is set. `widest_split` and `widest` are
|
||||
* the largest split input and the largest input of any recorded site, which size the gather
|
||||
* buffer and the scratch. */
|
||||
int begin(RadBuilder* b, Names& nm, const Geom& g, const RadBuildCtx* ctx, int64_t n_layer,
|
||||
int64_t widest_split, int64_t widest) {
|
||||
if (!ctx->calib_dir || !*ctx->calib_dir) return RAD_OK;
|
||||
on = true;
|
||||
dir = ctx->calib_dir;
|
||||
rank = g.rank;
|
||||
world = g.world;
|
||||
lo = ctx->calib_layer_hi ? ctx->calib_layer_lo : 0;
|
||||
hi = ctx->calib_layer_hi ? std::min<int64_t>(ctx->calib_layer_hi, n_layer) : n_layer;
|
||||
target = ctx->calib_tokens;
|
||||
if (lo >= hi) {
|
||||
std::fprintf(stderr, "radiance: --calib-layers %lld:%lld names no layer of %lld\n",
|
||||
(long long)lo, (long long)hi, (long long)n_layer);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (target <= 0) {
|
||||
std::fprintf(stderr, "radiance: --calib-dir records over a --calib-corpus run, which "
|
||||
"states the corpus's size\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (world > 1) {
|
||||
gather_w = widest_split;
|
||||
gathered = decl_b(b, nm.f("calib.gathered"), RAD_BF16, { g.max_tok, gather_w });
|
||||
if (!gathered) return RAD_E_INVAL;
|
||||
}
|
||||
kmax = widest;
|
||||
scratch = decl_b(b, nm.f("calib.scratch"), RAD_F32, { kmax, kmax }, RAD_BUF_PERSIST);
|
||||
return scratch ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* One input of layer `layer` (-1: the lm_head's, recorded by rank 0). `local` is the rank's
|
||||
* part, `k_local` its width; the input is split across ranks when k_local * world == K. */
|
||||
int site(RadBuilder* b, const Geom& g, int64_t layer, std::string stem, std::string linears,
|
||||
rad_buf local, int64_t k_local, int64_t K) {
|
||||
Site s;
|
||||
s.stem = std::move(stem);
|
||||
s.linears = std::move(linears);
|
||||
s.local = local;
|
||||
s.K = K;
|
||||
s.k_local = k_local;
|
||||
s.owner = (layer < 0 ? 0 : owner_of(layer)) == rank;
|
||||
const bool split = k_local != K;
|
||||
if (split) {
|
||||
if (k_local * world != K || !gathered || K > gather_w) return RAD_E_INVAL;
|
||||
s.op_gather = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", world),
|
||||
RAD_RANGE("numel", k_local, g.max_tok * k_local),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("row", k_local)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ local }, { gathered });
|
||||
if (!s.op_gather) return RAD_E_INVAL;
|
||||
}
|
||||
if (s.owner) {
|
||||
if (K > kmax) return RAD_E_INVAL;
|
||||
s.op_gram = rw(b, RAD_OP(b, "gram_accum",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
|
||||
RAD_INT("group", 128), RAD_STR("dtype", "bf16"), /* group: unread at bf16 */
|
||||
RAD_INT("upper", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ split ? gathered : local, scratch }, { scratch });
|
||||
if (!s.op_gram) return RAD_E_INVAL;
|
||||
}
|
||||
sites.push_back(std::move(s));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Site `i` over a step's T rows: gather (every rank), then on the owner the Gram into the
|
||||
* scratch, copied to a free square, the scratch zeroed, and the square handed to the worker. */
|
||||
void tap(RadCtx* c, size_t i, int64_t T) {
|
||||
Site& s = sites[i];
|
||||
RadOperand a = brows(s.local, T);
|
||||
if (s.op_gather) {
|
||||
RAD_ISSUE_N(c, s.op_gather, T * s.k_local, brows(s.local, T), bcol(gathered, 0, s.K, T));
|
||||
a = bcol(gathered, 0, s.K, T);
|
||||
}
|
||||
if (!s.owner) return;
|
||||
float* dev = static_cast<float*>(rad_buf_ptr(c, scratch));
|
||||
if (!dev || (!async && !start())) {
|
||||
rad_step_fail(c, "calibration: no scratch or pinned squares");
|
||||
return;
|
||||
}
|
||||
/* Allocated at the first step, not at declare: the engine may declare more than once. */
|
||||
if (s.tri.empty()) s.tri.assign((size_t)(s.K * (s.K + 1) / 2), 0.0f);
|
||||
Async& q = *async;
|
||||
const int k = q.next;
|
||||
q.next ^= 1;
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(q.mu);
|
||||
q.cv.wait(lk, [&] { return q.site[k] < 0 || q.failed; });
|
||||
if (q.failed) {
|
||||
lk.unlock();
|
||||
rad_step_fail(c, "calibration: waiting on a Gram's copy failed");
|
||||
return;
|
||||
}
|
||||
}
|
||||
const int64_t K = s.K;
|
||||
RAD_ISSUE_N(c, s.op_gram, T, a, RAD_NONE, praw2(dev, RAD_F32, K, K));
|
||||
/* `upper` 1 writes no entry below the diagonal, so only the upper triangle comes back:
|
||||
* band by band of kBand rows, each from its first row's diagonal on, about half the
|
||||
* square's bytes. The link is what a step's taps wait on, 25 GB a step on each rank of
|
||||
* Qwen3.8-27B as whole squares. */
|
||||
constexpr int64_t kBand = 512;
|
||||
bool ok = true;
|
||||
for (int64_t r = 0; r < K && ok; r += kBand)
|
||||
ok = rad_memcpy_2d_async(q.square[k] + r * K + r, K * 4, dev + r * K + r, K * 4,
|
||||
(K - r) * 4, std::min(kBand, K - r), rad_stream(c)) >= 0;
|
||||
if (!ok || rad_memset_async(dev, 0, K * K * 4, rad_stream(c)) < 0 ||
|
||||
rad_event_record(q.copied[k], rad_stream(c)) < 0) {
|
||||
rad_step_fail(c, "calibration: copying a Gram back failed");
|
||||
return;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(q.mu);
|
||||
q.site[k] = (int)i;
|
||||
q.queue.push_back(k);
|
||||
}
|
||||
q.cv.notify_all();
|
||||
}
|
||||
|
||||
/* After a step: once the corpus is through, every owned input to its file. */
|
||||
void after_step(RadCtx* c, int64_t T) {
|
||||
if (!on || written) return;
|
||||
seen += T;
|
||||
if (seen < target) return;
|
||||
written = true;
|
||||
int n = 0, bad = finish() ? 0 : 1;
|
||||
for (const Site& s : sites) {
|
||||
if (!s.owner || s.tri.empty()) continue;
|
||||
++n;
|
||||
if (!write(s)) ++bad;
|
||||
}
|
||||
std::fprintf(stderr, "radiance: calibration: rank %d wrote %d Hessian(s) of layers %lld:%lld "
|
||||
"after %lld rows to %s%s\n", rad_rank(c), n, (long long)lo, (long long)hi,
|
||||
seen, dir, bad ? ", with errors" : "");
|
||||
if (seen != target)
|
||||
std::fprintf(stderr, "radiance: calibration: %lld rows seen and the corpus has %lld\n",
|
||||
seen, target);
|
||||
}
|
||||
|
||||
private:
|
||||
bool start() {
|
||||
Async* q = new Async;
|
||||
bool ok = true;
|
||||
for (int k = 0; k < 2; ++k) {
|
||||
q->square[k] = static_cast<float*>(rad_dev_alloc(kmax * kmax * 4, RAD_MEM_HOST_PINNED));
|
||||
ok = ok && q->square[k] && rad_event_create(&q->copied[k]) >= 0;
|
||||
}
|
||||
if (!ok) {
|
||||
std::fprintf(stderr, "radiance: calibration could not pin 2 x %lld MiB of host squares "
|
||||
"on rank %d\n", (long long)((kmax * kmax * 4) >> 20), rank);
|
||||
release(q);
|
||||
return false;
|
||||
}
|
||||
async = q;
|
||||
q->worker = std::thread([this] { work(); });
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The worker: each copied square, in the order the rank issued them, into its site. */
|
||||
void work() {
|
||||
Async& q = *async;
|
||||
for (;;) {
|
||||
int k;
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(q.mu);
|
||||
q.cv.wait(lk, [&] { return q.stop || !q.queue.empty(); });
|
||||
if (q.queue.empty()) return;
|
||||
k = q.queue.front();
|
||||
q.queue.pop_front();
|
||||
}
|
||||
Site& s = sites[(size_t)q.site[k]];
|
||||
const bool ok = rad_event_sync(q.copied[k]) >= 0;
|
||||
if (ok) add_upper(s.tri.data(), q.square[k], s.K);
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(q.mu);
|
||||
q.site[k] = -1;
|
||||
if (!ok) q.failed = true;
|
||||
}
|
||||
q.cv.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/* Every square added and the worker gone; false if a copy failed. */
|
||||
bool finish() {
|
||||
if (!async) return true;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(async->mu);
|
||||
async->stop = true;
|
||||
}
|
||||
async->cv.notify_all();
|
||||
async->worker.join();
|
||||
const bool ok = !async->failed;
|
||||
if (!ok) std::fprintf(stderr, "radiance: calibration: a Gram's copy failed on rank %d\n", rank);
|
||||
release(async);
|
||||
async = nullptr;
|
||||
return ok;
|
||||
}
|
||||
|
||||
static void release(Async* q) {
|
||||
for (int k = 0; k < 2; ++k) {
|
||||
if (q->square[k]) rad_dev_free(q->square[k], RAD_MEM_HOST_PINNED);
|
||||
if (q->copied[k]) rad_event_destroy(q->copied[k]);
|
||||
}
|
||||
delete q;
|
||||
}
|
||||
|
||||
/* acc's upper triangle, packed row by row, += the upper triangle of the k x k row-major `full`. */
|
||||
static void add_upper(float* acc, const float* full, int64_t k) {
|
||||
const unsigned nt = std::max(1u, std::min(16u, std::thread::hardware_concurrency() / 2));
|
||||
std::vector<std::thread> th;
|
||||
for (unsigned t = 0; t < nt; ++t)
|
||||
th.emplace_back([=] {
|
||||
for (int64_t i = t; i < k; i += nt) {
|
||||
float* d = acc + (i * k - i * (i - 1) / 2);
|
||||
const float* s = full + i * k + i;
|
||||
for (int64_t j = 0; j < k - i; ++j) d[j] += s[j];
|
||||
}
|
||||
});
|
||||
for (std::thread& x : th) x.join();
|
||||
}
|
||||
|
||||
bool write(const Site& s) const {
|
||||
char path[1024];
|
||||
std::snprintf(path, sizeof path, "%s/%s.safetensors", dir, s.stem.c_str());
|
||||
const uint64_t bytes = (uint64_t)s.tri.size() * 4;
|
||||
std::string hdr = "{\"__metadata__\":{\"k\":\"" + std::to_string(s.K) + "\",\"rows\":\"" +
|
||||
std::to_string(seen) + "\",\"layout\":\"upper triangle, row-major, packed\","
|
||||
"\"linears\":\"" + s.linears + "\"},\"hessian_upper\":{\"dtype\":\"F32\","
|
||||
"\"shape\":[" + std::to_string(s.tri.size()) + "],\"data_offsets\":[0," +
|
||||
std::to_string(bytes) + "]}}";
|
||||
while (hdr.size() % 8) hdr += ' ';
|
||||
const uint64_t hl = hdr.size();
|
||||
FILE* f = std::fopen(path, "wb");
|
||||
if (!f) { std::fprintf(stderr, "radiance: calibration cannot write %s\n", path); return false; }
|
||||
bool ok = std::fwrite(&hl, 8, 1, f) == 1 && std::fwrite(hdr.data(), 1, hl, f) == hl &&
|
||||
std::fwrite(s.tri.data(), 4, s.tri.size(), f) == s.tri.size();
|
||||
ok = std::fclose(f) == 0 && ok;
|
||||
if (!ok) std::fprintf(stderr, "radiance: calibration write to %s was short\n", path);
|
||||
return ok;
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace rad::arch */
|
||||
@@ -0,0 +1,63 @@
|
||||
/* rad_deepseek41_chat.h -- DeepSeek-V4.1's reply format (reasoning and DSML tool calls) as data.
|
||||
*
|
||||
* The model's own encoder (encoding/encoding.py in the checkpoint) writes an assistant turn as
|
||||
*
|
||||
* [reasoning</think>]content\n\n<|DSML| calls>
|
||||
* <|DSML| invoke name="NAME">
|
||||
* <|DSML| parameter name="ARG" string="true">raw text</|DSML| parameter>
|
||||
* <|DSML| parameter name="ARG" string="false">JSON</|DSML| parameter>
|
||||
* </|DSML| invoke>
|
||||
* ...
|
||||
* </|DSML| calls><|end▁of▁sentence|>
|
||||
*
|
||||
* Every call sits in one section, each argument's tag says whether its value is a string or JSON,
|
||||
* and the tag names carry a leading space (V4 wrote `<|DSML|tool_calls>`, V3.2
|
||||
* `<|DSML|function_calls>`). The generation prompt ends in `<think>` with thinking on and in a
|
||||
* bare `</think>` with it off, so the reply starts inside the block only when the prompt opened
|
||||
* it.
|
||||
*
|
||||
* The template analysis cannot state the typed argument tags, so the plugin declares the format;
|
||||
* the reply-format tests read this same declaration. */
|
||||
#pragma once
|
||||
#include "rad_builder.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
inline const RadChatFormat* deepseek41_chat_format() {
|
||||
static const char* const kBreaks[] = { "<|DSML| calls>" };
|
||||
static const char* const kTriggers[] = { "<|DSML| calls>" };
|
||||
static const RadChatFormat f = [] {
|
||||
RadChatFormat c{};
|
||||
c.struct_size = (uint32_t)sizeof(RadChatFormat);
|
||||
c.name = "plugin:deepseek41";
|
||||
c.reasoning_open = "<think>";
|
||||
c.reasoning_close = "</think>";
|
||||
/* A section that starts inside an unclosed reasoning block ends it there. */
|
||||
c.reasoning_breaks = kBreaks;
|
||||
c.n_reasoning_breaks = 1;
|
||||
c.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT;
|
||||
|
||||
c.section_open = "<|DSML| calls>";
|
||||
c.section_close = "</|DSML| calls>";
|
||||
c.name_prefix = "<|DSML| invoke name=\"";
|
||||
c.name_suffix = "\">\n";
|
||||
c.call_end = "</|DSML| invoke>";
|
||||
c.arg_prefix = "<|DSML| parameter name=\"";
|
||||
c.arg_name_suffix = "\"";
|
||||
c.arg_value_prefix = " string=\"true\">";
|
||||
c.arg_json_value_prefix = " string=\"false\">";
|
||||
c.arg_value_suffix = "</|DSML| parameter>";
|
||||
c.string_value = RAD_CHAT_VALUE_RAW;
|
||||
c.other_value = RAD_CHAT_VALUE_JSON;
|
||||
c.value_newlines = 0;
|
||||
|
||||
c.triggers = kTriggers;
|
||||
c.n_triggers = 1;
|
||||
return c;
|
||||
}();
|
||||
return &f;
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
+380
-239
@@ -77,25 +77,29 @@ struct ActFP8 {
|
||||
rad_buf cq() const { return q8_fed ? q8 : q; }
|
||||
rad_buf cs() const { return q8_fed ? s8 : s; }
|
||||
|
||||
/* Declares the codes (and the int8 pair with `i8`); `x` is set by the caller.
|
||||
/* 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.
|
||||
*
|
||||
* `rows` defaults to g.max_tok and must be given for any buffer that is not one row per token
|
||||
* (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) {
|
||||
int64_t rows = 0, bool i8 = false, bool fp8_pair = true) {
|
||||
/* 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; }
|
||||
const int64_t m = rows > 0 ? rows : g.max_tok;
|
||||
if (fp8_pair) {
|
||||
q = decl_b(b, nm.f("%s.q", name), RAD_F8E4M3, { m, n });
|
||||
s = decl_b(b, nm.f("%s.s", name), RAD_F32, { m, fp8_blocks(n) });
|
||||
if (!q || !s) return RAD_E_INVAL;
|
||||
}
|
||||
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) });
|
||||
if (!q8 || !s8) return RAD_E_INVAL;
|
||||
}
|
||||
return (q && s) ? RAD_OK : RAD_E_INVAL;
|
||||
return (fp8_pair || i8) ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -290,6 +294,10 @@ struct ArPieces {
|
||||
* chunk a span of 1 makes, the state carried through the cache) and hand off the first
|
||||
* piece's reduction before the second piece's projection. Null for any other step. */
|
||||
const int32_t* cu = nullptr;
|
||||
/* The caller normed each piece's input itself (qwen35_fp8's pipelined prefill, on the second
|
||||
* lane behind the previous block's piece), so a block with its own norm takes the piece path
|
||||
* as one with an external input does and skips that norm. */
|
||||
bool in_ready = false;
|
||||
bool cuts(int64_t T) const { return done && rows > 0 && T > rows; }
|
||||
void hand(int64_t r0, int64_t n) { done(u, r0, n); ++handed; }
|
||||
};
|
||||
@@ -389,6 +397,9 @@ struct NormQuantFP8 {
|
||||
}
|
||||
/* Asked by the preceding block before issuing its own collective. */
|
||||
bool takes_ar(int64_t T) const { return pick(T) != op; }
|
||||
/* The plain op whatever the wire, for a caller that issued the preceding all-reduce itself
|
||||
* (qwen35_fp8's pipelined prefill, which runs it narrow beside compute). */
|
||||
void step_plain(RadCtx* c, int64_t T, int64_t r0 = 0, int64_t rows = 0) const;
|
||||
};
|
||||
|
||||
inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain, rad_buf x,
|
||||
@@ -466,6 +477,16 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* step() below with the plain op, whatever the wire. */
|
||||
inline void NormQuantFP8::step_plain(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (rows <= 0) rows = T - r0;
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(src, r0, rows, n),
|
||||
res ? brow_slice(res, r0, rows, n) : RAD_NONE, RAD_W(w),
|
||||
brow_slice(a.q, r0, rows, n),
|
||||
brow_slice(a.s, r0, rows, n / RAD_FP8_BLOCK),
|
||||
brow_slice(a.x, r0, rows, n));
|
||||
}
|
||||
|
||||
/* `r0`/`rows` select a row slice, defaulting to the whole step (`brow_slice` at offset 0 equals
|
||||
* `brows`). Slicing lets a block run in passes (the routed feed-forward). Each slice must land in
|
||||
* the same bucket-table band as the whole (core/runtime/ctx.h), or a different kernel with a
|
||||
@@ -508,6 +529,10 @@ struct GateQuantFP8 {
|
||||
* codes (`op_q`). */
|
||||
rad_op op_q = 0;
|
||||
|
||||
/* Set before declare: the product in bf16 alone, as for bf16 linears, for a consumer that
|
||||
* quantises its input itself (an int8 linear's op_q). */
|
||||
bool silu_only = false;
|
||||
|
||||
int declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act, int64_t n,
|
||||
const char* act_name = "silu", int64_t max_rows = 0, bool bf16_out = true,
|
||||
bool rot = false, double limit = 0);
|
||||
@@ -524,15 +549,16 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
|
||||
want_x = bf16_out;
|
||||
op_quant = 0;
|
||||
this->n = n;
|
||||
/* bf16 linears read the product itself: `silu_mul` into the bf16 plane only, and no
|
||||
* rotation. */
|
||||
bf16 = g.w_bf16;
|
||||
/* bf16 linears and `silu_only` read the product itself: `silu_mul` into the bf16 plane only,
|
||||
* and no rotation. */
|
||||
bf16 = g.w_bf16 || silu_only;
|
||||
clipped = limit > 0;
|
||||
clamped_fused = false;
|
||||
if (!std::isfinite(limit) || limit < 0) return RAD_E_INVAL;
|
||||
if (clipped) {
|
||||
/* No rotated int8 form: its quantiser would be quant_act_i8g, unrotated. */
|
||||
if (!gate_up || !a.x || n <= 0 || rot || (a.q8_fed && a.q8_rot) ||
|
||||
/* No rotated int8 form: its quantiser would be quant_act_i8g, unrotated; and no clamp
|
||||
* with `silu_only`. */
|
||||
if (!gate_up || !a.x || n <= 0 || rot || silu_only || (a.q8_fed && a.q8_rot) ||
|
||||
std::strcmp(act_name, "silu"))
|
||||
return RAD_E_INVAL;
|
||||
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
|
||||
@@ -708,10 +734,8 @@ struct LinearFP8 {
|
||||
* view whose layout hook reduces it). Read from the weight's encoding. */
|
||||
bool mx = false;
|
||||
rad_weight wref = 0;
|
||||
/* The M2XFP4 sibling (libquant `m2xfp4`): the MXFP4 weight plus one metadata byte a group,
|
||||
* read by `gemm_nt_q` at dtype m2xfp4 with the same E4M3 pair, `b_scale` and `b_ref` as MXFP4's
|
||||
* are, the meta plane riding the weight operand's stored blob. Read from the weight's
|
||||
* encoding. */
|
||||
/* Or M2XFP4 (libquant `m2xfp4`): the MXFP4 views, the meta plane riding the weight operand,
|
||||
* read by `gemm_nt_q` at dtype m2xfp4. */
|
||||
bool m2x = false;
|
||||
/* Rotated (ParoQuant) variant of `mx`: the same GEMM over an activation that
|
||||
* `givens_dense_quant` makes from the bf16 plane (channel scale, dense per-group rotation and
|
||||
@@ -724,13 +748,12 @@ struct LinearFP8 {
|
||||
* gemm_nt_q at w5a16 over u5 codes with an f16 scale and a zero point. */
|
||||
bool paro5 = false;
|
||||
/* A 4-bit weight with a zero point and no rotation (linear_is_w4): the int4 W4A16 releases.
|
||||
* At or below `w4_split` rows `op_a16` casts the input's bf16 plane to f16 (`a16`) for the
|
||||
* w4a16_asym GEMM `op`; above it `op_q` quantises it to int8 with a scale per (row, 128)
|
||||
* At or below `w4_split` rows the w4a16_asym GEMM `op` reads the input's bf16 plane and
|
||||
* narrows it on load; above it `op_q` quantises it to int8 with a scale per (row, 128)
|
||||
* (`a8q`, `a8s`) for the w4a8i8_asym GEMM `op2`. */
|
||||
bool w4 = false;
|
||||
int64_t w4_split = 0;
|
||||
rad_buf a16 = 0, a8q = 0, a8s = 0;
|
||||
rad_op op_a16 = 0;
|
||||
rad_buf a8q = 0, a8s = 0;
|
||||
/* Prefill band for z-lab's int4 and the int5: above `rot_split` rows the f16 skinny kernel is
|
||||
* bound by the slow f16 matrix instruction, so a second chain runs: the same rotation to int8
|
||||
* with a scale per (row, 128) into `rot_q2`/`rot_s2`, then the int8 tiled GEMM (`w4a8i8_asym` /
|
||||
@@ -745,11 +768,20 @@ 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;
|
||||
/* 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
|
||||
* caller keeps the split and its bits. Set before declare(). */
|
||||
bool short_split = false;
|
||||
/* Whether this linear reads the input's bf16 plane, known from probe() before the producer is
|
||||
* declared. A producer writes the bf16 plane only when asked, so the block must ask for it when
|
||||
* this is set; otherwise the linear reads unwritten arena bytes. */
|
||||
bool reads_x = false;
|
||||
bool mapped = false; /* probe() made the name map; declare() does not make it again */
|
||||
/* The stored weight this linear's views take when it is not `<base>.weight`: a second linear
|
||||
* over one container entry, e.g. a whole projection beside its tensor-parallel slice. Set
|
||||
* before declare(); no name map is made, and only block fp8 is served this way. */
|
||||
const char* stored = nullptr;
|
||||
/* The weight's access class (rad_builder.h): read every pass by default; a linear run once a
|
||||
* request (an encoder's) says so, which lets placement keep it off the card. Set before
|
||||
* declare(). */
|
||||
@@ -803,8 +835,10 @@ struct LinearFP8 {
|
||||
rad_weight decl_dense(RadBuilder* b, Names& nm, const char* base, const char* wn, const RadEncoding& enc,
|
||||
int64_t K,
|
||||
RadWeightGroup grp);
|
||||
/* Rows [r0, r0 + rows) of the input into the same rows of `y`, or from row `y0` of `y` when
|
||||
* that is set: a rank's run of a step's rows written to a buffer sized for the run. */
|
||||
void step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0 = 0,
|
||||
int64_t rows = 0) const;
|
||||
int64_t rows = 0, int64_t y0 = -1) const;
|
||||
/* A span per stacked row part (rad_weight_shard_span_parts), in weight rows; the scale plane
|
||||
* gets the same spans in its rows. Call after declare(). With a 1/128 plane every span and
|
||||
* total must be whole scale blocks. */
|
||||
@@ -856,13 +890,99 @@ inline bool linear_is_w8(const RadEncoding& e) {
|
||||
|
||||
/* The same planes rotated by the unnormalised 128-wide Hadamard along K, the 1/128 in the scale
|
||||
* (libquant's `transform=fwht128`), served at i8a8h behind had_quant_act_i8g. */
|
||||
inline bool linear_is_w8h(const RadEncoding& e) {
|
||||
if (!rad_enc_is(&e, "affine") || e.n_planes != 2 ||
|
||||
/* How a weight served at i8a8h stores its codes on the same grid (a bf16 scale per [1 x 128],
|
||||
* /fwht128): int8, or a narrower form kept at its codes' width in VRAM and decoded by the GEMM that
|
||||
* reads it (libr4d's gemm_iqr rows) -- signed 2..7-bit codes; unsigned codes less a zero point per
|
||||
* [1 x 128]; unsigned codes indexing an int8 codebook; the codes a bitshift trellis shifts in down
|
||||
* each column ("trellis", whose scale may also be an E4M3 one per [1 x 128] under an f32 or bf16
|
||||
* second level, the bf16 of their product). Each decodes to the int8 grid's values exactly. */
|
||||
enum class W8hForm { None, I8, Signed, Zero, Table, Grid, Trellis };
|
||||
/* A computed trellis (libquant's tcq_code=mad) carries its code's constants as one more plane,
|
||||
* "trellis.mad", which the GEMM reads instead of the table. */
|
||||
inline int linear_w8h_mad(const RadEncoding& e) { return rad_enc_plane(&e, "trellis.mad") ? 1 : 0; }
|
||||
/* A trellis under one f32 scale a row times one f32 a 128-K block for all rows (libquant's
|
||||
* tcq_colf): "scale" [1 x whole] and "scale.col" [whole x 128], one view. */
|
||||
inline bool linear_w8h_rowf(const RadEncoding& e) {
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
const RadEncPlane* cf = rad_enc_plane(&e, "scale.col");
|
||||
return rad_enc_is(&e, "trellis") && sc && cf && sc->kind == RAD_PLANE_TILED &&
|
||||
sc->dtype == RAD_F32 && sc->block[0] == 1 && sc->block[1] == 0 &&
|
||||
cf->kind == RAD_PLANE_TILED && cf->dtype == RAD_F32 && cf->block[0] == 0 &&
|
||||
cf->block[1] == RAD_FP8_BLOCK && !rad_enc_plane(&e, "scale.1");
|
||||
}
|
||||
/* A trellis weight's scale in two levels: E4M3 per [1 x 128] under "scale.1" for the tensor or
|
||||
* the row. */
|
||||
inline bool linear_w8h_scale2(const RadEncoding& e) {
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
const RadEncPlane* s2 = rad_enc_plane(&e, "scale.1");
|
||||
return rad_enc_is(&e, "trellis") && e.n_planes - linear_w8h_mad(e) == 4 && sc && s2 &&
|
||||
sc->dtype == RAD_F8E4M3 &&
|
||||
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;
|
||||
}
|
||||
inline W8hForm linear_w8h_form(const RadEncoding& e) {
|
||||
const bool trellis = rad_enc_is(&e, "trellis");
|
||||
if ((!rad_enc_is(&e, "affine") && !trellis) ||
|
||||
std::strncmp(e.transform, "fwht128", RAD_ENC_STR) != 0)
|
||||
return W8hForm::None;
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
const bool two = linear_w8h_scale2(e), rowf = linear_w8h_rowf(e);
|
||||
if (!sc || (sc->dtype != RAD_BF16 && !two && !rowf) || sc->block[0] != 1 ||
|
||||
sc->block[1] != (rowf ? 0 : RAD_FP8_BLOCK))
|
||||
return W8hForm::None;
|
||||
const uint32_t cd = e.plane[0].dtype;
|
||||
/* A vector grid: one code a [1 x V] run of columns, an i8 grid {E x V}. */
|
||||
if (e.n_planes == 3 && e.plane[0].block[1] > 1) {
|
||||
const RadEncPlane* gr = rad_enc_plane(&e, "grid");
|
||||
return gr && gr->kind == RAD_PLANE_TABLE && gr->dtype == RAD_I8 &&
|
||||
gr->extent[1] == e.plane[0].block[1] && RAD_FP8_BLOCK % gr->extent[1] == 0
|
||||
? W8hForm::Grid : W8hForm::None;
|
||||
}
|
||||
const bool sgn = cd == RAD_I2 || cd == RAD_I3 || cd == RAD_I4 || cd == RAD_I5 || cd == RAD_I6 ||
|
||||
cd == RAD_I7;
|
||||
const bool uns = cd == RAD_U1 || cd == RAD_U2 || cd == RAD_U3 || cd == RAD_U4 || cd == RAD_U5 ||
|
||||
cd == RAD_U6 || cd == RAD_U7 || cd == RAD_U8;
|
||||
if (e.plane[0].block[1] != 1) return W8hForm::None;
|
||||
if (e.n_planes == 2) return cd == RAD_I8 ? W8hForm::I8 : sgn ? W8hForm::Signed : W8hForm::None;
|
||||
if (e.n_planes - (trellis ? linear_w8h_mad(e) + (rowf ? 1 : 0) : 0) != (two ? 4 : 3) || !uns)
|
||||
return W8hForm::None;
|
||||
/* A trellis: the codes a bitshift trellis shifts in down each column, an i8 value a state. */
|
||||
if (trellis) {
|
||||
const RadEncPlane* tp = rad_enc_plane(&e, "trellis");
|
||||
if (!tp) return W8hForm::None;
|
||||
const int64_t S = tp->extent[0];
|
||||
return tp->kind == RAD_PLANE_TABLE && tp->dtype == RAD_I8 && tp->extent[1] == 1 &&
|
||||
tp->block[0] > 0 && S > ((int64_t)1 << rad_dtype_bits(cd)) && S <= 65536 &&
|
||||
(S & (S - 1)) == 0
|
||||
? W8hForm::Trellis : W8hForm::None;
|
||||
}
|
||||
const RadEncPlane* zp = rad_enc_plane(&e, "zero");
|
||||
if (zp && cd != RAD_U1 && cd != RAD_U8 && (zp->dtype == cd || zp->dtype == RAD_U8) &&
|
||||
zp->block[0] == 1 && zp->block[1] == RAD_FP8_BLOCK)
|
||||
return W8hForm::Zero;
|
||||
const RadEncPlane* tb = rad_enc_plane(&e, "table");
|
||||
if (tb && tb->kind == RAD_PLANE_TABLE && tb->dtype == RAD_I8 && tb->extent[0] == 1 &&
|
||||
tb->extent[1] >= 2 && tb->extent[1] <= ((int64_t)1 << rad_dtype_bits(cd)))
|
||||
return W8hForm::Table;
|
||||
return W8hForm::None;
|
||||
}
|
||||
inline bool linear_is_w8h(const RadEncoding& e) { return linear_w8h_form(e) != W8hForm::None; }
|
||||
|
||||
/* A rotated asymmetric weight at four or five bits: u4 or u5 codes, an f16 scale and a u8 (or
|
||||
* code-width) zero point per 128 of K under the 128-wide Hadamard (libquant `codes=u5 zero=u8
|
||||
* group=128 scale=f16 transform=fwht128`). Read by gemm_nt_q at w4a8i8_asym / w5a8i8 over the
|
||||
* rotated int8 codes an i8a8h trunk's producers write, so it mixes with i8a8h linears in one trunk.
|
||||
* The scale carries the transform's 1/128, as an i8a8h weight's does. */
|
||||
inline bool linear_is_wnh(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");
|
||||
return e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 && sc && sc->dtype == RAD_BF16 &&
|
||||
sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK;
|
||||
const RadEncPlane *sc = rad_enc_plane(&e, "scale"), *zp = rad_enc_plane(&e, "zero");
|
||||
const uint32_t cd = e.plane[0].dtype;
|
||||
return (cd == RAD_U4 || cd == RAD_U5) && e.plane[0].block[1] == 1 && sc && zp &&
|
||||
sc->dtype == RAD_F16 && sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK &&
|
||||
(zp->dtype == RAD_U8 || zp->dtype == cd) && zp->block[0] == 1 &&
|
||||
zp->block[1] == RAD_FP8_BLOCK;
|
||||
}
|
||||
|
||||
/* The OCP-MXFP4 weight LinearFP8 serves at mxfp4a8: e2m1 codes and an E8M0 exponent per [1 x 32],
|
||||
@@ -875,32 +995,16 @@ inline bool linear_is_mxfp4(const RadEncoding& e) {
|
||||
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP;
|
||||
}
|
||||
|
||||
/* The M2XFP4 sibling (arXiv 2601.19213, the paper's weight-side Sg-EM): the MXFP4 weight plus one
|
||||
* metadata byte per group of 32, four 2-bit subgroup extra mantissas that refine the exponent to
|
||||
* (1 + k/4) . 2^E (libquant's `m2xfp4` quantiser; libr4d's m2xfp4 layout hook). The exponent byte
|
||||
* carries the adaptive bias; the GEMM applies nothing beyond the planes. */
|
||||
/* M2XFP4 (arXiv 2601.19213, weight-side Sg-EM): the MXFP4 weight plus one metadata byte per group
|
||||
* of 32, four 2-bit subgroup extra mantissas that refine the scale to (1 + k/4) . 2^E. The
|
||||
* exponent byte carries the adaptive bias; the GEMM applies nothing beyond the planes. */
|
||||
inline bool linear_is_m2xfp4(const RadEncoding& e) {
|
||||
if (!rad_enc_is(&e, "m2xfp4") || e.n_planes != 3 || e.transform[0]) return false;
|
||||
const RadEncPlane *sc = rad_enc_plane(&e, "scale"), *mt = rad_enc_plane(&e, "meta");
|
||||
return e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[0] == 1 && e.plane[0].block[1] == 1 &&
|
||||
sc && sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP && mt &&
|
||||
mt->dtype == RAD_U8 && mt->block[0] == 1 && mt->block[1] == RAD_MX_GROUP;
|
||||
}
|
||||
|
||||
/* A rotated weight with M2XFP4 planes (ParoQuant's `m2xfp4` grid): the scheme's three planes in the
|
||||
* basis of a "givens" transform, whose tables are views of the weight's planes. Read exactly like
|
||||
* linear_is_paro_mxfp4 -- the meta plane rides the weight operand's stored blob -- over an
|
||||
* activation the rotation makes. */
|
||||
inline bool linear_is_paro_m2xfp4(const RadEncoding& e) {
|
||||
if (!rad_enc_is(&e, "m2xfp4") || std::strncmp(e.transform, "givens", RAD_ENC_STR) != 0) return false;
|
||||
if (!rad_enc_valid(&e) || e.n_planes < 6) return false;
|
||||
const RadEncPlane *sc = rad_enc_plane(&e, "scale"), *mt = rad_enc_plane(&e, "meta"),
|
||||
*pr = rad_enc_plane(&e, "t.pairs"), *an = rad_enc_plane(&e, "t.angle"),
|
||||
*rs = rad_enc_plane(&e, "t.scale");
|
||||
return pr && an && rs && pr->dtype == RAD_I32 && an->dtype == RAD_F32 && rs->dtype == RAD_F32 &&
|
||||
e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[0] == 1 && e.plane[0].block[1] == 1 &&
|
||||
sc && sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP && mt &&
|
||||
mt->dtype == RAD_U8 && mt->block[0] == 1 && mt->block[1] == RAD_MX_GROUP;
|
||||
return e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[0] == 1 &&
|
||||
e.plane[0].block[1] == 1 && sc && sc->dtype == RAD_E8M0 && sc->block[0] == 1 &&
|
||||
sc->block[1] == RAD_MX_GROUP && mt && mt->dtype == RAD_U8 && mt->block[0] == 1 &&
|
||||
mt->block[1] == RAD_MX_GROUP;
|
||||
}
|
||||
|
||||
/* A rotated weight (ParoQuant): an affine encoding in the basis of a "givens" transform, with the
|
||||
@@ -921,10 +1025,28 @@ inline bool linear_is_paro_mxfp4(const RadEncoding& e) {
|
||||
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP;
|
||||
}
|
||||
|
||||
/* A rotated weight with M2XFP4 planes (ParoQuant's `m2xfp4` grid): the scheme's three planes in
|
||||
* the basis of a "givens" transform, whose tables are views of the weight's planes. Read like the
|
||||
* plain M2XFP4 weight -- the meta plane rides the weight operand's stored blob -- over an
|
||||
* activation the rotation makes, as linear_is_paro_mxfp4's is. */
|
||||
inline bool linear_is_paro_m2xfp4(const RadEncoding& e) {
|
||||
if (!rad_enc_is(&e, "m2xfp4") || std::strncmp(e.transform, "givens", RAD_ENC_STR) != 0 ||
|
||||
!rad_enc_valid(&e) || e.n_planes < 6)
|
||||
return false;
|
||||
const RadEncPlane *sc = rad_enc_plane(&e, "scale"), *mt = rad_enc_plane(&e, "meta"),
|
||||
*pr = rad_enc_plane(&e, "t.pairs"), *an = rad_enc_plane(&e, "t.angle"),
|
||||
*rs = rad_enc_plane(&e, "t.scale");
|
||||
return pr && an && rs && pr->dtype == RAD_I32 && an->dtype == RAD_F32 && rs->dtype == RAD_F32 &&
|
||||
e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[0] == 1 &&
|
||||
e.plane[0].block[1] == 1 && sc && sc->dtype == RAD_E8M0 && sc->block[0] == 1 &&
|
||||
sc->block[1] == RAD_MX_GROUP && mt && mt->dtype == RAD_U8 && mt->block[0] == 1 &&
|
||||
mt->block[1] == RAD_MX_GROUP;
|
||||
}
|
||||
|
||||
/* 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). Read by gemm_nt_q at w4a16_asym over an f16 activation, or w4a8i8_asym
|
||||
* over an int8 one, the rotated int4's GEMMs with no rotation. */
|
||||
* over an int4 release). At decode w4a16_asym narrows the BF16 input to F16 on load; larger
|
||||
* batches use w4a8i8_asym over an int8 activation, the rotated int4's GEMMs with no rotation. */
|
||||
inline bool linear_is_w4(const RadEncoding& e) {
|
||||
if (!rad_enc_is(&e, "affine") || e.n_planes != 3 || e.transform[0]) return false;
|
||||
const RadEncPlane *sc = rad_enc_plane(&e, "scale"), *zp = rad_enc_plane(&e, "zero");
|
||||
@@ -954,7 +1076,7 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char*
|
||||
const bool known = weight_enc(b, wn, &enc);
|
||||
const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
|
||||
enc.plane[0].dtype == RAD_BF16;
|
||||
probed_i8 = known && (linear_is_w8(enc) || linear_is_w8h(enc));
|
||||
probed_i8 = known && (linear_is_w8(enc) || linear_is_w8h(enc) || linear_is_wnh(enc));
|
||||
/* A rotated weight rotates and quantises the bf16 plane itself; a 4-bit one casts or
|
||||
* quantises it. */
|
||||
const bool rotated = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc) ||
|
||||
@@ -1071,9 +1193,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
|
||||
/* Name map first: the weight's encoding, looked up through it, picks the branch below. */
|
||||
const char* wn = nm.f("%s.weight", base);
|
||||
if (!mapped) RAD_ARCH_TRY(map_linear(b, wn, src));
|
||||
if (!mapped && !stored) RAD_ARCH_TRY(map_linear(b, wn, src));
|
||||
const char* sw = stored ? stored : wn;
|
||||
RadEncoding enc{};
|
||||
const bool known = weight_enc(b, wn, &enc);
|
||||
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;
|
||||
|
||||
@@ -1083,6 +1206,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
* constraints. */
|
||||
bf16 = g.w_bf16 || plain;
|
||||
if (bf16) {
|
||||
if (stored) {
|
||||
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
|
||||
"may\n", wn, stored);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (known && !plain) {
|
||||
char en[256];
|
||||
rad_enc_format(&enc, en, sizeof en);
|
||||
@@ -1118,20 +1246,29 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
*
|
||||
* A rotated weight (i8a8h) takes had_quant_act_i8g instead. It reads a producer's codes only
|
||||
* when they are rotated too (ActFP8::q8_rot, a `_had_quant_i8g` producer); a plain int8 weight
|
||||
* only when they are not. */
|
||||
const bool rot8 = known && linear_is_w8h(enc);
|
||||
* only when they are not. A rotated four- or five-bit asymmetric weight (linear_is_wnh) reads
|
||||
* the same rotated codes at w4a8i8_asym / w5a8i8, through two views: codes, and (scale, zero)
|
||||
* as `b_scale` at the logical extents. */
|
||||
const bool asym = known && linear_is_wnh(enc);
|
||||
const bool rot8 = known && (linear_is_w8h(enc) || asym);
|
||||
i8 = known && (linear_is_w8(enc) || rot8);
|
||||
if (i8) {
|
||||
if (stored) {
|
||||
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
|
||||
"may\n", wn, stored);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (a.q8_fed && rot8 != a.q8_rot) {
|
||||
fprintf(stderr, "radiance: '%s' is a%s int8 weight and its input is fed codes its "
|
||||
"producer wrote %s\n", wn, rot8 ? " rotated" : " plain",
|
||||
rot8 ? "unrotated" : "rotated");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (!a.x || !a.q8 || !a.s8) {
|
||||
fprintf(stderr, "radiance: '%s' is an int8 weight and its input lacks the bf16 plane "
|
||||
"or the int8 code pair (the model declared its input before learning "
|
||||
"the trunk is int8)\n", wn);
|
||||
/* The bf16 plane only when this linear quantises it itself. */
|
||||
if (!a.q8 || !a.s8 || (!a.q8_fed && !a.x)) {
|
||||
fprintf(stderr, "radiance: '%s' is an int8 weight and its input lacks the int8 code "
|
||||
"pair%s (the model declared its input before learning the trunk is "
|
||||
"int8)\n", wn, a.q8_fed ? "" : " or the bf16 plane it quantises");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
@@ -1143,13 +1280,36 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
RowParts rp;
|
||||
RAD_ARCH_TRY(rp.set(row_parts, 1, 1, base, "rows"));
|
||||
const char* sn = nm.f("%s.scale", base);
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, access, shard, grp,
|
||||
/* A narrower i8a8h weight's codes view takes the plane that decodes it too. */
|
||||
const W8hForm form = linear_w8h_form(enc);
|
||||
const RadEncPlane* tpl = rad_enc_plane(&enc, "trellis");
|
||||
const bool trb = form == W8hForm::Trellis && tpl && tpl->block[1] > 1;
|
||||
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";
|
||||
/* Declared at the stored codes' dtype; the kernel's layout keeps them at that width
|
||||
* (libr4d's r4d_iqr_layout.cpp). */
|
||||
w = decl_view(b, wn, nullptr, cv, enc.plane[0].dtype, { N, K }, access, shard, grp,
|
||||
rp.w, rp.n);
|
||||
ws = decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, access,
|
||||
/* 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);
|
||||
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,
|
||||
shard, grp, rp.w, rp.n);
|
||||
if (!w || !ws) return RAD_E_INVAL;
|
||||
if (span_hi > 0) {
|
||||
const bool col = shard == RAD_SHARD_COL;
|
||||
/* 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)) {
|
||||
fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
|
||||
"%d-column scale group\n", base, (long long)span_lo,
|
||||
@@ -1157,6 +1317,13 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
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)) {
|
||||
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);
|
||||
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));
|
||||
}
|
||||
@@ -1167,10 +1334,19 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a.x }, { a.q8, a.s8 });
|
||||
op = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
const char* qdt = asym ? (enc.plane[0].dtype == RAD_U5 ? "w5a8i8" : "w4a8i8_asym")
|
||||
: rot8 ? "i8a8h" : "i8a8";
|
||||
/* A trellis on an int8 grid of several rows a scale (libquant's tcq_rb) says how many
|
||||
* (`w_rb`), which a GEMM's fold may read as one scale a block of rows. */
|
||||
op = trb ? 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", rot8 ? "i8a8h" : "i8a8")),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", qdt),
|
||||
RAD_INT("w_rb", tpl->block[1])),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ 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_WEIGHTS(w, ws)),
|
||||
{ a.q8, a.s8 }, { y });
|
||||
return (op_q || a.q8_fed) && op ? RAD_OK : RAD_E_INVAL;
|
||||
@@ -1181,6 +1357,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
* codes, and (scale, zero) as `b_scale`. */
|
||||
paro5 = known && linear_is_paro_w5(enc);
|
||||
if (paro5) {
|
||||
if (stored) {
|
||||
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
|
||||
"may\n", wn, stored);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int bits = enc.plane[0].dtype == RAD_U4 ? 4 : 5;
|
||||
if (!a.x) {
|
||||
fprintf(stderr, "radiance: '%s' is a rotated %d-bit weight, rotated from its input's "
|
||||
@@ -1239,14 +1420,19 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
}
|
||||
|
||||
/* ---- 4-bit weight with a zero point and no rotation: the rotated int4's two GEMMs over this
|
||||
* linear's own copies of the input's bf16 plane. At or below kSplit rows (the skinny f16
|
||||
* kernel's ceiling) the plane is cast to f16 for w4a16_asym; above it, where that kernel is
|
||||
* bound by the f16 matrix instruction, it is quantised to int8 with an f32 scale per
|
||||
* linear's BF16 input. At or below kSplit rows (the skinny F16 kernel's ceiling) the GEMM
|
||||
* narrows that input on load; above it, where that kernel is bound by the F16 matrix
|
||||
* instruction, the input is quantised to int8 with an F32 scale per
|
||||
* (row, 128) for w4a8i8_asym. Two views: codes, and (scale, zero) as `b_scale`, both at the
|
||||
* logical extents, so row parts and spans apply to both as they are; a column slice must be
|
||||
* whole 128s, the scale group. */
|
||||
w4 = known && linear_is_w4(enc);
|
||||
if (w4) {
|
||||
if (stored) {
|
||||
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
|
||||
"may\n", wn, stored);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!a.x) {
|
||||
fprintf(stderr, "radiance: '%s' is a 4-bit weight, read from its input's bf16 plane, "
|
||||
"and its input has none\n", wn);
|
||||
@@ -1277,15 +1463,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
|
||||
const int64_t kSplit = 64;
|
||||
const int64_t f16_hi = hi > kSplit ? kSplit : hi;
|
||||
a16 = decl_b(b, nm.f("%s.a16", base), RAD_F16, { f16_hi, K });
|
||||
if (!a16) return RAD_E_INVAL;
|
||||
op_a16 = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, f16_hi), RAD_INT("n", K),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", "f16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a.x }, { a16 });
|
||||
op = decl_gemm_q(b, 1, f16_hi, RAD_FP8_BLOCK, "w4a16_asym", 0, 0, { w, ws }, { a16 }, y);
|
||||
if (!op_a16 || !op) return RAD_E_INVAL;
|
||||
op = decl_gemm_q(b, 1, f16_hi, RAD_FP8_BLOCK, "w4a16_asym", 0, 0, { w, ws }, { a.x }, y);
|
||||
if (!op) return RAD_E_INVAL;
|
||||
if (hi > kSplit) {
|
||||
w4_split = kSplit;
|
||||
a8q = decl_b(b, nm.f("%s.a8q", base), RAD_I8, { hi, K });
|
||||
@@ -1311,124 +1490,50 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
|
||||
/* ---- M2XFP4 weight over the E4M3 pair: the MXFP4 weight's views plus the metadata plane,
|
||||
* which rides the weight operand -- the declared view takes codes and meta together, and the
|
||||
* stored blob carries the meta in its tail (libr4d's m2xfp4 layout). The exponent plane is
|
||||
* `b_scale` and `b_ref` as MXFP4's is; the row parts, the shape bounds and the column-shard
|
||||
* rule are the MXFP4 ones.
|
||||
*
|
||||
* A rotated weight (ParoQuant) carries the same planes in the basis its "givens" tables name,
|
||||
* so it is declared exactly like the rotated MXFP4 one: `givens_dense_quant` makes the E4M3
|
||||
* pair from the input's bf16 plane, once per rotated part, and the GEMM meets copy p with part
|
||||
* p's rows. `paro` makes step() issue that rotation first. */
|
||||
const bool m2rot = known && linear_is_paro_m2xfp4(enc);
|
||||
const bool m2 = known && (linear_is_m2xfp4(enc) || m2rot);
|
||||
if (m2) {
|
||||
m2x = true;
|
||||
paro = m2rot;
|
||||
if (m2rot) {
|
||||
if (!a.x) {
|
||||
fprintf(stderr, "radiance: '%s' is a rotated M2XFP4 weight, rotated and quantised "
|
||||
"from its input's bf16 plane, and its input has none\n", wn);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (g.world > 1 || span_hi > 0) {
|
||||
fprintf(stderr, "radiance: '%s' is a rotated M2XFP4 weight; its rotation is per "
|
||||
"projection and is not cut by a tensor-parallel shard (world %d)\n",
|
||||
wn, g.world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
} else if (!a.q || !a.s) {
|
||||
fprintf(stderr, "radiance: '%s' is an M2XFP4 weight read against its input's E4M3 "
|
||||
"pair, and its input has none\n", wn);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an M2XFP4 weight takes rows in "
|
||||
"16s and K in whole %d-column activation scale blocks\n",
|
||||
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
|
||||
/* ---- OCP-MXFP4 or M2XFP4 weight over an E4M3 pair, the producer's or, for a rotated
|
||||
* (ParoQuant) weight, its own. Three views: codes (M2XFP4's with its meta plane, which rides
|
||||
* the weight operand), exponents as `b_scale`, and the same plane as `b_ref`. Row parts apply
|
||||
* as is (the exponent grid is one row tall); column slices must be whole 128s, the
|
||||
* activation's scale block. */
|
||||
const bool paro_mx = known && linear_is_paro_mxfp4(enc);
|
||||
const bool paro_m2 = known && linear_is_paro_m2xfp4(enc);
|
||||
paro = paro_mx || paro_m2;
|
||||
mx = known && (linear_is_mxfp4(enc) || paro_mx);
|
||||
m2x = known && (linear_is_m2xfp4(enc) || paro_m2);
|
||||
if (mx || m2x) {
|
||||
const char* fmt = m2x ? "M2XFP4" : "MXFP4";
|
||||
if (stored) {
|
||||
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
|
||||
"may\n", wn, stored);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RowParts rp;
|
||||
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "M2XFP4 tiles"));
|
||||
int64_t pb1 = 0, pb2 = 0;
|
||||
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
|
||||
if (m2rot) {
|
||||
std::vector<int64_t> cut;
|
||||
for (int64_t p : rot_part_rows) cut.push_back(p);
|
||||
if (cut.empty()) for (int64_t p : row_parts) cut.push_back(p);
|
||||
RAD_ARCH_TRY(declare_rotation(b, nm, base, wn, enc, N, K, grp, cut, &pb1, &pb2));
|
||||
rot_q = decl_b(b, nm.f("%s.rot_q", base), RAD_F8E4M3, { hi, rot_parts * K });
|
||||
rot_s = decl_b(b, nm.f("%s.rot_s", base), RAD_F32,
|
||||
{ hi, rot_parts * (K / RAD_FP8_BLOCK) });
|
||||
if (!rot_q || !rot_s) return RAD_E_INVAL;
|
||||
rot_dense = decl_dense(b, nm, base, wn, enc, K, grp);
|
||||
if (!rot_dense) return RAD_E_INVAL;
|
||||
op_rot = decl_dense_op(b, g, a, "fp8", 1, hi, { rot_q, rot_s });
|
||||
if (!op_rot) return RAD_E_INVAL;
|
||||
}
|
||||
const char* sn = nm.f("%s.scale", base);
|
||||
const char* rn = nm.f("%s.ref", base);
|
||||
w = decl_view(b, wn, nullptr, "codes,meta", RAD_FP4E2M1, { N, K }, access, shard, grp,
|
||||
rp.w, rp.n);
|
||||
ws = decl_view(b, sn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
access, shard, grp, rp.w, rp.n);
|
||||
wref = decl_view(b, rn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
access, shard, grp, rp.w, rp.n);
|
||||
if (!w || !ws || !wref) return RAD_E_INVAL;
|
||||
if (span_hi > 0) {
|
||||
const bool col = shard == RAD_SHARD_COL;
|
||||
if (col && (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
|
||||
"%d-column activation scale block\n", base, (long long)span_lo,
|
||||
(long long)span_hi, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t lo = col ? span_lo / RAD_MX_GROUP : span_lo;
|
||||
const int64_t hi_n = col ? span_hi / RAD_MX_GROUP : span_hi;
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, lo, hi_n));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, wref, lo, hi_n));
|
||||
}
|
||||
/* A rotated weight reads its own rotated pair, a plain one the producer's. */
|
||||
op = decl_gemm_q(b, 1, hi, RAD_MX_GROUP, "m2xfp4", pb1, pb2, { w, ws, wref },
|
||||
{ m2rot ? rot_q : a.q, m2rot ? rot_s : a.s }, y);
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- OCP-MXFP4 weight over the E4M3 pair. Three views: codes, exponents as `b_scale`, and
|
||||
* the same plane as `b_ref`. Row parts apply as is (the exponent grid is one row tall); column
|
||||
* slices must be whole 128s, the activation's scale block. */
|
||||
paro = known && linear_is_paro_mxfp4(enc);
|
||||
mx = known && (linear_is_mxfp4(enc) || paro);
|
||||
if (mx) {
|
||||
if (paro) {
|
||||
/* The rotation is applied to the activation, so this linear needs the input's bf16
|
||||
* plane (probe() set reads_x) and quantises it itself. */
|
||||
if (!a.x) {
|
||||
fprintf(stderr, "radiance: '%s' is a rotated MXFP4 weight, rotated and quantised "
|
||||
"from its input's bf16 plane, and its input has none\n", wn);
|
||||
fprintf(stderr, "radiance: '%s' is a rotated %s weight, rotated and quantised "
|
||||
"from its input's bf16 plane, and its input has none\n", wn, fmt);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (g.world > 1 || span_hi > 0) {
|
||||
fprintf(stderr, "radiance: '%s' is a rotated MXFP4 weight; its rotation is per "
|
||||
fprintf(stderr, "radiance: '%s' is a rotated %s weight; its rotation is per "
|
||||
"projection and is not cut by a tensor-parallel shard (world %d)\n",
|
||||
wn, g.world);
|
||||
wn, fmt, g.world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
} else if (!a.q || !a.s) {
|
||||
fprintf(stderr, "radiance: '%s' is an MXFP4 weight read against its input's E4M3 "
|
||||
"pair, and its input has none\n", wn);
|
||||
fprintf(stderr, "radiance: '%s' is an %s weight read against its input's E4M3 "
|
||||
"pair, and its input has none\n", wn, fmt);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an MXFP4 weight takes rows in "
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an %s weight takes rows in "
|
||||
"16s and K in whole %d-column activation scale blocks\n",
|
||||
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
|
||||
base, (long long)N, (long long)K, fmt, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RowParts rp;
|
||||
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "MXFP4 tiles"));
|
||||
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, m2x ? "M2XFP4 tiles" : "MXFP4 tiles"));
|
||||
int64_t pb1 = 0, pb2 = 0;
|
||||
if (paro) {
|
||||
std::vector<int64_t> cut;
|
||||
@@ -1446,8 +1551,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
}
|
||||
const char* sn = nm.f("%s.scale", base);
|
||||
const char* rn = nm.f("%s.ref", base);
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, access,
|
||||
shard, grp, rp.w, rp.n);
|
||||
w = decl_view(b, wn, nullptr, m2x ? "codes,meta" : "codes", RAD_FP4E2M1, { N, K },
|
||||
access, shard, grp, rp.w, rp.n);
|
||||
ws = decl_view(b, sn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
access, shard, grp, rp.w, rp.n);
|
||||
wref = decl_view(b, rn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
@@ -1468,7 +1573,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, wref, lo, hi));
|
||||
}
|
||||
/* One GEMM: a rotated weight reads its own rotated pair, a plain one the producer's. */
|
||||
op = decl_gemm_q(b, 1, max_rows > 0 ? max_rows : g.max_tok, RAD_MX_GROUP, "mxfp4a8", pb1, pb2,
|
||||
op = decl_gemm_q(b, 1, max_rows > 0 ? max_rows : g.max_tok, RAD_MX_GROUP,
|
||||
m2x ? "m2xfp4" : "mxfp4a8", pb1, pb2,
|
||||
{ w, ws, wref }, { paro ? rot_q : a.q, paro ? rot_s : a.s }, y);
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
@@ -1513,10 +1619,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
f32_scale = fp8_scale && fp8_scale->dtype == RAD_F32;
|
||||
/* One stored weight, two operands: the codes and scale plane of `<base>.weight`, block fp8 in
|
||||
* the checkpoint or made so by rad-convert's recipe. */
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K },
|
||||
w = decl_view(b, wn, stored, "codes", RAD_F8E4M3, { N, K },
|
||||
access, shard, grp, rp.w, rp.n);
|
||||
ws_row_div = RAD_FP8_BLOCK;
|
||||
ws = decl_view(b, sn, wn, "scale", f32_scale ? RAD_F32 : RAD_BF16,
|
||||
ws = decl_view(b, sn, sw, "scale", f32_scale ? RAD_F32 : RAD_BF16,
|
||||
{ fp8_blocks(N), fp8_blocks(K) }, access, shard, grp, rp.s, rp.n);
|
||||
if (!w || !ws) return RAD_E_INVAL;
|
||||
/* An uneven slice; the scale plane takes the same slice in blocks. */
|
||||
@@ -1536,7 +1642,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
* caller with a tighter bound (the lm_head, over sampled rows only) passes `max_rows`, so the
|
||||
* narrow kernel's split-K scratch is not sized for max_tok. */
|
||||
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
|
||||
op = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
op = rw(b, RAD_OP(b, short_split && !f32_scale ? "gemm_nt_q_short" : "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", f32_scale?"fp8a8f32":"fp8a8")),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
@@ -1548,10 +1654,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
* asymmetric integer and mxfp4 grids) are passed as RAD_NONE when unused, since the runtime checks
|
||||
* the operand count against the schema (core/runtime/issue.cpp). */
|
||||
inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0,
|
||||
int64_t rows) const {
|
||||
int64_t rows, int64_t y0) const {
|
||||
if (rows <= 0) rows = T - r0;
|
||||
const int64_t yr = y0 < 0 ? r0 : y0;
|
||||
if (bf16) {
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.x, r0, rows, K), RAD_W(w), brow_slice(y, r0, rows, N));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.x, r0, rows, K), RAD_W(w), brow_slice(y, yr, rows, N));
|
||||
return;
|
||||
}
|
||||
if (i8) {
|
||||
@@ -1560,7 +1667,7 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.q8, r0, rows, K),
|
||||
brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
/* The 4-bit weight's copies of the input start at their buffers' first row: they live only
|
||||
@@ -1570,13 +1677,12 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
brow_slice(a8s, 0, rows, K / RAD_FP8_BLOCK));
|
||||
RAD_ISSUE_N(c, op2, rows, brow_slice(a8q, 0, rows, K),
|
||||
brow_slice(a8s, 0, rows, K / RAD_FP8_BLOCK), RAD_W(w), RAD_W(ws),
|
||||
brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (w4) {
|
||||
RAD_ISSUE_N(c, op_a16, rows, brow_slice(a.x, r0, rows, K), brow_slice(a16, 0, rows, K));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a16, 0, rows, K), RAD_NONE, RAD_W(w), RAD_W(ws),
|
||||
brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.x, r0, rows, K), RAD_NONE, RAD_W(w), RAD_W(ws),
|
||||
brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (paro5 && rot_split && rows > rot_split) {
|
||||
@@ -1585,20 +1691,19 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)));
|
||||
RAD_ISSUE_N(c, op2, rows, brow_slice(rot_q2, r0, rows, rot_parts * K),
|
||||
brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (paro5) {
|
||||
RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs),
|
||||
RAD_W(rot_angle), RAD_W(rot_scale), brow_slice(rot_q, r0, rows, rot_parts * K));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(rot_q, r0, rows, rot_parts * K), RAD_NONE,
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (mx || m2x) {
|
||||
/* A rotated weight first rotates its input into its own codes, `rot_parts` copies side by
|
||||
* side; a plain weight reads the producer's. An M2XFP4 weight runs the same issue: it
|
||||
* takes the operands MXFP4's does, its meta riding the weight operand's stored blob. */
|
||||
/* A rotated weight (MXFP4 or M2XFP4) first rotates its input into its own codes,
|
||||
* `rot_parts` copies side by side; a plain weight reads the producer's. */
|
||||
const rad_buf aq = paro ? rot_q : a.q, as = paro ? rot_s : a.s;
|
||||
const int64_t ak = rot_parts * K;
|
||||
if (paro)
|
||||
@@ -1607,12 +1712,12 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(aq, r0, rows, ak),
|
||||
brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_W(wref));
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_W(wref));
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K),
|
||||
brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
}
|
||||
|
||||
/* ================================================== an fp8 weight with no op of its own
|
||||
@@ -1633,13 +1738,8 @@ struct DenseFP8 {
|
||||
* works against the same E4M3 activation pair. */
|
||||
rad_weight ref = 0;
|
||||
bool mx = false;
|
||||
/* Or M2XFP4 (libquant `m2xfp4`): the MXFP4 weight plus one metadata byte a group, read by
|
||||
* `gemm_nt_q` at dtype m2xfp4 with the same views and the same `b_ref`. The meta plane rides
|
||||
* the weight operand's stored blob (libr4d's m2xfp4 layout), so the declared weight takes the
|
||||
* codes and meta planes together. */
|
||||
/* Or M2XFP4 (libquant `m2xfp4`): the MXFP4 views, the meta plane riding the weight operand. */
|
||||
bool m2x = false;
|
||||
/* The caller made the name map (a row range of a checkpoint tensor); declare() does not. */
|
||||
bool mapped = false;
|
||||
|
||||
/* `mapped`: the caller made the name map already, to ask the encoding before choosing this
|
||||
* struct over another grid's -- a COPY map declared twice is refused (rad_builder.cpp). */
|
||||
@@ -1658,6 +1758,7 @@ struct DenseFP8 {
|
||||
if (lo < 0 || hi <= lo || lo % RAD_FP8_BLOCK || hi % RAD_FP8_BLOCK || K % RAD_FP8_BLOCK)
|
||||
return RAD_E_INVAL;
|
||||
mx = false;
|
||||
m2x = false;
|
||||
ref = 0;
|
||||
const char* wn = nm.f("%s.weight", base);
|
||||
const char* sn = nm.f("%s.scale", base);
|
||||
@@ -1676,16 +1777,11 @@ 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 (m2x)
|
||||
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),
|
||||
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "m2xfp4")),
|
||||
RAD_WEIGHTS(w, s, ref)),
|
||||
reads, writes);
|
||||
if (mx)
|
||||
return rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")),
|
||||
RAD_INT("group", RAD_MX_GROUP),
|
||||
RAD_STR("dtype", m2x ? "m2xfp4" : "mxfp4a8")),
|
||||
RAD_WEIGHTS(w, s, ref)),
|
||||
reads, writes);
|
||||
if (split_n > 0)
|
||||
@@ -1701,7 +1797,8 @@ struct DenseFP8 {
|
||||
RAD_WEIGHTS(w, s)),
|
||||
reads, writes);
|
||||
}
|
||||
/* The op's trailing `b_ref` operand: the reference view for MXFP4 and M2XFP4, absent for fp8. */
|
||||
/* The op's trailing `b_ref` operand: the reference view for MXFP4 and M2XFP4, absent for
|
||||
* fp8. */
|
||||
RadOperand bref() const { return mx || m2x ? RAD_W(ref) : RAD_NONE; }
|
||||
};
|
||||
|
||||
@@ -1711,44 +1808,27 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
|
||||
std::initializer_list<int64_t> row_parts, bool mapped) {
|
||||
if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL;
|
||||
|
||||
/* ---- OCP-MXFP4, from the weight's encoding. The exponent grid is one row tall, so parts need
|
||||
* only whole 16-row tiles; K takes whole 128s for the activation's per-(row, 128) scale. */
|
||||
/* ---- OCP-MXFP4 or M2XFP4, from the weight's encoding. The exponent grid is one row tall, so
|
||||
* parts need only whole 16-row tiles; K takes whole 128s for the activation's per-(row, 128)
|
||||
* scale. */
|
||||
{
|
||||
const char* wn = nm.f("%s.weight", base);
|
||||
if (!mapped) RAD_ARCH_TRY(map_linear(b, wn, src));
|
||||
RadEncoding enc{};
|
||||
mx = weight_enc(b, wn, &enc) && linear_is_mxfp4(enc);
|
||||
/* ---- M2XFP4: the MXFP4 views plus the metadata plane riding the weight operand, the
|
||||
* same bounds. */
|
||||
m2x = weight_enc(b, wn, &enc) && linear_is_m2xfp4(enc);
|
||||
if (m2x) {
|
||||
const bool known = weight_enc(b, wn, &enc);
|
||||
mx = known && linear_is_mxfp4(enc);
|
||||
m2x = known && linear_is_m2xfp4(enc);
|
||||
if (mx || m2x) {
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an M2XFP4 weight takes rows "
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an %s weight takes rows "
|
||||
"in 16s and K in whole %d-column activation scale blocks\n",
|
||||
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
|
||||
base, (long long)N, (long long)K, m2x ? "M2XFP4" : "MXFP4", RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RowParts rp;
|
||||
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "M2XFP4 tiles"));
|
||||
w = decl_view(b, wn, nullptr, "codes,meta", RAD_FP4E2M1, { N, K }, access, shard, grp,
|
||||
rp.w, rp.n);
|
||||
s = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, m2x ? "M2XFP4 tiles" : "MXFP4 tiles"));
|
||||
w = decl_view(b, wn, nullptr, m2x ? "codes,meta" : "codes", RAD_FP4E2M1, { N, K },
|
||||
access, shard, grp, rp.w, rp.n);
|
||||
ref = decl_view(b, nm.f("%s.ref", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
access, shard, grp, rp.w, rp.n);
|
||||
return w && s && ref ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
if (mx) {
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an MXFP4 weight takes rows "
|
||||
"in 16s and K in whole %d-column activation scale blocks\n",
|
||||
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RowParts rp;
|
||||
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "MXFP4 tiles"));
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, access, shard, grp,
|
||||
rp.w, rp.n);
|
||||
s = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
access, shard, grp, rp.w, rp.n);
|
||||
ref = decl_view(b, nm.f("%s.ref", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
@@ -1777,14 +1857,16 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
|
||||
|
||||
/* gate_up, silu_mul and the E4M3 quantiser in one GEMM epilogue (`gemm_nt_q_gated`, an fp8a8
|
||||
* tile over a block-fp8 [2n, K] weight), declared for M up to min(rows, 64): the kernel refuses M
|
||||
* past that band. Optional: when it does not resolve the caller's unfused ops run, and the issue
|
||||
* past that band, unless the caller asks for the wide row (`wide`), whose gated prefill tile
|
||||
* serves every M. Optional: when it does not resolve the caller's unfused ops run, and the issue
|
||||
* site checks `*gated_rows`, set to the band only when the op exists. */
|
||||
inline rad_op decl_gated_fold(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w,
|
||||
rad_weight ws, std::initializer_list<rad_buf> reads,
|
||||
std::initializer_list<rad_buf> writes, int64_t* gated_rows) {
|
||||
const int64_t hi = rows < 64 ? rows : 64;
|
||||
std::initializer_list<rad_buf> writes, int64_t* gated_rows,
|
||||
bool wide = false) {
|
||||
const int64_t hi = wide ? rows : (rows < 64 ? rows : 64);
|
||||
if (hi <= 0) return 0;
|
||||
const rad_op op = rw(b, RAD_OP(b, "gemm_nt_q_gated",
|
||||
const rad_op op = rw(b, RAD_OP(b, wide ? "gemm_nt_q_gated_wide" : "gemm_nt_q_gated",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8"),
|
||||
RAD_STR("act", "silu")),
|
||||
@@ -1794,6 +1876,65 @@ inline rad_op decl_gated_fold(RadBuilder* b, int64_t rows, int64_t N, int64_t K,
|
||||
return op;
|
||||
}
|
||||
|
||||
/* The same fold over an OCP-MXFP4 [2n, K] gate_up weight (`gemm_nt_q_gated_mx`: codes, the E8M0
|
||||
* plane and that plane again as the per-row reference), declared for M up to min(rows, 16):
|
||||
* libr4d's gated_gemv serves 1..8 rows and gated_gemv_wide 9..64, each byte-identical to its band's
|
||||
* GEMM row (gemv, gemv_wide) followed by gated_quant_fp8. 16, not the wide row's 64: Qwen3.8-27B
|
||||
* at TP2 on 2x R9700 (spec 7, ms a decode step, three interleaved rounds against the 1..8 band)
|
||||
* gains at 16 rows (two sequences: 1k 20.96 -> 20.78, 16k 21.96 -> 21.70) but loses at 32 (four
|
||||
* sequences at 1k 23.97 -> 24.10, eight in the short block 24.99 -> 25.14), and 64 lost more
|
||||
* (16k x16 +2.1 %). The wide row refuses a short K (decode_shortk's corner), so where 1..16 does
|
||||
* not resolve the band drops to 1..8 rather than lose the fold. Optional like decl_gated_fold, and
|
||||
* asked for only when a loaded library declares the op: libref does not, so a CPU-only engine takes
|
||||
* the pair without ever naming it. */
|
||||
inline rad_op decl_gated_fold_mx(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w,
|
||||
rad_weight ws, rad_weight wref,
|
||||
std::initializer_list<rad_buf> reads,
|
||||
std::initializer_list<rad_buf> writes, int64_t* gated_rows) {
|
||||
if (rows <= 0 || N % 256 || K % RAD_FP8_BLOCK) return 0;
|
||||
if (!rad_op_declared(b, "gemm_nt_q_gated_mx")) return 0;
|
||||
for (const int64_t band : { (int64_t)16, (int64_t)8 }) {
|
||||
const int64_t hi = rows < band ? rows : band;
|
||||
const rad_op op = rw(b, RAD_OP(b, "gemm_nt_q_gated_mx",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_MX_GROUP),
|
||||
RAD_STR("dtype", "mxfp4a8"), RAD_STR("act", "silu")),
|
||||
RAD_WEIGHTS(w, ws, wref)),
|
||||
reads, writes);
|
||||
if (op) {
|
||||
*gated_rows = hi;
|
||||
return op;
|
||||
}
|
||||
if (hi <= 8) break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ================================================== a calibration tap */
|
||||
/* One tap of the GPTQ calibration (calib_dir): the Gram of a linear's bf16 input, summed over the
|
||||
* corpus in a PERSIST [K, K] f32 buffer that calib_write() saves. */
|
||||
struct CalibTap {
|
||||
rad_buf h = 0;
|
||||
rad_op op = 0;
|
||||
int64_t K = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, int64_t max_tok, const char* name, rad_buf a, int64_t k) {
|
||||
K = k;
|
||||
h = decl_b(b, nm.f("%s.gram", name), RAD_F32, { k, k }, RAD_BUF_PERSIST);
|
||||
if (!h) return RAD_E_INVAL;
|
||||
op = rw(b, RAD_OP(b, "gram_accum",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, max_tok), RAD_INT("n", k),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a, h }, { h });
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
/* gram_accum takes a, a_scale?, h: no scale for a bf16 input. */
|
||||
void step(RadCtx* c, rad_buf a, int64_t T, bool live) const {
|
||||
if (op && live) RAD_ISSUE_N(c, op, T, brows(a, T), RAD_NONE, brows(h, K));
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
|
||||
@@ -40,7 +40,8 @@
|
||||
* The sliding layers are causal and the full layer is not. The checkpoint's `layer_types` names
|
||||
* four sliding layers and one full one, and the PR's test pins `causal True` on the sliding
|
||||
* layers and `False` on the full one, so this block declares two attention ops and issues the one
|
||||
* each layer's type names.
|
||||
* each layer's type names. A config that states `dflash_config.causal` (NVIDIA's E4B drafter:
|
||||
* false, all five layers sliding) sets the sliding layers' causality.
|
||||
*
|
||||
* The logits are soft-capped, which is deliberately ignored: the draft is an argmax, and
|
||||
* cap * tanh(x / cap) is strictly increasing.
|
||||
@@ -187,6 +188,10 @@ inline bool dflash2_probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
out->draft_depth = (int)(bs - 1);
|
||||
out->draft_depth_fixed = 1;
|
||||
out->chain_pays = 1;
|
||||
/* Its proposals verified as a tree of the same node count (dflash_tree, rad_drafter_tree): on
|
||||
* 4x R9700 +7% single-stream decode and +6-9% aggregate at 1-16 users over the selector's
|
||||
* chain (BetterBench, thinking off; on two cards +4% and +6-12%). */
|
||||
out->tree_pays = 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -235,6 +240,7 @@ struct Dflash1 {
|
||||
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
|
||||
int64_t block = 0; /* query rows per sequence: the anchor plus block - 1 masks */
|
||||
int64_t window = 0; /* the sliding layers' window; 0 for none */
|
||||
int causal = 1; /* the sliding layers: causal (z-lab) or not (dflash_config.causal) */
|
||||
int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */
|
||||
double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */
|
||||
int64_t kv_rep = 1; /* how many times the cache holds each kv head (kv_rep_for) */
|
||||
@@ -616,6 +622,11 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta,
|
||||
"window\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* z-lab's configs state no causality and train the sliding layers causal; NVIDIA's
|
||||
* (Nemotron-3.5-Bolt-E4B's DFlash) states `dflash_config.causal: false`, every layer
|
||||
* sliding and non-causal over its window. */
|
||||
dc.causal = rad_meta_geti(meta, "draft.dflash_config.causal",
|
||||
rad_meta_geti(meta, "draft.is_causal", 1)) != 0 ? 1 : 0;
|
||||
}
|
||||
}
|
||||
if (!head_sharded(dg) && dg.world > 1) {
|
||||
@@ -670,11 +681,12 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta,
|
||||
int nfull = 0;
|
||||
for (int64_t l = 0; l < dg.n_layer; ++l) nfull += dc.full[l];
|
||||
rad_note(b, "the DFlash drafter is declared: %lld layers at absolute %d..%d (%d full, %lld "
|
||||
"sliding over %lld causal), %lld heads / %lld kv x %lld, ffn %lld, reading the "
|
||||
"sliding over %lld, %s), %lld heads / %lld kv x %lld, ffn %lld, reading the "
|
||||
"trunk at %lld tap(s); linears %s. One forward over %lld rows proposes %lld "
|
||||
"tokens; the head is %s, argmax %s",
|
||||
(long long)dg.n_layer, t.base_layer, t.base_layer + (int)dg.n_layer - 1, nfull,
|
||||
(long long)(dg.n_layer - nfull), (long long)dc.window, (long long)dg.n_head,
|
||||
(long long)(dg.n_layer - nfull), (long long)dc.window,
|
||||
dc.causal ? "causal" : "non-causal", (long long)dg.n_head,
|
||||
(long long)dg.n_head_kv, (long long)dg.head_dim, (long long)dg.n_ff,
|
||||
(long long)t.n_taps,
|
||||
df->i8 ? "int8 (w8a8, an int8 activation per row)" : "on the E4M3 grid (fp8a8 / mxfp4a8)",
|
||||
@@ -855,7 +867,7 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
};
|
||||
bool any_full = false, any_swa = false;
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true;
|
||||
if (any_swa) op_attn_swa = attn(1, cfg.window);
|
||||
if (any_swa) op_attn_swa = attn(cfg.causal, cfg.window);
|
||||
if (any_full) op_attn_full = attn(0, 0);
|
||||
|
||||
/* The copies into the cache's layout (rep_kv), a head-wide strided row copy each. Each pass's
|
||||
|
||||
@@ -13,9 +13,10 @@
|
||||
* row-interleaved all_gather, bit for bit the replicated projection
|
||||
*
|
||||
* The one rule for a run: ceil(T / world) rows, rounded up to whole 16-byte words of the gathered
|
||||
* row, because an all_gather moves whole words. The indexer gathers one i32 length a row beside
|
||||
* its page tables, so its runs are multiples of four rows. The last rank's run may be short, or
|
||||
* lie wholly past a small step (`run_of`). */
|
||||
* row, because an all_gather moves whole words. The MLA gathers 4096-wide bf16 rows, so its runs
|
||||
* are ceil(T / world); the indexer gathers one i32 length a row beside its page tables, so its
|
||||
* runs are multiples of four rows. The last rank's run may be short, or lie wholly past a small
|
||||
* step (`run_of`). */
|
||||
#ifndef RAD_GLM_TP_H
|
||||
#define RAD_GLM_TP_H
|
||||
#include "rad_arch.h"
|
||||
|
||||
@@ -216,6 +216,9 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
d.head_dim = c.head_dim / (2 * c.ratio);
|
||||
*bk = rad_decl_kv_group(b, nm.f("kv_qsa_bkey"), &d);
|
||||
if (!*bk) return RAD_E_INVAL;
|
||||
/* qsa_score reads every complete block of the history each step, so this group stays resident
|
||||
* and holds every sequence's context while a sibling streams (kvstream/carve.h). */
|
||||
RAD_ARCH_TRY(rad_kv_group_dense_read(b, *bk));
|
||||
}
|
||||
kv_bk = *bk;
|
||||
/* Under M-RoPE a block key rotates at its first token's three components, which qsa_work
|
||||
@@ -255,6 +258,9 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("seqs", g.max_seqs)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.score, w.nc}, {w.sel, w.nsel, w.sequ});
|
||||
|
||||
/* When the attention group streams, the attention block resolves `sel` to ring slots after its
|
||||
* layer's store (AttnGatedFP8::step); prefill runs on the stage and never resolves. */
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
@@ -28,9 +28,10 @@
|
||||
* `dimensions` first), so the pooled row here is the unnormalised mean.
|
||||
*
|
||||
* Everything the checkpoint carries is declared: the text model, the vision tower
|
||||
* (rad_block_gemma4_vision.h) and the audio encoder.
|
||||
* (rad_block_gemma4_vision.h) and the audio encoder (rad_block_gemma4_audio.h).
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_gemma4_audio.h>
|
||||
#include <arch/rad_block_gemma4_vision.h>
|
||||
|
||||
#include <cmath>
|
||||
@@ -65,435 +66,6 @@ struct Layer {
|
||||
rad_op op_post_ple = 0, op_add_ple = 0, op_scale = 0;
|
||||
};
|
||||
|
||||
/* ============================== THE AUDIO ENCODER (Gemma 4's USM conformer) ==============================
|
||||
*
|
||||
* a frame is 128 log-mel bins (the processor's), four frames an output row
|
||||
* subsampling: two 3x3 stride-2 convolutions over (time, frequency) -- 1 -> 128 -> 32 channels,
|
||||
* each input masked to the clip's real frames first, each followed by a channel LayerNorm (no
|
||||
* bias) and a ReLU -- then 32 x 32 features a row through a 1024 linear
|
||||
* 12 conformer blocks: a feed-forward at half weight, local attention (11 frames back, a
|
||||
* relative-position term, a softplus per-dimension query scale, a softcap of 50), a gated
|
||||
* depthwise causal convolution, a second half-weight feed-forward, a norm; their linears are
|
||||
* clipped: input and output clamped to bounds the checkpoint stores
|
||||
* 1024 -> 1536 with a bias, then the multimodal embedder: an RMS norm with no gain, 1536 -> 512.
|
||||
*
|
||||
* The blocks' clamps at +-1e10 ("gradient clipping") are omitted: they are ten orders of magnitude
|
||||
* beyond the activations' range and change nothing. One clip is one segment; a pass carries up to
|
||||
* RadBuildCtx::max_audio_frames frames. */
|
||||
struct Audio {
|
||||
/* A clipped linear: the weight and its four bounds. */
|
||||
struct Clip {
|
||||
rad_weight w = 0, in_lo = 0, in_hi = 0, out_lo = 0, out_hi = 0;
|
||||
rad_op op_in = 0, op_mm = 0, op_out = 0;
|
||||
};
|
||||
struct FF {
|
||||
rad_weight pre = 0, post = 0;
|
||||
Clip l1, l2;
|
||||
rad_op op_pre = 0, op_act = 0, op_post = 0, op_add = 0;
|
||||
};
|
||||
struct Layer {
|
||||
FF ff1, ff2;
|
||||
rad_weight n_pre_attn = 0, n_post_attn = 0, n_out = 0, w_rel = 0, pds = 0;
|
||||
Clip q, k, v, post;
|
||||
rad_weight lc_pre = 0, lc_dw = 0, lc_norm = 0;
|
||||
Clip lc_start, lc_end;
|
||||
rad_op op_npa = 0, op_rel = 0, op_attn = 0, op_npo = 0, op_add_attn = 0;
|
||||
rad_op op_lc_pre = 0, op_glu = 0, op_dw = 0, op_lc_norm = 0, op_lc_act = 0, op_lc_add = 0;
|
||||
rad_op op_out = 0;
|
||||
};
|
||||
bool on = false;
|
||||
int64_t P = 0, R = 0, H = 0, heads = 0, hd = 0, ffw = 0, n_embd = 0, out_dims = 0;
|
||||
int64_t c0 = 0, c1 = 0, nmel = 0, merge = 4, left = 0, chunk = 0, n_rel = 0;
|
||||
double eps = 1e-6, softcap = 0;
|
||||
rad_weight w_c0 = 0, w_c1 = 0, w_n0 = 0, w_n1 = 0, w_in = 0, w_out = 0, b_outw = 0, w_emb = 0;
|
||||
rad_op op_c0 = 0, op_n0 = 0, op_r0 = 0, op_c1 = 0, op_n1 = 0, op_r1 = 0, op_in = 0;
|
||||
rad_op op_relpos = 0, op_outp = 0, op_en = 0, op_emb = 0;
|
||||
rad_buf b_s0 = 0, b_s1 = 0, b_x = 0, b_h = 0, b_hc = 0, b_f = 0, b_q = 0, b_k = 0, b_v = 0;
|
||||
rad_buf b_att = 0, b_o = 0, b_g = 0, b_u = 0, b_relpos = 0, b_relk = 0, b_o2 = 0, b_on = 0;
|
||||
rad_buf b_out = 0;
|
||||
std::vector<Layer> L;
|
||||
|
||||
static bool present(const RadModelMeta* m) {
|
||||
const char* t = rad_meta_gets(m, "audio_config.model_type", "");
|
||||
return t && !std::strcmp(t, "gemma4_audio");
|
||||
}
|
||||
/* The longest clip in frames: 30 s at the extractor's 10 ms hop, rounded up to whole rows. */
|
||||
static int64_t frames_for(const RadModelMeta* m) {
|
||||
const int64_t rate = rad_meta_geti(m, "preprocessor.sampling_rate", 16000);
|
||||
const int64_t fl = rad_meta_geti(m, "preprocessor.frame_length", 320);
|
||||
const int64_t hop = rad_meta_geti(m, "preprocessor.hop_length", 160);
|
||||
if (rate <= 0 || hop <= 0) return 0;
|
||||
const int64_t n = 30 * rate;
|
||||
const int64_t real = (n + fl / 2 - fl - 1) / hop + 1;
|
||||
return (real + 3) / 4 * 4;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK;
|
||||
const char* A = "audio_config";
|
||||
auto gi = [&](const char* k, int64_t d) {
|
||||
char key[96];
|
||||
std::snprintf(key, sizeof key, "%s.%s", A, k);
|
||||
return rad_meta_geti(m, key, d);
|
||||
};
|
||||
auto gf = [&](const char* k, double d) {
|
||||
char key[96];
|
||||
std::snprintf(key, sizeof key, "%s.%s", A, k);
|
||||
return rad_meta_getf(m, key, d);
|
||||
};
|
||||
H = gi("hidden_size", 0);
|
||||
heads = gi("num_attention_heads", 0);
|
||||
out_dims = gi("output_proj_dims", 0);
|
||||
chunk = gi("attention_chunk_size", 0);
|
||||
/* transformers masks a key unless 0 <= q - k < attention_context_left - 1, so the
|
||||
* furthest key back is context_left - 2 frames: 11 for this checkpoint, the query and
|
||||
* eleven before it. */
|
||||
left = gi("attention_context_left", 0) - 2;
|
||||
softcap = gf("attention_logit_cap", 0.0);
|
||||
eps = gf("rms_norm_eps", 1e-6);
|
||||
const int64_t depth = gi("num_hidden_layers", 0);
|
||||
const int64_t kconv = gi("conv_kernel_size", 0);
|
||||
const int64_t right = gi("attention_context_right", 0);
|
||||
const double resw = gf("residual_weight", 0.0);
|
||||
const char* act = rad_meta_gets(m, "audio_config.hidden_act", "");
|
||||
const char* chs = rad_meta_gets(m, "audio_config.subsampling_conv_channels", "");
|
||||
nmel = rad_meta_geti(m, "preprocessor.feature_size", 0);
|
||||
if (std::sscanf(chs ? chs : "", "%lld %lld", (long long*)&c0, (long long*)&c1) != 2)
|
||||
c0 = c1 = 0;
|
||||
hd = heads > 0 ? H / heads : 0;
|
||||
ffw = 4 * H;
|
||||
n_rel = left + 1;
|
||||
if (H <= 0 || heads <= 0 || hd * heads != H || out_dims <= 0 || depth <= 0 || kconv <= 0 ||
|
||||
chunk <= 0 || left < 0 || right != 0 || !(softcap > 0) || resw != 0.5 ||
|
||||
std::strcmp(act ? act : "", "silu") || c0 <= 0 || c1 <= 0 || nmel != 128 ||
|
||||
(nmel / 4) * c1 != H) {
|
||||
fprintf(stderr, "radiance: embgemma2: the container's audio_config is not the "
|
||||
"conformer this plugin serves (hidden %lld, heads %lld, output %lld, "
|
||||
"layers %lld, conv %lld, left %lld right %lld, residual %g, act %s, "
|
||||
"subsampling %lld/%lld over %lld bins)\n", (long long)H,
|
||||
(long long)heads, (long long)out_dims, (long long)depth, (long long)kconv,
|
||||
(long long)left, (long long)right, resw, act ? act : "", (long long)c0,
|
||||
(long long)c1, (long long)nmel);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
n_embd = model_embd;
|
||||
P = ctx->max_audio_frames;
|
||||
if (P % merge) return RAD_E_SHAPE;
|
||||
R = P / merge;
|
||||
const int AC = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
|
||||
const char* T = "audio_tower";
|
||||
|
||||
/* ---- weights */
|
||||
auto w = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
|
||||
RadWeightGroup g) -> rad_weight {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, RAD_BF16, shp, AC, N, g);
|
||||
};
|
||||
auto clip = [&](Clip& c, const char* dn, const char* src, int64_t out, int64_t in,
|
||||
RadWeightGroup g) {
|
||||
char d1[160], s1[200];
|
||||
std::snprintf(d1, sizeof d1, "%s.w", dn); std::snprintf(s1, sizeof s1, "%s.linear.weight", src);
|
||||
c.w = w(nm.f("%s", d1), nm.ckpt("%s", s1), {out, in}, g);
|
||||
const char* bn[4] = { "input_min", "input_max", "output_min", "output_max" };
|
||||
rad_weight* dst[4] = { &c.in_lo, &c.in_hi, &c.out_lo, &c.out_hi };
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
std::snprintf(d1, sizeof d1, "%s.%s", dn, bn[i]);
|
||||
std::snprintf(s1, sizeof s1, "%s.%s", src, bn[i]);
|
||||
*dst[i] = w(nm.f("%s", d1), nm.ckpt("%s", s1), {1}, g);
|
||||
}
|
||||
};
|
||||
w_c0 = w(nm.f("a.sscp.c0"), nm.ckpt("%s.subsample_conv_projection.layer0.conv.weight", T), {c0, 1, 3, 3}, grp_model());
|
||||
w_n0 = w(nm.f("a.sscp.n0"), nm.ckpt("%s.subsample_conv_projection.layer0.norm.weight", T), {c0}, grp_model());
|
||||
w_c1 = w(nm.f("a.sscp.c1"), nm.ckpt("%s.subsample_conv_projection.layer1.conv.weight", T), {c1, c0, 3, 3}, grp_model());
|
||||
w_n1 = w(nm.f("a.sscp.n1"), nm.ckpt("%s.subsample_conv_projection.layer1.norm.weight", T), {c1}, grp_model());
|
||||
w_in = w(nm.f("a.sscp.proj"), nm.ckpt("%s.subsample_conv_projection.input_proj_linear.weight", T), {H, H}, grp_model());
|
||||
w_out = w(nm.f("a.out.w"), nm.ckpt("%s.output_proj.weight", T), {out_dims, H}, grp_model());
|
||||
b_outw = w(nm.f("a.out.b"), nm.ckpt("%s.output_proj.bias", T), {out_dims}, grp_model());
|
||||
w_emb = w(nm.f("a.embed"), nm.ckpt("embed_audio.embedding_projection.weight"), {n_embd, out_dims}, grp_model());
|
||||
L.assign((size_t)depth, Layer{});
|
||||
for (int64_t i = 0; i < depth; ++i) {
|
||||
Layer& l = L[(size_t)i];
|
||||
const long long li = (long long)i;
|
||||
const RadWeightGroup g = grp_layer(first_group + (int)i);
|
||||
char d[96], s[160];
|
||||
auto D = [&](const char* x) { std::snprintf(d, sizeof d, "a.blk.%lld.%s", li, x); return nm.f("%s", d); };
|
||||
auto S = [&](const char* x) { std::snprintf(s, sizeof s, "%s.layers.%lld.%s", T, li, x); return nm.ckpt("%s", s); };
|
||||
for (int f = 0; f < 2; ++f) {
|
||||
FF& ff = f ? l.ff2 : l.ff1;
|
||||
const char* fn = f ? "feed_forward2" : "feed_forward1";
|
||||
char px[64]; std::snprintf(px, sizeof px, "%s.pre_layer_norm.weight", fn);
|
||||
ff.pre = w(D(px), S(px), {H}, g);
|
||||
std::snprintf(px, sizeof px, "%s.post_layer_norm.weight", fn);
|
||||
ff.post = w(D(px), S(px), {H}, g);
|
||||
char dn[96], sn[160];
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.%s.l1", li, fn);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.%s.ffw_layer_1", T, li, fn);
|
||||
clip(ff.l1, dn, sn, ffw, H, g);
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.%s.l2", li, fn);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.%s.ffw_layer_2", T, li, fn);
|
||||
clip(ff.l2, dn, sn, H, ffw, g);
|
||||
}
|
||||
l.n_pre_attn = w(D("norm_pre_attn"), S("norm_pre_attn.weight"), {H}, g);
|
||||
l.n_post_attn = w(D("norm_post_attn"), S("norm_post_attn.weight"), {H}, g);
|
||||
l.n_out = w(D("norm_out"), S("norm_out.weight"), {H}, g);
|
||||
l.w_rel = w(D("rel_k"), S("self_attn.relative_k_proj.weight"), {H, H}, g);
|
||||
l.pds = w(D("per_dim_scale"), S("self_attn.per_dim_scale"), {hd}, g);
|
||||
const char* qn[4] = { "q_proj", "k_proj", "v_proj", "post" };
|
||||
Clip* qc[4] = { &l.q, &l.k, &l.v, &l.post };
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
char dn[96], sn[160];
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.attn.%s", li, qn[j]);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.self_attn.%s", T, li, qn[j]);
|
||||
clip(*qc[j], dn, sn, H, H, g);
|
||||
}
|
||||
l.lc_pre = w(D("lconv.pre"), S("lconv1d.pre_layer_norm.weight"), {H}, g);
|
||||
l.lc_dw = w(D("lconv.dw"), S("lconv1d.depthwise_conv1d.weight"), {H, 1, kconv}, g);
|
||||
l.lc_norm = w(D("lconv.norm"), S("lconv1d.conv_norm.weight"), {H}, g);
|
||||
{
|
||||
char dn[96], sn[160];
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.lconv.start", li);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.lconv1d.linear_start", T, li);
|
||||
clip(l.lc_start, dn, sn, 2 * H, H, g);
|
||||
std::snprintf(dn, sizeof dn, "a.blk.%lld.lconv.end", li);
|
||||
std::snprintf(sn, sizeof sn, "%s.layers.%lld.lconv1d.linear_end", T, li);
|
||||
clip(l.lc_end, dn, sn, H, H, g);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- activations: the subsampler's planes at their own widths, the blocks' at R rows */
|
||||
b_s0 = decl_b(b, nm.f("a.s0"), RAD_BF16, {P / 2, (nmel / 2) * c0});
|
||||
b_s1 = decl_b(b, nm.f("a.s1"), RAD_BF16, {R, (nmel / 4) * c1});
|
||||
b_x = decl_b(b, nm.f("a.x"), RAD_BF16, {R, H});
|
||||
b_h = decl_b(b, nm.f("a.h"), RAD_BF16, {R, H});
|
||||
b_hc = decl_b(b, nm.f("a.hc"), RAD_BF16, {R, H});
|
||||
b_f = decl_b(b, nm.f("a.f"), RAD_BF16, {R, ffw});
|
||||
b_q = decl_b(b, nm.f("a.q"), RAD_BF16, {R, H});
|
||||
b_k = decl_b(b, nm.f("a.k"), RAD_BF16, {R, H});
|
||||
b_v = decl_b(b, nm.f("a.v"), RAD_BF16, {R, H});
|
||||
b_att = decl_b(b, nm.f("a.att"), RAD_BF16, {R, H});
|
||||
b_o = decl_b(b, nm.f("a.o"), RAD_BF16, {R, H});
|
||||
b_g = decl_b(b, nm.f("a.g"), RAD_BF16, {R, 2 * H});
|
||||
b_u = decl_b(b, nm.f("a.u"), RAD_BF16, {R, H});
|
||||
b_relpos = decl_b(b, nm.f("a.relpos"), RAD_BF16, {n_rel, H});
|
||||
b_relk = decl_b(b, nm.f("a.relk"), RAD_BF16, {n_rel, H});
|
||||
b_o2 = decl_b(b, nm.f("a.o2"), RAD_BF16, {R, out_dims});
|
||||
b_on = decl_b(b, nm.f("a.on"), RAD_BF16, {R, out_dims});
|
||||
b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {R, n_embd});
|
||||
|
||||
auto gemm = [&](int64_t rows, int64_t Nn, int64_t K, rad_weight wt) {
|
||||
return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn),
|
||||
RAD_INT("K", K), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
auto rms = [&](int64_t rows, int64_t n, rad_weight wt, double mult) {
|
||||
if (!wt)
|
||||
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("mult", mult)),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
auto clamp = [&](int64_t rows, int64_t n, rad_weight lo, rad_weight hi) {
|
||||
return RAD_OP(b, "clamp", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(lo, hi));
|
||||
};
|
||||
auto unary = [&](const char* op, int64_t rows, int64_t n) {
|
||||
return RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto add = [&](int64_t rows, int64_t n) { return unary("add", rows, n); };
|
||||
auto lnorm = [&](int64_t rows, int64_t n, rad_weight g) {
|
||||
return RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
|
||||
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(g));
|
||||
};
|
||||
auto conv = [&](int64_t rows, int64_t width, int64_t ci, int64_t co, int64_t cu_div,
|
||||
int64_t vstride, rad_weight wt) {
|
||||
return RAD_OP(b, "conv2d", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("width", width),
|
||||
RAD_INT("cin", ci), RAD_INT("cout", co),
|
||||
RAD_INT("kh", 3), RAD_INT("kw", 3),
|
||||
RAD_INT("stride", 2), RAD_INT("pad", 1),
|
||||
RAD_INT("cu_div", cu_div),
|
||||
RAD_INT("valid_stride", vstride),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
/* A clipped linear over rows of `in` into `out`: the input clamp writes a copy (the input
|
||||
* feeds several projections, each with its own bounds), the output clamp is in place. The
|
||||
* copy is a whole [R, n_in] buffer, since a GEMM's input must be contiguous. */
|
||||
auto clipped = [&](Clip& c, int64_t n_out, int64_t n_in, rad_buf in, rad_buf tmp,
|
||||
rad_buf out) {
|
||||
c.op_in = rw(b, clamp(R, n_in, c.in_lo, c.in_hi), {in}, {tmp});
|
||||
c.op_mm = rw(b, gemm(R, n_out, n_in, c.w), {tmp}, {out});
|
||||
c.op_out = rw(b, clamp(R, n_out, c.out_lo, c.out_hi), {out}, {out});
|
||||
};
|
||||
|
||||
op_c0 = rw(b, conv(P, nmel, 1, c0, 1, 1, w_c0), {}, {b_s0});
|
||||
op_n0 = rw(b, lnorm(P / 2 * (nmel / 2), c0, w_n0), {b_s0}, {b_s0});
|
||||
op_r0 = rw(b, unary("relu", P / 2 * (nmel / 2), c0), {b_s0}, {b_s0});
|
||||
op_c1 = rw(b, conv(P / 2, nmel / 2, c0, c1, 2, 2, w_c1), {b_s0}, {b_s1});
|
||||
op_n1 = rw(b, lnorm(R * (nmel / 4), c1, w_n1), {b_s1}, {b_s1});
|
||||
op_r1 = rw(b, unary("relu", R * (nmel / 4), c1), {b_s1}, {b_s1});
|
||||
op_in = rw(b, gemm(R, H, H, w_in), {b_s1}, {b_x});
|
||||
op_relpos = rw(b, RAD_OP(b, "rel_sinusoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, n_rel), RAD_INT("n", H),
|
||||
RAD_F64("max_timescale", 10000.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {b_relpos});
|
||||
for (Layer& l : L) {
|
||||
auto ffw_block = [&](FF& ff) {
|
||||
ff.op_pre = rw(b, rms(R, H, ff.pre, 1.0), {b_x}, {b_h});
|
||||
clipped(ff.l1, ffw, H, b_h, b_hc, b_f);
|
||||
ff.op_act = rw(b, unary("silu", R, ffw), {b_f}, {b_f});
|
||||
/* the activation's only reader is this linear, so its clamp is in place */
|
||||
clipped(ff.l2, H, ffw, b_f, b_f, b_o);
|
||||
ff.op_post = rw(b, rms(R, H, ff.post, 0.5), {b_o}, {b_o});
|
||||
ff.op_add = rw(b, add(R, H), {b_x, b_o}, {b_x});
|
||||
};
|
||||
ffw_block(l.ff1);
|
||||
l.op_npa = rw(b, rms(R, H, l.n_pre_attn, 1.0), {b_x}, {b_h});
|
||||
clipped(l.q, H, H, b_h, b_hc, b_q);
|
||||
clipped(l.k, H, H, b_h, b_hc, b_k);
|
||||
clipped(l.v, H, H, b_h, b_hc, b_v);
|
||||
l.op_rel = rw(b, gemm(n_rel, H, H, l.w_rel), {b_relpos}, {b_relk});
|
||||
l.op_attn = rw(b, RAD_OP(b, "attn_local_rel",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd),
|
||||
RAD_INT("n_head", heads), RAD_INT("left", left),
|
||||
RAD_INT("right", 0), RAD_F64("softcap", softcap),
|
||||
RAD_INT("cu_div", merge), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(l.pds)),
|
||||
{b_q, b_k, b_v, b_relk}, {b_att});
|
||||
clipped(l.post, H, H, b_att, b_hc, b_o);
|
||||
l.op_npo = rw(b, rms(R, H, l.n_post_attn, 1.0), {b_o}, {b_o});
|
||||
l.op_add_attn = rw(b, add(R, H), {b_x, b_o}, {b_x});
|
||||
l.op_lc_pre = rw(b, rms(R, H, l.lc_pre, 1.0), {b_x}, {b_h});
|
||||
clipped(l.lc_start, 2 * H, H, b_h, b_hc, b_g);
|
||||
/* GLU: the first half times the sigmoid of the second. */
|
||||
l.op_glu = rw(b, RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
|
||||
RAD_STR("act", "sigmoid"), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_g}, {b_u});
|
||||
l.op_dw = rw(b, RAD_OP(b, "conv1d_dw",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
|
||||
RAD_INT("k", kconv), RAD_INT("cu_div", merge),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(l.lc_dw)),
|
||||
{b_u}, {b_o});
|
||||
l.op_lc_norm = rw(b, rms(R, H, l.lc_norm, 1.0), {b_o}, {b_o});
|
||||
l.op_lc_act = rw(b, unary("silu", R, H), {b_o}, {b_o});
|
||||
clipped(l.lc_end, H, H, b_o, b_hc, b_u);
|
||||
l.op_lc_add = rw(b, add(R, H), {b_x, b_u}, {b_x});
|
||||
ffw_block(l.ff2);
|
||||
l.op_out = rw(b, rms(R, H, l.n_out, 1.0), {b_x}, {b_x});
|
||||
}
|
||||
op_outp = rw(b, RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("N", out_dims),
|
||||
RAD_INT("K", H), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("act", "none")),
|
||||
RAD_WEIGHTS(w_out, b_outw)),
|
||||
{b_x}, {b_o2});
|
||||
op_en = rw(b, rms(R, out_dims, 0, 1.0), {b_o2}, {b_on});
|
||||
op_emb = rw(b, gemm(R, n_embd, out_dims, w_emb), {b_on}, {b_out});
|
||||
|
||||
RadEncoderDecl e{};
|
||||
e.name = "audio";
|
||||
e.modalities = RAD_MM_AUDIO;
|
||||
e.patch_dim = nmel;
|
||||
e.merge = merge;
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "audio encoder: %lld conformer blocks of %lld (%lld heads x %lld), "
|
||||
"subsampling %lld/%lld channels, local attention %lld back; %lld frames a "
|
||||
"pass -> %lld rows of %lld", (long long)depth, (long long)H, (long long)heads,
|
||||
(long long)hd, (long long)c0, (long long)c1, (long long)left, (long long)P,
|
||||
(long long)R, (long long)n_embd);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
|
||||
if (!on || Pn <= 0 || Pn > P || Pn % merge || S <= 0) {
|
||||
rad_step_fail(c, "an audio pass this program's audio encoder cannot serve: none "
|
||||
"declared, more frames than it was declared for, or not whole rows");
|
||||
return;
|
||||
}
|
||||
const int64_t Rn = Pn / merge;
|
||||
const int32_t* crd = batch->enc_coord;
|
||||
const RadOperand frames = praw2(batch->enc_pixels, RAD_BF16, Pn, nmel);
|
||||
const RadOperand valid = praw(crd + Pn, RAD_I32, Pn);
|
||||
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
|
||||
auto clipped = [&](const Clip& cl, rad_buf in, int64_t n_in, rad_buf tmp, rad_buf out,
|
||||
int64_t n_out) {
|
||||
RAD_ISSUE_N(c, cl.op_in, Rn, bcol(in, 0, n_in, Rn), RAD_W(cl.in_lo), RAD_W(cl.in_hi),
|
||||
bcol(tmp, 0, n_in, Rn));
|
||||
RAD_ISSUE_N(c, cl.op_mm, Rn, bcol(tmp, 0, n_in, Rn), RAD_W(cl.w), bcol(out, 0, n_out, Rn));
|
||||
RAD_ISSUE_N(c, cl.op_out, Rn, bcol(out, 0, n_out, Rn), RAD_W(cl.out_lo), RAD_W(cl.out_hi),
|
||||
bcol(out, 0, n_out, Rn));
|
||||
};
|
||||
|
||||
RAD_ISSUE_N(c, op_c0, Pn, frames, RAD_W(w_c0), cu, valid, brows(b_s0, Pn / 2), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_n0, Pn / 2 * (nmel / 2), brows(b_s0, Pn / 2), RAD_W(w_n0), RAD_NONE,
|
||||
brows(b_s0, Pn / 2));
|
||||
RAD_ISSUE_N(c, op_r0, Pn / 2 * (nmel / 2), brows(b_s0, Pn / 2), brows(b_s0, Pn / 2));
|
||||
RAD_ISSUE_N(c, op_c1, Pn / 2, brows(b_s0, Pn / 2), RAD_W(w_c1), cu, valid, brows(b_s1, Rn),
|
||||
RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_n1, Rn * (nmel / 4), brows(b_s1, Rn), RAD_W(w_n1), RAD_NONE,
|
||||
brows(b_s1, Rn));
|
||||
RAD_ISSUE_N(c, op_r1, Rn * (nmel / 4), brows(b_s1, Rn), brows(b_s1, Rn));
|
||||
RAD_ISSUE_N(c, op_in, Rn, brows(b_s1, Rn), RAD_W(w_in), brows(b_x, Rn));
|
||||
RAD_ISSUE_N(c, op_relpos, n_rel, brows(b_relpos, n_rel));
|
||||
for (const Layer& l : L) {
|
||||
auto ffw_block = [&](const FF& ff) {
|
||||
RAD_ISSUE_N(c, ff.op_pre, Rn, brows(b_x, Rn), RAD_W(ff.pre), brows(b_h, Rn));
|
||||
clipped(ff.l1, b_h, H, b_hc, b_f, ffw);
|
||||
RAD_ISSUE_N(c, ff.op_act, Rn, brows(b_f, Rn), brows(b_f, Rn));
|
||||
clipped(ff.l2, b_f, ffw, b_f, b_o, H);
|
||||
RAD_ISSUE_N(c, ff.op_post, Rn, brows(b_o, Rn), RAD_W(ff.post), brows(b_o, Rn));
|
||||
RAD_ISSUE_N(c, ff.op_add, Rn, brows(b_x, Rn), brows(b_o, Rn), brows(b_x, Rn));
|
||||
};
|
||||
ffw_block(l.ff1);
|
||||
RAD_ISSUE_N(c, l.op_npa, Rn, brows(b_x, Rn), RAD_W(l.n_pre_attn), brows(b_h, Rn));
|
||||
clipped(l.q, b_h, H, b_hc, b_q, H);
|
||||
clipped(l.k, b_h, H, b_hc, b_k, H);
|
||||
clipped(l.v, b_h, H, b_hc, b_v, H);
|
||||
RAD_ISSUE_N(c, l.op_rel, n_rel, brows(b_relpos, n_rel), RAD_W(l.w_rel),
|
||||
brows(b_relk, n_rel));
|
||||
RAD_ISSUE_N(c, l.op_attn, Rn, brows(b_q, Rn), brows(b_k, Rn), brows(b_v, Rn),
|
||||
brows(b_relk, n_rel), RAD_W(l.pds), cu, brows(b_att, Rn));
|
||||
clipped(l.post, b_att, H, b_hc, b_o, H);
|
||||
RAD_ISSUE_N(c, l.op_npo, Rn, brows(b_o, Rn), RAD_W(l.n_post_attn), brows(b_o, Rn));
|
||||
RAD_ISSUE_N(c, l.op_add_attn, Rn, brows(b_x, Rn), brows(b_o, Rn), brows(b_x, Rn));
|
||||
RAD_ISSUE_N(c, l.op_lc_pre, Rn, brows(b_x, Rn), RAD_W(l.lc_pre), brows(b_h, Rn));
|
||||
clipped(l.lc_start, b_h, H, b_hc, b_g, 2 * H);
|
||||
RAD_ISSUE_N(c, l.op_glu, Rn, bcol(b_g, H, H, Rn), bcol(b_g, 0, H, Rn), brows(b_u, Rn));
|
||||
RAD_ISSUE_N(c, l.op_dw, Rn, brows(b_u, Rn), RAD_W(l.lc_dw), cu, brows(b_o, Rn),
|
||||
RAD_NONE);
|
||||
RAD_ISSUE_N(c, l.op_lc_norm, Rn, brows(b_o, Rn), RAD_W(l.lc_norm), brows(b_o, Rn));
|
||||
RAD_ISSUE_N(c, l.op_lc_act, Rn, brows(b_o, Rn), brows(b_o, Rn));
|
||||
clipped(l.lc_end, b_o, H, b_hc, b_u, H);
|
||||
RAD_ISSUE_N(c, l.op_lc_add, Rn, brows(b_x, Rn), brows(b_u, Rn), brows(b_x, Rn));
|
||||
ffw_block(l.ff2);
|
||||
RAD_ISSUE_N(c, l.op_out, Rn, brows(b_x, Rn), RAD_W(l.n_out), brows(b_x, Rn));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_outp, Rn, brows(b_x, Rn), RAD_W(w_out), RAD_W(b_outw), RAD_NONE,
|
||||
brows(b_o2, Rn));
|
||||
RAD_ISSUE_N(c, op_en, Rn, brows(b_o2, Rn), RAD_NONE, brows(b_on, Rn));
|
||||
RAD_ISSUE_N(c, op_emb, Rn, brows(b_on, Rn), RAD_W(w_emb), brows(b_out, Rn));
|
||||
}
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{};
|
||||
@@ -511,7 +83,7 @@ struct Model {
|
||||
|
||||
std::vector<Layer> layers;
|
||||
Gemma4Vision vis;
|
||||
Audio aud;
|
||||
Gemma4Audio aud;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
@@ -700,7 +272,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* A media part's rows overwrite its placeholders' embeddings before anything reads them, so an
|
||||
* image token's per-layer inputs come from its image row (declared only with a tower). */
|
||||
if ((Gemma4Vision::present(meta) && ctx->max_enc_patches > 0) ||
|
||||
(Audio::present(meta) && ctx->max_audio_frames > 0))
|
||||
(Gemma4Audio::present(meta) && ctx->max_audio_frames > 0))
|
||||
m.op_mm = rw(b, RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
@@ -816,8 +388,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
{m.b_proj}, {m.b_pooled});
|
||||
|
||||
RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, E, (int)g.n_layer, "", "embgemma2"));
|
||||
RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, E,
|
||||
(int)g.n_layer + (int)m.vis.L.size()));
|
||||
RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, E, (int)g.n_layer + (int)m.vis.L.size(), "",
|
||||
"embgemma2"));
|
||||
|
||||
int n_full = 0;
|
||||
for (int f : full) n_full += f;
|
||||
@@ -840,7 +412,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
const int64_t k = rad_meta_geti(meta, "vision_config.pooling_kernel_size", 0);
|
||||
if (k > 0) out->enc_merge = k * k;
|
||||
}
|
||||
if (Audio::present(meta)) out->audio_frames = Audio::frames_for(meta);
|
||||
if (Gemma4Audio::present(meta)) out->audio_frames = Gemma4Audio::frames_for(meta);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/fishomni -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(fishomni LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(fishomni architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/fishomni.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
+55
-37
@@ -69,18 +69,25 @@ namespace FLUX3_NS {
|
||||
using namespace rad::arch;
|
||||
|
||||
/* ================================================================== the model's constants */
|
||||
/* The largest image: 2048 x 2048 pixels, 16384 latent tokens; 1024 x 1024 is the default. */
|
||||
/* The largest image: 2048 x 2048 pixels, 16384 latent tokens; 1024 x 1024 is the default.
|
||||
* --image-gen-max-pixels lowers it (Model::max_img), and the buffers sized for it with it. */
|
||||
enum { kMaxImageTokens = 16384 };
|
||||
/* Reference pictures: ten at most, each shrunk to 1024 x 1024 pixels of area when larger. */
|
||||
/* Reference pictures: ten at most, each shrunk to 1024 x 1024 pixels of area when larger;
|
||||
* --image-gen-max-refs lowers the count (Model::max_refs). */
|
||||
enum { kMaxRefs = 10, kRefArea = 1024 * 1024 };
|
||||
/* The prompt with its padding, at most; the pipeline pads to a multiple of 80. */
|
||||
enum { kMaxText = 1040, kPadMultiple = 80 };
|
||||
/* A reference picture's latent tokens at most: its area over 16 x 16 and the slack of its sides'
|
||||
* rounding (the driver's bound). */
|
||||
static inline int64_t ref_tokens_max() { return (int64_t)kRefArea / 256 * 11 / 10 + 64; }
|
||||
/* The longest conditioning: the text and every reference picture's tokens. */
|
||||
static inline int64_t cond_rows() { return kMaxText + kMaxRefs * ref_tokens_max(); }
|
||||
/* Images in flight. Each lane keeps both branches' conditioning (cond_rows() rows apiece). */
|
||||
/* The largest image's latent tokens under --image-gen-max-pixels `px` (0: the model's own). */
|
||||
static inline int64_t image_tokens(int64_t px) {
|
||||
return px > 0 ? std::clamp<int64_t>(px / 256, 1, kMaxImageTokens) : (int64_t)kMaxImageTokens;
|
||||
}
|
||||
/* The longest conditioning with `refs` reference pictures: the text and every picture's tokens. */
|
||||
static inline int64_t cond_rows(int64_t refs) { return kMaxText + refs * ref_tokens_max(); }
|
||||
/* Images in flight, at most; --max-num-seqs lowers it (Model::lanes). Each lane keeps both
|
||||
* branches' conditioning (cond_rows() rows apiece). */
|
||||
enum { kMaxLanes = 4 };
|
||||
/* The language model's hidden states read: hidden_states[i], the output of layer i - 1. */
|
||||
static const int kTaps[] = { 4, 8, 12, 16, 20, 24, 28, 32 };
|
||||
@@ -120,6 +127,10 @@ struct Model {
|
||||
Names nm{""};
|
||||
Geom gt{}, gd{};
|
||||
bool flow_map = false;
|
||||
/* The deployment's bounds (declare, from RadBuildCtx): the largest image in latent tokens, the
|
||||
* reference pictures a request and the images in flight. Every per-image, conditioning and
|
||||
* lane buffer is sized for them. */
|
||||
int64_t max_img = kMaxImageTokens, max_refs = kMaxRefs, lanes = kMaxLanes;
|
||||
std::string te_pre;
|
||||
|
||||
/* ---- the language model and context_embedder */
|
||||
@@ -386,7 +397,7 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.b_ctx, &m.w_ctx, RAD_ACCESS_PER_REQUEST, kGrpCtx);
|
||||
m.op_store_t = rw(b, RAD_OP(b, "lane_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D),
|
||||
RAD_INT("stride", 2 * cond_rows()),
|
||||
RAD_INT("stride", 2 * cond_rows(m.max_refs)),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_ctx, m.b_store }, { m.b_store });
|
||||
@@ -403,8 +414,8 @@ static int declare_encoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
v.scope = "venc";
|
||||
v.down = true;
|
||||
v.first_group = kGrpVaeEnc;
|
||||
v.base_px = ref_tokens_max() * 256 > (int64_t)kMaxImageTokens * 256
|
||||
? ref_tokens_max() * 256 : (int64_t)kMaxImageTokens * 256;
|
||||
v.base_px = ref_tokens_max() * 256 > m.max_img * 256
|
||||
? ref_tokens_max() * 256 : m.max_img * 256;
|
||||
/* The mid-block attends over the 8x grid: four of the pass's 16x tokens a 16x token. */
|
||||
m.b_ecu = decl_b(b, nm.f("venc.cu"), RAD_I32, { 2 });
|
||||
m.op_ecu = rw(b, RAD_OP(b, "cu_repeat", RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", 4)),
|
||||
@@ -483,21 +494,21 @@ static int declare_encoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
tok, m.b_elat, m.b_eemb, &m.w_xc, RAD_ACCESS_PER_REQUEST, kGrpDit);
|
||||
m.op_store_r = rw(b, RAD_OP(b, "lane_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, tok), RAD_INT("n", m.gd.n_embd),
|
||||
RAD_INT("stride", 2 * cond_rows()),
|
||||
RAD_INT("stride", 2 * cond_rows(m.max_refs)),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_eemb, m.b_store }, { m.b_store });
|
||||
m.op_lstore_lat = rw(b, RAD_OP(b, "lane_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxImageTokens),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, m.max_img),
|
||||
RAD_INT("n", 4 * zc),
|
||||
RAD_INT("stride", (int64_t)kMaxImageTokens),
|
||||
RAD_INT("stride", m.max_img),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_elat, m.b_inp }, { m.b_inp });
|
||||
m.op_lstore_mask = rw(b, RAD_OP(b, "lane_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxImageTokens),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, m.max_img),
|
||||
RAD_INT("n", 1),
|
||||
RAD_INT("stride", (int64_t)kMaxImageTokens),
|
||||
RAD_INT("stride", m.max_img),
|
||||
RAD_STR("dtype", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_mask }, { m.b_mask });
|
||||
@@ -585,7 +596,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
Names& nm = m.nm;
|
||||
const int64_t T = g.max_tok, S = g.max_seqs, D = g.n_embd, C = m.C;
|
||||
const int gx = kGrpDit;
|
||||
const int64_t NI = std::min<int64_t>(T, 2 * (int64_t)kMaxImageTokens);
|
||||
const int64_t NI = std::min<int64_t>(T, 2 * m.max_img);
|
||||
const int64_t te = rad_meta_geti(meta, "transformer.timestep_channels", 256);
|
||||
m.t_ch = te;
|
||||
|
||||
@@ -695,13 +706,13 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.b_h = decl_b(b, nm.f("dit.h"), RAD_BF16, { T, D });
|
||||
m.op_randn = rw(b, RAD_OP(b, "randn_lanes",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C),
|
||||
RAD_INT("stride", (int64_t)kMaxImageTokens),
|
||||
RAD_INT("stride", m.max_img),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_state }, { m.b_state });
|
||||
m.op_lgather = rw(b, RAD_OP(b, "lane_gather",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C),
|
||||
RAD_INT("stride", (int64_t)kMaxImageTokens),
|
||||
RAD_INT("stride", m.max_img),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_state }, { m.b_lat });
|
||||
@@ -799,7 +810,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
&m.w_pout, RAD_ACCESS_PER_TOKEN, gx);
|
||||
m.op_euler = rw(b, RAD_OP(b, "flow_euler",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C),
|
||||
RAD_INT("stride", (int64_t)kMaxImageTokens),
|
||||
RAD_INT("stride", m.max_img),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_v, m.b_inp, m.b_mask, m.b_state, m.b_prev }, { m.b_state, m.b_prev });
|
||||
@@ -818,7 +829,7 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
v.scope = "vdec";
|
||||
v.down = false;
|
||||
v.first_group = kGrpVaeDec;
|
||||
v.base_px = (int64_t)kMaxImageTokens * 4;
|
||||
v.base_px = m.max_img * 4;
|
||||
std::vector<double> ch = meta_list(meta, "vae.decoder_block_out_channels");
|
||||
if (ch.empty()) ch = meta_list(meta, "vae.block_out_channels");
|
||||
if (ch.empty()) ch = { 128, 256, 512, 512 };
|
||||
@@ -826,7 +837,7 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
const int64_t groups = rad_meta_geti(meta, "vae.norm_num_groups", 32);
|
||||
const int64_t zc = rad_meta_geti(meta, "vae.latent_channels", 32);
|
||||
const double eps = 1e-6;
|
||||
const int64_t NT = kMaxImageTokens;
|
||||
const int64_t NT = m.max_img;
|
||||
m.b_dl = decl_b(b, nm.f("vdec.lat"), RAD_BF16, { NT, 4 * zc });
|
||||
m.b_decin = decl_b(b, nm.f("vdec.in"), RAD_BF16, { 4 * NT, zc });
|
||||
m.b_cu4 = decl_b(b, nm.f("vdec.cu"), RAD_I32, { 2 });
|
||||
@@ -872,7 +883,7 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.dec_out = v.conv(x, 3, 3, 1, 1, "same", "vae.decoder.conv_out");
|
||||
if (!m.dec_out.buf) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(v.attn_reads(m.b_cu4));
|
||||
const int64_t px = (int64_t)kMaxImageTokens * 256;
|
||||
const int64_t px = m.max_img * 256;
|
||||
m.b_img = decl_b(b, nm.f("image_out"), RAD_U8, { px * 3 }, RAD_BUF_PERSIST);
|
||||
m.op_rgb = rw(b, RAD_OP(b, "to_rgba8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("n", 3),
|
||||
@@ -894,6 +905,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.te_pre = std::strstr(rad_meta_gets(meta, "architectures", ""), "ForConditionalGeneration")
|
||||
? "model.language_model" : "language_model";
|
||||
m.flow_map = rad_meta_geti(meta, "transformer.flow_map", 0) != 0;
|
||||
/* The deployment's bounds: --image-gen-max-pixels in latent tokens of 16 x 16 pixels,
|
||||
* --image-gen-max-refs, and --max-num-seqs's images in flight (0: the model's own). */
|
||||
m.max_img = image_tokens(ctx->gen_max_pixels);
|
||||
if (ctx->gen_max_refs > 0) m.max_refs = std::min<int64_t>(ctx->gen_max_refs, kMaxRefs);
|
||||
if (ctx->max_seqs > 0) m.lanes = std::min<int64_t>(ctx->max_seqs, kMaxLanes);
|
||||
|
||||
Geom& gd = m.gd;
|
||||
gd = m.gt;
|
||||
@@ -930,13 +946,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
gd.w_bf16 = m.gt.w_bf16 = plain;
|
||||
}
|
||||
|
||||
const int64_t lane_rows = (int64_t)kMaxLanes * kMaxImageTokens;
|
||||
const int64_t lane_rows = m.lanes * m.max_img;
|
||||
m.b_state = decl_b(b, nm.f("lat_state"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST);
|
||||
m.b_prev = decl_b(b, nm.f("lat_preview"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST);
|
||||
m.b_inp = decl_b(b, nm.f("lat_repaint"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST);
|
||||
m.b_mask = decl_b(b, nm.f("lat_mask"), RAD_F32, { lane_rows, 1 }, RAD_BUF_PERSIST);
|
||||
m.b_store = decl_b(b, nm.f("cond_store"), RAD_BF16,
|
||||
{ 2 * (int64_t)kMaxLanes * cond_rows(), gd.n_embd }, RAD_BUF_PERSIST);
|
||||
{ 2 * m.lanes * cond_rows(m.max_refs), gd.n_embd }, RAD_BUF_PERSIST);
|
||||
/* ---- adapter key names. LoRA files name the blocks by Black Forest Labs' modules, as
|
||||
* ComfyUI loads them (comfy/ldm/flux3): `single_blocks.N.q_proj` or a fused `qkv`,
|
||||
* `attn_out`, `mlp_in`, `mlp_out`, and the mode blocks under `content_mode_blocks`. */
|
||||
@@ -980,12 +996,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
d.size_multiple = 16;
|
||||
d.pixel_channels = 3;
|
||||
d.slot_rows = 1;
|
||||
d.max_tokens = kMaxImageTokens;
|
||||
d.max_refs = kMaxRefs;
|
||||
d.max_tokens = m.max_img;
|
||||
d.max_refs = m.max_refs;
|
||||
d.ref_area = kRefArea;
|
||||
d.ref_shrink_only = 1;
|
||||
d.default_width = 1024;
|
||||
d.default_height = 1024;
|
||||
/* 1024 x 1024, or the largest square under --image-gen-max-pixels. */
|
||||
const int64_t side = std::min<int64_t>(64, (int64_t)std::sqrt((double)m.max_img));
|
||||
d.default_width = side * 16;
|
||||
d.default_height = side * 16;
|
||||
d.default_steps = m.flow_map ? 16 : 50;
|
||||
d.shift = rad_meta_getf(meta, "scheduler.shift", 6.93);
|
||||
d.dyn_shift = (int32_t)rad_meta_geti(meta, "scheduler.use_dynamic_shifting", 0);
|
||||
@@ -998,9 +1016,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
d.shift_terminal = rad_meta_getf(meta, "scheduler.shift_terminal", 0.0);
|
||||
d.default_cfg = m.flow_map ? 1.0 : 3.5;
|
||||
d.default_negative = "";
|
||||
d.max_lanes = kMaxLanes;
|
||||
d.max_lanes = m.lanes;
|
||||
d.image_out = m.b_img;
|
||||
d.cond_rows = cond_rows();
|
||||
d.cond_rows = cond_rows(m.max_refs);
|
||||
d.rope_hw_scale = 0.5;
|
||||
d.rope_text_l = 1;
|
||||
d.pad_multiple = kPadMultiple;
|
||||
@@ -1073,8 +1091,8 @@ static int64_t step_encode(RadCtx* c, const Model& m, const uint16_t* px, int64_
|
||||
static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const RadGenBatch* G = batch->gen_b;
|
||||
const int64_t T = batch->n_tok, D = m.gd.n_embd;
|
||||
const int64_t base = (int64_t)G->branch * cond_rows();
|
||||
const int64_t store_rows = 2 * (int64_t)kMaxLanes * cond_rows();
|
||||
const int64_t base = (int64_t)G->branch * cond_rows(m.max_refs);
|
||||
const int64_t store_rows = 2 * m.lanes * cond_rows(m.max_refs);
|
||||
const RadOperand lanes = praw(G->lane, RAD_I32, G->n_lane);
|
||||
step_te(c, batch, m);
|
||||
RAD_ISSUE_N(c, m.op_ctx, T, brows(m.b_taps, T), RAD_W(m.w_ctx), brows(m.b_ctx, T));
|
||||
@@ -1092,7 +1110,7 @@ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
brow_slice(m.b_store, base + row, store_rows - base - row, D));
|
||||
row += n;
|
||||
} else {
|
||||
const int64_t L = (int64_t)kMaxLanes * kMaxImageTokens;
|
||||
const int64_t L = m.lanes * m.max_img;
|
||||
RAD_ISSUE_N(c, m.op_lstore_lat, n, brows(m.b_elat, n), lanes, brows(m.b_inp, L));
|
||||
RAD_ISSUE_N(c, m.op_lstore_mask, n, praw2(G->inp_mask, RAD_F32, n, 1), lanes,
|
||||
brows(m.b_mask, L));
|
||||
@@ -1141,7 +1159,7 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1);
|
||||
const RadOperand icu = praw(G->img_cu, RAD_I32, S + 1);
|
||||
const RadOperand lanes = praw(G->lane, RAD_I32, S);
|
||||
const int64_t LR = (int64_t)kMaxLanes * kMaxImageTokens;
|
||||
const int64_t LR = m.lanes * m.max_img;
|
||||
|
||||
/* ---- the timestep embeddings and every modulation */
|
||||
RAD_ISSUE_N(c, m.op_tp, S, praw(G->sigma, RAD_F32, S), brows(m.b_tp, S));
|
||||
@@ -1180,7 +1198,7 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
RAD_ISSUE_N(c, m.op_xi, NI, brows(m.b_lat, NI), RAD_W(m.w_xi),
|
||||
brow_slice(m.b_xc, nt + nr, NI, D));
|
||||
if (nt + nr > 0)
|
||||
RAD_ISSUE_N(c, m.op_gtxt, nt + nr, brows(m.b_store, 2 * (int64_t)kMaxLanes * cond_rows()),
|
||||
RAD_ISSUE_N(c, m.op_gtxt, nt + nr, brows(m.b_store, 2 * m.lanes * cond_rows(m.max_refs)),
|
||||
praw(G->mode_src, RAD_I32, nt + nr), brows(m.b_xc, nt + nr));
|
||||
|
||||
/* ---- each mode's early blocks over its own rows, the last sum gated in */
|
||||
@@ -1222,7 +1240,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const RadGenBatch* G = batch->gen_b;
|
||||
const int64_t H = G->dec_height / 16, W = G->dec_width / 16, n = H * W, C = m.C;
|
||||
const rad_buf src = G->dec_preview ? m.b_prev : m.b_state;
|
||||
RAD_ISSUE_N(c, m.op_dbn, n, brow_slice(src, (int64_t)G->dec_lane * kMaxImageTokens, n, C),
|
||||
RAD_ISSUE_N(c, m.op_dbn, n, brow_slice(src, (int64_t)G->dec_lane * m.max_img, n, C),
|
||||
RAD_W(m.w_bnm), RAD_W(m.w_bnv), brows(m.b_dl, n));
|
||||
const int64_t zc = C / 4, H0 = 2 * H, W0 = 2 * W;
|
||||
RAD_ISSUE_N(c, m.op_dzero, H0 * W0, brows(m.b_decin, H0 * W0));
|
||||
@@ -1250,11 +1268,11 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
}
|
||||
|
||||
/* ================================================================== the probe */
|
||||
/* The rows a pass carries: an image at the largest size with one reference picture and its
|
||||
* longest text, both branches of guidance. */
|
||||
/* The rows a pass carries: an image at the largest size (under --image-gen-max-pixels) with one
|
||||
* reference picture and its longest text, both branches of guidance. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->gen_rows = 2 * ((int64_t)kMaxImageTokens + kMaxText + ref_tokens_max());
|
||||
out->gen_rows = 2 * (image_tokens(out->gen_max_pixels) + kMaxText + ref_tokens_max());
|
||||
out->gen_patches = 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
+569
-66
@@ -22,6 +22,7 @@
|
||||
#include <arch/rad_fp8.h>
|
||||
#include <arch/rad_block_dflash2.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cmath>
|
||||
@@ -94,7 +95,18 @@ struct G3Linear {
|
||||
bool i8g = false;
|
||||
bool mx = false;
|
||||
bool a4 = false; /* asymmetric int4 over the per-(row, 128) int8 activation */
|
||||
/* a4 at decode heights, as LinearFP8's w4 (rad_fp8.h): up to kA4Split rows the bf16 input is
|
||||
* cast to f16 (`a16`) for w4a16_asym's skinny kernel; w4a8i8_asym has only a prefill kernel,
|
||||
* which at one row does 16 times the matrix work. */
|
||||
static constexpr int64_t kA4Split = 64;
|
||||
int64_t a4_split = 0;
|
||||
rad_buf a16 = 0;
|
||||
rad_op op_a16 = 0, op_dec = 0;
|
||||
bool shared_in = false;
|
||||
/* Set before declare: an E4M3 (MXFP4) linear's input pair given by the caller (the pipelined
|
||||
* prefill's one pair for every block) instead of one of its own. It keeps its own quantiser
|
||||
* into it, so a step that does not write the pair by a fused junction still fills it. */
|
||||
rad_buf q8_into = 0, s8_into = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& g, const char* base,
|
||||
std::initializer_list<const char*> src,
|
||||
@@ -104,6 +116,9 @@ struct G3Linear {
|
||||
const G3Linear* in_from = nullptr);
|
||||
void step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const;
|
||||
void gemm(RadCtx* c, rad_buf y, int64_t T) const;
|
||||
/* The same over rows [r0, r0 + n) of an E4M3 (MXFP4) linear, for the pipelined prefill. */
|
||||
void step_rows(RadCtx* c, rad_buf a, rad_buf y, int64_t r0, int64_t n) const;
|
||||
void gemm_rows(RadCtx* c, rad_buf y, int64_t r0, int64_t n) const;
|
||||
};
|
||||
|
||||
inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char* base,
|
||||
@@ -198,7 +213,8 @@ inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K },
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
if (!w || !ws) return RAD_E_INVAL;
|
||||
if (in_from && (in_from->i8g || in_from->a4) && in_from->q8 && in_from->K == K) {
|
||||
/* not an a4 linear's pair: below its decode band it writes none */
|
||||
if (in_from && in_from->i8g && in_from->q8 && in_from->K == K) {
|
||||
q8 = in_from->q8;
|
||||
s8 = in_from->s8;
|
||||
shared_in = true;
|
||||
@@ -218,7 +234,21 @@ inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "w4a8i8_asym")),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ q8, s8 }, { y });
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
if (!op) return RAD_E_INVAL;
|
||||
a4_split = std::min<int64_t>(kA4Split, g.max_tok);
|
||||
a16 = decl_b(b, nm.f("%s.a16", base), RAD_F16, { a4_split, K });
|
||||
if (!a16) return RAD_E_INVAL;
|
||||
op_a16 = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("n", K),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", "f16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a }, { a16 });
|
||||
op_dec = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "w4a16_asym")),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ a16 }, { y });
|
||||
return (op_a16 && op_dec) ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
if (i8g || mx) {
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
@@ -239,13 +269,13 @@ inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
ws = decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
if (!w || !ws) return RAD_E_INVAL;
|
||||
}
|
||||
if (in_from && in_from->mx == mx && (in_from->i8g || in_from->a4) == i8g && in_from->q8 && in_from->K == K) {
|
||||
if (in_from && in_from->mx == mx && in_from->i8g == i8g && !in_from->a4 && in_from->q8 && in_from->K == K) {
|
||||
q8 = in_from->q8;
|
||||
s8 = in_from->s8;
|
||||
shared_in = true;
|
||||
} else {
|
||||
q8 = decl_b(b, nm.f("%s.q8", base), mx ? RAD_F8E4M3 : RAD_I8, { g.max_tok, K });
|
||||
s8 = decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, K / RAD_FP8_BLOCK });
|
||||
q8 = mx && q8_into ? q8_into : decl_b(b, nm.f("%s.q8", base), mx ? RAD_F8E4M3 : RAD_I8, { g.max_tok, K });
|
||||
s8 = mx && s8_into ? s8_into : decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, K / RAD_FP8_BLOCK });
|
||||
if (!q8 || !s8) return RAD_E_INVAL;
|
||||
op_q = rw(b, RAD_OP(b, mx ? "quant_act_fp8" : "quant_act_i8g",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
|
||||
@@ -281,6 +311,10 @@ inline void G3Linear::step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const {
|
||||
if (!shared_in)
|
||||
RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(q8, T), brows(s8, T), RAD_NONE);
|
||||
gemm(c, y, T);
|
||||
} else if (a4 && T <= a4_split) {
|
||||
RAD_ISSUE_N(c, op_a16, T, brows(a, T), brows(a16, T));
|
||||
RAD_ISSUE_N(c, op_dec, T, brows(a16, T), RAD_NONE, RAD_W(w), RAD_W(ws), brows(y, T),
|
||||
RAD_NONE, RAD_NONE);
|
||||
} else if (i8g || mx || a4) {
|
||||
/* quant_act_i8g / quant_act_fp8 take x, q, scale: no optional `asum`. */
|
||||
if (!shared_in)
|
||||
@@ -295,32 +329,23 @@ inline void G3Linear::gemm(RadCtx* c, rad_buf y, int64_t T) const {
|
||||
brows(y, T), RAD_NONE, mx ? RAD_W(wref) : RAD_NONE);
|
||||
}
|
||||
|
||||
/* ---- the GPTQ calibration tap (rad_arch.h's calib_*): the Gram of one linear's bf16 input,
|
||||
* summed over the corpus in a PERSIST [K, K] f32 buffer. Declared only with RADIANCE_CALIB_DIR set,
|
||||
* for the layers RADIANCE_G3_CALIB_LAYERS names ("lo:hi", default every layer): a down projection's
|
||||
* Gram is 10752^2 f32 a rank at TP2, so 62 layers of four taps do not fit beside the weights and a
|
||||
* calibration runs in slices of layers, the corpus pushed through once per slice. */
|
||||
struct G3Tap {
|
||||
rad_buf h = 0;
|
||||
rad_op op = 0;
|
||||
int64_t K = 0;
|
||||
inline void G3Linear::gemm_rows(RadCtx* c, rad_buf y, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op, n, brow_slice(q8, r0, n, K), brow_slice(s8, r0, n, K / RAD_FP8_BLOCK),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, n, N), RAD_NONE, RAD_W(wref));
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& g, const char* name, rad_buf a, int64_t k) {
|
||||
K = k;
|
||||
h = decl_b(b, nm.f("%s.gram", name), RAD_F32, { k, k }, RAD_BUF_PERSIST);
|
||||
if (!h) return RAD_E_INVAL;
|
||||
op = rw(b, RAD_OP(b, "gram_accum",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", k),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a, h }, { h });
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
inline void G3Linear::step_rows(RadCtx* c, rad_buf a, rad_buf y, int64_t r0, int64_t n) const {
|
||||
if (a4 && n <= a4_split) {
|
||||
RAD_ISSUE_N(c, op_a16, n, brow_slice(a, r0, n, K), brows(a16, n));
|
||||
RAD_ISSUE_N(c, op_dec, n, brows(a16, n), RAD_NONE, RAD_W(w), RAD_W(ws),
|
||||
brow_slice(y, r0, n, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
/* gram_accum takes a, a_scale?, h: no scale for a bf16 input. */
|
||||
void step(RadCtx* c, rad_buf a, int64_t T, const bool* live) const {
|
||||
if (op && live && *live) RAD_ISSUE_N(c, op, T, brows(a, T), RAD_NONE, brows(h, K));
|
||||
if (!shared_in)
|
||||
RAD_ISSUE_N(c, op_q, n, brow_slice(a, r0, n, K), brow_slice(q8, r0, n, K),
|
||||
brow_slice(s8, r0, n, K / RAD_FP8_BLOCK));
|
||||
gemm_rows(c, y, r0, n);
|
||||
}
|
||||
};
|
||||
|
||||
/* ---- one attention block, parameterised by class. */
|
||||
struct Gemma3Attn {
|
||||
@@ -341,8 +366,14 @@ struct Gemma3Attn {
|
||||
* resolves; byte-identical to the four */
|
||||
rad_op op_qnr = 0;
|
||||
/* Calibration: q|k|v's shared input and o_proj's (this rank's columns). */
|
||||
G3Tap tap_in{}, tap_o{};
|
||||
CalibTap tap_in{}, tap_o{};
|
||||
const bool* tap_live = nullptr;
|
||||
/* Set before declare by a pipelined deployment: the all-reduce a second time at `overlap` 1 (a
|
||||
* launch that leaves the CUs to the compute beside it), and q|k|v's input pair shared by every
|
||||
* block (the junctions write it a piece at a time on the second lane). */
|
||||
int ar_overlap = 0;
|
||||
rad_op op_ar_ov = 0;
|
||||
const G3Linear* pipe_in = nullptr;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo,
|
||||
rad_kvgroup group, const Wire& wire, double scale);
|
||||
@@ -352,6 +383,17 @@ struct Gemma3Attn {
|
||||
void post(RadCtx* c, int64_t T) const {
|
||||
RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T));
|
||||
}
|
||||
/* The pipelined prefill (step_pipelined): the block over one prefill sequence in two pieces,
|
||||
* its input pair already written; hands the first piece behind its out projection. */
|
||||
void step_pieces(RadCtx* c, const RadBatch* batch, ArPieces* pc, const int32_t* used0) const;
|
||||
/* The tail a piece at a time on the second lane: the overlap all-reduce and the post-norm. */
|
||||
void ar_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op_ar_ov, n * g.n_embd, brow_slice(w.h, r0, n, g.n_embd), RAD_NONE);
|
||||
}
|
||||
void post_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op_post, n, brow_slice(w.h, r0, n, g.n_embd), RAD_W(w_post),
|
||||
brow_slice(w.h, r0, n, g.n_embd));
|
||||
}
|
||||
};
|
||||
|
||||
int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo,
|
||||
@@ -359,6 +401,7 @@ int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
g = geom; cls = cgeo; layer = l; kv = group; w = wire; attn_scale = scale;
|
||||
const int64_t qd = cls.q_dim(), kvd = cls.kv_dim();
|
||||
const char* pre = kLayers;
|
||||
if (pipe_in) { ln_q.q8_into = pipe_in->q8; ln_q.s8_into = pipe_in->s8; }
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), nm.ckpt("%s.%lld.self_attn.q_norm.weight", pre, (long long)l)));
|
||||
@@ -460,6 +503,13 @@ int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
if (g.world > 1 && ar_overlap > 0)
|
||||
op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes), RAD_INT("overlap", ar_overlap)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
|
||||
op_post = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
@@ -474,6 +524,49 @@ int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Each piece is the chunk a span of 1 makes: its rows, positions and slots, and an attention over
|
||||
* its own query bounds (ArPieces::cu) seeing the cache up to its own end -- `used0`, the group's
|
||||
* seqused less the second piece's rows, for the first; the step's seqused for the second, which
|
||||
* reads the first piece's keys from the cache as a later chunk would (the sliding window included:
|
||||
* a window group's seqused counts from its rebased first block). */
|
||||
void Gemma3Attn::step_pieces(RadCtx* c, const RadBatch* batch, ArPieces* pc,
|
||||
const int32_t* used0) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
const int64_t T = batch->n_tok, R = pc->rows;
|
||||
const int64_t qd = cls.q_dim(), kvd = cls.kv_dim();
|
||||
const int64_t tpitch = kvb ? kvb->block_table_pitch : 0;
|
||||
for (int64_t p = 0; p < 2; ++p) {
|
||||
const int64_t r0 = p == 0 ? 0 : R;
|
||||
const int64_t n = p == 0 ? R : T - R;
|
||||
const int32_t* pos = batch->positions + r0;
|
||||
ln_q.gemm_rows(c, w.q, r0, n);
|
||||
ln_k.gemm_rows(c, w.k, r0, n);
|
||||
ln_v.gemm_rows(c, w.v, r0, n);
|
||||
if (op_qnr) {
|
||||
RAD_ISSUE_N(c, op_qnr, n, brow_slice(w.q, r0, n, qd), brow_slice(w.k, r0, n, kvd),
|
||||
brow_slice(w.v, r0, n, kvd), praw(pos, RAD_I32, n), RAD_W(w_qn), RAD_W(w_kn));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_qn, n * cls.n_head, brow_slice(w.q, r0, n, qd), RAD_W(w_qn),
|
||||
brow_slice(w.q, r0, n, qd));
|
||||
RAD_ISSUE_N(c, op_kn, n * cls.n_head_kv, brow_slice(w.k, r0, n, kvd), RAD_W(w_kn),
|
||||
brow_slice(w.k, r0, n, kvd));
|
||||
RAD_ISSUE_N(c, op_rq, n, brow_slice(w.q, r0, n, qd), praw(pos, RAD_I32, n));
|
||||
RAD_ISSUE_N(c, op_rk, n, brow_slice(w.k, r0, n, kvd), praw(pos, RAD_I32, n));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_kv, n, brow_slice(w.k, r0, n, kvd), brow_slice(w.v, r0, n, kvd),
|
||||
praw(slot + r0, RAD_I32, n), kv_cache(kv, layer));
|
||||
RAD_ISSUE_N(c, op_attn, n, brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, 1, tpitch),
|
||||
praw(p == 0 ? used0 : used, RAD_I32, 1),
|
||||
RAD_NONE, RAD_NONE, praw(pc->cu + p, RAD_I32, 2), brows(w.attn, T));
|
||||
ln_o.step_rows(c, w.attn, w.h, r0, n);
|
||||
if (p == 0) pc->hand(r0, n);
|
||||
}
|
||||
}
|
||||
|
||||
void Gemma3Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tail_fused,
|
||||
bool ar_fused) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
@@ -491,7 +584,7 @@ void Gemma3Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta
|
||||
ln_q.step(c, w.h, w.q, T);
|
||||
ln_k.step(c, w.h, w.k, T);
|
||||
ln_v.step(c, w.h, w.v, T);
|
||||
tap_in.step(c, w.h, T, tap_live);
|
||||
tap_in.step(c, w.h, T, tap_live && *tap_live);
|
||||
}
|
||||
|
||||
if (op_qnr) {
|
||||
@@ -515,7 +608,7 @@ void Gemma3Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn, T));
|
||||
|
||||
tap_o.step(c, w.attn, T, tap_live);
|
||||
tap_o.step(c, w.attn, T, tap_live && *tap_live);
|
||||
ln_o.step(c, w.attn, w.h, T);
|
||||
/* All-reduce before the post-norm: o_proj is column-sharded, and the norm is of the sum. */
|
||||
if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
@@ -535,9 +628,18 @@ struct Gemma3Mlp {
|
||||
G3Linear ln_gu{}, ln_down{};
|
||||
rad_op op_norm = 0, op_act = 0, op_post = 0, op_ar = 0, op_add = 0;
|
||||
rad_op op_gq = 0;
|
||||
/* gate|up, the GeGLU and down's E4M3 quantiser in one launch (gemm_nt_q_gated_mx at gelu_tanh)
|
||||
* up to `fold_rows` rows, when both linears are MXFP4: byte-identical to the GEMM, gelu_mul and
|
||||
* quant_act_fp8 it replaces. */
|
||||
rad_op op_fold = 0;
|
||||
int64_t fold_rows = 0;
|
||||
/* Calibration: gate|up's input and down's (this rank's columns). */
|
||||
G3Tap tap_gu{}, tap_dn{};
|
||||
CalibTap tap_gu{}, tap_dn{};
|
||||
const bool* tap_live = nullptr;
|
||||
/* Set before declare by a pipelined deployment, as Gemma3Attn's. */
|
||||
int ar_overlap = 0;
|
||||
rad_op op_ar_ov = 0;
|
||||
const G3Linear* pipe_in = nullptr;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire);
|
||||
void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false,
|
||||
@@ -545,11 +647,30 @@ struct Gemma3Mlp {
|
||||
void post(RadCtx* c, int64_t T) const {
|
||||
RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T));
|
||||
}
|
||||
/* The pipelined prefill: the block over rows [r0, r0 + n), its input pair already written, up
|
||||
* to the down projection; then the tail a piece at a time on the second lane. */
|
||||
void body_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
ln_gu.gemm_rows(c, w.gu, r0, n);
|
||||
RAD_ISSUE_N(c, op_act, n, brow_slice(w.gu, r0, n, 2 * g.n_ff), brow_slice(w.ffn, r0, n, g.n_ff));
|
||||
ln_down.step_rows(c, w.ffn, w.h, r0, n);
|
||||
}
|
||||
void ar_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op_ar_ov, n * g.n_embd, brow_slice(w.h, r0, n, g.n_embd), RAD_NONE);
|
||||
}
|
||||
void post_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op_post, n, brow_slice(w.h, r0, n, g.n_embd), RAD_W(w_post),
|
||||
brow_slice(w.h, r0, n, g.n_embd));
|
||||
}
|
||||
void add_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op_add, n, brow_slice(w.x, r0, n, g.n_embd), brow_slice(w.h, r0, n, g.n_embd),
|
||||
brow_slice(w.x, r0, n, g.n_embd));
|
||||
}
|
||||
};
|
||||
|
||||
int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire) {
|
||||
g = geom; layer = l; w = wire;
|
||||
const char* pre = kLayers;
|
||||
if (pipe_in) { ln_gu.q8_into = pipe_in->q8; ln_gu.s8_into = pipe_in->s8; }
|
||||
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_norm.weight", l), nm.ckpt("%s.%lld.pre_feedforward_layernorm.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_post_norm.weight", l), nm.ckpt("%s.%lld.post_feedforward_layernorm.weight", pre, (long long)l)));
|
||||
@@ -582,6 +703,26 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
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});
|
||||
// Not under calibration either: the down tap reads the bf16 product, which the fold never writes.
|
||||
{
|
||||
/* libr4d folds 1..8 rows (gemm_mxfp4a8_gated_gemv) and, from K 2688, 9..64
|
||||
* (_gated_gemv_wide), each byte-identical to its band's GEMM row followed by gelu_mul and
|
||||
* quant_act_fp8. At 2-8 sequences with speculation a decode step is 16-64 rows. */
|
||||
const int64_t fold_max = ln_gu.K >= 2688 ? 64 : 8;
|
||||
const int64_t hi = g.max_tok < fold_max ? g.max_tok : fold_max;
|
||||
// G3Linear's mx is linear_is_mxfp4, never a rotated (ParoQuant) weight, so one part.
|
||||
if (ln_gu.mx && ln_down.mx && !ln_down.shared_in && !calib_dir() && hi > 0 &&
|
||||
ln_gu.N % 256 == 0 && ln_gu.K % RAD_FP8_BLOCK == 0 &&
|
||||
rad_op_declared(b, "gemm_nt_q_gated_mx")) {
|
||||
op_fold = rw(b, RAD_OP(b, "gemm_nt_q_gated_mx",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", ln_gu.N), RAD_INT("K", ln_gu.K),
|
||||
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8"),
|
||||
RAD_STR("act", "gelu_tanh")),
|
||||
RAD_WEIGHTS(ln_gu.w, ln_gu.ws, ln_gu.wref)),
|
||||
{ln_gu.q8, ln_gu.s8}, {ln_down.q8, ln_down.s8});
|
||||
if (op_fold) fold_rows = hi;
|
||||
}
|
||||
}
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
@@ -589,6 +730,13 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
if (g.world > 1 && ar_overlap > 0)
|
||||
op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes), RAD_INT("overlap", ar_overlap)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
op_post = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
|
||||
@@ -604,19 +752,28 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
void Gemma3Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tail_fused,
|
||||
bool ar_fused) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const bool fold = op_fold && T <= fold_rows;
|
||||
if (entry_done) {
|
||||
ln_gu.gemm(c, w.gu, T);
|
||||
if (!fold) ln_gu.gemm(c, w.gu, T);
|
||||
} else {
|
||||
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
if (!fold)
|
||||
ln_gu.step(c, w.h, w.gu, T);
|
||||
tap_gu.step(c, w.h, T, tap_live);
|
||||
else if (!ln_gu.shared_in)
|
||||
RAD_ISSUE_N(c, ln_gu.op_q, T, brows(w.h, T), brows(ln_gu.q8, T), brows(ln_gu.s8, T));
|
||||
tap_gu.step(c, w.h, T, tap_live && *tap_live);
|
||||
}
|
||||
if (op_gq) {
|
||||
if (fold) {
|
||||
RAD_ISSUE_N(c, op_fold, T, brows(ln_gu.q8, T), brows(ln_gu.s8, T), RAD_W(ln_gu.w),
|
||||
RAD_W(ln_gu.ws), RAD_W(ln_gu.wref), brows(ln_down.q8, T), brows(ln_down.s8, T),
|
||||
RAD_NONE);
|
||||
ln_down.gemm(c, w.h, T);
|
||||
} else if (op_gq) {
|
||||
RAD_ISSUE_N(c, op_gq, T, brows(w.gu, T), brows(ln_down.q8, T), brows(ln_down.s8, T), RAD_NONE);
|
||||
ln_down.gemm(c, w.h, T);
|
||||
} else {
|
||||
RAD_ISSUE(c, op_act, brows(w.gu, T), brows(w.ffn, T));
|
||||
tap_dn.step(c, w.ffn, T, tap_live);
|
||||
tap_dn.step(c, w.ffn, T, tap_live && *tap_live);
|
||||
ln_down.step(c, w.ffn, w.h, T);
|
||||
}
|
||||
if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
@@ -651,7 +808,7 @@ struct G3Junction {
|
||||
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 && g.wire_exact && rad_op_declared(b, "ar_rmsnorm_quant_i8")) {
|
||||
if (res && g.world == 2 && rad_op_declared(b, "ar_rmsnorm_quant_i8")) {
|
||||
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) };
|
||||
@@ -671,6 +828,15 @@ struct G3Junction {
|
||||
}
|
||||
};
|
||||
|
||||
/* The tallest step that takes the fp8 junction's lossy twin (G3JunctionFP8::op_ar6); a taller one
|
||||
* keeps the standalone lossy all-reduce, unfused. The fused kernel gives each block one row, so past
|
||||
* a few sequences the standalone all-reduce, spread over more blocks, wins despite its extra
|
||||
* launches. TranslateGemma-27B MXFP4 + DFlash2 at tp 2 on 2x R9700 (--tp-wire wht6,
|
||||
* --draft-short-from 8, greedy): fusing raises aggregate throughput by 1-6% up to 24 rows and
|
||||
* lowers it by 6-8% at 32. One stream's 8 rows go out exact under the default --tp-wire-min-kb
|
||||
* (op_ar). */
|
||||
constexpr int64_t kAr6MaxRows = 24;
|
||||
|
||||
/* ---- the MXFP4 trunk's junction (libr4d `rmsnorm_quant_fp8`): the add of the branch `x` into
|
||||
* the stream `res`, the next block's norm and its E4M3 quantiser, in one op. It has no post-norm
|
||||
* slot (rmsnorm_quant_i8's w_post is Gemma 4's), so the branch's post-norm runs just before it:
|
||||
@@ -678,16 +844,21 @@ struct G3Junction {
|
||||
* embedding stream. */
|
||||
struct G3JunctionFP8 {
|
||||
rad_op op = 0;
|
||||
/* At two ranks on the exact wire: the branch's all-reduce and post-norm folded in front
|
||||
* (ar_rmsnorm_post_quant_fp8), `x` then being this rank's partial sum. One launch. */
|
||||
rad_op op_ar = 0;
|
||||
/* At two ranks: the branch's all-reduce and post-norm folded in front
|
||||
* (ar_rmsnorm_post_quant_fp8), `x` then being this rank's partial sum. One launch. `op_ar` sends
|
||||
* the exact wire, for the steps whose message goes out exact (ar_wire_is_exact: a decode step
|
||||
* of a few rows, under --tp-wire-min-kb). `op_ar6` sends the rotated 6-bit one: declared under
|
||||
* a lossy --tp-wire, it takes the steps above that up to kAr6MaxRows and is byte-identical to
|
||||
* the standalone lossy all-reduce, rmsnorm and rmsnorm_quant_fp8 it replaces. */
|
||||
rad_op op_ar = 0, op_ar6 = 0;
|
||||
Geom gm{};
|
||||
rad_buf x = 0, res = 0, q = 0, s = 0;
|
||||
rad_weight w = 0, wp = 0;
|
||||
int64_t n = 0;
|
||||
|
||||
int declare(RadBuilder* b, const Geom& g, rad_buf x_, rad_buf res_, rad_weight w_,
|
||||
const G3Linear& into, rad_weight wp_ = 0) {
|
||||
x = x_; res = res_; w = w_; wp = wp_; q = into.q8; s = into.s8; n = g.n_embd;
|
||||
x = x_; res = res_; w = w_; wp = wp_; q = into.q8; s = into.s8; n = g.n_embd; gm = g;
|
||||
if (!into.mx || into.shared_in || !q || !s || !w) return RAD_E_INVAL;
|
||||
if (!rad_op_declared(b, "rmsnorm_quant_fp8")) return RAD_OK;
|
||||
op = RAD_OP(b, "rmsnorm_quant_fp8",
|
||||
@@ -700,7 +871,7 @@ struct G3JunctionFP8 {
|
||||
const rad_buf wr[3] = { q, s, res };
|
||||
rad_op_reads (b, op, rd, res ? 2 : 1);
|
||||
rad_op_writes(b, op, wr, res ? 3 : 2);
|
||||
if (res && wp && g.world == 2 && g.wire_exact && rad_op_declared(b, "ar_rmsnorm_post_quant_fp8")) {
|
||||
if (res && wp && g.world == 2 && rad_op_declared(b, "ar_rmsnorm_post_quant_fp8")) {
|
||||
const rad_weight ws[2] = { w, wp };
|
||||
const RadParam pa[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), RAD_F64("eps", g.eps),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_INT("world_size", g.world),
|
||||
@@ -710,27 +881,66 @@ struct G3JunctionFP8 {
|
||||
const rad_buf wa[4] = { x, q, s, res };
|
||||
rad_op_reads (b, op_ar, rd, 2);
|
||||
rad_op_writes(b, op_ar, wa, 4);
|
||||
/* The lossy twin, under a lossy wire and for a row of whole 64-element groups
|
||||
* (the kernel pads a partial last 512-element chunk). */
|
||||
if (!g.wire_exact && n % 64 == 0) {
|
||||
const RadParam p6[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
|
||||
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_INT("world_size", g.world), RAD_STR("dtype", g.dtype),
|
||||
RAD_F64("wadd", g.wadd), RAD_INT("wire", 6) };
|
||||
op_ar6 = rad_decl_op(b, "ar_rmsnorm_post_quant_fp8", p6,
|
||||
(int)(sizeof p6 / sizeof p6[0]), ws, 2);
|
||||
if (op_ar6) {
|
||||
rad_op_reads (b, op_ar6, rd, 2);
|
||||
rad_op_writes(b, op_ar6, wa, 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
/* The fused op for a T-row step's wire, or 0 when its all-reduce stays standalone. */
|
||||
rad_op ar_op(int64_t T) const {
|
||||
if (op_ar && ar_wire_is_exact(gm, T)) return op_ar;
|
||||
return T <= kAr6MaxRows ? op_ar6 : 0;
|
||||
}
|
||||
/* x, residual?, w -> q, scale, out_bf16?[, w_post]: the bf16 normed copy is not wanted. */
|
||||
void step(RadCtx* c, int64_t T, bool with_ar = false) const {
|
||||
if (with_ar)
|
||||
RAD_ISSUE_N(c, op_ar, T, brows(x, T), brows(res, T), RAD_W(w), brows(q, T), brows(s, T),
|
||||
RAD_ISSUE_N(c, ar_op(T), T, brows(x, T), brows(res, T), RAD_W(w), brows(q, T), brows(s, T),
|
||||
RAD_NONE, RAD_W(wp));
|
||||
else
|
||||
RAD_ISSUE_N(c, op, T, brows(x, T), res ? brows(res, T) : RAD_NONE, RAD_W(w),
|
||||
brows(q, T), brows(s, T), RAD_NONE);
|
||||
}
|
||||
/* Rows [r0, r0 + n), without the all-reduce: the pipelined prefill's second lane. */
|
||||
void step_rows(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(x, r0, rows, n), res ? brow_slice(res, r0, rows, n) : RAD_NONE,
|
||||
RAD_W(w), brow_slice(q, r0, rows, n), brow_slice(s, r0, rows, n / RAD_FP8_BLOCK),
|
||||
RAD_NONE);
|
||||
}
|
||||
};
|
||||
|
||||
/* The weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h): a weight's first
|
||||
* kPrefetchBytes, on decode steps of up to kPrefetchStepRows rows (a verify of four sequences at
|
||||
* speculation 7). TranslateGemma-27B MXFP4 + DFlash2, tp 2 on two R9700s: 24 MB was best, +13 %
|
||||
* at one stream and +10 % at eight with no speculation, +12 % / +5 % at one / four streams with
|
||||
* speculation 7. Larger than qwen35_fp8's 12 MB, since this model's wider all-reduces take longer;
|
||||
* past ~24 MB the read outlasts the reduction and takes bandwidth from the GEMM it feeds. The
|
||||
* drafter's reads (Dflash2::Config::prefetch) take the same size. */
|
||||
constexpr int64_t kPrefetchBytes = (int64_t)24 << 20;
|
||||
constexpr int64_t kPrefetchStepRows = 32;
|
||||
|
||||
struct Layer {
|
||||
bool global = false;
|
||||
Gemma3Attn attn{};
|
||||
Gemma3Mlp mlp{};
|
||||
G3Junction j_am{}, j_ma{};
|
||||
G3JunctionFP8 jf_am{}, jf_ma{};
|
||||
/* gate|up's leading bytes beside the attention block's reduction, the next layer's q's beside
|
||||
* the feed-forward's; 0 where none is declared. */
|
||||
rad_op op_pf_gu = 0, op_pf_next = 0;
|
||||
rad_weight pf_gu_w = 0, pf_next_w = 0;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
@@ -755,6 +965,7 @@ struct Model {
|
||||
G3JunctionFP8 jf0{};
|
||||
bool fuse_mx = false; /* the MXFP4 trunk's junctions (G3JunctionFP8) */
|
||||
bool fuse_mx_ar = false; /* ... each with the all-reduce and post-norm folded in */
|
||||
bool fuse_mx_ar6 = false; /* ... on the lossy wire too (G3JunctionFP8::op_ar6) */
|
||||
bool fuse_ar = false;
|
||||
|
||||
/* The DFlash2 drafter and the trunk taps it reads, only when the container carries one and
|
||||
@@ -773,10 +984,31 @@ struct Model {
|
||||
bool calib = false, tap_live = false;
|
||||
int64_t calib_lo = 0, calib_hi = 0;
|
||||
long long calib_rows = 0;
|
||||
|
||||
/* The pipelined prefill (step_pipelined): on where declare allowed it; the input pair every
|
||||
* block's q|k|v and gate|up read (the junctions write it); the bounds buffer and its pinned
|
||||
* table of {0, pipe_rows(T), T}; whether rank 0 has said it pipelines, or why not. */
|
||||
bool pipe_on = false;
|
||||
G3Linear pipe_in{};
|
||||
rad_buf b_pipe_cu = 0;
|
||||
/* Each KV group's seqused for the first piece, [2] (sliding, global): the step's less the
|
||||
* second piece's rows (sub_i32 from b_pipe_cu[3] = T - R). A window group's seqused counts from
|
||||
* its rebased first block, not from position 0, so the first piece's position cannot stand in. */
|
||||
rad_buf b_pipe_used = 0;
|
||||
rad_op op_pipe_used = 0;
|
||||
int32_t* pipe_tbl = nullptr;
|
||||
bool pipe_tbl_tried = false;
|
||||
bool pipe_noted = false;
|
||||
bool pipe_serial_noted = false;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
/* The narrowest step the pipelined prefill takes, and its first piece: half the step rounded up
|
||||
* to 64 rows (qwen35_fp8 says why). */
|
||||
static const int64_t kPipeMinRows = 1024;
|
||||
static int64_t pipe_rows(int64_t T) { return ((T + 1) / 2 + 63) / 64 * 64; }
|
||||
|
||||
/* ================================================================== the DFlash2 drafter
|
||||
*
|
||||
* A second model at absolute layers n_layer.. with its own KV group (rad_block_dflash2.h), as
|
||||
@@ -793,6 +1025,8 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "gemma3 DFlash2"));
|
||||
|
||||
Dflash2::Config dc{};
|
||||
dc.short_block = 1; /* rad_drafter_short_block below */
|
||||
dc.prefetch = kPrefetchBytes; /* reads beside the drafter's all-reduces (at tp > 1) */
|
||||
dc.n_taps = m.n_taps;
|
||||
dc.block = ctx->max_spec + 1;
|
||||
dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2);
|
||||
@@ -904,6 +1138,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
|
||||
if (m.df.block_lo > 0) RAD_ARCH_TRY(rad_drafter_short_block(b, m.df.block_lo));
|
||||
rad_note(b, "DFlash2 drafter: %lld layers at absolute %d.., %lld heads / %lld kv x %lld, ffn %lld, "
|
||||
"%s attention with a %lld-token window, %d trunk taps, embedding x %g, %s head",
|
||||
(long long)dg.n_layer, base_layer, (long long)dg.n_head, (long long)dg.n_head_kv,
|
||||
@@ -917,6 +1152,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (m.pipe_tbl) rad_dev_free(m.pipe_tbl, RAD_MEM_HOST_PINNED);
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
@@ -1034,6 +1270,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_F64("mult", emult)),
|
||||
RAD_WEIGHTS(m.w_tok)),
|
||||
{}, {m.b_x});
|
||||
/* The second lane's window (rad_lane1_window_begin): from the embedding's reduction to the final
|
||||
* norm, where the pipelined prefill runs its boundaries; the drafter and the heads lie outside it
|
||||
* and can share the concurrent buffers' bytes. */
|
||||
RAD_ARCH_TRY(rad_lane1_window_begin(b));
|
||||
if (g.world > 1)
|
||||
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
@@ -1042,6 +1282,21 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
|
||||
/* The pipelined prefill (step_pipelined), at two ranks wherever a step can be wide enough, on
|
||||
* an MXFP4 trunk with fused junctions (decided below); two ranks only, as in qwen35_fp8. Its
|
||||
* second lane touches the stream, the branch output, the shared input pair and the bounds, so
|
||||
* those leave the sharing pool (Ctx::lane1_; the drafter taps are copied on the first lane,
|
||||
* pipe_taps). The pair is one for every block so that this costs one pair, not one a
|
||||
* linear. */
|
||||
m.pipe_on = g.world == 2 && g.max_tok >= kPipeMinRows && !calib_dir();
|
||||
if (m.pipe_on) {
|
||||
m.pipe_in.mx = true;
|
||||
m.pipe_in.K = g.n_embd;
|
||||
m.pipe_in.q8 = decl_b(b, nm.f("pipe_in.q8"), RAD_F8E4M3, {g.max_tok, g.n_embd});
|
||||
m.pipe_in.s8 = decl_b(b, nm.f("pipe_in.s8"), RAD_F32, {g.max_tok, g.n_embd / RAD_FP8_BLOCK});
|
||||
if (!m.pipe_in.q8 || !m.pipe_in.s8) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
Gemma3Attn::Wire aw{}; aw.x = m.b_x; aw.h = m.b_h; aw.q = m.b_q; aw.k = m.b_k; aw.v = m.b_v; aw.attn = m.b_attn;
|
||||
Gemma3Mlp::Wire mw{}; mw.x = m.b_x; mw.h = m.b_h; mw.gu = m.b_gu; mw.ffn = m.b_ffn;
|
||||
|
||||
@@ -1052,6 +1307,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
const ClassGeom& cgeo = lay.global ? m.cg : m.cs;
|
||||
const rad_kvgroup kg = lay.global ? m.kv_g : m.kv_s;
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg));
|
||||
if (m.pipe_on) {
|
||||
lay.attn.ar_overlap = lay.mlp.ar_overlap = 1;
|
||||
lay.attn.pipe_in = lay.mlp.pipe_in = &m.pipe_in;
|
||||
}
|
||||
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, attn_scale));
|
||||
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw));
|
||||
}
|
||||
@@ -1118,31 +1377,70 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
ar = lay.jf_am.op_ar != 0 && (l + 1 >= g.n_layer || lay.jf_ma.op_ar != 0);
|
||||
}
|
||||
m.fuse_mx_ar = ar;
|
||||
bool ar6 = ar;
|
||||
for (int64_t l = 0; ar6 && l < g.n_layer; ++l) {
|
||||
const Layer& lay = m.layers[(size_t)l];
|
||||
ar6 = lay.jf_am.op_ar6 != 0 && (l + 1 >= g.n_layer || lay.jf_ma.op_ar6 != 0);
|
||||
}
|
||||
m.fuse_mx_ar6 = ar6;
|
||||
}
|
||||
/* ---- the weight reads beside the decode all-reduces, at more than one rank;
|
||||
* --weight-prefetch off declares none. */
|
||||
if (g.world > 1 && !ctx->weight_prefetch_off && rad_op_declared(b, "prefetch")) {
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.pf_gu_w = lay.mlp.ln_gu.w;
|
||||
lay.op_pf_gu = decl_prefetch(b, lay.pf_gu_w, kPrefetchBytes);
|
||||
if (l + 1 < g.n_layer) {
|
||||
lay.pf_next_w = m.layers[(size_t)l + 1].attn.ln_q.w;
|
||||
lay.op_pf_next = decl_prefetch(b, lay.pf_next_w, kPrefetchBytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
/* The pipeline needs the fused fp8 junctions and every block's overlap all-reduce. */
|
||||
if (m.pipe_on) {
|
||||
bool ok = m.fuse_mx;
|
||||
/* ... and the pieces' row-sliced linears are the E4M3 (MXFP4) path throughout. */
|
||||
for (const Layer& lay : m.layers)
|
||||
ok = ok && lay.attn.op_ar_ov && lay.mlp.op_ar_ov && lay.attn.ln_o.mx && lay.mlp.ln_down.mx;
|
||||
if (!ok)
|
||||
rad_note(b, "the pipelined prefill is off: it needs an MXFP4 trunk with the fused fp8 "
|
||||
"junctions and an overlap all-reduce for every block");
|
||||
m.pipe_on = ok;
|
||||
}
|
||||
if (m.pipe_on) {
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_x));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_h));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.pipe_in.q8));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.pipe_in.s8));
|
||||
m.b_pipe_cu = decl_b(b, nm.f("pipe_cu"), RAD_I32, {4});
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_pipe_cu));
|
||||
m.b_pipe_used = decl_b(b, nm.f("pipe_used"), RAD_I32, {2});
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_pipe_used));
|
||||
m.op_pipe_used = rad_op_declared(b, "sub_i32")
|
||||
? RAD_OP(b, "sub_i32", RAD_PARAMS(RAD_RANGE("M", 1, 1)), RAD_NOWEIGHTS) : 0;
|
||||
if (m.op_pipe_used) {
|
||||
const rad_buf rd[1] = { m.b_pipe_cu };
|
||||
const rad_buf wr[1] = { m.b_pipe_used };
|
||||
rad_op_reads (b, m.op_pipe_used, rd, 1);
|
||||
rad_op_writes(b, m.op_pipe_used, wr, 1);
|
||||
} else {
|
||||
m.pipe_on = false; /* no way to put the first piece's seqused on the card */
|
||||
rad_note(b, "the pipelined prefill is off: no plugin serves sub_i32");
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the calibration tap. It reads the bf16 input of every linear, which the fused junctions
|
||||
* never write, so under it none is declared (above): any container calibrates, unfused. */
|
||||
if (calib_dir()) {
|
||||
m.calib_lo = 0;
|
||||
m.calib_hi = g.n_layer;
|
||||
if (const char* s = std::getenv("RADIANCE_G3_CALIB_LAYERS")) {
|
||||
long long lo = 0, hi = 0;
|
||||
int used = 0;
|
||||
if (std::sscanf(s, "%lld:%lld%n", &lo, &hi, &used) != 2 || s[used] != '\0' || lo < 0 ||
|
||||
hi > g.n_layer || lo >= hi) {
|
||||
fprintf(stderr, "radiance: gemma3: RADIANCE_G3_CALIB_LAYERS '%s' is not lo:hi within "
|
||||
"0:%lld\n", s, (long long)g.n_layer);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
m.calib_lo = lo;
|
||||
m.calib_hi = hi;
|
||||
}
|
||||
RAD_ARCH_TRY(calib_layers("gemma3", "RADIANCE_G3_CALIB_LAYERS", g.n_layer, &m.calib_lo,
|
||||
&m.calib_hi));
|
||||
for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
RAD_ARCH_TRY(lay.attn.tap_in.declare(b, nm, g, nm.f("blk.%d.attn_in", (int)l), m.b_h, g.n_embd));
|
||||
RAD_ARCH_TRY(lay.attn.tap_o.declare(b, nm, g, nm.f("blk.%d.attn_o", (int)l), m.b_attn, m.cs.q_dim()));
|
||||
RAD_ARCH_TRY(lay.mlp.tap_gu.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up", (int)l), m.b_h, g.n_embd));
|
||||
RAD_ARCH_TRY(lay.mlp.tap_dn.declare(b, nm, g, nm.f("blk.%d.ffn_down", (int)l), m.b_ffn, g.n_ff));
|
||||
RAD_ARCH_TRY(lay.attn.tap_in.declare(b, nm, g.max_tok, nm.f("blk.%d.attn_in", (int)l), m.b_h, g.n_embd));
|
||||
RAD_ARCH_TRY(lay.attn.tap_o.declare(b, nm, g.max_tok, nm.f("blk.%d.attn_o", (int)l), m.b_attn, m.cs.q_dim()));
|
||||
RAD_ARCH_TRY(lay.mlp.tap_gu.declare(b, nm, g.max_tok, nm.f("blk.%d.ffn_gate_up", (int)l), m.b_h, g.n_embd));
|
||||
RAD_ARCH_TRY(lay.mlp.tap_dn.declare(b, nm, g.max_tok, nm.f("blk.%d.ffn_down", (int)l), m.b_ffn, g.n_ff));
|
||||
}
|
||||
m.calib = true;
|
||||
m.tap_live = true;
|
||||
@@ -1154,6 +1452,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_out)),
|
||||
{m.b_x}, {m.b_h});
|
||||
RAD_ARCH_TRY(rad_lane1_window_end(b));
|
||||
m.op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
@@ -1180,6 +1479,191 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ============================== A prefill step in two pieces ==============================
|
||||
*
|
||||
* qwen35_fp8's step_pipelined on Gemma 3's trunk: at two ranks every layer of a prefill chunk makes
|
||||
* two all-reduces, each in a hard chain behind its block (all-reduce, post-norm, the junction's add
|
||||
* and next norm, then the next block). A step of one prefill sequence of at least kPipeMinRows tokens
|
||||
* is cut into two pieces of about half; every block runs a piece at a time on the first lane, and
|
||||
* the work between two blocks -- the block's all-reduce at `overlap` 1, its post-norm and the fp8
|
||||
* junction, and after the last block its add and the final norm -- runs a
|
||||
* piece at a time on the second; the drafter taps run on the first (pipe_taps). The ops are the serial step's at a narrower width, so a pipelined
|
||||
* step is bit for bit the serial one where a chunk's rows do not depend on its width.
|
||||
*
|
||||
* The second lane's requirements (Ctx::lane1_) hold as in qwen35_fp8: every collective of the step
|
||||
* is on it, the embedding's included; none carries a device-wide arrival counter; the buffers it
|
||||
* touches left the sharing pool at declare, the per-linear input pairs replaced by one shared pair. */
|
||||
|
||||
template <class F>
|
||||
static void pipe_on1(RadCtx* c, const F& issue) {
|
||||
rad_lane(c, 1);
|
||||
rad_lane_join(c, 0, 1);
|
||||
issue();
|
||||
rad_lane(c, 0);
|
||||
}
|
||||
static void pipe_wait1(RadCtx* c) { rad_lane_join(c, 1, 0); }
|
||||
|
||||
/* The work after block `s` (2l the attention of layer l, 2l + 1 its feed-forward), rows
|
||||
* [r0, r0 + n). */
|
||||
static void pipe_boundary(RadCtx* c, const Model& m, int64_t s, int64_t r0, int64_t n) {
|
||||
const Geom& g = m.g;
|
||||
const int64_t li = s / 2;
|
||||
const Layer& l = m.layers[(size_t)li];
|
||||
const bool last = li + 1 == (int64_t)m.layers.size();
|
||||
if (s % 2 == 0) {
|
||||
l.attn.ar_rows(c, r0, n);
|
||||
l.attn.post_rows(c, r0, n);
|
||||
l.jf_am.step_rows(c, r0, n);
|
||||
return;
|
||||
}
|
||||
l.mlp.ar_rows(c, r0, n);
|
||||
l.mlp.post_rows(c, r0, n);
|
||||
if (!last) l.jf_ma.step_rows(c, r0, n);
|
||||
else l.mlp.add_rows(c, r0, n);
|
||||
if (last)
|
||||
RAD_ISSUE_N(c, m.op_final, n, brow_slice(m.b_x, r0, n, g.n_embd), RAD_W(m.w_out),
|
||||
brow_slice(m.b_h, r0, n, g.n_embd));
|
||||
}
|
||||
|
||||
/* Layer `li`'s drafter taps of rows [r0, r0 + n), on lane 0. Issued once lane 0 has waited for that
|
||||
* piece's feed-forward boundary (its junction is the last write to those rows of x before the next
|
||||
* block's boundary, which lane 1 starts only behind lane 0's next issues), so the taps buffer is
|
||||
* never touched from lane 1 and stays in the sharing pool: rad_buf_concurrent would hold its
|
||||
* [max_tok, n_taps * n_embd] for the whole program. */
|
||||
static void pipe_taps(RadCtx* c, const Model& m, int64_t li, int64_t r0, int64_t n) {
|
||||
for (int t = 0; t < m.n_taps; ++t) {
|
||||
if (m.tap_layer[t] != (int)li) continue;
|
||||
RAD_ISSUE_N(c, m.op_tap, n, brow_slice(m.b_x, r0, n, m.g.n_embd),
|
||||
bcol_at(m.b_dfsrc, r0, (int64_t)m.n_taps * m.g.n_embd, (int64_t)t * m.g.n_embd,
|
||||
m.g.n_embd, n));
|
||||
}
|
||||
}
|
||||
|
||||
/* An attention block's first piece is done (ArPieces): lane 0 takes the previous block's second
|
||||
* boundary before the second piece (and the previous layer's second-piece taps behind it), and
|
||||
* lane 1 this block's first behind it. */
|
||||
struct PipeHand {
|
||||
RadCtx* c = nullptr;
|
||||
const Model* m = nullptr;
|
||||
int64_t s = 0;
|
||||
int64_t T = 0;
|
||||
};
|
||||
static void pipe_hand(void* u, int64_t r0, int64_t n) {
|
||||
const PipeHand& h = *(const PipeHand*)u;
|
||||
pipe_wait1(h.c);
|
||||
if (h.s >= 2) {
|
||||
const int64_t R = pipe_rows(h.T);
|
||||
pipe_taps(h.c, *h.m, h.s / 2 - 1, R, h.T - R);
|
||||
}
|
||||
pipe_on1(h.c, [&] { pipe_boundary(h.c, *h.m, h.s, r0, n); });
|
||||
}
|
||||
|
||||
/* The bounds of this step's pieces on the card, {0, pipe_rows(T), T}, if the step is pipelined;
|
||||
* null for a serial step, and null with `failed` set when the step has been failed (a rank-local
|
||||
* failure past the batch's own conditions: the other rank would pipeline). */
|
||||
static const int32_t* pipe_ready(RadCtx* c, const RadBatch* batch, Model& m, bool* failed) {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (!m.pipe_on || !m.b_pipe_cu || T < kPipeMinRows || T > m.g.max_tok ||
|
||||
batch->phase != RAD_PHASE_PREFILL)
|
||||
return nullptr;
|
||||
auto serial = [&](const char* why) -> const int32_t* {
|
||||
if (!m.pipe_serial_noted && m.g.rank == 0)
|
||||
fprintf(stderr, "radiance: gemma3: a %lld-row prefill step runs serially: %s\n",
|
||||
(long long)T, why);
|
||||
m.pipe_serial_noted = true;
|
||||
return nullptr;
|
||||
};
|
||||
if (batch->n_seq != 1 || batch->n_seq_decode != 0) return serial("more than one sequence");
|
||||
if (!batch->positions || batch->rope_pos) return serial("no one-component positions");
|
||||
const RadKVGroupBatch* kvs = kv_batch(batch, m.kv_s);
|
||||
const RadKVGroupBatch* kvg = kv_batch(batch, m.kv_g);
|
||||
if (!kvs || !kvg || !kvs->slot_mapping || !kvg->slot_mapping || !kvs->block_table ||
|
||||
!kvg->block_table || !kvs->seqused || !kvg->seqused)
|
||||
return serial("a KV group without slots, tables or lengths");
|
||||
int32_t* d = (int32_t*)rad_buf_ptr(c, m.b_pipe_cu);
|
||||
if (!d || !rad_buf_ptr(c, m.b_pipe_used)) {
|
||||
rad_step_fail(c, "gemma3: the pipelined prefill's bounds have no storage");
|
||||
*failed = true;
|
||||
return nullptr;
|
||||
}
|
||||
if (!m.pipe_tbl_tried) {
|
||||
m.pipe_tbl_tried = true;
|
||||
const int64_t n = m.g.max_tok + 1;
|
||||
m.pipe_tbl = (int32_t*)rad_dev_alloc(4 * n * (int64_t)sizeof(int32_t), RAD_MEM_HOST_PINNED);
|
||||
if (m.pipe_tbl)
|
||||
for (int64_t t = 0; t < n; ++t) {
|
||||
m.pipe_tbl[4 * t] = 0;
|
||||
m.pipe_tbl[4 * t + 1] = (int32_t)pipe_rows(t);
|
||||
m.pipe_tbl[4 * t + 2] = (int32_t)t;
|
||||
m.pipe_tbl[4 * t + 3] = (int32_t)(t - pipe_rows(t));
|
||||
}
|
||||
}
|
||||
if (!m.pipe_tbl ||
|
||||
rad_memcpy_async(d, m.pipe_tbl + 4 * T, 4 * (int64_t)sizeof(int32_t), rad_stream(c)) !=
|
||||
RAD_OK) {
|
||||
rad_step_fail(c, "gemma3: the pipelined prefill's piece bounds could not be put on the card "
|
||||
"(no pinned host memory, or the copy failed)");
|
||||
*failed = true;
|
||||
return nullptr;
|
||||
}
|
||||
int32_t* u = (int32_t*)rad_buf_ptr(c, m.b_pipe_used);
|
||||
RAD_ISSUE_N(c, m.op_pipe_used, 1, praw(kvs->seqused, RAD_I32, 1), praw(d + 3, RAD_I32, 1),
|
||||
praw(u, RAD_I32, 1));
|
||||
RAD_ISSUE_N(c, m.op_pipe_used, 1, praw(kvg->seqused, RAD_I32, 1), praw(d + 3, RAD_I32, 1),
|
||||
praw(u + 1, RAD_I32, 1));
|
||||
return d;
|
||||
}
|
||||
|
||||
static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int32_t* pcu) {
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, R = pipe_rows(T);
|
||||
const int64_t L = (int64_t)m.layers.size();
|
||||
if (!m.pipe_noted) {
|
||||
m.pipe_noted = true;
|
||||
if (g.rank == 0)
|
||||
fprintf(stderr, "radiance: gemma3: prefill steps of one sequence from %lld rows are "
|
||||
"pipelined: two pieces, block boundaries on the second lane\n",
|
||||
(long long)kPipeMinRows);
|
||||
}
|
||||
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
|
||||
/* The embedding's reduction and layer 0's norm over the whole step, on lane 1 with every other
|
||||
* collective. */
|
||||
pipe_on1(c, [&] {
|
||||
if (m.op_embed_ar) RAD_ISSUE_N(c, m.op_embed_ar, T * g.n_embd, brows(m.b_x, T), RAD_NONE);
|
||||
m.jf0.step(c, T);
|
||||
});
|
||||
pipe_wait1(c);
|
||||
for (int64_t li = 0; li < L; ++li) {
|
||||
const Layer& l = m.layers[(size_t)li];
|
||||
PipeHand h{c, &m, 2 * li, T};
|
||||
ArPieces pc{};
|
||||
pc.rows = R; pc.done = pipe_hand; pc.u = &h; pc.cu = pcu; pc.in_ready = true;
|
||||
const int32_t* used0 = (const int32_t*)rad_buf_ptr(c, m.b_pipe_used) + (l.global ? 1 : 0);
|
||||
l.attn.step_pieces(c, batch, &pc, used0);
|
||||
if (pc.handed != 1) {
|
||||
rad_step_fail(c, "gemma3: an attention block did not run its two pieces");
|
||||
return;
|
||||
}
|
||||
pipe_wait1(c);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, 2 * li, R, T - R); });
|
||||
l.mlp.body_rows(c, 0, R);
|
||||
pipe_wait1(c);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, 2 * li + 1, 0, R); });
|
||||
l.mlp.body_rows(c, R, T - R);
|
||||
pipe_wait1(c);
|
||||
pipe_taps(c, m, li, 0, R);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, 2 * li + 1, R, T - R); });
|
||||
}
|
||||
pipe_wait1(c);
|
||||
if (L > 0) pipe_taps(c, m, L - 1, R, T - R);
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_h, T),
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out), RAD_W(m.w_lm),
|
||||
brows(m.b_logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
if (batch->enc) {
|
||||
@@ -1197,6 +1681,14 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
else m.df.context(c, batch);
|
||||
return;
|
||||
}
|
||||
{
|
||||
bool pipe_failed = false;
|
||||
if (const int32_t* pcu = pipe_ready(c, batch, m, &pipe_failed)) {
|
||||
step_pipelined(c, batch, m, pcu);
|
||||
return;
|
||||
}
|
||||
if (pipe_failed) return;
|
||||
}
|
||||
const int64_t T = batch->n_tok;
|
||||
/* The drafter conditions on a tapped layer's output, which the next layer overwrites: copy it
|
||||
* into the tap's column slice once the layer's residual is complete. */
|
||||
@@ -1210,6 +1702,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
if (m.op_embed_ar)
|
||||
RAD_ISSUE_N(c, m.op_embed_ar, T * m.g.n_embd, brows(m.b_x, T), RAD_NONE);
|
||||
|
||||
/* Decode steps of up to kPrefetchStepRows rows only, as qwen35_fp8's. */
|
||||
const int64_t pf_h = batch->phase == RAD_PHASE_DECODE && T <= kPrefetchStepRows ? 1 : INT64_MAX;
|
||||
if (m.fuse_mx) {
|
||||
/* MXFP4 trunk: [post-norm, then add + next norm + quantiser as one op] at every junction;
|
||||
* the last block's tail runs unfused into the final norm. */
|
||||
@@ -1217,11 +1711,17 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
for (size_t li = 0; li < m.layers.size(); ++li) {
|
||||
const Layer& l = m.layers[li];
|
||||
const bool last = li + 1 == m.layers.size();
|
||||
const bool far = m.fuse_mx_ar;
|
||||
/* Per step: the fused junction takes the step's all-reduce on the exact wire
|
||||
* (G3JunctionFP8::op_ar), and on the lossy one up to kAr6MaxRows where every junction
|
||||
* declared its twin (op_ar6). */
|
||||
const bool far = m.fuse_mx_ar &&
|
||||
(ar_wire_is_exact(m.g, T) || (m.fuse_mx_ar6 && T <= kAr6MaxRows));
|
||||
l.attn.step(c, batch, true, true, far);
|
||||
prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h);
|
||||
if (!far) l.attn.post(c, T);
|
||||
l.jf_am.step(c, T, far);
|
||||
l.mlp.step(c, batch, true, !last, far);
|
||||
prefetch_beside(c, l.op_pf_next, l.pf_next_w, pf_h);
|
||||
if (!last) {
|
||||
if (!far) l.mlp.post(c, T);
|
||||
l.jf_ma.step(c, T, far);
|
||||
@@ -1233,10 +1733,13 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
for (size_t li = 0; !m.fuse_mx && li < m.layers.size(); ++li) {
|
||||
const Layer& l = m.layers[li];
|
||||
const bool last = li + 1 == m.layers.size();
|
||||
l.attn.step(c, batch, m.fuse, m.fuse, m.fuse_ar);
|
||||
if (m.fuse) l.j_am.step(c, T, m.fuse_ar);
|
||||
l.mlp.step(c, batch, m.fuse, m.fuse && !last, m.fuse_ar);
|
||||
if (m.fuse && !last) l.j_ma.step(c, T, m.fuse_ar);
|
||||
const bool ar = m.fuse_ar && ar_wire_is_exact(m.g, T); /* exact wire only, as above */
|
||||
l.attn.step(c, batch, m.fuse, m.fuse, ar);
|
||||
prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h);
|
||||
if (m.fuse) l.j_am.step(c, T, ar);
|
||||
l.mlp.step(c, batch, m.fuse, m.fuse && !last, ar);
|
||||
prefetch_beside(c, l.op_pf_next, l.pf_next_w, pf_h);
|
||||
if (m.fuse && !last) l.j_ma.step(c, T, ar);
|
||||
tap(li);
|
||||
}
|
||||
/* With fused junctions the last layer's tail ran unfused (tail_fused false), so the stream is
|
||||
|
||||
@@ -187,6 +187,10 @@ struct Layer {
|
||||
rad_weight w_next = 0;
|
||||
/* the drafter's tap, on a layer the drafter reads (see declare) */
|
||||
rad_op op_tap = 0;
|
||||
/* Calibration: the attention's input (q, k and v share it), its output (this rank's columns,
|
||||
* o_proj's input), the dense arm's input and its gated product (this rank's columns, down's
|
||||
* input). */
|
||||
CalibTap tap_in{}, tap_o{}, tap_gu{}, tap_dn{};
|
||||
};
|
||||
|
||||
struct Model {
|
||||
@@ -227,6 +231,12 @@ struct Model {
|
||||
int tap_layer[MAX_TAPS] = {};
|
||||
rad_buf b_dfsrc = 0;
|
||||
|
||||
/* The calibration tap: on while `tap_live`, over layers [calib_lo, calib_hi). Written by step,
|
||||
* which owns the corpus count. */
|
||||
bool calib = false, tap_live = false;
|
||||
int64_t calib_lo = 0, calib_hi = 0;
|
||||
long long calib_rows = 0;
|
||||
|
||||
Dflash1 df{};
|
||||
rad_kvgroup kv_draft = 0;
|
||||
bool have_df = false;
|
||||
@@ -1223,6 +1233,30 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* ~120 us per layer on 4x R9700), so it hides behind the experts' bandwidth. No collective
|
||||
* rides it, so the reductions stay on lane 0. Its buffers leave the arena's sharing. */
|
||||
m.arms = m.moe;
|
||||
/* ---- the calibration tap. It reads each dense linear's bf16 input where trunk issues the
|
||||
* linear, so a calibration runs every step whole and on one lane. The files are named after
|
||||
* the weights the 31B's w4a8 container quantises (gemma4_bf16: blk.N.attn_qkv, attn_o,
|
||||
* ffn_gate_up, ffn_down), which a GPTQ recipe reads with calib=DIR: the Hessians of the bf16
|
||||
* model, whose activations a quantised container's own tap would see through its quantisers.
|
||||
* The routed arm is not tapped. */
|
||||
if (calib_dir()) {
|
||||
m.overlap = false;
|
||||
m.arms = false;
|
||||
RAD_ARCH_TRY(calib_layers("gemma4", "RADIANCE_G4_CALIB_LAYERS", (int64_t)m.layers.size(),
|
||||
&m.calib_lo, &m.calib_hi));
|
||||
for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) {
|
||||
Layer& y = m.layers[(size_t)l];
|
||||
const Kind& k = y.full ? m.kf : m.ks;
|
||||
const int i = (int)l;
|
||||
RAD_ARCH_TRY(y.tap_in.declare(b, nm, T, nm.f("blk.%d.attn_in", i), m.b_h, E));
|
||||
RAD_ARCH_TRY(y.tap_o.declare(b, nm, T, nm.f("blk.%d.attn_o", i),
|
||||
y.full ? m.b_attf : m.b_atts, k.q()));
|
||||
RAD_ARCH_TRY(y.tap_gu.declare(b, nm, T, nm.f("blk.%d.ffn_gate_up", i), m.b_h, E));
|
||||
RAD_ARCH_TRY(y.tap_dn.declare(b, nm, T, nm.f("blk.%d.ffn_down", i), m.b_act, m.n_ff));
|
||||
}
|
||||
m.calib = true;
|
||||
m.tap_live = true;
|
||||
}
|
||||
if (m.overlap) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_o));
|
||||
if (m.overlap || m.arms) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_ff2));
|
||||
if (m.arms)
|
||||
@@ -1464,8 +1498,10 @@ static void trunk(RadCtx* c, const Model& m, const RadBatch* batch) {
|
||||
RAD_ISSUE(c, y.op_q, brows(m.b_h, T), RAD_W(y.w_q), brows(m.b_qf, T));
|
||||
RAD_ISSUE(c, y.op_k, brows(m.b_h, T), RAD_W(y.w_k), brows(m.b_kf, T));
|
||||
}
|
||||
y.tap_in.step(c, m.b_h, T, m.tap_live);
|
||||
attend(c, m, y, li, batch);
|
||||
RAD_ISSUE(c, y.op_o, brows(y.full ? m.b_attf : m.b_atts, T), RAD_W(y.w_o), brows(m.b_o, T));
|
||||
y.tap_o.step(c, y.full ? m.b_attf : m.b_atts, T, m.tap_live);
|
||||
if (y.op_ar_o) RAD_ISSUE_N(c, y.op_ar_o, T * E, brows(m.b_o, T), RAD_NONE);
|
||||
if (y.op_join_r) {
|
||||
RAD_ISSUE(c, y.op_join_r, brows(m.b_o, T), RAD_W(y.w_apost), brows(m.b_x, T),
|
||||
@@ -1485,9 +1521,11 @@ static void trunk(RadCtx* c, const Model& m, const RadBatch* batch) {
|
||||
if (m.arms)
|
||||
lanes_ok = lanes_ok && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK;
|
||||
RAD_ISSUE(c, y.op_gu, brows(m.b_h, T), RAD_W(y.w_gu), brows(m.b_gu, T));
|
||||
y.tap_gu.step(c, m.b_h, T, m.tap_live);
|
||||
RAD_ISSUE(c, y.op_act, bcol(m.b_gu, 0, m.n_ff, T), bcol(m.b_gu, m.n_ff, m.n_ff, T),
|
||||
brows(m.b_act, T));
|
||||
RAD_ISSUE(c, y.op_dn, brows(m.b_act, T), RAD_W(y.w_dn), brows(m.b_ff2, T));
|
||||
y.tap_dn.step(c, m.b_act, T, m.tap_live);
|
||||
if (m.arms) lanes_ok = rad_lane(c, 0) == RAD_OK && lanes_ok;
|
||||
if (m.moe) {
|
||||
routed(c, m, y, T, 0, T, T);
|
||||
@@ -1668,6 +1706,36 @@ static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int6
|
||||
"the first");
|
||||
}
|
||||
|
||||
/* The tap's rows, and its files once the corpus reached RADIANCE_CALIB_TOKENS. The input of q|k|v
|
||||
* and of gate|up is whole on every rank, so rank 0 writes it, under the name of the linear that
|
||||
* reads it. The column-split linears (o, down) see this rank's columns only: each rank writes its
|
||||
* block as `<stem>.part`, which libquant's calib_sum places on the diagonal in rank order (the
|
||||
* cross-rank products are never formed on one card). */
|
||||
static void calib_count(RadCtx* c, Model& m, int64_t T) {
|
||||
m.calib_rows += T;
|
||||
if (m.calib_rows < calib_target()) return;
|
||||
const int rk = rad_rank(c);
|
||||
bool ok = true;
|
||||
for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) {
|
||||
const Layer& y = m.layers[(size_t)l];
|
||||
char stem[96];
|
||||
if (rk == 0) {
|
||||
std::snprintf(stem, sizeof stem, "blk.%d.attn_qkv", (int)l);
|
||||
ok = calib_write(c, y.tap_in.h, y.tap_in.K, m.calib_rows, stem, 0) && ok;
|
||||
std::snprintf(stem, sizeof stem, "blk.%d.ffn_gate_up", (int)l);
|
||||
ok = calib_write(c, y.tap_gu.h, y.tap_gu.K, m.calib_rows, stem, 0) && ok;
|
||||
}
|
||||
std::snprintf(stem, sizeof stem, "blk.%d.attn_o.part", (int)l);
|
||||
ok = calib_write(c, y.tap_o.h, y.tap_o.K, m.calib_rows, stem, 0) && ok;
|
||||
std::snprintf(stem, sizeof stem, "blk.%d.ffn_down.part", (int)l);
|
||||
ok = calib_write(c, y.tap_dn.h, y.tap_dn.K, m.calib_rows, stem, 0) && ok;
|
||||
}
|
||||
m.tap_live = false;
|
||||
std::fprintf(stderr, "radiance: gemma4: rank %d wrote the Hessians of layers %lld:%lld after "
|
||||
"%lld tokens to %s%s\n", rk, (long long)m.calib_lo, (long long)m.calib_hi,
|
||||
m.calib_rows, calib_dir(), ok ? "" : ", with errors");
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(c)];
|
||||
if (batch->draft_pass != 0) {
|
||||
@@ -1695,6 +1763,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.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) {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+68
-12
@@ -46,6 +46,10 @@ struct Layer {
|
||||
struct Model {
|
||||
Names nm{};
|
||||
Geom g{};
|
||||
/* The MLA's split of a prefill-sized step under TP (RadBuildCtx::tp_attn_rows). The head
|
||||
* form declares none of the row form's full-width weights (1.29 GiB a card at eight ranks);
|
||||
* the row form is opt-in because it is not bit-identical to it (docs/ARCHITECTURES.md). */
|
||||
GlmMla::Form form = GlmMla::Form::heads;
|
||||
std::vector<Layer> layers;
|
||||
rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0;
|
||||
/* The streams and the step's stream-wide buffers. */
|
||||
@@ -102,7 +106,11 @@ static int stream_buffers(RadBuilder* b, Model& m) {
|
||||
m.h0 = decl_b(b, nm.f("manifold"), RAD_BF16, { T, 16384 });
|
||||
m.h1 = decl_b(b, nm.f("manifold_mid"), RAD_BF16, { T, 16384 });
|
||||
m.x = decl_b(b, nm.f("collapsed"), RAD_BF16, { T, 4096 });
|
||||
m.y = decl_b(b, nm.f("attn_delta"), RAD_BF16, { T, 4096 });
|
||||
/* The MLA row form gathers every rank's run at full length, so its output is rounded up to
|
||||
* whole runs; the head form keeps the step's rows. */
|
||||
const bool rows = g.world > 1 && m.form == GlmMla::Form::rows;
|
||||
m.y = decl_b(b, nm.f("attn_delta"), RAD_BF16,
|
||||
{ rows ? g.world * GlmMla::rows_for(T, g.world) : T, 4096 });
|
||||
m.post = decl_b(b, nm.f("post"), RAD_F32, { T, 4 });
|
||||
m.comb = decl_b(b, nm.f("mix"), RAD_F32, { T, 16 });
|
||||
m.act.x = decl_b(b, nm.f("normalized"), RAD_BF16, { T, 4096 });
|
||||
@@ -132,9 +140,9 @@ static int kda_buffers(RadBuilder* b, Model& m) {
|
||||
kw.core.out = bf("recurrent_out", W);
|
||||
return RAD_OK;
|
||||
}
|
||||
/* The head form's buffers, then the selection planes the indexer writes and the MLA reads. Under
|
||||
* TP the selection planes hold every rank's run of rows, which can reach past the step
|
||||
* (DsaCache::part_rows). */
|
||||
/* The head form's buffers, then the selection planes the indexer writes and the MLA reads, then
|
||||
* the row form's (Model::form). Under TP the selection planes hold every rank's run of rows,
|
||||
* which can reach past the step (DsaCache::part_rows). */
|
||||
static int mla_buffers(RadBuilder* b, Model& m) {
|
||||
auto& g = m.g;
|
||||
auto& nm = m.nm;
|
||||
@@ -160,6 +168,16 @@ static int mla_buffers(RadBuilder* b, Model& m) {
|
||||
const int64_t TQ = g.world > 1 ? std::max(T, g.world * part) : T;
|
||||
aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { TQ, 513 });
|
||||
aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { TQ });
|
||||
if (g.world > 1 && m.form == GlmMla::Form::rows) {
|
||||
auto& rows = aw.rows;
|
||||
const int64_t R = GlmMla::rows_for(T, g.world);
|
||||
rows.q = decl_b(b, nm.f("rows_query"), RAD_BF16, { R, 16384 });
|
||||
rows.q_latent = decl_b(b, nm.f("rows_q_latent"), RAD_BF16, { R, 64, 512 });
|
||||
rows.attn_latent = decl_b(b, nm.f("rows_attn_latent"), RAD_BF16, { R, 64, 512 });
|
||||
rows.attn.x = decl_b(b, nm.f("rows_expanded"), RAD_BF16, { R, 16384 });
|
||||
RAD_ARCH_TRY(rows.attn.declare_qs(b, nm, g, "rows_expanded", 16384, R));
|
||||
rows.out = decl_b(b, nm.f("rows_out"), RAD_BF16, { R, 4096 });
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
static int indexer_buffers(RadBuilder* b, Model& m) {
|
||||
@@ -196,6 +214,8 @@ static int indexer_buffers(RadBuilder* b, Model& m) {
|
||||
c.selected = m.aw.core.selected;
|
||||
c.length = m.aw.core.length;
|
||||
c.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T });
|
||||
/* The MLA block's resolve count: qsa_select's second output, never `length`. */
|
||||
m.aw.core.nsel = c.nsel;
|
||||
if (g.world > 1) {
|
||||
c.cu_part = decl_b(b, nm.f("index_part_bounds"), RAD_I32, { g.max_seqs + 1 });
|
||||
c.sel_part = decl_b(b, nm.f("selected_part"), RAD_I32, { part, 513 });
|
||||
@@ -226,9 +246,13 @@ static int ffn_buffers(RadBuilder* b, Model& m) {
|
||||
mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 });
|
||||
mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { T * 8 });
|
||||
mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { T * 8 });
|
||||
mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { T * 8, 2 * F });
|
||||
mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { T * 8, F });
|
||||
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * 8));
|
||||
// FE: the routed experts' WHOLE intermediate (2048). Under expert parallelism a rank owns
|
||||
// whole experts, so the routed arm's buffers are full-width at every world size; the SHARED
|
||||
// expert stays width-sharded (F). The two coincide at world 1.
|
||||
const int64_t FE = 2048;
|
||||
mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { T * 8, 2 * FE });
|
||||
mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { T * 8, FE });
|
||||
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", FE, T * 8));
|
||||
mw.edn = decl_b(b, nm.f("expert_down"), RAD_BF16, { T * 8, 4096 });
|
||||
mw.sgu = bf("shared_gate_up", 2 * F);
|
||||
mw.sff.x = bf("shared_ff", F);
|
||||
@@ -292,7 +316,10 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
|
||||
decl_w(b, nn, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
RAD_ARCH_TRY(lay.norm.declare(b, g, gain, input, m.act, 4096));
|
||||
if (lay.full) {
|
||||
RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, m.aw, ap, m.latent, true, true));
|
||||
// The MTP layer keeps the head form: its row form would cost another 126 MB a card.
|
||||
auto aw = m.aw;
|
||||
if (draft) aw.rows = {};
|
||||
RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, aw, ap, m.latent, true, true));
|
||||
DsaCache::Config c;
|
||||
c.blocks = (g.max_ctx + 3) / 4 + 1;
|
||||
c.work = (g.max_tok + 3) / 4 + g.max_seqs;
|
||||
@@ -334,9 +361,26 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
|
||||
s.router_bias = nm.ckpt("%s.mlp.gate.e_score_correction_bias", pre);
|
||||
s.experts = nm.ckpt("%s.mlp.experts", pre);
|
||||
s.shared = nm.ckpt("%s.mlp.shared_experts", pre);
|
||||
s.cfg.n_expert = s.cfg.n_expert_all = 288;
|
||||
// EXPERT PARALLELISM AT TP: each rank owns 288/world WHOLE experts (the contiguous
|
||||
// window [expert_base, expert_base+n_expert) of the checkpoint's numbering), which the
|
||||
// helper declares RAD_SHARD_NONE -- unsharded, so an expert unit is file-direct and can
|
||||
// live in the container's mapping or the file tier
|
||||
// instead of needing VRAM+pinned-pool residency for all 151 GiB of them. The router
|
||||
// stays replicated over n_expert_all; moe_scatter/router_topk_scatter drop slots
|
||||
// outside the window (moe_scatter schema: "which is how EXPERT PARALLELISM is
|
||||
// expressed"); the shared expert stays width-sharded on its own declaration path; the
|
||||
// block's all-reduce sums the partials exactly as width TP did. At world 1 this
|
||||
// degenerates to the old whole-model declaration (n_expert == n_expert_all, no spans).
|
||||
s.cfg.n_expert_all = 288;
|
||||
s.cfg.top_k = 8;
|
||||
s.cfg.n_ff_exp = s.cfg.n_ff_shared = GlmTp::expert_width(g.world);
|
||||
s.cfg.n_expert = 288 / g.world;
|
||||
// A shape probe may pass rank >= world (arch_test's parallel declares reuse i % 4);
|
||||
// old code tolerated that because expert_base stayed 0, so clamp to rank 0's window.
|
||||
const int ep_rank = g.rank < g.world ? g.rank : 0;
|
||||
s.cfg.expert_base = ep_rank * (288 / g.world);
|
||||
s.cfg.probed_expert = s.cfg.expert_base; // probe this rank's first owned expert
|
||||
s.cfg.n_ff_exp = 2048; // whole: whole experts' intermediate
|
||||
s.cfg.n_ff_shared = 2048 / g.world;
|
||||
s.cfg.rows = g.max_tok;
|
||||
s.cfg.sigmoid_router = 1;
|
||||
s.cfg.route_scale = 2.5;
|
||||
@@ -344,9 +388,14 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
|
||||
s.cfg.shared_ungated = 1;
|
||||
s.cfg.router_fuse = 1;
|
||||
s.cfg.swiglu_quant = 1;
|
||||
// At world 1 the width-slice declaration IS the whole model: keep the spans so the
|
||||
// graph stays the pinned one. At world > 1 expert parallelism is in force and whole
|
||||
// experts need no width spans (split && ep is refused by the helper).
|
||||
if (g.world == 1) {
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
s.cfg.ff_lo[q] = g.rank * GlmTp::expert_width(g.world);
|
||||
s.cfg.ff_hi[q] = (g.rank + 1) * GlmTp::expert_width(g.world);
|
||||
s.cfg.ff_lo[q] = g.rank * (2048 / g.world);
|
||||
s.cfg.ff_hi[q] = (g.rank + 1) * (2048 / g.world);
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, s, &s.cfg));
|
||||
RAD_ARCH_TRY(lay.moe.declare(b, nm, g, l, w, s, false, draft));
|
||||
@@ -375,6 +424,9 @@ static int geometry(Geom& g, const RadModelMeta* meta, const RadBuildCtx* ctx, i
|
||||
g.max_ctx = ctx->max_ctx;
|
||||
g.max_seqs = ctx->max_seqs;
|
||||
g.max_spec = ctx->max_spec;
|
||||
/* Filled by hand here, not by geom_from: without it kv_resolve would declare the whole context as
|
||||
* the ring. */
|
||||
g.kv_resident = ctx->kv_resident_blocks;
|
||||
g.max_logit_rows = std::min<int64_t>(g.max_tok, g.max_seqs * (g.max_spec + 1));
|
||||
if (ctx->max_out_rows > g.max_logit_rows) g.max_logit_rows = ctx->max_out_rows;
|
||||
g.eps = meta->rms_eps;
|
||||
@@ -429,6 +481,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
auto& g = m.g;
|
||||
m.nm = Names(ctx->scope);
|
||||
auto& nm = m.nm;
|
||||
m.form = ctx->tp_attn_rows ? GlmMla::Form::rows : GlmMla::Form::heads;
|
||||
RAD_ARCH_TRY(geometry(g, meta, ctx, world));
|
||||
RAD_ARCH_TRY(stream_buffers(b, m));
|
||||
RAD_ARCH_TRY(kda_buffers(b, m));
|
||||
@@ -571,6 +624,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
}
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
/* The MLA block declares the streamed store and the resolve (rad_block_glm_mla.h). */
|
||||
out->kv_stream_ok = 1;
|
||||
if (cfg(meta, "num_nextn_predict_layers", 0) == 1) out->draft_depth = GlmMtp::kDepth;
|
||||
// The tower's merged block, so a pass size the core picks itself is whole output rows.
|
||||
if (GlmVision::present(meta)) {
|
||||
@@ -578,6 +633,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (k > 0) out->enc_merge = k * k;
|
||||
}
|
||||
out->shape_probe_ok = 1;
|
||||
out->tp_attn_rows_ok = 1;
|
||||
return RAD_OK;
|
||||
}
|
||||
} // namespace glm5next
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(hyv3_bf16 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(hyv3_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hyv3_bf16.cpp)
|
||||
@@ -0,0 +1,5 @@
|
||||
#define HYV3_NS hyv3_bf16
|
||||
#define HYV3_QUANT ""
|
||||
#define HYV3_FP8_SOURCE 0
|
||||
#define HYV3_PLUGIN_NAME "hyv3_bf16"
|
||||
#include "../hyv3_common/hyv3_impl.cpp"
|
||||
@@ -0,0 +1,250 @@
|
||||
/* HYV3 full GQA attention with block-scaled FP8 projections and per-head
|
||||
* Q/K RMSNorm before NeoX RoPE (the HYV3 attention path).
|
||||
*
|
||||
* rmsnorm -> q/k/v gemm_nt_q -> per-head q/k RMSNorm -> rope -> kv_store -> attn_paged
|
||||
* -> quant_act_fp8 -> o gemm_nt_q -> [all_reduce] -> residual add
|
||||
*
|
||||
* Unlike AttnFP8, the projections stay separate so Q and K can be normalized independently before
|
||||
* rotation. The weights and all non-attention activations use the same contracts as the other FP8
|
||||
* blocks in rad_fp8.h.
|
||||
*/
|
||||
#ifndef HYV3_ATTENTION_H
|
||||
#define HYV3_ATTENTION_H
|
||||
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct AttnQKFP8 {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] residual stream */
|
||||
ActFP8 h{}; /* [max_tok, n_embd] normed input, then o output */
|
||||
rad_buf q = 0; /* [max_tok, q_dim], projected, normed and rotated */
|
||||
rad_buf k = 0; /* [max_tok, kv_dim], projected, normed and rotated */
|
||||
rad_buf v = 0; /* [max_tok, kv_dim], projected */
|
||||
ActFP8 attn{}; /* [max_tok, q_dim] attention output */
|
||||
};
|
||||
|
||||
struct Src {
|
||||
const char* norm = nullptr;
|
||||
const char* q = nullptr;
|
||||
const char* k = nullptr;
|
||||
const char* v = nullptr;
|
||||
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{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
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;
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
const Wire& wire, const Src& src, bool fold = false, bool add_out = true);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_kvgroup group, const Wire& wire, const Src& src,
|
||||
bool fold, bool add_out) {
|
||||
g = geom;
|
||||
w = wire;
|
||||
layer = l;
|
||||
kv = group;
|
||||
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
|
||||
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
|
||||
"with n_head_kv = %lld\n", __func__, g.world,
|
||||
(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));
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
if (!w_norm || !w_q_norm || !w_k_norm) return RAD_E_INVAL;
|
||||
|
||||
// As in the other pre-norm blocks, absorb a preceding delta into the residual stream.
|
||||
// The fused kernel normalises the BF16-rounded sum, not an unrounded FP32 substitute.
|
||||
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
|
||||
fold ? w.x : 0));
|
||||
RAD_ARCH_TRY(q.declare(b, nm, g, nm.f("blk.%d.attn_q", l), q_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.q}, w.h, w.q));
|
||||
RAD_ARCH_TRY(k.declare(b, nm, g, nm.f("blk.%d.attn_k", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.k}, w.h, w.k));
|
||||
RAD_ARCH_TRY(v.declare(b, nm, g, nm.f("blk.%d.attn_v", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), {src.v}, w.h, w.v));
|
||||
|
||||
auto head_norm = [&](int64_t heads, rad_weight wt) {
|
||||
return RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * heads), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(wt));
|
||||
};
|
||||
op_q_norm = rw(b, head_norm(g.n_head, w_q_norm), {w.q}, {w.q});
|
||||
op_k_norm = rw(b, head_norm(g.n_head_kv, w_k_norm), {w.k}, {w.k});
|
||||
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim, "neox"),
|
||||
{w.q}, {w.q});
|
||||
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",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
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_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_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
|
||||
* launches; the fused kernel preserves the BF16 norm rounding before the rotary. */
|
||||
if (g.head_dim == 128 && !std::strcmp(g.dtype, "bf16") &&
|
||||
!std::strcmp(g.kv_dtype, "bf16") &&
|
||||
!g.rope_mc && g.yarn.factor == 0.0f &&
|
||||
rad_op_declared(b, "qkv_norm_rope_kv_store")) {
|
||||
qkr_rows = qk_fuse_rows(g);
|
||||
op_qkr_store = RAD_OP(b, "qkv_norm_rope_kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qkr_rows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("eps", g.eps),
|
||||
RAD_F64("scale", g.rope_scale), RAD_STR("mode", "neox"),
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("v_norm", 0), RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_WEIGHTS(w_q_norm, w_k_norm));
|
||||
if (!op_qkr_store || !rad_op_resolved(b, op_qkr_store)) op_qkr_store = 0;
|
||||
if (op_qkr_store)
|
||||
op_qkr_store = rw(b, op_qkr_store, {w.q, w.k, w.v}, {w.q, w.k, w.v});
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(q_attn.declare(b, g, w.attn, q_dim));
|
||||
RAD_ARCH_TRY(o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim,
|
||||
RAD_SHARD_COL, grp_layer(l), {src.o}, w.attn, w.h.x));
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
if (add_out) op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h.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;
|
||||
}
|
||||
|
||||
inline void AttnQKFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
nq_h.step(c, T);
|
||||
q.step(c, w.h, w.q, T);
|
||||
k.step(c, w.h, w.k, T);
|
||||
v.step(c, w.h, w.v, T);
|
||||
if (op_qkr_store && T <= qkr_rows) {
|
||||
RAD_ISSUE_N(c, op_qkr_store, T, brows(w.q, T), brows(w.k, T), brows(w.v, T),
|
||||
rope_posmc(g, batch, T), RAD_W(w_q_norm), RAD_W(w_k_norm),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_q_norm, T * g.n_head, brows(w.q, T), RAD_W(w_q_norm), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
|
||||
RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T));
|
||||
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
|
||||
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));
|
||||
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);
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} // namespace arch
|
||||
} // namespace rad
|
||||
|
||||
#endif /* HYV3_ATTENTION_H */
|
||||
@@ -0,0 +1,554 @@
|
||||
/* Shared HYV3 graph. Thin architecture wrappers select the source descriptor and source format. */
|
||||
#ifndef HYV3_NS
|
||||
#define HYV3_NS hyv3_fp8
|
||||
#endif
|
||||
#ifndef HYV3_QUANT
|
||||
#define HYV3_QUANT "fp8"
|
||||
#endif
|
||||
#ifndef HYV3_FP8_SOURCE
|
||||
#define HYV3_FP8_SOURCE 1
|
||||
#endif
|
||||
#ifndef HYV3_PLUGIN_NAME
|
||||
#define HYV3_PLUGIN_NAME "hyv3_fp8"
|
||||
#endif
|
||||
#ifndef HYV3_GGUF_SOURCE
|
||||
#define HYV3_GGUF_SOURCE 0
|
||||
#endif
|
||||
#include <arch/rad_arch.h>
|
||||
#include "hyv3_attention.h"
|
||||
#include "rad_abi_layout.h"
|
||||
#include <arch/rad_block_mlp_fp8.h>
|
||||
#include <arch/rad_block_moe_fp8.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace HYV3_NS {
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
bool dense = false;
|
||||
AttnQKFP8 attn{};
|
||||
MlpFP8 dense_mlp{};
|
||||
MoeFP8 moe{};
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{};
|
||||
Geom g{};
|
||||
int64_t n_ff_expert = 0, n_ff_shared = 0;
|
||||
rad_kvgroup kv_full = 0;
|
||||
|
||||
rad_buf x = 0, h_out = 0, logits = 0;
|
||||
ActFP8 h{};
|
||||
rad_buf q = 0, k = 0, v = 0;
|
||||
ActFP8 attn{};
|
||||
rad_buf dense_gate_up = 0;
|
||||
ActFP8 dense_ffn{};
|
||||
MoeFP8::Wire mw{};
|
||||
|
||||
rad_weight token = 0, final_norm = 0, lm_head = 0;
|
||||
rad_op embed = 0, embed_ar = 0, shared_one = 0, final_rms = 0, gather = 0, logits_op = 0;
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model models[MAX_RANKS];
|
||||
|
||||
static int check_format(const RadModelMeta* meta) {
|
||||
const char* q = meta && meta->quant ? meta->quant : "";
|
||||
#if HYV3_GGUF_SOURCE
|
||||
if (std::strcmp(q, "gguf_ftype_15") != 0) {
|
||||
fprintf(stderr, "radiance: HYV3 GGUF adapter expects quant descriptor 'gguf_ftype_15'; "
|
||||
"got '%s'\n", *q ? q : "(none)");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
#elif HYV3_FP8_SOURCE
|
||||
if (std::strcmp(q, "fp8") != 0) {
|
||||
fprintf(stderr, "radiance: HYV3 FP8 expects quant descriptor 'fp8'; got '%s'\n",
|
||||
*q ? q : "(none)");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const char* fmt = rad_meta_gets(meta, "quantization_config.fmt", nullptr);
|
||||
if (fmt && std::strcmp(fmt, "e4m3") != 0) return RAD_E_UNSUPPORTED;
|
||||
const char* method = rad_meta_gets(meta, "quantization_config.quant_method", nullptr);
|
||||
if (method && std::strcmp(method, "fp8") != 0) return RAD_E_UNSUPPORTED;
|
||||
#else
|
||||
if (*q) {
|
||||
fprintf(stderr, "radiance: HYV3 BF16 expects an unquantized checkpoint; got '%s'\n", q);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
#endif
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int check_model_config(const RadModelMeta* meta, const Geom& g, Model& model) {
|
||||
if (meta_text_geti(meta, "qk_norm", 0) != 1 ||
|
||||
meta_text_geti(meta, "moe_router_use_sigmoid", 0) != 1 ||
|
||||
meta_text_geti(meta, "moe_router_enable_expert_bias", 0) != 1 ||
|
||||
meta_text_geti(meta, "route_norm", 0) != 1 ||
|
||||
meta_text_geti(meta, "enable_moe_fp32_combine", 0) != 1 ||
|
||||
meta_text_geti(meta, "attention_bias", 0) != 0 ||
|
||||
meta_text_geti(meta, "mlp_bias", 0) != 0) {
|
||||
fprintf(stderr, "radiance: hyv3 requires QK norm, sigmoid routing with correction bias, "
|
||||
"route normalization, FP32 MoE combine, and bias-free projections\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
const int64_t first_dense = meta_text_geti(meta, "first_k_dense_replace", -1);
|
||||
const int64_t n_expert = meta_text_geti(meta, "num_experts", 0);
|
||||
const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", 0);
|
||||
const int64_t n_shared = meta_text_geti(meta, "num_shared_experts", 0);
|
||||
const int64_t moe_intermediate = meta_text_geti(meta, "moe_intermediate_size", 0);
|
||||
const int64_t n_ff_shared = meta_text_geti(meta, "expert_hidden_dim", 0);
|
||||
model.n_ff_expert = meta_text_geti(meta, "expert_hidden_dim", 0);
|
||||
const int64_t route_norm = meta_text_geti(meta, "route_norm", 0);
|
||||
const double route_scale = meta_text_getf(meta, "router_scaling_factor", 1.0);
|
||||
const char* schedule = meta_text_gets(meta, "mlp_layer_types", nullptr);
|
||||
std::vector<int> kinds;
|
||||
|
||||
if (first_dense != 1 || n_expert != meta->n_expert || top_k != meta->n_expert_used ||
|
||||
n_expert != 128 || top_k != 8 || n_shared != 1 || model.n_ff_expert != 768 ||
|
||||
n_ff_shared != 768 || moe_intermediate != 1536 || route_norm != 1 ||
|
||||
!std::isfinite(route_scale) || route_scale <= 0 ||
|
||||
std::fabs(route_scale - 2.826) > 1e-6 || model.n_ff_expert % RAD_FP8_BLOCK != 0) {
|
||||
fprintf(stderr, "radiance: hyv3: unsupported MoE geometry/config; expected 128 experts, "
|
||||
"top-8, 768-wide routed and shared experts, normalized "
|
||||
"sigmoid routing scaled by 2.826, and one dense first layer\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (schedule && *schedule) {
|
||||
RAD_ARCH_TRY(parse_layer_kinds("hyv3", schedule, {"sparse"}, "dense", &kinds));
|
||||
if ((int64_t)kinds.size() != g.n_layer) {
|
||||
fprintf(stderr, "radiance: hyv3: mlp_layer_types names %zu layers; the model has %lld\n",
|
||||
kinds.size(), (long long)g.n_layer);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int want = l == 0 ? 0 : 1;
|
||||
if (kinds[(size_t)l] != want) {
|
||||
fprintf(stderr, "radiance: hyv3: layer %lld has an unsupported MLP kind; expected "
|
||||
"dense at layer 0 and sparse afterwards\n", (long long)l);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const int64_t shared_width = n_ff_shared * n_shared;
|
||||
if (shared_width <= 0 || shared_width % RAD_FP8_BLOCK != 0) return RAD_E_SHAPE;
|
||||
model.n_ff_shared = shared_width;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void block_slice_128(int64_t width, int world, int rank, int64_t* lo, int64_t* hi) {
|
||||
const int64_t blocks = width / RAD_FP8_BLOCK;
|
||||
const int64_t base = blocks / world, rem = blocks % world;
|
||||
const int64_t first = rank * base + std::min<int64_t>(rank, rem);
|
||||
const int64_t count = base + (rank < rem ? 1 : 0);
|
||||
*lo = first * RAD_FP8_BLOCK;
|
||||
*hi = (first + count) * RAD_FP8_BLOCK;
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = models[ctx->rank];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
int status = check_format(meta);
|
||||
if (status < 0) return status;
|
||||
status = geom_from(m.g, meta, ctx, "bf16", RAD_BF16);
|
||||
if (status < 0) return status;
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
|
||||
if (g.n_layer < 2 || g.n_embd != 2048 || g.n_head_all != 32 || g.n_head_kv_all != 4 ||
|
||||
g.head_dim != 128 || g.n_vocab_all != 120832 ||
|
||||
(g.world != 1 && g.world != 2)) {
|
||||
fprintf(stderr, "radiance: hyv3 supports Hy-Memory's 2048-wide, 32/4-head, "
|
||||
"head_dim=128 geometry at tensor-parallel world sizes 1 or 2\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
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");
|
||||
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;
|
||||
|
||||
const int64_t n_expert_all = meta_text_geti(meta, "num_experts", meta->n_expert);
|
||||
const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", meta->n_expert_used);
|
||||
if (n_expert_all % g.world != 0) return RAD_E_SHAPE;
|
||||
const int64_t n_expert_local = n_expert_all / g.world;
|
||||
|
||||
/* ---- Full-attention KV cache. All layers share one group. */
|
||||
RadKVGroupDecl kd{};
|
||||
kd.kind = RAD_KV_FULL;
|
||||
kd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
kd.n_head_kv = g.n_head_kv;
|
||||
kd.head_dim = g.head_dim;
|
||||
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &kd);
|
||||
if (!m.kv_full) return RAD_E_INVAL;
|
||||
g.kv_dtype = rad_dtype_name(kd.dtype);
|
||||
|
||||
const int64_t T = g.max_tok, qd = g.q_dim(), kvd = g.kv_dim();
|
||||
m.x = decl_b(b, nm.f("x"), RAD_BF16, {T, g.n_embd});
|
||||
m.h.x = decl_b(b, nm.f("h"), RAD_BF16, {T, g.n_embd});
|
||||
RAD_ARCH_TRY(m.h.declare_qs(b, nm, g, "h", g.n_embd, 0, !HYV3_FP8_SOURCE));
|
||||
m.q = decl_b(b, nm.f("attn_q"), RAD_BF16, {T, qd});
|
||||
m.k = decl_b(b, nm.f("attn_k"), RAD_BF16, {T, kvd});
|
||||
m.v = decl_b(b, nm.f("attn_v"), RAD_BF16, {T, kvd});
|
||||
m.attn.x = decl_b(b, nm.f("attn_out"), RAD_BF16, {T, qd});
|
||||
RAD_ARCH_TRY(m.attn.declare_qs(b, nm, g, "attn_out", qd, 0, !HYV3_FP8_SOURCE));
|
||||
m.dense_gate_up = decl_b(b, nm.f("dense_gate_up"), RAD_BF16, {T, 2 * g.n_ff});
|
||||
m.dense_ffn.x = decl_b(b, nm.f("dense_ffn"), RAD_BF16, {T, g.n_ff});
|
||||
RAD_ARCH_TRY(m.dense_ffn.declare_qs(b, nm, g, "dense_ffn", g.n_ff, 0, !HYV3_FP8_SOURCE));
|
||||
m.h_out = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, g.n_embd});
|
||||
m.logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
|
||||
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
|
||||
|
||||
/* The router is replicated, while the routed experts are expert-parallel. The shared expert
|
||||
* is split only on whole FP8 scale blocks; the final block remainder is assigned to early
|
||||
* ranks. At TP2, routed and shared BF16 outputs are all-reduced separately before FP32 combine. */
|
||||
MoeFP8::Config mc{};
|
||||
mc.n_expert_all = n_expert_all;
|
||||
mc.n_expert = n_expert_local;
|
||||
mc.expert_base = n_expert_local * g.rank;
|
||||
mc.probed_expert = mc.expert_base;
|
||||
mc.top_k = top_k;
|
||||
mc.n_ff_exp = m.n_ff_expert;
|
||||
mc.norm_topk = 1;
|
||||
mc.sigmoid_router = 1;
|
||||
mc.route_scale = meta_text_getf(meta, "router_scaling_factor", 2.826);
|
||||
mc.shared_ungated = 1;
|
||||
mc.shared_fp32_combine = 1;
|
||||
mc.shared_one_external = g.world == 1;
|
||||
mc.router_fuse = 1;
|
||||
mc.rows = T < 2048 ? T : 2048;
|
||||
block_slice_128(m.n_ff_shared, g.world, g.rank, &mc.shared_lo, &mc.shared_hi);
|
||||
mc.n_ff_shared = mc.shared_hi - mc.shared_lo;
|
||||
|
||||
#if HYV3_FP8_SOURCE
|
||||
/* The source's per-tensor scales are imported by the recipe to format 9 (block FP8 with F32
|
||||
* 128x128 scales). The model probes the source before recipe planning, so state that encoding
|
||||
* explicitly here. */
|
||||
mc.expert_f32_scale = 1;
|
||||
#endif
|
||||
|
||||
const int64_t R = T, S = mc.rows * top_k;
|
||||
m.mw.x = m.x;
|
||||
m.mw.h = m.h;
|
||||
m.mw.logits = decl_b(b, nm.f("moe_logits"), RAD_F32, {R, n_expert_all});
|
||||
m.mw.ids = decl_b(b, nm.f("moe_ids"), RAD_I32, {R, top_k});
|
||||
m.mw.ew = decl_b(b, nm.f("moe_weights"), RAD_F32, {R, top_k});
|
||||
m.mw.eoff = decl_b(b, nm.f("moe_offsets"), RAD_I32, {n_expert_local + 1});
|
||||
m.mw.ecnt = decl_b(b, nm.f("moe_counts"), RAD_I32, {n_expert_local}, RAD_BUF_PERSIST);
|
||||
m.mw.sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {S});
|
||||
m.mw.egu = decl_b(b, nm.f("moe_gate_up"), RAD_BF16, {S, 2 * mc.n_ff_exp});
|
||||
m.mw.eff.x = decl_b(b, nm.f("moe_ffn"), RAD_BF16, {S, mc.n_ff_exp});
|
||||
RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "moe_ffn", mc.n_ff_exp, S, !HYV3_FP8_SOURCE));
|
||||
m.mw.edn = decl_b(b, nm.f("moe_down"), RAD_BF16, {S, g.n_embd});
|
||||
m.mw.moe = decl_b(b, nm.f("moe_routed"), RAD_BF16, {T, g.n_embd});
|
||||
m.mw.sgu = decl_b(b, nm.f("shared_gate_up"), RAD_BF16, {T, 2 * mc.n_ff_shared});
|
||||
m.mw.sff.x = decl_b(b, nm.f("shared_ffn"), RAD_BF16, {T, mc.n_ff_shared});
|
||||
RAD_ARCH_TRY(m.mw.sff.declare_qs(b, nm, g, "shared_ffn", mc.n_ff_shared, 0,
|
||||
!HYV3_FP8_SOURCE));
|
||||
m.mw.sout = decl_b(b, nm.f("shared_out"), RAD_BF16, {T, g.n_embd});
|
||||
m.mw.sgate = decl_b(b, nm.f("shared_one"), RAD_BF16, {T, 1});
|
||||
if (mc.shared_one_external) {
|
||||
m.shared_one = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", 1),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("value", 1.0)),
|
||||
RAD_NOWEIGHTS), {}, {m.mw.sgate});
|
||||
if (!m.shared_one) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- Token embedding and head. */
|
||||
#if HYV3_GGUF_SOURCE
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("token_embd.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("output_norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("output.weight"),
|
||||
nm.ckpt("token_embd.weight")));
|
||||
#else
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.embed_tokens.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
nm.ckpt("model.embed_tokens.weight")));
|
||||
#endif
|
||||
m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.final_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.lm_head = decl_w(b, nm.f("output.weight"),
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(m.token)),
|
||||
{}, {m.x});
|
||||
if (g.world > 1)
|
||||
m.embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.x}, {m.x});
|
||||
|
||||
AttnQKFP8::Wire aw{};
|
||||
aw.x = m.x; aw.h = m.h; aw.q = m.q; aw.k = m.k; aw.v = m.v; aw.attn = m.attn;
|
||||
MlpFP8::Wire dw{};
|
||||
dw.x = m.x; dw.h = m.h; dw.gate_up = m.dense_gate_up; dw.ffn = m.dense_ffn;
|
||||
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.dense = (l == 0);
|
||||
#if HYV3_GGUF_SOURCE
|
||||
const char* pre = nm.ckpt("blk.%lld", (long long)l);
|
||||
#else
|
||||
const char* pre = nm.ckpt("model.layers.%lld", (long long)l);
|
||||
#endif
|
||||
AttnQKFP8::Src as{};
|
||||
#if HYV3_GGUF_SOURCE
|
||||
as.norm = nm.ckpt("%s.attn_norm.weight", pre);
|
||||
as.q = nm.ckpt("%s.attn_q.weight", pre);
|
||||
as.k = nm.ckpt("%s.attn_k.weight", pre);
|
||||
as.v = nm.ckpt("%s.attn_v.weight", pre);
|
||||
as.q_norm = nm.ckpt("%s.attn_q_norm.weight", pre);
|
||||
as.k_norm = nm.ckpt("%s.attn_k_norm.weight", pre);
|
||||
as.o = nm.ckpt("%s.attn_output.weight", pre);
|
||||
#else
|
||||
as.norm = nm.ckpt("%s.input_layernorm.weight", pre);
|
||||
as.q = nm.ckpt("%s.self_attn.q_proj.weight", pre);
|
||||
as.k = nm.ckpt("%s.self_attn.k_proj.weight", pre);
|
||||
as.v = nm.ckpt("%s.self_attn.v_proj.weight", pre);
|
||||
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
|
||||
// embedding directly; the final feed-forward keeps its add for the plain output norm.
|
||||
// Keep collective placement and both routed/shared BF16 rounding points.
|
||||
status = lay.attn.declare(b, nm, g, (int)l, m.kv_full, aw, as, l > 0, false);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: hyv3: attention layer %lld declaration failed (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
|
||||
if (lay.dense) {
|
||||
MlpFP8::Src ds{};
|
||||
#if HYV3_GGUF_SOURCE
|
||||
ds.norm = nm.ckpt("%s.ffn_norm.weight", pre);
|
||||
ds.gate = nm.ckpt("%s.ffn_gate.weight", pre);
|
||||
ds.up = nm.ckpt("%s.ffn_up.weight", pre);
|
||||
ds.down = nm.ckpt("%s.ffn_down.weight", pre);
|
||||
#else
|
||||
const char* mlp = nm.ckpt("%s.mlp", pre);
|
||||
ds.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
ds.gate = nm.ckpt("%s.gate_proj.weight", mlp);
|
||||
ds.up = nm.ckpt("%s.up_proj.weight", mlp);
|
||||
ds.down = nm.ckpt("%s.down_proj.weight", mlp);
|
||||
#endif
|
||||
status = lay.dense_mlp.declare(b, nm, g, (int)l, dw, ds, true,
|
||||
l + 1 == g.n_layer);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: hyv3: dense MLP declaration failed (%d)\n", status);
|
||||
return status;
|
||||
}
|
||||
} else {
|
||||
MoeFP8::Src ms{};
|
||||
ms.cfg = mc;
|
||||
#if HYV3_GGUF_SOURCE
|
||||
ms.norm = nm.ckpt("%s.ffn_norm.weight", pre);
|
||||
ms.router = nm.ckpt("%s.ffn_gate_inp.weight", pre);
|
||||
ms.router_bias = nm.ckpt("%s.exp_probs_b", pre);
|
||||
ms.experts_gate = nm.ckpt("%s.ffn_gate_exps.weight", pre);
|
||||
ms.experts_up = nm.ckpt("%s.ffn_up_exps.weight", pre);
|
||||
ms.experts_down = nm.ckpt("%s.ffn_down_exps.weight", pre);
|
||||
ms.shared_mlp_gate = nm.ckpt("%s.ffn_gate_shexp.weight", pre);
|
||||
ms.shared_mlp_up = nm.ckpt("%s.ffn_up_shexp.weight", pre);
|
||||
ms.shared_mlp_down = nm.ckpt("%s.ffn_down_shexp.weight", pre);
|
||||
#else
|
||||
const char* mlp = nm.ckpt("%s.mlp", pre);
|
||||
ms.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
ms.router = nm.ckpt("%s.router.gate.weight", mlp);
|
||||
ms.router_bias = nm.ckpt("%s.expert_bias", mlp);
|
||||
ms.experts = nm.ckpt("%s.experts", mlp);
|
||||
ms.shared = nm.ckpt("%s.shared_mlp", mlp);
|
||||
#endif
|
||||
#if !HYV3_FP8_SOURCE
|
||||
status = MoeFP8::probe(b, nm, (int)l, ms, &ms.cfg);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: HYV3: expert format probe failed at layer %lld (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
#endif
|
||||
status = lay.moe.declare(b, nm, g, (int)l, m.mw, ms, true, l + 1 == g.n_layer);
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "radiance: hyv3: MoE layer %lld declaration failed (%d)\n",
|
||||
(long long)l, status);
|
||||
return status;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m.final_rms = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.final_norm)),
|
||||
{m.x}, {m.h.x});
|
||||
m.gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.h.x}, {m.h_out});
|
||||
m.logits_op = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.lm_head)),
|
||||
{m.h_out}, {m.logits});
|
||||
|
||||
rad_note(b, "HYV3: %lld layers (dense first, then top-%lld/%lld sigmoid MoE), %lld/%lld "
|
||||
"attention/KV heads x %lld; expert width %lld, shared width %lld, router scale %.3f",
|
||||
(long long)g.n_layer, (long long)top_k, (long long)n_expert_all,
|
||||
(long long)g.n_head_all, (long long)g.n_head_kv_all, (long long)g.head_dim,
|
||||
(long long)m.n_ff_expert, (long long)m.n_ff_shared, mc.route_scale);
|
||||
#if HYV3_FP8_SOURCE
|
||||
rad_note(b, "E4M3 per-tensor scales are imported to 128x128 F32 planes; Q/K RMSNorm precedes "
|
||||
"NeoX RoPE and shared/routed outputs combine in FP32");
|
||||
#elif HYV3_GGUF_SOURCE
|
||||
rad_note(b, "GGUF-source HYV3; Q4_K/Q6_K tensors are decoded and recipe-converted to native "
|
||||
"Radiance weights, adding quantization loss to an already-lossy source");
|
||||
#else
|
||||
rad_note(b, "BF16-source HYV3; per-weight recipes may quantize linears or routed experts; "
|
||||
"Q/K RMSNorm precedes NeoX RoPE and shared/routed outputs combine in FP32");
|
||||
#endif
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = models[rad_rank(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));
|
||||
if (m.embed_ar)
|
||||
RAD_ISSUE_N(c, m.embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
|
||||
brows(m.x, batch->n_tok), RAD_NONE);
|
||||
|
||||
// All TP1 ungated gathers read this same ones plane; no per-layer fill or combine launch.
|
||||
if (m.shared_one)
|
||||
RAD_ISSUE_N(c, m.shared_one, batch->n_tok, brows(m.mw.sgate, batch->n_tok));
|
||||
for (Layer& layer : m.layers) {
|
||||
layer.attn.step(c, batch);
|
||||
if (layer.dense) layer.dense_mlp.step(c, batch);
|
||||
else layer.moe.step(c, batch);
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.final_rms, brows(m.x, batch->n_tok), RAD_W(m.final_norm),
|
||||
brows(m.h.x, batch->n_tok));
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.gather, batch->n_out,
|
||||
brows(m.h.x, batch->n_tok), praw(batch->out_ids, RAD_I32, batch->n_out),
|
||||
brows(m.h_out, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.logits_op, batch->n_out,
|
||||
brows(m.h_out, batch->n_out), RAD_W(m.lm_head),
|
||||
brows(m.logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->draft_depth = 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} // namespace HYV3_NS
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(HYV3_NS)
|
||||
static const char* const kHyv3ToolTriggers[] = { "<tool_calls>" };
|
||||
static const RadChatFormat kHyv3ChatFormat = {
|
||||
.struct_size = sizeof(RadChatFormat),
|
||||
.name = "hyv3",
|
||||
.reasoning_open = "<think>",
|
||||
.reasoning_close = "</think>",
|
||||
.reasoning_breaks = kHyv3ToolTriggers,
|
||||
.n_reasoning_breaks = 1,
|
||||
.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT,
|
||||
.section_open = "<tool_calls>",
|
||||
.section_close = "</tool_calls>",
|
||||
.name_prefix = "<tool_call>",
|
||||
.name_suffix = "<tool_sep>",
|
||||
.call_end = "</tool_call>",
|
||||
.arg_prefix = "<arg_key>",
|
||||
.arg_name_suffix = "</arg_key>\n",
|
||||
.arg_value_prefix = "<arg_value>",
|
||||
.arg_value_suffix = "</arg_value>",
|
||||
.string_value = RAD_CHAT_VALUE_RAW,
|
||||
.other_value = RAD_CHAT_VALUE_JSON,
|
||||
.triggers = kHyv3ToolTriggers,
|
||||
.n_triggers = 1,
|
||||
.args_form = RAD_CHAT_ARGS_TAGGED,
|
||||
};
|
||||
extern "C" const RadChatFormat* rad_arch_chat_format(const RadModelMeta*) {
|
||||
return &kHyv3ChatFormat;
|
||||
}
|
||||
extern "C" const char* rad_arch_id(void) { return "hyv3"; }
|
||||
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);
|
||||
}
|
||||
extern "C" void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch) {
|
||||
HYV3_NS::step(c, batch);
|
||||
}
|
||||
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
|
||||
RAD_PLUGIN_ABI_LAYOUT_EXPORT
|
||||
extern "C" const RadPluginInfo* rad_plugin_info(void) {
|
||||
static const RadPluginInfo info = {
|
||||
RAD_PLUGIN_ARCH, HYV3_PLUGIN_NAME, "0.2.0",
|
||||
"Tencent Hy-Memory HYV3: Q/K-normalized full attention and sigmoid MoE", ""
|
||||
};
|
||||
return &info;
|
||||
}
|
||||
#endif
|
||||
|
||||
#undef HYV3_NS
|
||||
#undef HYV3_QUANT
|
||||
#undef HYV3_FP8_SOURCE
|
||||
#undef HYV3_PLUGIN_NAME
|
||||
#undef HYV3_GGUF_SOURCE
|
||||
@@ -0,0 +1,9 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(hyv3_fp8 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(hyv3_fp8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hyv3_fp8.cpp)
|
||||
@@ -0,0 +1,5 @@
|
||||
#define HYV3_NS hyv3_fp8
|
||||
#define HYV3_QUANT "fp8"
|
||||
#define HYV3_FP8_SOURCE 1
|
||||
#define HYV3_PLUGIN_NAME "hyv3_fp8"
|
||||
#include "../hyv3_common/hyv3_impl.cpp"
|
||||
@@ -0,0 +1,9 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(hyv3_gguf LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(hyv3_gguf architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hyv3_gguf.cpp)
|
||||
@@ -0,0 +1,7 @@
|
||||
#define HYV3_NS hyv3_gguf
|
||||
#define HYV3_QUANT "gguf_ftype_15"
|
||||
#define HYV3_FP8_SOURCE 0
|
||||
#define HYV3_GGUF_SOURCE 1
|
||||
#define HYV3_PLUGIN_NAME "hyv3_gguf"
|
||||
#include "../hyv3_common/hyv3_impl.cpp"
|
||||
RAD_ARCH_SERVES_IMPORTS(0)
|
||||
+45
-17
@@ -73,10 +73,30 @@ enum { kMaxLanes = 8 };
|
||||
static const int kTaps[] = { 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35 };
|
||||
enum { kNTaps = 12 };
|
||||
|
||||
/* The rebalance a request may ask for (`rebalance`, RAD_GEN_COND_REBALANCE): every tap times a fixed
|
||||
* gain before the text fusion, ComfyUI's ConditioningKrea2Rebalance (nova452) at its defaults --
|
||||
* multiplier 4 times the per-layer weights 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1. */
|
||||
static const double kRebalance[] = { 4, 4, 4, 4, 4, 4, 4, 10, 20, 4.4, 16, 4 };
|
||||
/* The rebalance presets a request may ask for (`rebalance`, RAD_GEN_COND_REBALANCE with the row in
|
||||
* RAD_GEN_COND_REBALANCE_PRESET): every tap times a fixed gain before the text fusion.
|
||||
* legacy ComfyUI's ConditioningKrea2Rebalance (nova452) at its defaults -- multiplier 4 times
|
||||
* the per-layer weights 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1, about 9x the taps' RMS.
|
||||
* balanced, detail, subtle
|
||||
* comfyui-krea2-conditioning's presets (huwhitememes) with renormalize on, multiplier 1:
|
||||
* the weights times s = sqrt(sum m_t / sum w_t^2 m_t), m_t the mean square of tap t over
|
||||
* the prompt's rows. The node measures s per prompt; here it is a constant, m_t averaged
|
||||
* over twenty prompts through krea/Krea-2-Turbo's text encoder
|
||||
* (scripts/krea2_rebalance_calib.py), and per prompt s stayed within 1.7 % of it.
|
||||
* A preset row the plugin does not know scales nothing: the plain model. */
|
||||
enum { kNPresets = 4 };
|
||||
static const double kRebalance[kNPresets][kNTaps] = {
|
||||
{ 4, 4, 4, 4, 4, 4, 4, 10, 20, 4.4, 16, 4 },
|
||||
/* balanced: 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1 at s 0.44109 */
|
||||
{ 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 0.44109, 1.1027, 2.2055, 0.4852,
|
||||
1.7644, 0.44109 },
|
||||
/* detail: 0.8, 0.8, 0.9, 0.9, 1, 1, 1.2, 3, 6, 1.5, 5, 1.2 at s 0.35702 */
|
||||
{ 0.28562, 0.28562, 0.32132, 0.32132, 0.35702, 0.35702, 0.42842, 1.0711, 2.1421, 0.53553,
|
||||
1.7851, 0.42842 },
|
||||
/* subtle: 1, 1, 1, 1, 1, 1, 1, 1.5, 2, 1, 1.5, 1 at s 0.84759 */
|
||||
{ 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 0.84759, 1.2714, 1.6952, 0.84759,
|
||||
1.2714, 0.84759 },
|
||||
};
|
||||
|
||||
static const char* kSysPrompt =
|
||||
"Describe the image by detailing the color, shape, size, texture, quantity, text, spatial "
|
||||
@@ -90,7 +110,7 @@ struct TeLayer {
|
||||
GateQuantFP8 gq{};
|
||||
rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_ar1 = 0, op_add1 = 0;
|
||||
rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0, op_tap = 0;
|
||||
rad_op op_gain = 0; /* the tap's rebalance gain into te.h2 */
|
||||
rad_op op_gain[kNPresets] = {}; /* the tap's rebalance gain into te.h2, a preset each */
|
||||
rad_op op_tap_g = 0; /* the scatter from te.h2, when rebalanced */
|
||||
int tap = -1; /* this layer's output is tap `tap`, or none */
|
||||
};
|
||||
@@ -138,7 +158,7 @@ struct Model {
|
||||
ActFP8 a_th{}, a_tattn{}, a_tffn{};
|
||||
std::vector<TeLayer> te;
|
||||
rad_buf b_taps = 0; /* [T * 12, n_embd]: token t's tap i at row 12 t + i */
|
||||
std::string tap_mul[kNTaps]; /* chan_affine's `mul` for each tap's rebalance gain */
|
||||
std::string tap_mul[kNPresets][kNTaps]; /* chan_affine's `mul` for each preset's tap gain */
|
||||
std::string tap_add; /* chan_affine's `add`: zeros */
|
||||
|
||||
/* ---- the text fusion: the layer-wise blocks over the taps themselves, the refiner blocks
|
||||
@@ -390,13 +410,15 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
(int)kGainCh);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
for (int p = 0; p < kNPresets; ++p)
|
||||
for (int t = 0; t < kNTaps; ++t) {
|
||||
char v[32];
|
||||
std::snprintf(v, sizeof v, "%.9g", kRebalance[t]);
|
||||
m.tap_mul[t].clear();
|
||||
std::snprintf(v, sizeof v, "%.9g", kRebalance[p][t]);
|
||||
std::string& s = m.tap_mul[p][t];
|
||||
s.clear();
|
||||
for (int k = 0; k < kGainCh; ++k) {
|
||||
if (k) m.tap_mul[t] += ' ';
|
||||
m.tap_mul[t] += v;
|
||||
if (k) s += ' ';
|
||||
s += v;
|
||||
}
|
||||
}
|
||||
m.tap_add.clear();
|
||||
@@ -482,14 +504,18 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
L.op_add2 = add_op(b, T, g.n_embd, m.b_tx, m.b_th2, m.b_tx);
|
||||
if (L.tap >= 0) {
|
||||
/* f32 arithmetic, rounded once into bf16 (`round` 0) */
|
||||
L.op_gain = rw(b, RAD_OP(b, "chan_affine",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), RAD_INT("n", kGainCh),
|
||||
RAD_STR("mul", m.tap_mul[L.tap].c_str()),
|
||||
for (int p = 0; p < kNPresets; ++p) {
|
||||
L.op_gain[p] = rw(b, RAD_OP(b, "chan_affine",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, kTeRows),
|
||||
RAD_INT("n", kGainCh),
|
||||
RAD_STR("mul", m.tap_mul[p][L.tap].c_str()),
|
||||
RAD_STR("add", m.tap_add.c_str()),
|
||||
RAD_STR("mode", "fma"), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("round", 0)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_tx }, { m.b_th2 });
|
||||
if (!L.op_gain[p]) return RAD_E_INVAL;
|
||||
}
|
||||
L.op_tap_g = rw(b, RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, kTeRows),
|
||||
RAD_INT("n", g.n_embd), RAD_STR("dtype", "bf16")),
|
||||
@@ -503,7 +529,7 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_tx, m.b_tidx, m.b_taps }, { m.b_taps });
|
||||
if (!L.op_n1 || !L.op_qkr || !L.op_attn || !L.op_add1 || !L.op_n2 || !L.op_add2 ||
|
||||
(L.tap >= 0 && (!L.op_tap || !L.op_gain || !L.op_tap_g)))
|
||||
(L.tap >= 0 && (!L.op_tap || !L.op_tap_g)))
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return m.op_embed && m.op_iota ? RAD_OK : RAD_E_INVAL;
|
||||
@@ -1186,7 +1212,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
d.cond_rows = kCondRows;
|
||||
d.rope_hw_scale = 1.0;
|
||||
d.rope_text_l = 0;
|
||||
d.cond_opts = RAD_GEN_COND_REBALANCE;
|
||||
d.cond_opts = RAD_GEN_COND_REBALANCE | RAD_GEN_COND_REBALANCE_PRESET;
|
||||
RAD_ARCH_TRY(rad_declare_generator(b, &d));
|
||||
}
|
||||
rad_note(b, "rank %d/%d: Krea 2%s -- text encoder %d of %lld layers, text fusion %zu + %zu "
|
||||
@@ -1205,7 +1231,9 @@ static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
const Geom& g = m.gt;
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
|
||||
const bool rebalance = batch->gen_b && (batch->gen_b->cond_opts & RAD_GEN_COND_REBALANCE);
|
||||
const int32_t opts = batch->gen_b ? batch->gen_b->cond_opts : 0;
|
||||
const int preset = (opts & RAD_GEN_COND_REBALANCE_PRESET) >> RAD_GEN_COND_REBALANCE_PRESET_SHIFT;
|
||||
const bool rebalance = (opts & RAD_GEN_COND_REBALANCE) && preset < kNPresets;
|
||||
RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok),
|
||||
brows(m.b_tx, T));
|
||||
RAD_ISSUE_N(c, m.op_iota, T, brows(m.b_tidx, T));
|
||||
@@ -1230,7 +1258,7 @@ static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) {
|
||||
if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, T * g.n_embd, brows(m.b_th2, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, L.op_add2, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T));
|
||||
if (L.tap >= 0 && rebalance)
|
||||
RAD_ISSUE_N(c, L.op_gain, T, brows(m.b_tx, T), brows(m.b_th2, T));
|
||||
RAD_ISSUE_N(c, L.op_gain[preset], T, brows(m.b_tx, T), brows(m.b_th2, T));
|
||||
if (L.tap >= 0)
|
||||
RAD_ISSUE_N(c, rebalance ? L.op_tap_g : L.op_tap, T,
|
||||
brows(rebalance ? m.b_th2 : m.b_tx, T), brows(m.b_tidx, T),
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/laya -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(laya LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(laya architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/laya.cpp)
|
||||
@@ -0,0 +1,530 @@
|
||||
/* laya -- Convai Innovations' Laya decision models (laya, laya-typed-decisions,
|
||||
* laya-multilingual), served on /v1/systemone. bf16 weights and activations, f32 norms and biases.
|
||||
*
|
||||
* A Laya checkpoint is a ModernBERT encoder and a small decision head (DecisionModel in laya's
|
||||
* common.py). It reads one sequence a question,
|
||||
* [CLS] <type> question: <instructions> [SEP] [MASK] opt0 [MASK] opt1 ... [SEP] <state> [SEP]
|
||||
* which the server builds (core/server/laya.cpp), and scores each option at its [MASK]. Like
|
||||
* nomicbert it declares a pooled output and no logits, so the engine runs it with no sampler and
|
||||
* no KV cache, every sequence whole in one step, and returns each sequence's pooled row: here one
|
||||
* logit an option (abi/rad_laya.h). The request's words carry what the tokens do not: the
|
||||
* question's type and where its markers sit.
|
||||
*
|
||||
* ============================== THE SHAPE ==============================
|
||||
*
|
||||
* encoder (ModernBERT): token embedding, then LayerNorm; every norm has no bias, no linear has one
|
||||
* h += Wo attn(rope(Wqkv LN_a(h))) no LN_a on layer 0
|
||||
* h += Wo (gelu(Wi_in LN_m(h)) * Wi_gate LN_m(h)) Wi is one [2 ff, E] tensor, [in | gate]
|
||||
* a final LayerNorm
|
||||
* attention: a `full_attention` layer (layer_types) attends over the whole sequence with the full
|
||||
* rotary theta, the others over |i - j| <= local_attention / 2 with the sliding one; NeoX rotary
|
||||
* over the whole head, scale 1 / sqrt(head_dim)
|
||||
* head: h + type_emb[type]; head_layers pre-norm transformer layers (torch's
|
||||
* TransformerEncoderLayer with norm_first: E / 64 heads, a ReLU feed-forward of 4 E, every
|
||||
* linear and norm with a bias); the rows at the markers; LayerNorm, Linear + gelu, Linear to
|
||||
* one logit an option
|
||||
*
|
||||
* The release's escalation head (act_head) and its stored temperatures are not declared: the
|
||||
* answer is the option logits, and the server applies the fitted temperatures rad-convert writes
|
||||
* into the header from rl_agent_config.json.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <rad_laya.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace laya {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
bool sliding = false;
|
||||
rad_weight w_attn_norm = 0, w_qkv = 0, w_out = 0, w_mlp_norm = 0, w_wi = 0, w_wo = 0;
|
||||
rad_op op_attn_norm = 0, op_qkv = 0, op_rope = 0, op_attn = 0, op_out = 0, op_add_attn = 0;
|
||||
rad_op op_mlp_norm = 0, op_wi = 0, op_act = 0, op_wo = 0, op_add_mlp = 0;
|
||||
};
|
||||
|
||||
struct HeadLayer {
|
||||
rad_weight n1_w = 0, n1_b = 0, qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
|
||||
rad_weight n2_w = 0, n2_b = 0, l1_w = 0, l1_b = 0, l2_w = 0, l2_b = 0;
|
||||
rad_op op_n1 = 0, op_qkv = 0, op_attn = 0, op_out = 0, op_n2 = 0, op_l1 = 0, op_relu = 0,
|
||||
op_l2 = 0;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{};
|
||||
int64_t F = 0; /* the encoder's feed-forward width */
|
||||
int64_t head_dim_h = 0; /* the head's attention width, E / max(1, E / 64) */
|
||||
|
||||
rad_buf b_o = 0, b_x = 0, b_h = 0, b_t = 0, b_qkv = 0, b_att = 0, b_wi = 0, b_ff = 0,
|
||||
b_hff = 0, b_trow = 0, b_m = 0, b_m2 = 0, b_sc = 0, b_pooled = 0;
|
||||
|
||||
rad_weight w_tok = 0, w_emb_norm = 0, w_final_norm = 0, w_type = 0;
|
||||
rad_weight w_sn = 0, b_sn = 0, w_s1 = 0, b_s1 = 0, w_s2 = 0, b_s2 = 0;
|
||||
rad_op op_embed = 0, op_emb_norm = 0, op_final_norm = 0, op_type = 0, op_add_type = 0;
|
||||
rad_op op_gather = 0, op_sn = 0, op_s1 = 0, op_s2 = 0, op_fill = 0, op_out = 0;
|
||||
|
||||
std::vector<Layer> layers;
|
||||
std::vector<HeadLayer> head;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->draft_depth = 0;
|
||||
const char* dt = rad_meta_gets(meta, "decision.type", nullptr);
|
||||
if (!dt || std::strcmp(dt, "laya")) {
|
||||
fprintf(stderr, "radiance: laya: the container declares no Laya decision head "
|
||||
"(decision.type=laya); convert the checkpoint directory with rad-convert, "
|
||||
"which reads rl_agent_config.json beside it\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Which layers attend over the sliding window: `layer_types` as the config states it, or every
|
||||
* layer but each global_attn_every_n_layers-th in configs written before transformers 5. */
|
||||
static int sliding_layers(const RadModelMeta* meta, int64_t n_layer, std::vector<bool>* out) {
|
||||
out->assign((size_t)n_layer, false);
|
||||
if (const char* lt = rad_meta_gets(meta, "layer_types", nullptr)) {
|
||||
int64_t l = 0;
|
||||
for (const char* p = lt; *p;) {
|
||||
while (*p == ' ') ++p;
|
||||
const char* e = p;
|
||||
while (*e && *e != ' ') ++e;
|
||||
if (e == p) break;
|
||||
const std::string t(p, e);
|
||||
if (l >= n_layer || (t != "full_attention" && t != "sliding_attention")) return RAD_E_INVAL;
|
||||
(*out)[(size_t)l++] = t == "sliding_attention";
|
||||
p = e;
|
||||
}
|
||||
return l == n_layer ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
const int64_t every = rad_meta_geti(meta, "global_attn_every_n_layers", 0);
|
||||
if (every <= 0) return RAD_E_INVAL;
|
||||
for (int64_t l = 0; l < n_layer; ++l) (*out)[(size_t)l] = l % every != 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) 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");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RadArchProbe pr{};
|
||||
RAD_ARCH_TRY(probe(meta, &pr));
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
const int64_t T = g.max_tok, E = g.n_embd, S = g.max_seqs, P = RAD_LAYA_POOLED;
|
||||
m.F = g.n_ff;
|
||||
const int64_t F = m.F;
|
||||
|
||||
/* The variant flags this plugin does not serve, refused by name. */
|
||||
for (const char* k : { "norm_bias", "attention_bias", "mlp_bias" })
|
||||
if (rad_meta_geti(meta, k, 0) != 0) {
|
||||
fprintf(stderr, "radiance: laya: the encoder sets %s; ModernBERT as Laya ships it has "
|
||||
"no bias there\n", k);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const char* act = rad_meta_gets(meta, "hidden_activation", "gelu");
|
||||
if (std::strcmp(act, "gelu")) {
|
||||
fprintf(stderr, "radiance: laya: hidden_activation '%s'; this plugin serves exact gelu\n", act);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (g.n_head_kv != g.n_head || g.head_dim * g.n_head != E) {
|
||||
fprintf(stderr, "radiance: laya: %lld heads of %lld (%lld for keys) do not tile hidden %lld\n",
|
||||
(long long)g.n_head, (long long)g.head_dim, (long long)g.n_head_kv, (long long)E);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
std::vector<bool> sliding;
|
||||
if (sliding_layers(meta, g.n_layer, &sliding) != RAD_OK) {
|
||||
fprintf(stderr, "radiance: laya: neither layer_types (%lld entries of full_attention or "
|
||||
"sliding_attention) nor global_attn_every_n_layers says which layers "
|
||||
"attend locally\n", (long long)g.n_layer);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t local = rad_meta_geti(meta, "local_attention", 128);
|
||||
/* transformers masks the local layers to |i - j| <= local_attention / 2; attn_dense's window
|
||||
* keeps |i - j| < window. */
|
||||
const int64_t window = local / 2 + 1;
|
||||
const double theta_full = rad_meta_getf(meta, "rope_parameters.full_attention.rope_theta",
|
||||
rad_meta_getf(meta, "global_rope_theta", 160000.0));
|
||||
const double theta_slide = rad_meta_getf(meta, "rope_parameters.sliding_attention.rope_theta",
|
||||
rad_meta_getf(meta, "local_rope_theta", 10000.0));
|
||||
const int64_t n_head_layers = rad_meta_geti(meta, "decision.laya.head_layers", -1);
|
||||
if (local < 2 || !(theta_full > 0.0) || !(theta_slide > 0.0) || n_head_layers < 0) {
|
||||
fprintf(stderr, "radiance: laya: local_attention %lld, rotary thetas %g and %g, or "
|
||||
"decision.laya.head_layers %lld is not a Laya model\n", (long long)local,
|
||||
theta_full, theta_slide, (long long)n_head_layers);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* torch's MultiheadAttention in the head: E / 64 heads, at least one. */
|
||||
const int64_t hh = std::max<int64_t>(1, E / 64);
|
||||
m.head_dim_h = E / hh;
|
||||
if (m.head_dim_h * hh != E) {
|
||||
fprintf(stderr, "radiance: laya: hidden %lld does not split into %lld head heads\n",
|
||||
(long long)E, (long long)hh);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_declare_plugin_words(b, RAD_LAYA_MAX_WORDS));
|
||||
|
||||
/* ---- activations. b_sc is P rows longer than any step's markers: the last sequence's pooled
|
||||
* row is copied from P scores, its own and then filler. */
|
||||
m.b_o = decl_b(b, nm.f("o"), RAD_BF16, { T, E });
|
||||
m.b_x = decl_b(b, nm.f("x"), RAD_BF16, { T, E });
|
||||
m.b_h = decl_b(b, nm.f("h"), RAD_BF16, { T, E });
|
||||
m.b_t = decl_b(b, nm.f("t"), RAD_BF16, { T, E });
|
||||
m.b_qkv = decl_b(b, nm.f("qkv"), RAD_BF16, { T, 3 * E });
|
||||
m.b_att = decl_b(b, nm.f("attn"), RAD_BF16, { T, E });
|
||||
m.b_wi = decl_b(b, nm.f("wi"), RAD_BF16, { T, 2 * F });
|
||||
m.b_ff = decl_b(b, nm.f("ff"), RAD_BF16, { T, F });
|
||||
m.b_hff = decl_b(b, nm.f("hff"), RAD_BF16, { T, 4 * E });
|
||||
m.b_trow = decl_b(b, nm.f("type"), RAD_BF16, { S, E });
|
||||
m.b_m = decl_b(b, nm.f("mark"), RAD_BF16, { T, E });
|
||||
m.b_m2 = decl_b(b, nm.f("mark2"), RAD_BF16, { T, E });
|
||||
m.b_sc = decl_b(b, nm.f("score"), RAD_BF16, { T + P, 1 });
|
||||
m.b_pooled = decl_b(b, nm.f("pooled"), RAD_F32, { S, P }, RAD_BUF_PERSIST);
|
||||
if (!m.b_o || !m.b_x || !m.b_h || !m.b_t || !m.b_qkv || !m.b_att || !m.b_wi || !m.b_ff ||
|
||||
!m.b_hff || !m.b_trow || !m.b_m || !m.b_m2 || !m.b_sc || !m.b_pooled)
|
||||
return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(rad_declare_pooled(b, m.b_pooled));
|
||||
|
||||
/* ---- weights. Linears and tables bf16, norms and biases f32. */
|
||||
const int A = RAD_ACCESS_PER_TOKEN, N = RAD_SHARD_NONE;
|
||||
auto w_model = [&](const char* name, const char* src, uint32_t dt,
|
||||
std::initializer_list<int64_t> shape, int access = RAD_ACCESS_PER_TOKEN) {
|
||||
if (map_copy(b, nm.f("%s", name), nm.ckpt("%s", src)) != RAD_OK) return (rad_weight)0;
|
||||
return decl_w(b, nm.f("%s", name), dt, shape, access, N, grp_model());
|
||||
};
|
||||
m.w_tok = w_model("token_embd.weight", "encoder.embeddings.tok_embeddings.weight",
|
||||
RAD_BF16, { g.n_vocab, E }, RAD_ACCESS_VOCAB);
|
||||
m.w_emb_norm = w_model("emb_norm.weight", "encoder.embeddings.norm.weight", RAD_F32, { E });
|
||||
m.w_final_norm = w_model("output_norm.weight", "encoder.final_norm.weight", RAD_F32, { E });
|
||||
m.w_type = w_model("type_emb.weight", "type_emb.weight", RAD_BF16, { 3, E });
|
||||
m.w_sn = w_model("scorer.norm.weight", "scorer.0.weight", RAD_F32, { E });
|
||||
m.b_sn = w_model("scorer.norm.bias", "scorer.0.bias", RAD_F32, { E });
|
||||
m.w_s1 = w_model("scorer.fc1.weight", "scorer.1.weight", RAD_BF16, { E, E });
|
||||
m.b_s1 = w_model("scorer.fc1.bias", "scorer.1.bias", RAD_F32, { E });
|
||||
m.w_s2 = w_model("scorer.fc2.weight", "scorer.3.weight", RAD_BF16, { 1, E });
|
||||
m.b_s2 = w_model("scorer.fc2.bias", "scorer.3.bias", RAD_F32, { 1 });
|
||||
if (!m.w_tok || !m.w_emb_norm || !m.w_final_norm || !m.w_type || !m.w_sn || !m.b_sn ||
|
||||
!m.w_s1 || !m.b_s1 || !m.w_s2 || !m.b_s2)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* ---- ops, each kind stated once. */
|
||||
auto lnorm = [&](int64_t rows, bool bias, rad_weight w, rad_weight bw) {
|
||||
return bias ? RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bw))
|
||||
: RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto gemm = [&](int64_t rows, int64_t n_out, int64_t n_in, rad_weight w) {
|
||||
return RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", n_out), RAD_INT("K", n_in),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto gemmb = [&](int64_t rows, int64_t n_out, int64_t n_in, const char* act_name, rad_weight w,
|
||||
rad_weight bw) {
|
||||
return RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", n_out), RAD_INT("K", n_in),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("act", act_name)),
|
||||
RAD_WEIGHTS(w, bw));
|
||||
};
|
||||
auto unary = [&](const char* op, int64_t rows, int64_t n) {
|
||||
return RAD_OP(b, op,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto attn = [&](int64_t head_dim, double scale, int64_t win) {
|
||||
return win > 0 ? RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("scale", scale),
|
||||
RAD_INT("max_seqlen", T), RAD_INT("window", win)),
|
||||
RAD_NOWEIGHTS)
|
||||
: RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("scale", scale),
|
||||
RAD_INT("max_seqlen", T)),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto rope = [&](double theta) {
|
||||
return RAD_OP(b, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_F64("theta", theta), RAD_F64("scale", 1.0),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
|
||||
RAD_WEIGHTS(m.w_tok)),
|
||||
{}, { m.b_o });
|
||||
m.op_emb_norm = rw(b, lnorm(T, false, m.w_emb_norm, 0), { m.b_o }, { m.b_x });
|
||||
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& y = m.layers[(size_t)l];
|
||||
y.sliding = sliding[(size_t)l];
|
||||
const long long ll = (long long)l;
|
||||
const RadWeightGroup gl = grp_layer((int)l);
|
||||
auto src = [&](const char* s) { return nm.ckpt("encoder.layers.%lld.%s", ll, s); };
|
||||
if (l > 0) RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_norm.weight", ll), src("attn_norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_qkv.weight", ll), src("attn.Wqkv.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_out.weight", ll), src("attn.Wo.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_norm.weight", ll), src("mlp_norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_in_gate.weight", ll), src("mlp.Wi.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_down.weight", ll), src("mlp.Wo.weight")));
|
||||
if (l > 0)
|
||||
y.w_attn_norm = decl_w(b, nm.f("blk.%lld.attn_norm.weight", ll), RAD_F32, { E }, A, N, gl);
|
||||
y.w_qkv = decl_w(b, nm.f("blk.%lld.attn_qkv.weight", ll), RAD_BF16, { 3 * E, E }, A, N, gl);
|
||||
y.w_out = decl_w(b, nm.f("blk.%lld.attn_out.weight", ll), RAD_BF16, { E, E }, A, N, gl);
|
||||
y.w_mlp_norm = decl_w(b, nm.f("blk.%lld.ffn_norm.weight", ll), RAD_F32, { E }, A, N, gl);
|
||||
y.w_wi = decl_w(b, nm.f("blk.%lld.ffn_in_gate.weight", ll), RAD_BF16, { 2 * F, E }, A, N, gl);
|
||||
y.w_wo = decl_w(b, nm.f("blk.%lld.ffn_down.weight", ll), RAD_BF16, { E, F }, A, N, gl);
|
||||
if ((l > 0 && !y.w_attn_norm) || !y.w_qkv || !y.w_out || !y.w_mlp_norm || !y.w_wi || !y.w_wo)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
const rad_buf att_in = l > 0 ? m.b_h : m.b_x;
|
||||
if (l > 0) y.op_attn_norm = rw(b, lnorm(T, false, y.w_attn_norm, 0), { m.b_x }, { m.b_h });
|
||||
y.op_qkv = rw(b, gemm(T, 3 * E, E, y.w_qkv), { att_in }, { m.b_qkv });
|
||||
y.op_rope = rw(b, rope(y.sliding ? theta_slide : theta_full), { m.b_qkv }, { m.b_qkv });
|
||||
y.op_attn = rw(b, attn(g.head_dim, 1.0 / std::sqrt((double)g.head_dim), y.sliding ? window : 0),
|
||||
{ m.b_qkv }, { m.b_att });
|
||||
y.op_out = rw(b, gemm(T, E, E, y.w_out), { m.b_att }, { m.b_o });
|
||||
y.op_add_attn = rw(b, unary("add", T, E), { m.b_x, m.b_o }, { m.b_x });
|
||||
y.op_mlp_norm = rw(b, lnorm(T, false, y.w_mlp_norm, 0), { m.b_x }, { m.b_h });
|
||||
y.op_wi = rw(b, gemm(T, 2 * F, E, y.w_wi), { m.b_h }, { m.b_wi });
|
||||
y.op_act = rw(b, RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", F),
|
||||
RAD_STR("act", "gelu"), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_wi }, { m.b_ff });
|
||||
y.op_wo = rw(b, gemm(T, E, F, y.w_wo), { m.b_ff }, { m.b_o });
|
||||
y.op_add_mlp = rw(b, unary("add", T, E), { m.b_x, m.b_o }, { m.b_x });
|
||||
if ((l > 0 && !y.op_attn_norm) || !y.op_qkv || !y.op_rope || !y.op_attn || !y.op_out ||
|
||||
!y.op_add_attn || !y.op_mlp_norm || !y.op_wi || !y.op_act || !y.op_wo || !y.op_add_mlp)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
m.op_final_norm = rw(b, lnorm(T, false, m.w_final_norm, 0), { m.b_x }, { m.b_h });
|
||||
|
||||
/* ---- the head, over the encoder's rows in b_h. */
|
||||
m.op_type = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n_embd", E), RAD_INT("n_vocab", 3),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("vocab_offset", 0)),
|
||||
RAD_WEIGHTS(m.w_type)),
|
||||
{}, { m.b_trow });
|
||||
m.op_add_type = rw(b, unary("add", T, E), { m.b_h, m.b_trow }, { m.b_h });
|
||||
m.head.resize((size_t)n_head_layers);
|
||||
for (int64_t j = 0; j < n_head_layers; ++j) {
|
||||
HeadLayer& h = m.head[(size_t)j];
|
||||
const long long jj = (long long)j;
|
||||
auto hw = [&](const char* name, const char* src, uint32_t dt,
|
||||
std::initializer_list<int64_t> shape) {
|
||||
if (map_copy(b, nm.f("head.%lld.%s", jj, name), nm.ckpt("head.layers.%lld.%s", jj, src)) != RAD_OK)
|
||||
return (rad_weight)0;
|
||||
return decl_w(b, nm.f("head.%lld.%s", jj, name), dt, shape, A, N, grp_model());
|
||||
};
|
||||
h.n1_w = hw("norm1.weight", "norm1.weight", RAD_F32, { E });
|
||||
h.n1_b = hw("norm1.bias", "norm1.bias", RAD_F32, { E });
|
||||
h.qkv_w = hw("attn_qkv.weight", "self_attn.in_proj_weight", RAD_BF16, { 3 * E, E });
|
||||
h.qkv_b = hw("attn_qkv.bias", "self_attn.in_proj_bias", RAD_F32, { 3 * E });
|
||||
h.out_w = hw("attn_out.weight", "self_attn.out_proj.weight", RAD_BF16, { E, E });
|
||||
h.out_b = hw("attn_out.bias", "self_attn.out_proj.bias", RAD_F32, { E });
|
||||
h.n2_w = hw("norm2.weight", "norm2.weight", RAD_F32, { E });
|
||||
h.n2_b = hw("norm2.bias", "norm2.bias", RAD_F32, { E });
|
||||
h.l1_w = hw("ffn_up.weight", "linear1.weight", RAD_BF16, { 4 * E, E });
|
||||
h.l1_b = hw("ffn_up.bias", "linear1.bias", RAD_F32, { 4 * E });
|
||||
h.l2_w = hw("ffn_down.weight", "linear2.weight", RAD_BF16, { E, 4 * E });
|
||||
h.l2_b = hw("ffn_down.bias", "linear2.bias", RAD_F32, { E });
|
||||
if (!h.n1_w || !h.n1_b || !h.qkv_w || !h.qkv_b || !h.out_w || !h.out_b || !h.n2_w ||
|
||||
!h.n2_b || !h.l1_w || !h.l1_b || !h.l2_w || !h.l2_b)
|
||||
return RAD_E_INVAL;
|
||||
h.op_n1 = rw(b, lnorm(T, true, h.n1_w, h.n1_b), { m.b_h }, { m.b_t });
|
||||
h.op_qkv = rw(b, gemmb(T, 3 * E, E, "none", h.qkv_w, h.qkv_b), { m.b_t }, { m.b_qkv });
|
||||
h.op_attn = rw(b, attn(m.head_dim_h, 1.0 / std::sqrt((double)m.head_dim_h), 0),
|
||||
{ m.b_qkv }, { m.b_att });
|
||||
h.op_out = rw(b, gemmb(T, E, E, "none", h.out_w, h.out_b), { m.b_att, m.b_h }, { m.b_h });
|
||||
h.op_n2 = rw(b, lnorm(T, true, h.n2_w, h.n2_b), { m.b_h }, { m.b_t });
|
||||
h.op_l1 = rw(b, gemmb(T, 4 * E, E, "none", h.l1_w, h.l1_b), { m.b_t }, { m.b_hff });
|
||||
h.op_relu = rw(b, unary("relu", T, 4 * E), { m.b_hff }, { m.b_hff });
|
||||
h.op_l2 = rw(b, gemmb(T, E, 4 * E, "none", h.l2_w, h.l2_b), { m.b_hff, m.b_h }, { m.b_h });
|
||||
if (!h.op_n1 || !h.op_qkv || !h.op_attn || !h.op_out || !h.op_n2 || !h.op_l1 ||
|
||||
!h.op_relu || !h.op_l2)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The rows at the markers, a sequence at a time, then the scorer over all of them. */
|
||||
m.op_gather = rw(b, unary("gather_rows", RAD_LAYA_MAX_OPTIONS, E), { m.b_h }, { m.b_m });
|
||||
m.op_sn = rw(b, lnorm(T, true, m.w_sn, m.b_sn), { m.b_m }, { m.b_t });
|
||||
m.op_s1 = rw(b, gemmb(T, E, E, "gelu", m.w_s1, m.b_s1), { m.b_t }, { m.b_m2 });
|
||||
m.op_s2 = rw(b, gemmb(T, 1, E, "none", m.w_s2, m.b_s2), { m.b_m2 }, { m.b_sc });
|
||||
/* Past the last marker's score, P filler rows the last pooled row's copy may read. */
|
||||
m.op_fill = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", P),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("value", -1e4)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { m.b_sc });
|
||||
m.op_out = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", P),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.b_sc }, { m.b_pooled });
|
||||
if (!m.op_embed || !m.op_emb_norm || !m.op_final_norm || !m.op_type || !m.op_add_type ||
|
||||
!m.op_gather || !m.op_sn || !m.op_s1 || !m.op_s2 || !m.op_fill || !m.op_out)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
int64_t n_sliding = 0;
|
||||
for (bool s : sliding) n_sliding += s ? 1 : 0;
|
||||
rad_note(b, "laya decision model: ModernBERT %lld layers (%lld sliding over %lld, rotary %g "
|
||||
"and %g), hidden %lld, ffn %lld, %lld heads of %lld; head %lld layers of %lld "
|
||||
"heads; at most %d options a question, one logit each in the pooled row",
|
||||
(long long)g.n_layer, (long long)n_sliding, (long long)local, theta_full, theta_slide,
|
||||
(long long)E, (long long)F, (long long)g.n_head, (long long)g.head_dim,
|
||||
(long long)n_head_layers, (long long)hh, (int)RAD_LAYA_MAX_OPTIONS);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(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;
|
||||
if (T <= 0 || S <= 0) return;
|
||||
if (!batch->plugin_cu_h || !batch->plugin_words_h || !batch->plugin_words) {
|
||||
rad_step_fail(c, "laya: the step carries no words; every Laya sequence comes from "
|
||||
"/v1/systemone with its question's type and markers");
|
||||
return;
|
||||
}
|
||||
/* Each sequence's first row from the words: an embedding input runs whole in one step, so
|
||||
* the sequences' token counts add up to the step's. */
|
||||
std::vector<int64_t> first((size_t)S + 1, 0);
|
||||
for (int64_t s = 0; s < S; ++s) {
|
||||
const int32_t w0 = batch->plugin_cu_h[s], w1 = batch->plugin_cu_h[s + 1];
|
||||
const int32_t* hw = batch->plugin_words_h + w0;
|
||||
const int64_t n = w1 - w0 > RAD_LAYA_W_K ? hw[RAD_LAYA_W_N] : -1;
|
||||
const int64_t k = w1 - w0 > RAD_LAYA_W_K ? hw[RAD_LAYA_W_K] : -1;
|
||||
const int64_t type = w1 - w0 > RAD_LAYA_W_K ? hw[RAD_LAYA_W_TYPE] : -1;
|
||||
bool ok = n > 0 && k >= 1 && k <= RAD_LAYA_MAX_OPTIONS && w1 - w0 >= RAD_LAYA_W_MARKERS + k &&
|
||||
type >= RAD_LAYA_CHOICE && type <= RAD_LAYA_NOUL;
|
||||
for (int64_t i = 0; ok && i < k; ++i) {
|
||||
const int32_t at = hw[RAD_LAYA_W_MARKERS + i];
|
||||
ok = at >= 0 && at < n;
|
||||
}
|
||||
if (!ok) {
|
||||
rad_step_fail(c, "laya: a sequence's words are not a Laya question's (type, markers)");
|
||||
return;
|
||||
}
|
||||
first[(size_t)s + 1] = first[(size_t)s] + n;
|
||||
}
|
||||
if (first[(size_t)S] != T) {
|
||||
rad_step_fail(c, "laya: the words' token counts do not add up to the step's tokens");
|
||||
return;
|
||||
}
|
||||
const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1);
|
||||
const RadOperand pos = praw(batch->positions, RAD_I32, T);
|
||||
|
||||
/* ---- the encoder over every sequence at once. */
|
||||
RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_o, T));
|
||||
RAD_ISSUE_N(c, m.op_emb_norm, T, brows(m.b_o, T), RAD_W(m.w_emb_norm), RAD_NONE, brows(m.b_x, T));
|
||||
for (size_t l = 0; l < m.layers.size(); ++l) {
|
||||
const Layer& y = m.layers[l];
|
||||
rad_buf att_in = m.b_x;
|
||||
if (l > 0) {
|
||||
RAD_ISSUE_N(c, y.op_attn_norm, T, brows(m.b_x, T), RAD_W(y.w_attn_norm), RAD_NONE,
|
||||
brows(m.b_h, T));
|
||||
att_in = m.b_h;
|
||||
}
|
||||
RAD_ISSUE_N(c, y.op_qkv, T, brows(att_in, T), RAD_W(y.w_qkv), brows(m.b_qkv, T));
|
||||
RAD_ISSUE_N(c, y.op_rope, T, brows(m.b_qkv, T), pos);
|
||||
RAD_ISSUE_N(c, y.op_attn, T, bcol(m.b_qkv, 0, E, T), bcol(m.b_qkv, E, E, T),
|
||||
bcol(m.b_qkv, 2 * E, E, T), cu, brows(m.b_att, T));
|
||||
RAD_ISSUE_N(c, y.op_out, T, brows(m.b_att, T), RAD_W(y.w_out), brows(m.b_o, T));
|
||||
RAD_ISSUE_N(c, y.op_add_attn, T, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T));
|
||||
RAD_ISSUE_N(c, y.op_mlp_norm, T, brows(m.b_x, T), RAD_W(y.w_mlp_norm), RAD_NONE,
|
||||
brows(m.b_h, T));
|
||||
RAD_ISSUE_N(c, y.op_wi, T, brows(m.b_h, T), RAD_W(y.w_wi), brows(m.b_wi, T));
|
||||
RAD_ISSUE_N(c, y.op_act, T, bcol(m.b_wi, 0, F, T), bcol(m.b_wi, F, F, T), brows(m.b_ff, T));
|
||||
RAD_ISSUE_N(c, y.op_wo, T, brows(m.b_ff, T), RAD_W(y.w_wo), brows(m.b_o, T));
|
||||
RAD_ISSUE_N(c, y.op_add_mlp, T, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, m.op_final_norm, T, brows(m.b_x, T), RAD_W(m.w_final_norm), RAD_NONE,
|
||||
brows(m.b_h, T));
|
||||
|
||||
/* ---- the head: each sequence's type row added over its rows, then the head's layers. */
|
||||
for (int64_t s = 0; s < S; ++s) {
|
||||
const int32_t* dw = batch->plugin_words + batch->plugin_cu_h[s];
|
||||
const int64_t r0 = first[(size_t)s], n = first[(size_t)s + 1] - r0;
|
||||
RAD_ISSUE_N(c, m.op_type, 1, praw(dw + RAD_LAYA_W_TYPE, RAD_I32, 1), RAD_W(m.w_type),
|
||||
brow_slice(m.b_trow, s, 1, E));
|
||||
RAD_ISSUE_N(c, m.op_add_type, n, brow_slice(m.b_h, r0, n, E), brow_slice(m.b_trow, s, 1, E),
|
||||
brow_slice(m.b_h, r0, n, E));
|
||||
}
|
||||
for (const HeadLayer& h : m.head) {
|
||||
RAD_ISSUE_N(c, h.op_n1, T, brows(m.b_h, T), RAD_W(h.n1_w), RAD_W(h.n1_b), brows(m.b_t, T));
|
||||
RAD_ISSUE_N(c, h.op_qkv, T, brows(m.b_t, T), RAD_W(h.qkv_w), RAD_W(h.qkv_b), RAD_NONE,
|
||||
brows(m.b_qkv, T));
|
||||
RAD_ISSUE_N(c, h.op_attn, T, bcol(m.b_qkv, 0, E, T), bcol(m.b_qkv, E, E, T),
|
||||
bcol(m.b_qkv, 2 * E, E, T), cu, brows(m.b_att, T));
|
||||
RAD_ISSUE_N(c, h.op_out, T, brows(m.b_att, T), RAD_W(h.out_w), RAD_W(h.out_b),
|
||||
brows(m.b_h, T), brows(m.b_h, T));
|
||||
RAD_ISSUE_N(c, h.op_n2, T, brows(m.b_h, T), RAD_W(h.n2_w), RAD_W(h.n2_b), brows(m.b_t, T));
|
||||
RAD_ISSUE_N(c, h.op_l1, T, brows(m.b_t, T), RAD_W(h.l1_w), RAD_W(h.l1_b), RAD_NONE,
|
||||
brows(m.b_hff, T));
|
||||
RAD_ISSUE_N(c, h.op_relu, T, brows(m.b_hff, T), brows(m.b_hff, T));
|
||||
RAD_ISSUE_N(c, h.op_l2, T, brows(m.b_hff, T), RAD_W(h.l2_w), RAD_W(h.l2_b),
|
||||
brows(m.b_h, T), brows(m.b_h, T));
|
||||
}
|
||||
|
||||
/* ---- the markers' rows, consecutive across sequences, and one score each. */
|
||||
std::vector<int64_t> mark((size_t)S + 1, 0);
|
||||
for (int64_t s = 0; s < S; ++s) {
|
||||
const int32_t* dw = batch->plugin_words + batch->plugin_cu_h[s];
|
||||
const int64_t k = batch->plugin_words_h[batch->plugin_cu_h[s] + RAD_LAYA_W_K];
|
||||
const int64_t r0 = first[(size_t)s], n = first[(size_t)s + 1] - r0;
|
||||
RAD_ISSUE_N(c, m.op_gather, k, brow_slice(m.b_h, r0, n, E),
|
||||
praw(dw + RAD_LAYA_W_MARKERS, RAD_I32, k), brow_slice(m.b_m, mark[(size_t)s], k, E));
|
||||
mark[(size_t)s + 1] = mark[(size_t)s] + k;
|
||||
}
|
||||
const int64_t K = mark[(size_t)S];
|
||||
RAD_ISSUE_N(c, m.op_sn, K, brows(m.b_m, K), RAD_W(m.w_sn), RAD_W(m.b_sn), brows(m.b_t, K));
|
||||
RAD_ISSUE_N(c, m.op_s1, K, brows(m.b_t, K), RAD_W(m.w_s1), RAD_W(m.b_s1), RAD_NONE, brows(m.b_m2, K));
|
||||
RAD_ISSUE_N(c, m.op_s2, K, brows(m.b_m2, K), RAD_W(m.w_s2), RAD_W(m.b_s2), RAD_NONE, brows(m.b_sc, K));
|
||||
RAD_ISSUE_N(c, m.op_fill, 1, brow_slice(m.b_sc, K, P, 1));
|
||||
/* Each sequence's pooled row: its k scores and, past them, the next scores or filler, which
|
||||
* the server does not read. */
|
||||
for (int64_t s = 0; s < S; ++s)
|
||||
RAD_ISSUE_N(c, m.op_out, 1, brow_slice(m.b_sc, mark[(size_t)s], P, 1),
|
||||
bcol_at(m.b_pooled, s, P, 0, P, 1));
|
||||
}
|
||||
|
||||
} /* namespace laya */
|
||||
|
||||
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 "
|
||||
"sequence a question, served on /v1/systemone; bf16")
|
||||
RAD_ARCH_PROBE(laya)
|
||||
+249
-64
@@ -21,14 +21,35 @@
|
||||
* under `model`. Which one this is comes from the config (a VL checkpoint has a `text_config`),
|
||||
* not the model's name.
|
||||
*
|
||||
* ============================== 8-BIT LINEARS ==============================
|
||||
*
|
||||
* Every linear is a LinearFP8 (rad_fp8.h), so the container's encoding of each weight decides the
|
||||
* GEMM: plain bf16 is `gemm_nt` over the bf16 activation, exactly as a bf16 model runs; a recipe's
|
||||
* 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
|
||||
* 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.
|
||||
*
|
||||
* A block-fp8 trunk also takes the fused producers (rad_fp8.h), which matter once the GEMMs are
|
||||
* this cheap: each norm quantises in its own pass and does the preceding block's residual add
|
||||
* (rmsnorm_quant_fp8 with a fold), and the feed-forward is MlpFP8, whose gate|up GEMM applies
|
||||
* SiLU(gate) * up and quantises in its epilogue at decode and short-prompt rows. Six launches a
|
||||
* layer become two; the last layer's feed-forward keeps its add for the final norm. The fused
|
||||
* kernels are byte-identical to the chains they replace.
|
||||
*
|
||||
* ============================== WHAT IT DOES NOT SERVE ==============================
|
||||
*
|
||||
* Tensor parallelism (a 3B model needs one card). A drafter, MoE (LFM2-8B-A1B), conv bias, or a
|
||||
* checkpoint without the rotary: each is refused by name.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_mlp.h>
|
||||
#include <arch/rad_block_vit.h>
|
||||
#include <arch/rad_block_mlp_fp8.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#include "siglip2.h"
|
||||
|
||||
@@ -42,17 +63,32 @@ using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
bool attention = false;
|
||||
MlpBF16 mlp;
|
||||
rad_weight w_norm = 0, w_in = 0, w_out = 0;
|
||||
rad_weight w_norm = 0;
|
||||
/* in is q (attention) or the convolution's in_proj; out is the mixer's out-projection */
|
||||
LinearFP8 in, out;
|
||||
/* conv */
|
||||
rad_weight w_conv = 0;
|
||||
rad_op op_gate_in = 0, op_conv = 0, op_gate_out = 0;
|
||||
/* attention: w_in is q, these are k, v and the two head norms */
|
||||
rad_weight w_k = 0, w_v = 0, w_q_norm = 0, w_k_norm = 0;
|
||||
rad_op op_k = 0, op_v = 0, op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
|
||||
/* `gate_quant_fp8` at act none: C * conv(B * x) and its E4M3 codes in one pass. Absent
|
||||
* (bf16, int8, or no library serving it), op_gate_out and q_mix run the pair. */
|
||||
rad_op op_gate_q = 0;
|
||||
/* attention: k, v and the two head norms */
|
||||
LinearFP8 k, v;
|
||||
rad_weight w_q_norm = 0, w_k_norm = 0;
|
||||
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
|
||||
rad_op op_store = 0, op_attn = 0;
|
||||
/* both */
|
||||
rad_op op_norm = 0, op_in = 0, op_out = 0, op_add = 0;
|
||||
rad_op op_norm = 0, op_add = 0;
|
||||
/* the feed-forward: norm, gate|up (w1 | w3), SiLU(gate) * up, down (w2), residual add */
|
||||
rad_weight w_ffn_norm = 0;
|
||||
LinearFP8 gate_up, down;
|
||||
rad_op op_ffn_norm = 0, op_act = 0, op_ffn_add = 0;
|
||||
/* fp8a8 only: the activation quantisers, one per activation the linears read */
|
||||
QuantFP8 q_h, q_mix, q_ffn_h, q_ffn;
|
||||
/* fp8a8 fused: the mixer's norm (quantising, and adding the previous feed-forward's delta
|
||||
* from layer 1 on) and the whole feed-forward */
|
||||
NormQuantFP8 nq_mix;
|
||||
MlpFP8 mlp8;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
@@ -64,6 +100,12 @@ struct Model {
|
||||
rad_buf b_x = 0, b_h = 0, b_bcx = 0, b_conv_in = 0, b_conv_out = 0;
|
||||
rad_buf b_q = 0, b_k = 0, b_v = 0, b_attn = 0, b_gate_up = 0, b_ffn = 0;
|
||||
rad_buf b_hout = 0, b_logits = 0;
|
||||
/* The linears' inputs: the bf16 plane plus, for an 8-bit trunk, its codes. a_mix is the
|
||||
* mixer's output (attention or convolution), the out-projection's input. */
|
||||
ActFP8 a_h{}, a_attn{}, a_conv{}, a_ffn{};
|
||||
/* 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;
|
||||
|
||||
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;
|
||||
@@ -215,8 +257,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.w_lm_head = decl_w(b, nm.f("output.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
/* The head at its codes' dtype: bf16, or E4M3 / int8 where a recipe quantised it. */
|
||||
m.w_lm_head = decl_w(b, nm.f("output.weight"),
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
|
||||
@@ -227,66 +271,125 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.media = Siglip2::present(meta) && ctx->max_enc_patches > 0;
|
||||
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
|
||||
|
||||
MlpBF16::Wire mw{};
|
||||
mw.x = m.b_x; mw.h = m.b_h; mw.gate_up = m.b_gate_up; mw.ffn = m.b_ffn;
|
||||
|
||||
auto gemm = [&](int64_t N, int64_t K, rad_weight w, rad_buf in, rad_buf out) {
|
||||
return rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w)),
|
||||
{in}, {out});
|
||||
/* ---- the trunk's format, from layer 0's first linear: q, or the convolution's in_proj
|
||||
* (probe() makes its name map and reads its encoding). Plain bf16, or no encoding yet, is a
|
||||
* bf16 trunk; an int8 weight makes the activations carry int8 codes, any other 8-bit weight
|
||||
* E4M3 ones. */
|
||||
const char* ffn_fmt = "%s.layers.%d.feed_forward.%s";
|
||||
{
|
||||
Layer& L0 = m.layers[0];
|
||||
const char* base0 = nm.f(L0.attention ? "blk.%d.attn_q" : "blk.%d.conv_in", 0);
|
||||
RAD_ARCH_TRY(L0.in.probe(b, nm, g, base0,
|
||||
{ nm.ckpt(L0.attention ? "%s.layers.%d.self_attn.%s"
|
||||
: "%s.layers.%d.conv.%s",
|
||||
pre, 0, L0.attention ? "q_proj.weight"
|
||||
: "in_proj.weight") }));
|
||||
RadEncoding enc{};
|
||||
const bool known = weight_enc(b, nm.f("%s.weight", base0), &enc);
|
||||
const bool plain = !known || (rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
|
||||
enc.plane[0].dtype == RAD_BF16);
|
||||
g.w_bf16 = plain;
|
||||
m.q_i8 = !plain && L0.in.probed_i8;
|
||||
m.q_fp8 = !plain && !m.q_i8;
|
||||
m.fused = m.q_fp8;
|
||||
}
|
||||
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));
|
||||
/* 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) {
|
||||
return m.q_fp8 ? q.declare(b, g, a, n) : RAD_OK;
|
||||
};
|
||||
auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_buf in, rad_buf out) {
|
||||
return rw(b, RAD_OP(b, "rmsnorm",
|
||||
|
||||
/* `op`: "rmsnorm", or "rmsnorm_rows" for the head norms, whose short-row form a prefill's
|
||||
* thousands of head_dim-wide rows take. */
|
||||
auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_buf in, rad_buf out,
|
||||
const char* op = "rmsnorm") {
|
||||
return rw(b, RAD_OP(b, op,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", g.eps),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w)),
|
||||
{in}, {out});
|
||||
};
|
||||
auto add = [&](rad_buf x, rad_buf h) {
|
||||
return rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{x, h}, {x});
|
||||
};
|
||||
auto layer_w = [&](const char* name, int l, std::initializer_list<int64_t> shape,
|
||||
uint32_t dtype) {
|
||||
return decl_w(b, nm.f(name, l), dtype, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(l));
|
||||
};
|
||||
/* One linear: `base` is the declared name without `.weight`. Every linear must have the
|
||||
* trunk's format; LinearFP8 refuses a bf16 weight in an 8-bit trunk with no bf16 plane, and
|
||||
* this refuses the other mixes. */
|
||||
auto linear = [&](LinearFP8& lin, int l, const char* base_fmt, int64_t N, int64_t K,
|
||||
std::initializer_list<const char*> src, const ActFP8& a, rad_buf y,
|
||||
std::initializer_list<int64_t> parts) -> int {
|
||||
const char* base = nm.f(base_fmt, l);
|
||||
RAD_ARCH_TRY(lin.declare(b, nm, g, base, N, K, RAD_SHARD_NONE, grp_layer(l), src, a, y, 0,
|
||||
parts));
|
||||
const bool ok = g.w_bf16 ? lin.bf16 : m.q_i8 ? lin.i8 : (!lin.bf16 && !lin.i8);
|
||||
if (!ok) {
|
||||
fprintf(stderr, "radiance: lfm2: '%s.weight' is not in the trunk's format (%s); quantise "
|
||||
"every linear of the trunk alike\n",
|
||||
base, g.w_bf16 ? "bf16" : m.q_i8 ? "int8" : "block fp8");
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
return RAD_OK;
|
||||
};
|
||||
|
||||
for (int l = 0; l < (int)m.layers.size(); ++l) {
|
||||
Layer& L = m.layers[(size_t)l];
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l),
|
||||
nm.ckpt("%s.layers.%d.operator_norm.weight", pre, l)));
|
||||
L.w_norm = layer_w("blk.%d.attn_norm.weight", l, {g.n_embd}, RAD_F32);
|
||||
if (m.fused) {
|
||||
/* From layer 1 on the previous feed-forward's delta is still in h: the norm adds it
|
||||
* into the stream, then normalises and quantises. */
|
||||
const bool fold = l > 0;
|
||||
RAD_ARCH_TRY(L.nq_mix.declare(b, g, L.w_norm, fold ? m.b_h : m.b_x, m.a_h, g.n_embd,
|
||||
fold ? m.b_x : 0));
|
||||
} else {
|
||||
L.op_norm = rmsnorm(g.max_tok, g.n_embd, L.w_norm, m.b_x, m.b_h);
|
||||
RAD_ARCH_TRY(quant(L.q_h, m.a_h, g.n_embd));
|
||||
}
|
||||
|
||||
if (L.attention) {
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_attn));
|
||||
const char* a = "%s.layers.%d.self_attn.%s";
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l), nm.ckpt(a, pre, l, "q_proj.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), nm.ckpt(a, pre, l, "k_proj.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l), nm.ckpt(a, pre, l, "v_proj.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l),
|
||||
nm.ckpt(a, pre, l, "q_layernorm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l),
|
||||
nm.ckpt(a, pre, l, "k_layernorm.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l),
|
||||
nm.ckpt(a, pre, l, "out_proj.weight")));
|
||||
L.w_in = layer_w("blk.%d.attn_q.weight", l, {g.q_dim(), g.n_embd}, RAD_BF16);
|
||||
L.w_k = layer_w("blk.%d.attn_k.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16);
|
||||
L.w_v = layer_w("blk.%d.attn_v.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16);
|
||||
RAD_ARCH_TRY(linear(L.in, l, "blk.%d.attn_q", g.q_dim(), g.n_embd,
|
||||
{ nm.ckpt(a, pre, l, "q_proj.weight") }, m.a_h, m.b_q, {}));
|
||||
/* k and v are the trunk's narrowest linears: past 40 rows the narrow fp8 row's split
|
||||
* leaves each slice too few waves, so they ask for the short-prompt split rule. */
|
||||
L.k.short_split = L.v.short_split = true;
|
||||
RAD_ARCH_TRY(linear(L.k, l, "blk.%d.attn_k", g.kv_dim(), g.n_embd,
|
||||
{ nm.ckpt(a, pre, l, "k_proj.weight") }, m.a_h, m.b_k, {}));
|
||||
RAD_ARCH_TRY(linear(L.v, l, "blk.%d.attn_v", g.kv_dim(), g.n_embd,
|
||||
{ nm.ckpt(a, pre, l, "v_proj.weight") }, m.a_h, m.b_v, {}));
|
||||
L.w_q_norm = layer_w("blk.%d.attn_q_norm.weight", l, {g.head_dim}, RAD_F32);
|
||||
L.w_k_norm = layer_w("blk.%d.attn_k_norm.weight", l, {g.head_dim}, RAD_F32);
|
||||
L.w_out = layer_w("blk.%d.attn_output.weight", l, {g.n_embd, g.q_dim()}, RAD_BF16);
|
||||
|
||||
L.op_in = gemm(g.q_dim(), g.n_embd, L.w_in, m.b_h, m.b_q);
|
||||
L.op_k = gemm(g.kv_dim(), g.n_embd, L.w_k, m.b_h, m.b_k);
|
||||
L.op_v = gemm(g.kv_dim(), g.n_embd, L.w_v, m.b_h, m.b_v);
|
||||
/* The head norms run over rows of head_dim: a [T, heads * head_dim] buffer is
|
||||
* T * heads rows. */
|
||||
L.op_q_norm = rmsnorm(g.max_tok * g.n_head, g.head_dim, L.w_q_norm, m.b_q, m.b_q);
|
||||
L.op_k_norm = rmsnorm(g.max_tok * g.n_head_kv, g.head_dim, L.w_k_norm, m.b_k, m.b_k);
|
||||
L.op_q_norm = rmsnorm(g.max_tok * g.n_head, g.head_dim, L.w_q_norm, m.b_q, m.b_q,
|
||||
"rmsnorm_rows");
|
||||
L.op_k_norm = rmsnorm(g.max_tok * g.n_head_kv, g.head_dim, L.w_k_norm, m.b_k, m.b_k,
|
||||
"rmsnorm_rows");
|
||||
L.op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim,
|
||||
"neox"), {m.b_q}, {m.b_q});
|
||||
"neox", "rope_rows"), {m.b_q}, {m.b_q});
|
||||
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"), {m.b_k}, {m.b_k});
|
||||
"neox", "rope_rows"), {m.b_k}, {m.b_k});
|
||||
/* attn_paged before kv_store: the cache's block size is read from the resolved
|
||||
* attention kernel. */
|
||||
L.op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
@@ -309,21 +412,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_k, m.b_v}, {});
|
||||
L.op_out = gemm(g.n_embd, g.q_dim(), L.w_out, m.b_attn, m.b_h);
|
||||
RAD_ARCH_TRY(quant(L.q_mix, m.a_attn, g.q_dim()));
|
||||
RAD_ARCH_TRY(linear(L.out, l, "blk.%d.attn_output", g.n_embd, g.q_dim(),
|
||||
{ nm.ckpt(a, pre, l, "out_proj.weight") }, m.a_attn, m.b_h, {}));
|
||||
} else {
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_conv));
|
||||
const char* c = "%s.layers.%d.conv.%s";
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_in.weight", l), nm.ckpt(c, pre, l, "in_proj.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv.weight", l), nm.ckpt(c, pre, l, "conv.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_out.weight", l), nm.ckpt(c, pre, l, "out_proj.weight")));
|
||||
L.w_in = layer_w("blk.%d.conv_in.weight", l, {3 * g.n_embd, g.n_embd}, RAD_BF16);
|
||||
/* in_proj's row is [B | C | x]: conv(B * x), then C * that. */
|
||||
RAD_ARCH_TRY(linear(L.in, l, "blk.%d.conv_in", 3 * g.n_embd, g.n_embd,
|
||||
{ nm.ckpt(c, pre, l, "in_proj.weight") }, m.a_h, m.b_bcx, {}));
|
||||
/* The checkpoint ships [n_embd, 1, width]; the depthwise group axis is squeezed at
|
||||
* convert, as the gated delta net's conv1d is. */
|
||||
L.w_conv = layer_w("blk.%d.conv.weight", l, {g.n_embd, m.width}, RAD_BF16);
|
||||
L.w_out = layer_w("blk.%d.conv_out.weight", l, {g.n_embd, g.n_embd}, RAD_BF16);
|
||||
|
||||
/* in_proj's row is [B | C | x]: conv(B * x), then C * that. */
|
||||
L.op_in = gemm(3 * g.n_embd, g.n_embd, L.w_in, m.b_h, m.b_bcx);
|
||||
L.op_gate_in = rw(b, RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
@@ -334,25 +436,78 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_INT("width", m.width), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(L.w_conv)),
|
||||
{m.b_conv_in}, {m.b_conv_out});
|
||||
/* C * conv(B * x), then the codes the out projection reads, in one pass. The kernel
|
||||
* rounds the product to bf16 before taking the codes, so it is byte-identical to the
|
||||
* mul + quant_act_fp8 pair; the bf16 product has no reader in a block-fp8 trunk. */
|
||||
if (m.q_fp8 && rad_op_declared(b, "gate_quant_fp8"))
|
||||
L.op_gate_q = rw(b, RAD_OP(b, "gate_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", g.dtype),
|
||||
RAD_STR("act", "none")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_bcx, m.b_conv_out}, {m.a_conv.cq(), m.a_conv.cs()});
|
||||
if (!L.op_gate_q) {
|
||||
L.op_gate_out = rw(b, RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_bcx, m.b_conv_out}, {m.b_conv_out});
|
||||
L.op_out = gemm(g.n_embd, g.n_embd, L.w_out, m.b_conv_out, m.b_h);
|
||||
RAD_ARCH_TRY(quant(L.q_mix, m.a_conv, g.n_embd));
|
||||
}
|
||||
L.op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_ARCH_TRY(linear(L.out, l, "blk.%d.conv_out", g.n_embd, g.n_embd,
|
||||
{ nm.ckpt(c, pre, l, "out_proj.weight") }, m.a_conv, m.b_h, {}));
|
||||
}
|
||||
if (m.fused) {
|
||||
/* The feed-forward's norm adds the mixer's delta; its own add is left to the next
|
||||
* layer's norm, except after the last layer, whose output the final norm reads. */
|
||||
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;
|
||||
MlpFP8::Src ms{};
|
||||
ms.norm = nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l);
|
||||
ms.gate = nm.ckpt(ffn_fmt, pre, l, "w1.weight");
|
||||
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
|
||||
* 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));
|
||||
if (L.mlp8.gate_up.bf16 || L.mlp8.gate_up.i8 || L.mlp8.down.bf16 || L.mlp8.down.i8) {
|
||||
fprintf(stderr, "radiance: lfm2: layer %d's feed-forward is not block fp8 like the "
|
||||
"rest of the trunk; quantise every linear alike\n", l);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
L.op_add = add(m.b_x, m.b_h);
|
||||
|
||||
/* ---- the feed-forward */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_norm.weight", l),
|
||||
nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l)));
|
||||
L.w_ffn_norm = layer_w("blk.%d.ffn_norm.weight", l, {g.n_embd}, RAD_F32);
|
||||
L.op_ffn_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(L.w_ffn_norm)),
|
||||
{m.b_x}, {m.b_h});
|
||||
RAD_ARCH_TRY(quant(L.q_ffn_h, m.a_h, g.n_embd));
|
||||
RAD_ARCH_TRY(linear(L.gate_up, l, "blk.%d.ffn_gate_up", 2 * g.n_ff, g.n_embd,
|
||||
{ nm.ckpt(ffn_fmt, pre, l, "w1.weight"),
|
||||
nm.ckpt(ffn_fmt, pre, l, "w3.weight") },
|
||||
m.a_h, m.b_gate_up, { g.n_ff, g.n_ff }));
|
||||
L.op_act = rw(b, RAD_OP(b, "silu_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x, m.b_h}, {m.b_x});
|
||||
|
||||
MlpBF16::Src ms{};
|
||||
ms.norm = nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l);
|
||||
ms.gate = nm.ckpt("%s.layers.%d.feed_forward.w1.weight", pre, l);
|
||||
ms.up = nm.ckpt("%s.layers.%d.feed_forward.w3.weight", pre, l);
|
||||
ms.down = nm.ckpt("%s.layers.%d.feed_forward.w2.weight", pre, l);
|
||||
RAD_ARCH_TRY(L.mlp.declare(b, nm, g, l, mw, ms));
|
||||
{m.b_gate_up}, {m.b_ffn});
|
||||
RAD_ARCH_TRY(quant(L.q_ffn, m.a_ffn, g.n_ff));
|
||||
RAD_ARCH_TRY(linear(L.down, l, "blk.%d.ffn_down", g.n_embd, g.n_ff,
|
||||
{ nm.ckpt(ffn_fmt, pre, l, "w2.weight") }, m.a_ffn, m.b_h, {}));
|
||||
L.op_ffn_add = add(m.b_x, m.b_h);
|
||||
}
|
||||
|
||||
/* The final norm runs on the gathered rows only: it is per token, and those are the rows the
|
||||
@@ -363,6 +518,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_hout});
|
||||
m.op_final_norm = rmsnorm(g.max_logit_rows, g.n_embd, m.w_out_norm, m.b_hout, m.b_hout);
|
||||
/* A tied head is the bf16 embedding table, whatever codes the head itself is read at: a
|
||||
* scored step (/v1/systemone) leaves the final-normed rows in h_out and the core takes the
|
||||
* candidates' logits from the table on the host (rad_declare_scores), with no head read. */
|
||||
if (text_bool(meta, "tie_word_embeddings", false))
|
||||
RAD_ARCH_TRY(rad_declare_scores(b, m.b_hout, m.w_tok));
|
||||
m.op_logits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd),
|
||||
@@ -431,12 +591,17 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
|
||||
for (int l = 0; l < (int)m.layers.size(); ++l) {
|
||||
const Layer& L = m.layers[(size_t)l];
|
||||
if (m.fused) {
|
||||
L.nq_mix.step(c, T);
|
||||
} else {
|
||||
RAD_ISSUE(c, L.op_norm, brows(m.b_x, T), RAD_W(L.w_norm), brows(m.b_h, T));
|
||||
L.q_h.step(c, T);
|
||||
}
|
||||
if (L.attention) {
|
||||
const RadKVGroupBatch* kv = kv_batch(batch, m.kv_attn);
|
||||
RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_q, T));
|
||||
RAD_ISSUE(c, L.op_k, brows(m.b_h, T), RAD_W(L.w_k), brows(m.b_k, T));
|
||||
RAD_ISSUE(c, L.op_v, brows(m.b_h, T), RAD_W(L.w_v), brows(m.b_v, T));
|
||||
L.in.step(c, m.a_h, m.b_q, T);
|
||||
L.k.step(c, m.a_h, m.b_k, T);
|
||||
L.v.step(c, m.a_h, m.b_v, T);
|
||||
RAD_ISSUE_N(c, L.op_q_norm, T * g.n_head, brows(m.b_q, T), RAD_W(L.w_q_norm),
|
||||
brows(m.b_q, T));
|
||||
RAD_ISSUE_N(c, L.op_k_norm, T * g.n_head_kv, brows(m.b_k, T), RAD_W(L.w_k_norm),
|
||||
@@ -453,18 +618,36 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(m.b_attn, T));
|
||||
RAD_ISSUE(c, L.op_out, brows(m.b_attn, T), RAD_W(L.w_out), brows(m.b_h, T));
|
||||
L.q_mix.step(c, T);
|
||||
L.out.step(c, m.a_attn, m.b_h, T);
|
||||
} else {
|
||||
RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_bcx, T));
|
||||
L.in.step(c, m.a_h, m.b_bcx, T);
|
||||
RAD_ISSUE(c, L.op_gate_in, bcol(m.b_bcx, 0, n, T), bcol(m.b_bcx, 2 * n, n, T),
|
||||
brows(m.b_conv_in, T));
|
||||
conv_step(m, L, c, batch, l);
|
||||
if (L.op_gate_q) {
|
||||
RAD_ISSUE(c, L.op_gate_q, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T),
|
||||
brows(m.a_conv.cq(), T), brows(m.a_conv.cs(), T), RAD_NONE);
|
||||
} else {
|
||||
RAD_ISSUE(c, L.op_gate_out, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T),
|
||||
brows(m.b_conv_out, T));
|
||||
RAD_ISSUE(c, L.op_out, brows(m.b_conv_out, T), RAD_W(L.w_out), brows(m.b_h, T));
|
||||
L.q_mix.step(c, T);
|
||||
}
|
||||
L.out.step(c, m.a_conv, m.b_h, T);
|
||||
}
|
||||
if (m.fused) {
|
||||
L.mlp8.step(c, batch);
|
||||
continue;
|
||||
}
|
||||
RAD_ISSUE(c, L.op_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T));
|
||||
L.mlp.step(c, batch);
|
||||
|
||||
RAD_ISSUE(c, L.op_ffn_norm, brows(m.b_x, T), RAD_W(L.w_ffn_norm), brows(m.b_h, T));
|
||||
L.q_ffn_h.step(c, T);
|
||||
L.gate_up.step(c, m.a_h, m.b_gate_up, T);
|
||||
RAD_ISSUE(c, L.op_act, brows(m.b_gate_up, T), brows(m.b_ffn, T));
|
||||
L.q_ffn.step(c, T);
|
||||
L.down.step(c, m.a_ffn, m.b_h, T);
|
||||
RAD_ISSUE(c, L.op_ffn_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T));
|
||||
}
|
||||
|
||||
/* The lm_head runs only on the rows the sampler asked for; a prefill chunk that finishes no
|
||||
@@ -474,6 +657,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_final_norm, batch->n_out, brows(m.b_hout, batch->n_out),
|
||||
RAD_W(m.w_out_norm), brows(m.b_hout, batch->n_out));
|
||||
if (!batch->score_only)
|
||||
RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out),
|
||||
RAD_W(m.w_lm_head), brows(m.b_logits, batch->n_out));
|
||||
}
|
||||
@@ -482,7 +666,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
} /* namespace lfm2_bf16 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PLUGIN(lfm2_bf16, "lfm2", "", "0.1.0",
|
||||
"LiquidAI LFM2 / LFM2-VL, bf16: short gated convolutions and GQA attention in the "
|
||||
"checkpoint's own schedule, one rank; LFM2-VL's SigLIP2 tower for images")
|
||||
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 "
|
||||
"rank; LFM2-VL's SigLIP2 tower for images")
|
||||
#endif
|
||||
@@ -7,4 +7,9 @@ if(NOT COMMAND rad_add_plugin)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(minimaxh3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/minimaxh3.cpp)
|
||||
# rad_ref2va_pack.cpp holds the reference sequence's packing and rad_vae_geom.cpp the encoders'
|
||||
# geometry: pure host arithmetic, which tests/ref2va_pack_test.cpp and tests/vae_geom_test.cpp
|
||||
# compile in directly.
|
||||
rad_add_plugin(minimaxh3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/minimaxh3.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/rad_ref2va_pack.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/rad_vae_geom.cpp)
|
||||
+1672
-144
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,301 @@
|
||||
/* rad_ref2va_pack.cpp -- see rad_ref2va_pack.h. The positions are computed in f64 as ComfyUI
|
||||
* computes them and stored in f32. */
|
||||
|
||||
#include "rad_ref2va_pack.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace minimaxh3 {
|
||||
|
||||
/* The pixel frames the k-th latent frame of a video covers, cycling, and the time a pixel frame
|
||||
* spans in soundtrack latents. */
|
||||
static const int kFramePerToken[5] = { 1, 4, 4, 4, 4 };
|
||||
static const double kFrameRescale = 5.0 / 3.0;
|
||||
|
||||
int ref2va_seg_tag(int kind) {
|
||||
switch (kind) {
|
||||
case kR2VText: return 1;
|
||||
case kR2VAudio: case kR2VCondAudio: case kR2VRefAudio: return 2;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int ref2va_is_img(int kind) {
|
||||
return kind == kR2VCond || kind == kR2VRefImg || kind == kR2VVideo;
|
||||
}
|
||||
|
||||
int ref2va_is_audio(int kind) {
|
||||
return kind == kR2VCondAudio || kind == kR2VRefAudio || kind == kR2VAudio;
|
||||
}
|
||||
|
||||
/* A side of `dim` latents in 2x2 patches: dim / 2 positions over
|
||||
* [(1 - ratio) / 2, (1 + ratio) / 2) x 32, ratio = dim / sqrt(h w), so every aspect spans the same
|
||||
* area. */
|
||||
static std::vector<double> axis_from_sqrt_area(int dim, int patch, double sqrt_area) {
|
||||
const double ratio = (double)dim / sqrt_area;
|
||||
const int n = dim / patch;
|
||||
std::vector<double> v((size_t)n);
|
||||
for (int i = 0; i < n; ++i)
|
||||
v[(size_t)i] = ((double)i * (ratio / n) + (1.0 - ratio) / 2.0) * 32.0;
|
||||
return v;
|
||||
}
|
||||
|
||||
/* A latent frame's patches as (row, column) pairs, row-major, and the column axis, whose ends the
|
||||
* two soundtrack channels sit at. */
|
||||
static void frame_grid(int h, int w, std::vector<double>* frame, std::vector<double>* w_grid) {
|
||||
const double area = std::sqrt((double)h * (double)w);
|
||||
std::vector<double> hg = axis_from_sqrt_area(h, 2, area), wg = axis_from_sqrt_area(w, 2, area);
|
||||
frame->clear();
|
||||
frame->reserve(hg.size() * wg.size() * 2);
|
||||
for (const double& r : hg)
|
||||
for (const double& c : wg) { frame->push_back(r); frame->push_back(c); }
|
||||
*w_grid = std::move(wg);
|
||||
}
|
||||
|
||||
/* The time n latent frames of video span. */
|
||||
static double video_t_span_sum(int n) {
|
||||
double s = 0.0;
|
||||
for (int k = 0; k < n; ++k) s += kFrameRescale * (double)kFramePerToken[k % 5];
|
||||
return s;
|
||||
}
|
||||
|
||||
/* Each latent frame's time: where the frames before it end. */
|
||||
static std::vector<double> video_t_grid(int n, double origin) {
|
||||
std::vector<double> g((size_t)n);
|
||||
double t = origin;
|
||||
for (int k = 0; k < n; ++k) {
|
||||
g[(size_t)k] = t;
|
||||
t += kFrameRescale * (double)kFramePerToken[k % 5];
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
/* The time a reference spans: a picture 1, a soundtrack its length, a video the longer of its two
|
||||
* streams. */
|
||||
static double ref_t_span(const Ref2VARef& r) {
|
||||
if (r.kind == kR2VRefImage) return 1.0;
|
||||
if (r.kind == kR2VRefAudioOnly) return (double)r.audio_t;
|
||||
return std::max((double)r.audio_t, video_t_span_sum(r.latent_t));
|
||||
}
|
||||
|
||||
/* A soundtrack's rows, the first channel's then the second's, a latent each at `cursor` onwards;
|
||||
* the channels sit at the two ends of the width axis, row 0. */
|
||||
static void audio_grid(double cursor, int t, double w_low, double w_high, std::vector<float>* pos) {
|
||||
if (!pos) return;
|
||||
for (int ch = 0; ch < 2; ++ch) {
|
||||
const double w = ch == 0 ? w_low : w_high;
|
||||
for (int i = 0; i < t; ++i) {
|
||||
pos->push_back((float)(cursor + (double)i));
|
||||
pos->push_back(0.0f);
|
||||
pos->push_back((float)w);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* A video's rows: each latent frame's patches at its time. */
|
||||
static void video_grid(int vt, const std::vector<double>& frame, double origin,
|
||||
std::vector<float>* pos) {
|
||||
if (!pos) return;
|
||||
const std::vector<double> tg = video_t_grid(vt, origin);
|
||||
for (int k = 0; k < vt; ++k)
|
||||
for (size_t j = 0; j < frame.size(); j += 2) {
|
||||
pos->push_back((float)tg[(size_t)k]);
|
||||
pos->push_back((float)frame[j]);
|
||||
pos->push_back((float)frame[j + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
int ref2va_build(int text_len, const Ref2VAGeom& g, const std::vector<Ref2VAKeyframe>& keyframes,
|
||||
const std::vector<Ref2VARef>& refs, Ref2VAPack* out, bool positions) {
|
||||
if (text_len < 0 || g.latent_t < 0 || g.latent_h < 0 || g.latent_w < 0 || g.audio_t < 0)
|
||||
return -1;
|
||||
for (const Ref2VAKeyframe& kf : keyframes)
|
||||
if (kf.frame < 0 || kf.video_t < 0 || kf.audio_t < 0) return -1;
|
||||
for (const Ref2VARef& r : refs) {
|
||||
if (r.kind < kR2VRefImage || r.kind > kR2VRefVideoAudio) return -1;
|
||||
if (r.lat_h < 0 || r.lat_w < 0 || r.latent_t < 0 || r.audio_t < 0) return -1;
|
||||
}
|
||||
|
||||
Ref2VAPack p;
|
||||
std::vector<double> frame, w_grid;
|
||||
frame_grid(g.latent_h, g.latent_w, &frame, &w_grid);
|
||||
const size_t frame_rows = frame.size() / 2;
|
||||
const double w_low = w_grid.empty() ? 0.0 : w_grid.front();
|
||||
const double w_high = w_grid.empty() ? 0.0 : w_grid.back();
|
||||
|
||||
/* The prompt: its token positions on the time axis. */
|
||||
p.segs.push_back({ kR2VText, 0, (int64_t)text_len, 0 });
|
||||
std::vector<float>* pos = positions ? &p.pos : nullptr;
|
||||
for (int i = 0; i < text_len && pos; ++i) {
|
||||
p.pos.push_back((float)i);
|
||||
p.pos.push_back(0.0f);
|
||||
p.pos.push_back(0.0f);
|
||||
}
|
||||
int64_t row = text_len;
|
||||
|
||||
/* The video's clock, and the keyframes on it, starts after every reference's span. */
|
||||
double cursor = (double)text_len;
|
||||
for (const Ref2VARef& r : refs) cursor += ref_t_span(r);
|
||||
|
||||
/* A keyframe is on the video's grid, at its frame's time. */
|
||||
for (const Ref2VAKeyframe& kf : keyframes) {
|
||||
const double cond_t = cursor + kFrameRescale * (double)kf.frame;
|
||||
if (kf.video_t > 0) {
|
||||
const int64_t n = (int64_t)kf.video_t * (int64_t)frame_rows;
|
||||
video_grid(kf.video_t, frame, cond_t, pos);
|
||||
p.segs.push_back({ kR2VCond, row, row + n, 0 });
|
||||
row += n;
|
||||
}
|
||||
if (kf.audio_t > 0) {
|
||||
const int64_t n = (int64_t)kf.audio_t * 2;
|
||||
audio_grid(cond_t, kf.audio_t, w_low, w_high, pos);
|
||||
p.segs.push_back({ kR2VCondAudio, row, row + n, 0 });
|
||||
row += n;
|
||||
}
|
||||
}
|
||||
|
||||
/* The references in request order, each after the last. */
|
||||
cursor = (double)text_len;
|
||||
for (const Ref2VARef& r : refs) {
|
||||
if (r.kind == kR2VRefImage) {
|
||||
std::vector<double> rf, rw;
|
||||
frame_grid(r.lat_h, r.lat_w, &rf, &rw);
|
||||
const int64_t n = (int64_t)rf.size() / 2;
|
||||
for (int64_t i = 0; i < n && pos; ++i) {
|
||||
p.pos.push_back((float)cursor);
|
||||
p.pos.push_back((float)rf[(size_t)i * 2]);
|
||||
p.pos.push_back((float)rf[(size_t)i * 2 + 1]);
|
||||
}
|
||||
p.segs.push_back({ kR2VRefImg, row, row + n, 0 });
|
||||
row += n;
|
||||
cursor += 1.0;
|
||||
} else if (r.kind == kR2VRefAudioOnly) {
|
||||
if (r.audio_t > 0) {
|
||||
const int64_t n = (int64_t)r.audio_t * 2;
|
||||
audio_grid(cursor, r.audio_t, w_low, w_high, pos);
|
||||
p.segs.push_back({ kR2VRefAudio, row, row + n, 0 });
|
||||
row += n;
|
||||
}
|
||||
cursor += (double)r.audio_t;
|
||||
} else {
|
||||
/* A video's soundtrack, at the video's time and the ends of the video's own width
|
||||
* axis, comes right before it. */
|
||||
std::vector<double> rf, rw;
|
||||
frame_grid(r.lat_h, r.lat_w, &rf, &rw);
|
||||
if (r.audio_t > 0) {
|
||||
const int64_t n = (int64_t)r.audio_t * 2;
|
||||
audio_grid(cursor, r.audio_t, rw.empty() ? 0.0 : rw.front(),
|
||||
rw.empty() ? 0.0 : rw.back(), pos);
|
||||
p.segs.push_back({ kR2VRefAudio, row, row + n, 0 });
|
||||
row += n;
|
||||
}
|
||||
const int64_t n = (int64_t)r.latent_t * (int64_t)(rf.size() / 2);
|
||||
video_grid(r.latent_t, rf, cursor, pos);
|
||||
p.segs.push_back({ kR2VRefImg, row, row + n, 0 });
|
||||
row += n;
|
||||
cursor += std::max((double)r.audio_t, video_t_span_sum(r.latent_t));
|
||||
}
|
||||
}
|
||||
|
||||
/* The soundtrack and the video the sampler steps, last. */
|
||||
{
|
||||
const int64_t n = (int64_t)g.audio_t * 2;
|
||||
audio_grid(cursor, g.audio_t, w_low, w_high, pos);
|
||||
p.segs.push_back({ kR2VAudio, row, row + n, 1 });
|
||||
row += n;
|
||||
}
|
||||
{
|
||||
const int64_t n = (int64_t)g.latent_t * (int64_t)frame_rows;
|
||||
video_grid(g.latent_t, frame, cursor, pos);
|
||||
p.segs.push_back({ kR2VVideo, row, row + n, 1 });
|
||||
row += n;
|
||||
}
|
||||
|
||||
p.rows = row;
|
||||
if (positions) {
|
||||
/* From (t, h, w) triples to [3, rows]. */
|
||||
std::vector<float> tri = std::move(p.pos);
|
||||
p.pos.assign((size_t)row * 3, 0.0f);
|
||||
for (int64_t r = 0; r < row; ++r) {
|
||||
p.pos[(size_t)r] = tri[(size_t)r * 3];
|
||||
p.pos[(size_t)row + r] = tri[(size_t)r * 3 + 1];
|
||||
p.pos[2 * (size_t)row + r] = tri[(size_t)r * 3 + 2];
|
||||
}
|
||||
}
|
||||
*out = std::move(p);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* A kind's modulation cell (rad_ref2va_pack.h): the latents and the prompt read their schedule's
|
||||
* embeddings, a keyframe or reference its stream's pinned ones. */
|
||||
static void cell_of_kind(int kind, int64_t S, int* md, int64_t* r0) {
|
||||
switch (kind) {
|
||||
case kR2VAudio: *md = 2; *r0 = S; break;
|
||||
case kR2VCondAudio:
|
||||
case kR2VRefAudio: *md = 2; *r0 = 3 * S; break;
|
||||
case kR2VText: *md = 1; *r0 = 0; break;
|
||||
case kR2VCond:
|
||||
case kR2VRefImg: *md = 0; *r0 = 2 * S; break;
|
||||
default: *md = 0; *r0 = 0; break;
|
||||
}
|
||||
}
|
||||
|
||||
void ref2va_mod_groups(const Ref2VAPack& p, int64_t S, const std::vector<Ref2VATagRun>& runs,
|
||||
Ref2VAModGroups* out) {
|
||||
out->bound.clear(); out->col.clear(); out->md.clear(); out->r0.clear();
|
||||
std::vector<Ref2VATagRun> sorted;
|
||||
for (const Ref2VATagRun& r : runs)
|
||||
if (r.end > r.start) sorted.push_back(r);
|
||||
std::sort(sorted.begin(), sorted.end(),
|
||||
[](const Ref2VATagRun& a, const Ref2VATagRun& b) { return a.start < b.start; });
|
||||
|
||||
/* The rows in pieces of one cell each: a segment is one, except the prompt, which the runs cut
|
||||
* into text and pad pieces, every one on the text's block. */
|
||||
struct Piece { int64_t start, end; int md; int64_t r0; };
|
||||
std::vector<Piece> pieces;
|
||||
for (const Ref2VASeg& s : p.segs) {
|
||||
if (s.end <= s.start) continue;
|
||||
if (s.kind != kR2VText) {
|
||||
Piece pc{ s.start, s.end, 0, 0 };
|
||||
cell_of_kind(s.kind, S, &pc.md, &pc.r0);
|
||||
pieces.push_back(pc);
|
||||
continue;
|
||||
}
|
||||
int64_t at = s.start;
|
||||
for (const Ref2VATagRun& r : sorted) {
|
||||
const int64_t a = std::max(r.start, at), b = std::min(r.end, s.end);
|
||||
if (a >= s.end) break;
|
||||
if (b <= a) continue;
|
||||
if (a > at) pieces.push_back({ at, a, 1, 0 });
|
||||
pieces.push_back({ a, b, r.tag, 0 });
|
||||
at = b;
|
||||
}
|
||||
if (at < s.end) pieces.push_back({ at, s.end, 1, 0 });
|
||||
}
|
||||
|
||||
/* A group opens where the cell changes; cells are numbered in their first group's order. */
|
||||
auto column_of = [&](int md, int64_t r0) {
|
||||
for (size_t c = 0; c < out->md.size(); ++c)
|
||||
if (out->md[c] == md && out->r0[c] == r0) return (int)c;
|
||||
out->md.push_back(md);
|
||||
out->r0.push_back(r0);
|
||||
return (int)out->md.size() - 1;
|
||||
};
|
||||
int cur = -1;
|
||||
bool open = false;
|
||||
int64_t prev_end = 0;
|
||||
for (const Piece& pc : pieces) {
|
||||
const int col = column_of(pc.md, pc.r0);
|
||||
if (!open || col != cur || pc.start != prev_end) {
|
||||
out->bound.push_back(open ? pc.start : 0);
|
||||
cur = col;
|
||||
open = true;
|
||||
out->col.push_back(col);
|
||||
}
|
||||
prev_end = pc.end;
|
||||
}
|
||||
if (open) out->bound.push_back(p.rows);
|
||||
}
|
||||
|
||||
} /* namespace minimaxh3 */
|
||||
@@ -0,0 +1,107 @@
|
||||
/* rad_ref2va_pack.h -- MiniMax-H3's packed sequence with keyframes and reference media, on the
|
||||
* host: ComfyUI's PackedLayout (comfy/ldm/minimax/model.py), tested against that code's own numbers
|
||||
* (tests/data/ref2va).
|
||||
*
|
||||
* The sequence is [text | keyframes | references in request order | soundtrack | video]. The
|
||||
* video's clock starts after every reference's time span; a keyframe sits on it at 5/3 a pixel
|
||||
* frame; a reference clip's soundtrack rows come right before its video rows, at the same time
|
||||
* origin. Keyframes and references keep a near-clean timestep; the sampler steps the last two
|
||||
* segments only.
|
||||
*/
|
||||
|
||||
#ifndef RAD_ARCH_MINIMAXH3_REF2VA_PACK_H
|
||||
#define RAD_ARCH_MINIMAXH3_REF2VA_PACK_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
namespace minimaxh3 {
|
||||
|
||||
/* Segment kinds, named as the reference implementation names them. */
|
||||
enum Ref2VAKind {
|
||||
kR2VText = 0, /* the prompt's hidden states */
|
||||
kR2VCond, /* a keyframe's video latent rows */
|
||||
kR2VCondAudio, /* a keyframe's soundtrack latent rows */
|
||||
kR2VRefImg, /* a reference photo, or a reference clip's video */
|
||||
kR2VRefAudio, /* a reference clip's (or standalone audio's) soundtrack */
|
||||
kR2VAudio, /* the target soundtrack -- sampler-owned */
|
||||
kR2VVideo, /* the target video -- sampler-owned */
|
||||
kR2VKinds
|
||||
};
|
||||
|
||||
/* A reference's kind; a video with a soundtrack of its own is either of the last two. */
|
||||
enum Ref2VARefKind { kR2VRefImage = 0, kR2VRefAudioOnly = 1, kR2VRefVideo = 2, kR2VRefVideoAudio = 3 };
|
||||
|
||||
/* A keyframe: the frame of the video it is pinned at and its latent frames of each stream. */
|
||||
struct Ref2VAKeyframe {
|
||||
int frame; /* >= 0 */
|
||||
int video_t; /* 0: none */
|
||||
int audio_t; /* 0: none */
|
||||
};
|
||||
|
||||
/* A reference, in latents: its own grid and frames for a picture or video, its soundtrack's
|
||||
* length for one that has sound. */
|
||||
struct Ref2VARef {
|
||||
int kind; /* Ref2VARefKind */
|
||||
int lat_h, lat_w;
|
||||
int latent_t;
|
||||
int audio_t;
|
||||
};
|
||||
|
||||
/* The target, in latent units. */
|
||||
struct Ref2VAGeom {
|
||||
int latent_t, latent_h, latent_w, audio_t;
|
||||
};
|
||||
|
||||
struct Ref2VASeg {
|
||||
int kind;
|
||||
int64_t start, end; /* rows [start, end) */
|
||||
int update; /* 1 for the soundtrack and the video the sampler steps */
|
||||
};
|
||||
|
||||
struct Ref2VAPack {
|
||||
std::vector<Ref2VASeg> segs;
|
||||
int64_t rows = 0;
|
||||
/* The rotary positions, [3, rows]: every row's time, then row, then column. */
|
||||
std::vector<float> pos;
|
||||
};
|
||||
|
||||
/* A kind's modality in the modulation (ComfyUI's seg_tag): 0 video, 1 text, 2 sound. */
|
||||
int ref2va_seg_tag(int kind);
|
||||
/* Whether a kind's rows are video latents or soundtrack latents; text is neither. */
|
||||
int ref2va_is_img(int kind);
|
||||
int ref2va_is_audio(int kind);
|
||||
/* A keyframe's or reference's timestep is the larger of its stream's and these. */
|
||||
constexpr double kR2VVisualPin = 0.999, kR2VAudioPin = 1.0;
|
||||
|
||||
/* The modulation groups: runs of consecutive rows that read the same modulation cell, which the
|
||||
* segment's kind fixes (`md` its modality's projection, `r0` its block of timestep embeddings) --
|
||||
* except inside the prompt, where a picture's vision pads read the video projection on the text's
|
||||
* block, as ComfyUI tags them (`runs`). The modulated norm takes the group boundaries, the attention
|
||||
* the segments'. Groups that share a cell read one column of the modulation table (`col`), so the
|
||||
* table grows with the distinct cells, not with the references or the pads: nine pictures add one
|
||||
* cell. The groups cover the sequence; an empty segment opens none. */
|
||||
struct Ref2VATagRun {
|
||||
int64_t start, end; /* prompt rows [start, end) */
|
||||
int tag; /* the projection they read: 0 video for vision pads */
|
||||
};
|
||||
struct Ref2VAModGroups {
|
||||
std::vector<int64_t> bound; /* [groups + 1], from 0 to the rows */
|
||||
std::vector<int> col; /* [groups]: the cell the group reads */
|
||||
std::vector<int> md; /* [cells]: 0 video, 1 text, 2 sound */
|
||||
std::vector<int64_t> r0; /* [cells] */
|
||||
};
|
||||
/* `S` is the steps a schedule has, and the embeddings are [0, S) the video's, [S, 2S) the
|
||||
* soundtrack's, then each again with its pin, [2S, 3S) and [3S, 4S). The boundaries do not depend
|
||||
* on S. `runs` may come in any order; the parts outside the prompt are ignored. Without runs every
|
||||
* group has a cell of its own. */
|
||||
void ref2va_mod_groups(const Ref2VAPack& p, int64_t S, const std::vector<Ref2VATagRun>& runs,
|
||||
Ref2VAModGroups* out);
|
||||
|
||||
/* The sequence, and its positions when `positions`; -1 for a negative size or an unknown kind. */
|
||||
int ref2va_build(int text_len, const Ref2VAGeom& g, const std::vector<Ref2VAKeyframe>& keyframes,
|
||||
const std::vector<Ref2VARef>& refs, Ref2VAPack* out, bool positions = true);
|
||||
|
||||
} /* namespace minimaxh3 */
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,48 @@
|
||||
/* rad_vae_geom.cpp -- see rad_vae_geom.h. */
|
||||
|
||||
#include "rad_vae_geom.h"
|
||||
|
||||
namespace minimaxh3 {
|
||||
|
||||
/* vae.py's encode_temporal for more than one frame, its plain encode for one. */
|
||||
int64_t vae_latent_frames(int64_t frames) {
|
||||
if (frames <= 0) return -1;
|
||||
if (frames == 1) return 1;
|
||||
const int64_t clips = (frames + kVaeClipLength - 1) / kVaeClipLength;
|
||||
return clips * kVaeClipLatents - kVaeTokenDrop;
|
||||
}
|
||||
|
||||
int64_t vae_clip_latents(int64_t frames) {
|
||||
if (frames <= 0) return -1;
|
||||
if (frames == 1) return 1;
|
||||
return (frames + 3) / 4; /* ceil(ceil(T / 2) / 2) */
|
||||
}
|
||||
|
||||
/* Every strided convolution (k = 2 s, pad ceil(s / 2)) divides a padded length exactly. */
|
||||
int64_t vae_audio_latents(int64_t samples) {
|
||||
if (samples < 0) return -1;
|
||||
return (samples + kAudioHop - 1) / kAudioHop;
|
||||
}
|
||||
|
||||
const double kVaeLatentsMean[24] = {
|
||||
0.858090341091156, -0.9606591463088989, 1.0661640167236328, -0.5090325474739075,
|
||||
-0.2727581858634949, -1.3675414323806763, -0.2553254961967468, -0.26907554268836975,
|
||||
-0.5376840829849243, -0.0464097298681736, 0.6657370328903198, 0.19690127670764923,
|
||||
-0.5460608005523682, -0.4035342037677765, -0.23683024942874908, 0.25928452610969543,
|
||||
-0.30133944749832153, 0.211341992020607, -1.1206848621368408, 0.3581933379173279,
|
||||
-0.04225143790245056, 0.2604829967021942, 0.22864092886447906, 0.7056031823158264,
|
||||
};
|
||||
|
||||
const double kVaePixelMean[3] = { 0.485, 0.456, 0.406 };
|
||||
const double kVaePixelStd[3] = { 0.229, 0.224, 0.225 };
|
||||
|
||||
const double kVaeLatentsStd[24] = {
|
||||
1.2223774194717407, 1.2767263650894165, 1.68317747116088865, 1.7549455165863037,
|
||||
1.5636216402053833, 2.194143533706665, 0.96531379222869875, 1.05698859691619875,
|
||||
0.841948926448822, 0.7729952931404114, 1.8955937623977661, 0.946841835975647,
|
||||
0.7996809482574463, 0.44988900423049925, 0.7197399735450745, 0.69362932443618775,
|
||||
2.961095094680786, 2.7694199085235595, 3.0496184825897215, 2.1088054180145265,
|
||||
3.276226282119751, 3.1627357006073, 2.28168129920959475, 2.6127843856811525,
|
||||
};
|
||||
|
||||
} /* namespace minimaxh3 */
|
||||
@@ -0,0 +1,43 @@
|
||||
/* rad_vae_geom.h -- the latents MiniMax-H3's VAE encoders make of a media's frames or samples,
|
||||
* and their normalisation constants, on the host. ComfyUI's comfy/ldm/minimax/vae.py and
|
||||
* audio_vae.py, tested against those encoders' own outputs (tests/data/vae_geom). */
|
||||
|
||||
#ifndef RADIANCE_ARCH_MINIMAXH3_RAD_VAE_GEOM_H
|
||||
#define RADIANCE_ARCH_MINIMAXH3_RAD_VAE_GEOM_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace minimaxh3 {
|
||||
|
||||
/* The video VAE: 16 pixels a latent side, and in time clips of 17 frames to 5 latent frames
|
||||
* (17 -> 9 -> 5), of which an encode of more than one frame drops the last 3. */
|
||||
constexpr int kVaeRatio = 16;
|
||||
constexpr int kVaeClipLength = 17;
|
||||
constexpr int kVaeClipLatents = 5;
|
||||
constexpr int kVaeTokenDrop = 3;
|
||||
|
||||
/* The audio VAE: strides 2 4 4 5 5, a latent per 800 samples (40 a second at 32 kHz), the samples
|
||||
* padded with zeros to a whole latent. */
|
||||
constexpr int kAudioHop = 800;
|
||||
|
||||
/* The latent frames of `frames` pixel frames: 1 for a picture, else 5 a clip of 17 (the last
|
||||
* padded by repeating its last frame) less 3. -1 for no frames. */
|
||||
int64_t vae_latent_frames(int64_t frames);
|
||||
|
||||
/* The latent frames one clip of `frames` encodes to, ceil(T / 4) (one frame stays one). */
|
||||
int64_t vae_clip_latents(int64_t frames);
|
||||
|
||||
/* The latents of `samples` samples; -1 for a negative count. */
|
||||
int64_t vae_audio_latents(int64_t samples);
|
||||
|
||||
/* A video latent is normalised as (moments - mean) / std, vae.py's LATENTS_MEAN and LATENTS_STD. */
|
||||
extern const double kVaeLatentsMean[24];
|
||||
extern const double kVaeLatentsStd[24];
|
||||
|
||||
/* A pixel x in [0, 1] goes in as (x - mean) / std, ImageNet's. */
|
||||
extern const double kVaePixelMean[3];
|
||||
extern const double kVaePixelStd[3];
|
||||
|
||||
} /* namespace minimaxh3 */
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,8 @@
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(nemotron35_embed LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(nemotron35_embed architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/nemotron35_embed.cpp)
|
||||
@@ -0,0 +1,405 @@
|
||||
/* Nemotron-3.5-Embed: bidirectional BF16 text and a Pixtral encoder at TP1.
|
||||
*
|
||||
* The wrapper's language_model.* tensors are a Ministral3Model, without a logits head or Q/K
|
||||
* norms. Whole inputs attend bidirectionally and are mean-pooled after the final norm. The
|
||||
* endpoint normalises the vector after any dimensional truncation. Image rows replace only
|
||||
* their typed placeholders; separator tokens retain their vocabulary embeddings.
|
||||
*
|
||||
* Keep model-specific rotary interpretation here: the shared YaRN reader deliberately rejects
|
||||
* mscale, and changing its defaults would change unrelated models. This checkpoint's equal
|
||||
* mscale numerator/denominator give magnitude 1, independently of its position-dependent Q scale.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include "pixtral.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace nemotron35_embed {
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
rad_weight norm = 0, qkv = 0, out = 0, ff_norm = 0, gate_up = 0, down = 0;
|
||||
rad_op in_norm = 0, in_gain = 0, project = 0, rope = 0, qscale = 0, attn = 0, output = 0;
|
||||
rad_op add_attn = 0, pre_ff = 0, ff_gain = 0, gate = 0, act = 0, gate_mul = 0, ffn = 0,
|
||||
add_ff = 0;
|
||||
};
|
||||
struct Model {
|
||||
bool rerank = false;
|
||||
Geom g{};
|
||||
Names nm{""}, source{""};
|
||||
rad_buf x = 0, h = 0, qkv = 0, attn = 0, o = 0, gu = 0, ff = 0, mean = 0, pooled = 0;
|
||||
rad_weight tok = 0, norm = 0, score = 0;
|
||||
rad_op embed = 0, inject = 0, final_norm = 0, final_gain = 0, pool = 0, cast = 0, head = 0;
|
||||
std::vector<Layer> layers;
|
||||
Pixtral vision;
|
||||
};
|
||||
static Model model;
|
||||
|
||||
/* JSON booleans reach plugins as 0/1, while out-of-tree callers may use their JSON spelling. */
|
||||
static bool false_value(const char* s) {
|
||||
return s && (!std::strcmp(s, "0") || !std::strcmp(s, "false"));
|
||||
}
|
||||
|
||||
static int read_rope(Geom& g, const RadModelMeta* meta) {
|
||||
constexpr const char* pre = "text_config.rope_parameters.";
|
||||
auto val = [&](const char* key, const char* fallback = nullptr) {
|
||||
return rad_meta_gets(meta, (std::string(pre) + key).c_str(), fallback);
|
||||
};
|
||||
const char* type = val("rope_type", val("type"));
|
||||
if (!type || std::strcmp(type, "yarn")) return RAD_E_UNSUPPORTED;
|
||||
const double factor = rad_meta_getf(meta, "text_config.rope_parameters.factor", 0);
|
||||
const double num = rad_meta_getf(meta, "text_config.rope_parameters.mscale", NAN);
|
||||
const double den = rad_meta_getf(meta, "text_config.rope_parameters.mscale_all_dim", NAN);
|
||||
if (!(factor >= 1) || !std::isfinite(factor) || !std::isfinite(num) || !std::isfinite(den) ||
|
||||
num < 0 || den < 0)
|
||||
return RAD_E_INVAL;
|
||||
auto magnitude = [&](double m) { return factor > 1 ? 1 + 0.1 * m * std::log(factor) : 1; };
|
||||
const double mag = num && den ? magnitude(num) / magnitude(den) : magnitude(1);
|
||||
if (!(mag > 0) || !std::isfinite(mag)) return RAD_E_INVAL;
|
||||
|
||||
/* Canonicalise only this plugin's temporary metadata view; never change the checkpoint or
|
||||
* shared reader. An explicit attention_factor, if present, is authoritative in Transformers. */
|
||||
std::vector<const char*> keys, vals;
|
||||
for (int i = 0; i < meta->n_kv; ++i) {
|
||||
const char* k = meta->kv_key[i];
|
||||
if (!std::strcmp(k, "text_config.rope_parameters.mscale") ||
|
||||
!std::strcmp(k, "text_config.rope_parameters.mscale_all_dim"))
|
||||
continue;
|
||||
keys.push_back(k);
|
||||
vals.push_back(meta->kv_val[i]);
|
||||
}
|
||||
char mag_text[48];
|
||||
std::snprintf(mag_text, sizeof mag_text, "%.17g", mag);
|
||||
const std::string derived = mag_text;
|
||||
if (!val("attention_factor")) {
|
||||
keys.push_back("text_config.rope_parameters.attention_factor");
|
||||
vals.push_back(derived.c_str());
|
||||
}
|
||||
RadModelMeta view = *meta;
|
||||
view.n_kv = (int)keys.size();
|
||||
view.kv_key = keys.data();
|
||||
view.kv_val = vals.data();
|
||||
return yarn_from(g, &view, "", g.head_dim);
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->max_seqs <= 0) 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;
|
||||
}
|
||||
if (ctx->max_audio_frames > 0) {
|
||||
std::fprintf(stderr, "radiance: nemotron35_embed does not serve audio\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (ctx->max_ctx <= 0 || ctx->max_ctx > 32768) {
|
||||
std::fprintf(
|
||||
stderr,
|
||||
"radiance: nemotron35_embed: the embedding limit is 32768 tokens; set --max-model-len 32768 or lower\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (std::strcmp(rad_meta_gets(meta, "model_type", ""), "mistral3") ||
|
||||
std::strcmp(rad_meta_gets(meta, "text_config.model_type", ""), "ministral3") ||
|
||||
!false_value(rad_meta_gets(meta, "is_causal", nullptr)) ||
|
||||
!false_value(rad_meta_gets(meta, "text_config.is_causal", nullptr)) ||
|
||||
std::strcmp(rad_meta_gets(meta, "text_config.hidden_act", ""), "silu") ||
|
||||
(meta->quant && *meta->quant))
|
||||
return RAD_E_UNSUPPORTED;
|
||||
const char* window = rad_meta_gets(meta, "text_config.sliding_window", nullptr);
|
||||
if (window && std::strcmp(window, "null") && std::strcmp(window, "0")) return RAD_E_UNSUPPORTED;
|
||||
const double beta =
|
||||
rad_meta_getf(meta, "text_config.rope_parameters.llama_4_scaling_beta", NAN);
|
||||
const int64_t original =
|
||||
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;
|
||||
m.rerank =
|
||||
!std::strcmp(rad_meta_gets(meta, "architectures", ""), "Mistral3ForSequenceClassification");
|
||||
const char* architecture = rad_meta_gets(meta, "architectures", "");
|
||||
if (*architecture && !m.rerank && std::strcmp(architecture, "Mistral3Model"))
|
||||
return RAD_E_UNSUPPORTED;
|
||||
if (m.rerank && (std::strcmp(rad_meta_gets(meta, "pooling", ""), "avg") ||
|
||||
std::strcmp(rad_meta_gets(meta, "text_config.pooling", ""), "avg")))
|
||||
return RAD_E_UNSUPPORTED;
|
||||
m.nm = Names(ctx->scope);
|
||||
// The classifier wrapper prefixes the backbone with model.; its score head stays at root.
|
||||
m.source = Names(m.rerank ? "model" : "");
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
Names& source = m.source;
|
||||
if (g.n_head_kv <= 0 || g.n_head % g.n_head_kv || g.head_dim % 2) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(read_rope(g, meta));
|
||||
const int64_t T = g.max_tok, E = g.n_embd, Q = g.q_dim(), K = g.kv_dim(), F = g.n_ff;
|
||||
m.x = decl_b(b, nm.f("x"), RAD_BF16, {T, E});
|
||||
m.h = decl_b(b, nm.f("h"), RAD_BF16, {T, E});
|
||||
m.qkv = decl_b(b, nm.f("qkv"), RAD_BF16, {T, Q + 2 * K});
|
||||
m.attn = decl_b(b, nm.f("attn"), RAD_BF16, {T, Q});
|
||||
m.o = decl_b(b, nm.f("o"), RAD_BF16, {T, E});
|
||||
m.gu = decl_b(b, nm.f("gate_up"), RAD_BF16, {T, 2 * F});
|
||||
m.ff = decl_b(b, nm.f("ff"), RAD_BF16, {T, F});
|
||||
m.mean = decl_b(b, nm.f("mean"), RAD_BF16, {g.max_seqs, E});
|
||||
m.pooled = decl_b(b, nm.f("pooled"), RAD_F32, {g.max_seqs, m.rerank ? 1 : E}, RAD_BUF_PERSIST);
|
||||
RAD_ARCH_TRY(rad_declare_pooled(b, m.pooled));
|
||||
auto weight = [&](const char* dest, const char* src, std::initializer_list<int64_t> shape,
|
||||
RadWeightGroup group) {
|
||||
if (map_copy(b, dest, src) < 0) return rad_weight(0);
|
||||
return decl_w(b, dest, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, group);
|
||||
};
|
||||
auto gemm = [&](int64_t N, int64_t kk, rad_weight w) {
|
||||
return RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("N", N), RAD_INT("K", kk),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto rms = [&] {
|
||||
// Ministral rounds the weightless norm before multiplying by the BF16 gain.
|
||||
return RAD_OP(b, "rmsnorm_p",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_F64("eps", g.eps),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
auto gain = [&](rad_weight w) {
|
||||
return RAD_OP(b, "mul_weight",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto add = [&] {
|
||||
return RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
RAD_ARCH_TRY(
|
||||
map_copy(b, nm.f("token_embd.weight"), source.f("language_model.embed_tokens.weight")));
|
||||
m.tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, E}, RAD_ACCESS_VOCAB,
|
||||
RAD_SHARD_NONE, grp_model());
|
||||
m.norm = weight(nm.f("output_norm.weight"), source.f("language_model.norm.weight"), {E},
|
||||
grp_model());
|
||||
m.embed = rw(b,
|
||||
RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(m.tok)),
|
||||
{}, {m.x});
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
for (int64_t i = 0; i < g.n_layer; ++i) {
|
||||
Layer& l = m.layers[(size_t)i];
|
||||
const auto group = grp_layer((int)i);
|
||||
const auto n = (long long)i;
|
||||
l.norm =
|
||||
weight(nm.f("blk.%lld.attn_norm.weight", n),
|
||||
source.f("language_model.layers.%lld.input_layernorm.weight", n), {E}, group);
|
||||
l.ff_norm = weight(
|
||||
nm.f("blk.%lld.ffn_norm.weight", n),
|
||||
source.f("language_model.layers.%lld.post_attention_layernorm.weight", n), {E}, group);
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.qkv.weight", n),
|
||||
{source.f("language_model.layers.%lld.self_attn.q_proj.weight", n),
|
||||
source.f("language_model.layers.%lld.self_attn.k_proj.weight", n),
|
||||
source.f("language_model.layers.%lld.self_attn.v_proj.weight", n)},
|
||||
0));
|
||||
l.qkv = decl_w(b, nm.f("blk.%lld.qkv.weight", n), RAD_BF16, {Q + 2 * K, E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, group);
|
||||
l.out = weight(nm.f("blk.%lld.attn_o.weight", n),
|
||||
source.f("language_model.layers.%lld.self_attn.o_proj.weight", n), {E, Q},
|
||||
group);
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.gate_up.weight", n),
|
||||
{source.f("language_model.layers.%lld.mlp.gate_proj.weight", n),
|
||||
source.f("language_model.layers.%lld.mlp.up_proj.weight", n)},
|
||||
0));
|
||||
l.gate_up = decl_w(b, nm.f("blk.%lld.gate_up.weight", n), RAD_BF16, {2 * F, E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, group);
|
||||
l.down =
|
||||
weight(nm.f("blk.%lld.ffn_down.weight", n),
|
||||
source.f("language_model.layers.%lld.mlp.down_proj.weight", n), {E, F}, group);
|
||||
l.in_norm = rw(b, rms(), {m.x}, {m.h});
|
||||
l.in_gain = rw(b, gain(l.norm), {m.h}, {m.h});
|
||||
l.project = rw(b, gemm(Q + 2 * K, E, l.qkv), {m.h}, {m.qkv});
|
||||
l.rope = rw(
|
||||
b,
|
||||
decl_rotary(b, g, "ministral_rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.qkv}, {m.qkv});
|
||||
l.qscale = rw(
|
||||
b,
|
||||
RAD_OP(b, "position_scale",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", Q), RAD_INT("original", original),
|
||||
RAD_F64("beta", beta), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.qkv}, {m.qkv});
|
||||
l.attn = rw(b,
|
||||
RAD_OP(b, "embed_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 0),
|
||||
RAD_INT("max_seqlen", std::min(T, g.max_ctx)),
|
||||
RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)g.head_dim))),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.qkv}, {m.attn});
|
||||
l.output = rw(b, gemm(E, Q, l.out), {m.attn}, {m.o});
|
||||
l.add_attn = rw(b, add(), {m.x, m.o}, {m.x});
|
||||
l.pre_ff = rw(b, rms(), {m.x}, {m.h});
|
||||
l.ff_gain = rw(b, gain(l.ff_norm), {m.h}, {m.h});
|
||||
l.gate = rw(b, gemm(2 * F, E, l.gate_up), {m.h}, {m.gu});
|
||||
l.act =
|
||||
rw(b,
|
||||
RAD_OP(b, "silu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", F), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.gu}, {m.gu});
|
||||
l.gate_mul =
|
||||
rw(b,
|
||||
RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", F), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.gu}, {m.ff});
|
||||
l.ffn = rw(b, gemm(E, F, l.down), {m.ff}, {m.o});
|
||||
l.add_ff = rw(b, add(), {m.x, m.o}, {m.x});
|
||||
}
|
||||
m.final_norm = rw(b, rms(), {m.x}, {m.h});
|
||||
m.final_gain = rw(b, gain(m.norm), {m.h}, {m.h});
|
||||
m.pool = rw(b,
|
||||
RAD_OP(b, m.rerank ? "seg_mean_bf16_sum" : "seg_mean",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.h}, {m.mean});
|
||||
if (m.rerank) {
|
||||
m.score = weight(nm.f("score.weight"), nm.ckpt("language_model.score.weight"), {1, E},
|
||||
grp_model());
|
||||
m.head = rw(b,
|
||||
RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n_vocab", 1),
|
||||
RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(m.score)),
|
||||
{m.mean}, {m.pooled});
|
||||
} else {
|
||||
m.cast = rw(b,
|
||||
RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", E),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.mean}, {m.pooled});
|
||||
}
|
||||
/* Recipes may quantise weights without changing the architecture descriptor. Do not read an
|
||||
* INT8 plane with a BF16-only graph, even when a container still advertises quant="". */
|
||||
const RadEncoding plain = rad_enc_plain(RAD_BF16);
|
||||
auto bf16_only = [&](const char* name) -> int {
|
||||
RadEncoding enc{};
|
||||
const int rc = rad_weight_encoding(b, name, &enc, nullptr, nullptr);
|
||||
if (rc == RAD_E_NOTFOUND) return RAD_OK; // conversion has not populated the encoding yet
|
||||
if (rc < 0) return rc;
|
||||
if (rad_enc_equal(&enc, &plain)) return RAD_OK;
|
||||
std::fprintf(
|
||||
stderr,
|
||||
"radiance: nemotron35_embed requires BF16 weight '%s'; quantised linears are not implemented yet\n",
|
||||
name);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
};
|
||||
RAD_ARCH_TRY(bf16_only(nm.f("token_embd.weight")));
|
||||
RAD_ARCH_TRY(bf16_only(nm.f("output_norm.weight")));
|
||||
if (m.rerank)
|
||||
RAD_ARCH_TRY(bf16_only(nm.f("score.weight")));
|
||||
for (int64_t i = 0; i < g.n_layer; ++i)
|
||||
for (const char* suffix : {"attn_norm", "ffn_norm", "qkv", "attn_o", "gate_up", "ffn_down"})
|
||||
RAD_ARCH_TRY(bf16_only(nm.f("blk.%lld.%s.weight", (long long)i, suffix)));
|
||||
RAD_ARCH_TRY(m.vision.declare(b, meta, ctx, nm, source, E, (int)g.n_layer));
|
||||
if (m.vision.on)
|
||||
m.inject =
|
||||
rw(b,
|
||||
RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.x}, {m.x});
|
||||
if (m.rerank)
|
||||
rad_note(b,
|
||||
"Nemotron-3.5-Rerank: BF16 bidirectional query/document scoring, TP1; "
|
||||
"BF16 sum/division, FP32 score; Pixtral encoder %s",
|
||||
m.vision.on ? "on" : "off");
|
||||
else
|
||||
rad_note(
|
||||
b,
|
||||
"Nemotron-3.5-Embed: BF16 bidirectional embeddings, TP1; mean-pooled to %lld; Pixtral encoder %s",
|
||||
(long long)E, m.vision.on ? "on" : "off");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
if (!std::strcmp(rad_meta_gets(meta, "vision_config.model_type", ""), "pixtral")) {
|
||||
if (rad_meta_geti(meta, "spatial_merge_size", 0) != 2) return RAD_E_UNSUPPORTED;
|
||||
out->enc_merge = 4;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = model;
|
||||
const Geom& g = m.g;
|
||||
if (batch->enc) {
|
||||
m.vision.step(c, batch);
|
||||
return;
|
||||
}
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq, Q = g.q_dim(), K = g.kv_dim();
|
||||
if (batch->phase != RAD_PHASE_PREFILL || T <= 0 || T > g.max_tok || S <= 0 || S > g.max_seqs ||
|
||||
batch->max_q_len > g.max_ctx || !batch->token_ids || !batch->positions ||
|
||||
!batch->cu_seqlens) {
|
||||
rad_step_fail(
|
||||
c,
|
||||
"nemotron35_embed: expected whole text inputs within the declared token/context bounds");
|
||||
return;
|
||||
}
|
||||
if (batch->n_mm_rows < 0 || batch->n_mm_rows > T ||
|
||||
(batch->n_mm_rows && (!m.inject || !batch->mm_rows || !batch->mm_embd))) {
|
||||
rad_step_fail(
|
||||
c,
|
||||
"nemotron35_embed: image rows require a declared Pixtral encoder and valid row data");
|
||||
return;
|
||||
}
|
||||
const auto pos = praw(batch->positions, RAD_I32, T),
|
||||
cu = praw(batch->cu_seqlens, RAD_I32, S + 1);
|
||||
RAD_ISSUE(c, m.embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.tok), brows(m.x, T));
|
||||
if (batch->n_mm_rows)
|
||||
RAD_ISSUE_N(c, m.inject, batch->n_mm_rows,
|
||||
praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, g.n_embd),
|
||||
praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.x, T));
|
||||
for (const Layer& l : m.layers) {
|
||||
RAD_ISSUE(c, l.in_norm, brows(m.x, T), brows(m.h, T));
|
||||
RAD_ISSUE(c, l.in_gain, brows(m.h, T), RAD_W(l.norm), brows(m.h, T));
|
||||
RAD_ISSUE(c, l.project, brows(m.h, T), RAD_W(l.qkv), brows(m.qkv, T));
|
||||
RAD_ISSUE(c, l.rope, brows(m.qkv, T), pos);
|
||||
RAD_ISSUE(c, l.qscale, bcol(m.qkv, 0, Q, T), pos);
|
||||
RAD_ISSUE(c, l.attn, bcol(m.qkv, 0, Q, T), bcol(m.qkv, Q, K, T), bcol(m.qkv, Q + K, K, T),
|
||||
cu, brows(m.attn, T));
|
||||
RAD_ISSUE(c, l.output, brows(m.attn, T), RAD_W(l.out), brows(m.o, T));
|
||||
RAD_ISSUE(c, l.add_attn, brows(m.x, T), brows(m.o, T), brows(m.x, T));
|
||||
RAD_ISSUE(c, l.pre_ff, brows(m.x, T), brows(m.h, T));
|
||||
RAD_ISSUE(c, l.ff_gain, brows(m.h, T), RAD_W(l.ff_norm), brows(m.h, T));
|
||||
RAD_ISSUE(c, l.gate, brows(m.h, T), RAD_W(l.gate_up), brows(m.gu, T));
|
||||
RAD_ISSUE(c, l.act, bcol(m.gu, 0, g.n_ff, T), bcol(m.gu, 0, g.n_ff, T));
|
||||
RAD_ISSUE(c, l.gate_mul, bcol(m.gu, 0, g.n_ff, T), bcol(m.gu, g.n_ff, g.n_ff, T),
|
||||
brows(m.ff, T));
|
||||
RAD_ISSUE(c, l.ffn, brows(m.ff, T), RAD_W(l.down), brows(m.o, T));
|
||||
RAD_ISSUE(c, l.add_ff, brows(m.x, T), brows(m.o, T), brows(m.x, T));
|
||||
}
|
||||
RAD_ISSUE(c, m.final_norm, brows(m.x, T), brows(m.h, T));
|
||||
RAD_ISSUE(c, m.final_gain, brows(m.h, T), RAD_W(m.norm), brows(m.h, T));
|
||||
RAD_ISSUE(c, m.pool, brows(m.h, T), cu, brows(m.mean, S));
|
||||
if (m.rerank)
|
||||
RAD_ISSUE_N(c, m.head, S, brows(m.mean, S), RAD_W(m.score), brows(m.pooled, S));
|
||||
else
|
||||
RAD_ISSUE_N(c, m.cast, S, brows(m.mean, S), brows(m.pooled, S));
|
||||
}
|
||||
} // namespace nemotron35_embed
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
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)
|
||||
#endif
|
||||
@@ -0,0 +1,304 @@
|
||||
/* Nemotron 3.5's Pixtral tower and Mistral3 projector, BF16 at TP1.
|
||||
* The processor supplies complete raster grids. Image/text prompt integration is a separate
|
||||
* acceptance gate: a working encoder pass alone does not make image embeddings serviceable. */
|
||||
#pragma once
|
||||
#include <arch/rad_arch.h>
|
||||
|
||||
namespace nemotron35_embed {
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Pixtral {
|
||||
struct Norm {
|
||||
rad_weight w = 0;
|
||||
rad_op rms = 0, gain = 0;
|
||||
};
|
||||
struct Layer {
|
||||
Norm n1, n2;
|
||||
rad_weight qkv = 0, out = 0, gu = 0, down = 0;
|
||||
rad_op project = 0, rope = 0, attn = 0, output = 0, add1 = 0;
|
||||
rad_op gate = 0, act = 0, gate_mul = 0, ffn = 0, add2 = 0;
|
||||
};
|
||||
bool on = false;
|
||||
int64_t P = 0, width = 0, heads = 0, hd = 0, ff = 0, depth = 0, patch_dim = 0;
|
||||
int64_t merge = 0, embd = 0, max_grid = 0;
|
||||
rad_buf x = 0, h = 0, qkv = 0, att = 0, o = 0, gu = 0, ffn = 0, packed = 0, merged = 0,
|
||||
proj = 0, out = 0;
|
||||
rad_weight patch = 0, merger = 0, linear1 = 0, linear2 = 0;
|
||||
rad_op stem = 0, pack = 0, merge_op = 0, project1 = 0, gelu = 0, project2 = 0;
|
||||
Norm pre, post;
|
||||
std::vector<Layer> layers;
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, Names& nm,
|
||||
Names& source, int64_t output_width, int first_group) {
|
||||
on = false;
|
||||
if (ctx->max_enc_patches <= 0) return RAD_OK;
|
||||
auto vi = [&](const char* k) {
|
||||
return rad_meta_geti(meta, (std::string("vision_config.") + k).c_str(), 0);
|
||||
};
|
||||
const char* bias = rad_meta_gets(meta, "multimodal_projector_bias", "");
|
||||
if (std::strcmp(rad_meta_gets(meta, "vision_config.model_type", ""), "pixtral") ||
|
||||
std::strcmp(rad_meta_gets(meta, "vision_config.hidden_act", ""), "silu") ||
|
||||
std::strcmp(rad_meta_gets(meta, "projector_hidden_act", ""), "gelu") ||
|
||||
(std::strcmp(bias, "0") && std::strcmp(bias, "false")) ||
|
||||
rad_meta_geti(meta, "vision_feature_layer", 0) != -1)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
const char* rope = rad_meta_gets(meta, "vision_config.rope_parameters.rope_type", "");
|
||||
/* This checkpoint saves `default`; PixtralVisionConfig interprets it as axial. */
|
||||
if (std::strcmp(rope, "default") && std::strcmp(rope, "axial")) return RAD_E_UNSUPPORTED;
|
||||
width = vi("hidden_size");
|
||||
heads = vi("num_attention_heads");
|
||||
ff = vi("intermediate_size");
|
||||
depth = vi("num_hidden_layers");
|
||||
const int64_t ps = vi("patch_size"), channels = vi("num_channels"),
|
||||
image_size = vi("image_size");
|
||||
merge = rad_meta_geti(meta, "spatial_merge_size", 0);
|
||||
embd = output_width;
|
||||
const double theta = rad_meta_getf(meta, "vision_config.rope_parameters.rope_theta", 0);
|
||||
const double eps = meta->rms_eps;
|
||||
if (width <= 0 || heads <= 0 || width % heads || (width / heads) % 4 || ff <= 0 ||
|
||||
depth <= 0 || ps <= 0 || channels != 3 || merge != 2 || embd <= 0 || image_size < ps ||
|
||||
!(theta > 0) || !std::isfinite(theta) || !(eps > 0) || !std::isfinite(eps))
|
||||
return RAD_E_INVAL;
|
||||
hd = width / heads;
|
||||
patch_dim = channels * ps * ps;
|
||||
max_grid = image_size / ps;
|
||||
if (vi("head_dim") && vi("head_dim") != hd) return RAD_E_INVAL;
|
||||
const int64_t mm = merge * merge, max_seg = ctx->max_enc_patches;
|
||||
P = max_seg;
|
||||
if (P % mm) return RAD_E_SHAPE;
|
||||
if (ctx->shape_probe) P = std::max(mm, std::min(P, ctx->max_tok) / mm * mm);
|
||||
if (P < mm) return RAD_E_INVAL;
|
||||
const int64_t R = P / mm;
|
||||
auto buf = [&](const char* name, int64_t rows, int64_t cols, uint32_t flags = 0) {
|
||||
return decl_b(b, nm.f("v.%s", name), RAD_BF16, {rows, cols}, flags);
|
||||
};
|
||||
x = buf("x", P, width);
|
||||
h = buf("h", P, width);
|
||||
qkv = buf("qkv", P, 3 * width);
|
||||
att = buf("attn", P, width);
|
||||
o = buf("o", P, width);
|
||||
gu = buf("gate_up", P, 2 * ff);
|
||||
ffn = buf("ff", P, ff);
|
||||
packed = buf("packed", R, mm * width);
|
||||
merged = buf("merged", R, width);
|
||||
proj = buf("proj", R, embd);
|
||||
out = buf("out", R, embd, RAD_BUF_PERSIST);
|
||||
auto weight = [&](const char* dest, const char* src, std::initializer_list<int64_t> shape,
|
||||
RadWeightGroup group) {
|
||||
if (map_copy(b, dest, src) < 0) return rad_weight(0);
|
||||
return decl_w(b, dest, RAD_BF16, shape, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, group);
|
||||
};
|
||||
auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) {
|
||||
return RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto norm = [&](Norm& n, const char* dest, const char* src, RadWeightGroup group, double e,
|
||||
rad_buf from, rad_buf to) {
|
||||
n.w = weight(dest, src, {width}, group);
|
||||
/* The reference narrows the weightless norm before multiplying by the BF16 gain. */
|
||||
n.rms = rw(b,
|
||||
RAD_OP(b, "rmsnorm_p",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_F64("eps", e), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{from}, {to});
|
||||
n.gain = rw(b,
|
||||
RAD_OP(b, "mul_weight",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(n.w)),
|
||||
{to}, {to});
|
||||
};
|
||||
auto add = [&] {
|
||||
return RAD_OP(
|
||||
b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
patch = weight(nm.f("v.patch.weight"), source.f("vision_tower.patch_conv.weight"),
|
||||
{width, patch_dim}, grp_model());
|
||||
stem = rw(b, gemm(P, width, patch_dim, patch), {}, {x});
|
||||
norm(pre, nm.f("v.pre.weight"), source.f("vision_tower.ln_pre.weight"), grp_model(), 1e-5,
|
||||
x, x);
|
||||
layers.resize((size_t)depth);
|
||||
for (int64_t i = 0; i < depth; ++i) {
|
||||
auto& l = layers[(size_t)i];
|
||||
const long long li = i;
|
||||
const auto group = grp_layer(first_group + (int)i);
|
||||
norm(l.n1, nm.f("v.blk.%lld.n1.weight", li),
|
||||
source.f("vision_tower.transformer.layers.%lld.attention_norm.weight", li), group,
|
||||
1e-5, x, h);
|
||||
norm(l.n2, nm.f("v.blk.%lld.n2.weight", li),
|
||||
source.f("vision_tower.transformer.layers.%lld.ffn_norm.weight", li), group, 1e-5,
|
||||
x, h);
|
||||
RAD_ARCH_TRY(map_concat(
|
||||
b, nm.f("v.blk.%lld.qkv.weight", li),
|
||||
{source.f("vision_tower.transformer.layers.%lld.attention.q_proj.weight", li),
|
||||
source.f("vision_tower.transformer.layers.%lld.attention.k_proj.weight", li),
|
||||
source.f("vision_tower.transformer.layers.%lld.attention.v_proj.weight", li)},
|
||||
0));
|
||||
l.qkv = decl_w(b, nm.f("v.blk.%lld.qkv.weight", li), RAD_BF16, {3 * width, width},
|
||||
RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, group);
|
||||
l.out =
|
||||
weight(nm.f("v.blk.%lld.out.weight", li),
|
||||
source.f("vision_tower.transformer.layers.%lld.attention.o_proj.weight", li),
|
||||
{width, width}, group);
|
||||
RAD_ARCH_TRY(map_concat(
|
||||
b, nm.f("v.blk.%lld.gate_up.weight", li),
|
||||
{source.f("vision_tower.transformer.layers.%lld.feed_forward.gate_proj.weight", li),
|
||||
source.f("vision_tower.transformer.layers.%lld.feed_forward.up_proj.weight", li)},
|
||||
0));
|
||||
l.gu = decl_w(b, nm.f("v.blk.%lld.gate_up.weight", li), RAD_BF16, {2 * ff, width},
|
||||
RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, group);
|
||||
l.down = weight(
|
||||
nm.f("v.blk.%lld.down.weight", li),
|
||||
source.f("vision_tower.transformer.layers.%lld.feed_forward.down_proj.weight", li),
|
||||
{width, ff}, group);
|
||||
l.project = rw(b, gemm(P, 3 * width, width, l.qkv), {h}, {qkv});
|
||||
l.rope = rw(b,
|
||||
RAD_OP(b, "pixtral_rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd),
|
||||
RAD_INT("n_head", heads), RAD_F64("theta", theta),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{qkv}, {qkv});
|
||||
l.attn = rw(
|
||||
b,
|
||||
RAD_OP(b, "embed_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd), RAD_INT("gqa", 1),
|
||||
RAD_INT("causal", 0), RAD_INT("max_seqlen", max_seg),
|
||||
RAD_F64("scale", 1 / std::sqrt((double)hd)),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{qkv}, {att});
|
||||
l.output = rw(b, gemm(P, width, width, l.out), {att}, {o});
|
||||
l.add1 = rw(b, add(), {x, o}, {x});
|
||||
l.gate = rw(b, gemm(P, 2 * ff, width, l.gu), {h}, {gu});
|
||||
l.act = rw(
|
||||
b,
|
||||
RAD_OP(b, "silu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", ff), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{gu}, {gu});
|
||||
l.gate_mul = rw(
|
||||
b,
|
||||
RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", ff), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{gu}, {ffn});
|
||||
l.ffn = rw(b, gemm(P, width, ff, l.down), {ffn}, {o});
|
||||
l.add2 = rw(b, add(), {x, o}, {x});
|
||||
}
|
||||
norm(post, nm.f("v.post.weight"), source.f("multi_modal_projector.norm.weight"),
|
||||
grp_model(), eps, x, h);
|
||||
merger = weight(nm.f("v.merger.weight"),
|
||||
source.f("multi_modal_projector.patch_merger.merging_layer.weight"),
|
||||
{width, mm * width}, grp_model());
|
||||
linear1 =
|
||||
weight(nm.f("v.linear1.weight"), source.f("multi_modal_projector.linear_1.weight"),
|
||||
{embd, width}, grp_model());
|
||||
linear2 =
|
||||
weight(nm.f("v.linear2.weight"), source.f("multi_modal_projector.linear_2.weight"),
|
||||
{embd, embd}, grp_model());
|
||||
pack = rw(b,
|
||||
RAD_OP(b, "pixtral_merge",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_INT("merge", merge), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{h}, {packed});
|
||||
merge_op = rw(b, gemm(R, width, mm * width, merger), {packed}, {merged});
|
||||
project1 = rw(b, gemm(R, embd, width, linear1), {merged}, {proj});
|
||||
gelu = rw(
|
||||
b,
|
||||
RAD_OP(b, "gelu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", embd), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{proj}, {proj});
|
||||
project2 = rw(b, gemm(R, embd, embd, linear2), {proj}, {out});
|
||||
const RadEncoding plain = rad_enc_plain(RAD_BF16);
|
||||
auto bf16_only = [&](const char* name) -> int {
|
||||
RadEncoding enc{};
|
||||
const int rc = rad_weight_encoding(b, name, &enc, nullptr, nullptr);
|
||||
if (rc == RAD_E_NOTFOUND) return RAD_OK;
|
||||
if (rc < 0) return rc;
|
||||
return rad_enc_equal(&enc, &plain) ? RAD_OK : RAD_E_UNSUPPORTED;
|
||||
};
|
||||
for (const char* name : {"patch", "pre", "post", "merger", "linear1", "linear2"})
|
||||
RAD_ARCH_TRY(bf16_only(nm.f("v.%s.weight", name)));
|
||||
for (int64_t i = 0; i < depth; ++i)
|
||||
for (const char* name : {"n1", "n2", "qkv", "out", "gate_up", "down"})
|
||||
RAD_ARCH_TRY(bf16_only(nm.f("v.blk.%lld.%s.weight", (long long)i, name)));
|
||||
if (!ctx->shape_probe) {
|
||||
RadEncoderDecl e{};
|
||||
e.name = "vision";
|
||||
e.modalities = RAD_MM_IMAGE;
|
||||
e.patch_dim = patch_dim;
|
||||
e.merge = mm;
|
||||
e.max_patches = P;
|
||||
e.n_embd = embd;
|
||||
e.out = out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
}
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t n = batch->enc_n_patch, s = batch->enc_n_seg, mm = merge * merge;
|
||||
if (!on || batch->enc != RAD_MM_IMAGE || n <= 0 || n > P || n % mm || s <= 0 ||
|
||||
s > n / mm || batch->enc_max_seg <= 0 || batch->enc_max_seg > P || !batch->enc_pixels ||
|
||||
!batch->enc_coord || !batch->enc_cu || !batch->enc_seg_h || !batch->enc_seg_w) {
|
||||
rad_step_fail(c, "nemotron35_embed: invalid Pixtral encoder pass");
|
||||
return;
|
||||
}
|
||||
int64_t total = 0;
|
||||
for (int64_t i = 0; i < s; ++i) {
|
||||
const int64_t hh = batch->enc_seg_h[i], ww = batch->enc_seg_w[i];
|
||||
if (hh <= 0 || ww <= 0 || hh % merge || ww % merge || hh > max_grid || ww > max_grid ||
|
||||
hh * ww > batch->enc_max_seg || hh * ww > n - total) {
|
||||
rad_step_fail(c, "nemotron35_embed: Pixtral expects complete even raster grids");
|
||||
return;
|
||||
}
|
||||
total += hh * ww;
|
||||
}
|
||||
if (total != n) {
|
||||
rad_step_fail(c, "nemotron35_embed: Pixtral grid sizes disagree with patches");
|
||||
return;
|
||||
}
|
||||
const int64_t r = n / mm;
|
||||
const auto coord = praw2(batch->enc_coord, RAD_I32, 2, n),
|
||||
cu = praw(batch->enc_cu, RAD_I32, s + 1);
|
||||
auto norm = [&](const Norm& nrm, rad_buf from, rad_buf to) {
|
||||
RAD_ISSUE_N(c, nrm.rms, n, brows(from, n), brows(to, n));
|
||||
RAD_ISSUE_N(c, nrm.gain, n, brows(to, n), RAD_W(nrm.w), brows(to, n));
|
||||
};
|
||||
RAD_ISSUE_N(c, stem, n, praw2(batch->enc_pixels, RAD_BF16, n, patch_dim), RAD_W(patch),
|
||||
brows(x, n));
|
||||
norm(pre, x, x);
|
||||
for (const auto& l : layers) {
|
||||
norm(l.n1, x, h);
|
||||
RAD_ISSUE_N(c, l.project, n, brows(h, n), RAD_W(l.qkv), brows(qkv, n));
|
||||
RAD_ISSUE_N(c, l.rope, n, brows(qkv, n), coord);
|
||||
RAD_ISSUE_N(c, l.attn, n, bcol(qkv, 0, width, n), bcol(qkv, width, width, n),
|
||||
bcol(qkv, 2 * width, width, n), cu, brows(att, n));
|
||||
RAD_ISSUE_N(c, l.output, n, brows(att, n), RAD_W(l.out), brows(o, n));
|
||||
RAD_ISSUE_N(c, l.add1, n, brows(x, n), brows(o, n), brows(x, n));
|
||||
norm(l.n2, x, h);
|
||||
RAD_ISSUE_N(c, l.gate, n, brows(h, n), RAD_W(l.gu), brows(gu, n));
|
||||
RAD_ISSUE_N(c, l.act, n, bcol(gu, 0, ff, n), bcol(gu, 0, ff, n));
|
||||
RAD_ISSUE_N(c, l.gate_mul, n, bcol(gu, 0, ff, n), bcol(gu, ff, ff, n), brows(ffn, n));
|
||||
RAD_ISSUE_N(c, l.ffn, n, brows(ffn, n), RAD_W(l.down), brows(o, n));
|
||||
RAD_ISSUE_N(c, l.add2, n, brows(x, n), brows(o, n), brows(x, n));
|
||||
}
|
||||
norm(post, x, h);
|
||||
RAD_ISSUE_N(c, pack, n, brows(h, n), praw2(batch->enc_coord, RAD_I32, 4, n),
|
||||
brows(packed, r));
|
||||
RAD_ISSUE_N(c, merge_op, r, brows(packed, r), RAD_W(merger), brows(merged, r));
|
||||
RAD_ISSUE_N(c, project1, r, brows(merged, r), RAD_W(linear1), brows(proj, r));
|
||||
RAD_ISSUE_N(c, gelu, r, brows(proj, r), brows(proj, r));
|
||||
RAD_ISSUE_N(c, project2, r, brows(proj, r), RAD_W(linear2), brows(out, r));
|
||||
}
|
||||
};
|
||||
} // namespace nemotron35_embed
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/nomicbert -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(nomicbert LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(nomicbert architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/nomicbert.cpp)
|
||||
@@ -0,0 +1,508 @@
|
||||
/* nomicbert -- Nomic BERT (model_type nomic_bert), the encoder behind nomic-embed-text-v2-moe.
|
||||
* bf16 weights and activations, with f32 norms and biases.
|
||||
*
|
||||
* An embedding model: it declares a pooled output (rad_declare_pooled) and no logits, so the
|
||||
* engine runs it with no sampler and no KV cache, carries every input whole in one step, and
|
||||
* returns each sequence's pooled row. Attention is bidirectional on every layer, so nothing is
|
||||
* paged: a token attends to later tokens, and there is nothing to carry between steps.
|
||||
*
|
||||
* Shape:
|
||||
*
|
||||
* 12 layers, hidden 768, 12 heads of 64, ffn 3072, vocab 250048, type vocab 1
|
||||
* post-norm block, the config's `prenorm: false`:
|
||||
* a = out_proj(attn(rope(Wqkv h + b))) + b_out; h = LN1(h + a)
|
||||
* dense layer: m = fc2(gelu(fc1 h + b1)) + b2; h = LN2(h + m)
|
||||
* MoE layer (every second, moe_every_n_layers 2): router top-2 over eight experts, no
|
||||
* renormalisation, no shared bias; h = LN2(h + moe(h))
|
||||
* fused Wqkv [q|k|v], no GQA, non-causal, scale 1/sqrt(64) = 0.125
|
||||
* NeoX rotary over all 64 dimensions, theta 1e4, on q and k only, no position table
|
||||
* embeddings: word + token_type, then emb_ln; no final norm and no pooler tensor
|
||||
* output: the mean of every real token, then cast to the f32 pooled buffer
|
||||
*
|
||||
* The expert tables are one concatenated tensor each: w1 [8 * 3072, 768] as [out, in], w2
|
||||
* [8 * 3072, 768] as [in, out] per expert, so w2 is sliced, then transposed (RAD_MAP_TRANSPOSE
|
||||
* with src_index and src_rows). Every expert's two tensors take distinct group slots.
|
||||
*
|
||||
* The block order and the omitted shared bias match llama.cpp's embedder for this model
|
||||
* (post-norm, no expert bias). The checkpoint's `experts.bias` tensors are not declared and stay
|
||||
* unconverted.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace nomicbert {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
/* Post-norm: attention on the raw stream, then LN1, then the feed-forward on LN1's output, then
|
||||
* LN2 over that output plus the feed-forward's. */
|
||||
|
||||
struct Layer {
|
||||
bool moe = false;
|
||||
rad_weight w_norm1 = 0, b_norm1 = 0, w_qkv = 0, b_qkv = 0, w_out = 0, b_out = 0;
|
||||
rad_weight w_norm2 = 0, b_norm2 = 0;
|
||||
rad_weight w_fc1 = 0, b_fc1 = 0, w_fc2 = 0, b_fc2 = 0;
|
||||
rad_weight w_router = 0;
|
||||
std::vector<rad_weight> w_w1, w_w2;
|
||||
|
||||
rad_op op_qkv = 0, op_rope = 0, op_attn = 0, op_out = 0, op_norm1 = 0, op_norm2 = 0;
|
||||
rad_op op_fc1 = 0, op_fc2 = 0;
|
||||
rad_op op_router = 0, op_topk = 0, op_scatter = 0, op_egu = 0, op_gelu = 0, op_edn = 0;
|
||||
rad_op op_gather = 0, op_add = 0;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{};
|
||||
int64_t n_expert = 0, n_expert_used = 0, n_type = 1;
|
||||
|
||||
rad_buf b_x = 0, b_h = 0, b_o = 0, b_qkv = 0, b_att = 0, b_ff = 0;
|
||||
rad_buf b_egu = 0, b_eact = 0, b_edn = 0, b_emoe = 0;
|
||||
rad_buf b_logits = 0, b_ids = 0, b_ew = 0, b_sorted = 0, b_eoff = 0, b_ecnt = 0;
|
||||
rad_buf b_mean = 0, b_pooled = 0;
|
||||
|
||||
rad_weight w_tok = 0, w_type = 0, w_emb_ln = 0, b_emb_ln = 0;
|
||||
rad_op op_embed = 0, op_type = 0, op_emb_ln = 0, op_mean = 0, op_cast = 0;
|
||||
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
/* 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
|
||||
* (l + 1) % moe_every_n_layers == 0, as nomic's modeling_hf_nomic_bert builds it. */
|
||||
static bool is_moe_layer(int64_t l, int64_t every) {
|
||||
return every > 0 && (l + 1) % every == 0;
|
||||
}
|
||||
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->draft_depth = 0;
|
||||
const char* mt = rad_meta_gets(meta, "model_type", nullptr);
|
||||
if (mt && *mt && std::strcmp(mt, "nomic_bert") && std::strcmp(mt, "nomicbert")) {
|
||||
fprintf(stderr, "radiance: nomicbert: model_type '%s' is not nomic_bert\n", mt);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) 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) {
|
||||
fprintf(stderr, "radiance: nomicbert runs on one card (--tp 1); the model is 475M "
|
||||
"parameters\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
const int64_t T = g.max_tok, E = g.n_embd;
|
||||
|
||||
/* The variant flags this plugin does not serve, refused by name. */
|
||||
if (rad_meta_geti(meta, "prenorm", 0) != 0) {
|
||||
fprintf(stderr, "radiance: nomicbert: the container sets prenorm; this plugin declares "
|
||||
"the post-norm block\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (rad_meta_geti(meta, "causal", 0) != 0) {
|
||||
fprintf(stderr, "radiance: nomicbert: the container sets causal; this encoder attends "
|
||||
"over the whole input\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (rad_meta_geti(meta, "rotary_emb_interleaved", 0) != 0 ||
|
||||
rad_meta_getf(meta, "rotary_emb_fraction", 1.0) != 1.0 ||
|
||||
rad_meta_gets(meta, "rotary_emb_scale_base", nullptr) ||
|
||||
rad_meta_gets(meta, "rotary_scaling_factor", nullptr)) {
|
||||
fprintf(stderr, "radiance: nomicbert: this plugin serves NeoX rotary over the whole head, "
|
||||
"theta 1e4, with no scale base and no scaling factor\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const char* act = rad_meta_gets(meta, "activation_function", nullptr);
|
||||
if (act && *act && std::strcmp(act, "gelu")) {
|
||||
fprintf(stderr, "radiance: nomicbert: activation_function '%s'; this plugin serves exact "
|
||||
"gelu\n", act);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (rad_meta_geti(meta, "moe_normalize_expert_weights", 0) != 0) {
|
||||
fprintf(stderr, "radiance: nomicbert: moe_normalize_expert_weights is set; the router's "
|
||||
"top-k weights are used without renormalisation\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (rad_meta_geti(meta, "num_shared_experts", 0) != 0) {
|
||||
fprintf(stderr, "radiance: nomicbert: num_shared_experts is set; this checkpoint has no "
|
||||
"shared expert\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
m.n_expert = meta->n_expert;
|
||||
m.n_expert_used = meta->n_expert_used;
|
||||
m.n_type = rad_meta_geti(meta, "type_vocab_size", 1);
|
||||
const int64_t every = rad_meta_geti(meta, "moe_every_n_layers", 0);
|
||||
const bool any_moe = m.n_expert > 0;
|
||||
if ((g.n_layer <= 0) || (E <= 0) || (g.n_head <= 0) || (g.head_dim <= 0) ||
|
||||
(g.n_ff <= 0) || (g.n_vocab <= 0) || (g.n_head_kv != g.n_head) ||
|
||||
(g.head_dim * g.n_head != E)) {
|
||||
fprintf(stderr, "radiance: nomicbert: the container does not describe the model "
|
||||
"(layers %lld, hidden %lld, heads %lld of %lld, ffn %lld, vocab %lld)\n",
|
||||
(long long)g.n_layer, (long long)E, (long long)g.n_head,
|
||||
(long long)g.head_dim, (long long)g.n_ff, (long long)g.n_vocab);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (any_moe && (every <= 0 || m.n_expert_used <= 0 || m.n_expert_used > m.n_expert)) {
|
||||
fprintf(stderr, "radiance: nomicbert: %lld experts with top_k %lld and "
|
||||
"moe_every_n_layers %lld does not describe a routed layer\n",
|
||||
(long long)m.n_expert, (long long)m.n_expert_used, (long long)every);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (m.n_type != 1) {
|
||||
fprintf(stderr, "radiance: nomicbert: type_vocab_size %lld; this checkpoint carries one "
|
||||
"token-type row\n", (long long)m.n_type);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const int64_t K = m.n_expert_used;
|
||||
const int64_t P = T * K;
|
||||
|
||||
/* ---- activations. */
|
||||
m.b_x = decl_b(b, nm.f("x"), RAD_BF16, {T, E});
|
||||
m.b_h = decl_b(b, nm.f("h"), RAD_BF16, {T, E});
|
||||
m.b_o = decl_b(b, nm.f("o"), RAD_BF16, {T, E});
|
||||
m.b_qkv = decl_b(b, nm.f("qkv"), RAD_BF16, {T, 3 * E});
|
||||
m.b_att = decl_b(b, nm.f("attn"), RAD_BF16, {T, E});
|
||||
m.b_ff = decl_b(b, nm.f("ff"), RAD_BF16, {T, g.n_ff});
|
||||
if (any_moe) {
|
||||
m.b_egu = decl_b(b, nm.f("moe_egu"), RAD_BF16, {P, g.n_ff});
|
||||
m.b_eact = decl_b(b, nm.f("moe_eact"), RAD_BF16, {P, g.n_ff});
|
||||
m.b_edn = decl_b(b, nm.f("moe_edn"), RAD_BF16, {P, E});
|
||||
m.b_emoe = decl_b(b, nm.f("moe_out"), RAD_BF16, {T, E});
|
||||
m.b_logits = decl_b(b, nm.f("moe_logits"), RAD_BF16, {T, m.n_expert});
|
||||
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_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {P});
|
||||
m.b_eoff = decl_b(b, nm.f("moe_eoff"), RAD_I32, {m.n_expert + 1});
|
||||
/* PERSIST: rad_route_report reads the histogram, not a declared op, so liveness would
|
||||
* otherwise treat the scatter's write as dead. */
|
||||
m.b_ecnt = decl_b(b, nm.f("moe_ecnt"), RAD_I32, {m.n_expert}, RAD_BUF_PERSIST);
|
||||
}
|
||||
m.b_mean = decl_b(b, nm.f("mean"), RAD_BF16, {g.max_seqs, E});
|
||||
m.b_pooled = decl_b(b, nm.f("pooled"), RAD_F32, {g.max_seqs, E}, RAD_BUF_PERSIST);
|
||||
RAD_ARCH_TRY(rad_declare_pooled(b, m.b_pooled));
|
||||
|
||||
/* ---- the model-level weights. Norms and biases stay f32 where the kernels read a wider
|
||||
* gain; the embedding, the token-type table and the linears are bf16. table_add_bf16 reads a
|
||||
* bf16 table, and the CPU rows (libref, libavx) read any dtype the tensor carries. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), "embeddings.word_embeddings.weight"));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_type.weight"),
|
||||
"embeddings.token_type_embeddings.weight"));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("emb_ln.weight"), "emb_ln.weight"));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("emb_ln.bias"), "emb_ln.bias"));
|
||||
m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, E},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
m.w_type = decl_w(b, nm.f("token_type.weight"), RAD_BF16, {1, E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.w_emb_ln = decl_w(b, nm.f("emb_ln.weight"), RAD_F32, {E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.b_emb_ln = decl_w(b, nm.f("emb_ln.bias"), RAD_F32, {E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
auto layernorm_op = [&](rad_weight w, rad_weight bias) {
|
||||
return RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto gemm_bias_op = [&](int64_t N, int64_t Width, rad_weight w, rad_weight bias,
|
||||
const char* act_name) {
|
||||
if (act_name)
|
||||
return RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("N", N),
|
||||
RAD_INT("K", Width), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("act", act_name)),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
return RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("N", N),
|
||||
RAD_INT("K", Width), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto gemm_op = [&](int64_t N, int64_t Width, rad_weight w) {
|
||||
return RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("N", N),
|
||||
RAD_INT("K", Width), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto table_add_op = [&](int64_t rows, rad_weight w) {
|
||||
return RAD_OP(b, "table_add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", E), RAD_INT("L", 1),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto add_op = [&](rad_buf a, rad_buf c, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{a, c}, {y});
|
||||
};
|
||||
auto moe_gemm_op = [&](int64_t N, int64_t Width, const char* order,
|
||||
const std::vector<rad_weight>& tab, rad_buf a, rad_buf y) {
|
||||
rad_op h = rad_decl_op(b, "moe_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("N", N),
|
||||
RAD_INT("K", Width), RAD_INT("n_expert", m.n_expert),
|
||||
RAD_INT("top_k", K), RAD_STR("a_order", order),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
tab.data(), (int)tab.size());
|
||||
return rw(b, h, {a, m.b_sorted, m.b_eoff}, {y});
|
||||
};
|
||||
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("vocab_offset", 0),
|
||||
RAD_F64("mult", 1.0)),
|
||||
RAD_WEIGHTS(m.w_tok)),
|
||||
{}, {m.b_o});
|
||||
m.op_type = rw(b, table_add_op(T, m.w_type), {m.b_o}, {m.b_o});
|
||||
m.op_emb_ln = rw(b, layernorm_op(m.w_emb_ln, m.b_emb_ln), {m.b_o}, {m.b_x});
|
||||
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& y = m.layers[(size_t)l];
|
||||
y.moe = any_moe && is_moe_layer(l, every);
|
||||
const long long ll = (long long)l;
|
||||
const RadWeightGroup gl = grp_layer((int)l);
|
||||
auto src = [&](const char* s) { return nm.ckpt("encoder.layers.%lld.%s", ll, s); };
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_norm.weight", ll), src("norm1.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_norm.bias", ll), src("norm1.bias")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_qkv.weight", ll), src("attn.Wqkv.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_qkv.bias", ll), src("attn.Wqkv.bias")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_out.weight", ll),
|
||||
src("attn.out_proj.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_out.bias", ll),
|
||||
src("attn.out_proj.bias")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_norm.weight", ll), src("norm2.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_norm.bias", ll), src("norm2.bias")));
|
||||
|
||||
const int A = RAD_ACCESS_PER_TOKEN, N = RAD_SHARD_NONE;
|
||||
y.w_norm1 = decl_w(b, nm.f("blk.%lld.attn_norm.weight", ll), RAD_F32, {E}, A, N, gl);
|
||||
y.b_norm1 = decl_w(b, nm.f("blk.%lld.attn_norm.bias", ll), RAD_F32, {E}, A, N, gl);
|
||||
y.w_qkv = decl_w(b, nm.f("blk.%lld.attn_qkv.weight", ll), RAD_BF16, {3 * E, E}, A, N, gl);
|
||||
y.b_qkv = decl_w(b, nm.f("blk.%lld.attn_qkv.bias", ll), RAD_F32, {3 * E}, A, N, gl);
|
||||
y.w_out = decl_w(b, nm.f("blk.%lld.attn_out.weight", ll), RAD_BF16, {E, E}, A, N, gl);
|
||||
y.b_out = decl_w(b, nm.f("blk.%lld.attn_out.bias", ll), RAD_F32, {E}, A, N, gl);
|
||||
y.w_norm2 = decl_w(b, nm.f("blk.%lld.ffn_norm.weight", ll), RAD_F32, {E}, A, N, gl);
|
||||
y.b_norm2 = decl_w(b, nm.f("blk.%lld.ffn_norm.bias", ll), RAD_F32, {E}, A, N, gl);
|
||||
|
||||
if (!y.moe) {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_fc1.weight", ll), src("mlp.fc1.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_fc1.bias", ll), src("mlp.fc1.bias")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_fc2.weight", ll), src("mlp.fc2.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_fc2.bias", ll), src("mlp.fc2.bias")));
|
||||
y.w_fc1 = decl_w(b, nm.f("blk.%lld.ffn_fc1.weight", ll), RAD_BF16, {g.n_ff, E},
|
||||
A, N, gl);
|
||||
y.b_fc1 = decl_w(b, nm.f("blk.%lld.ffn_fc1.bias", ll), RAD_F32, {g.n_ff}, A, N, gl);
|
||||
y.w_fc2 = decl_w(b, nm.f("blk.%lld.ffn_fc2.weight", ll), RAD_BF16, {E, g.n_ff},
|
||||
A, N, gl);
|
||||
y.b_fc2 = decl_w(b, nm.f("blk.%lld.ffn_fc2.bias", ll), RAD_F32, {E}, A, N, gl);
|
||||
} else {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_router.weight", ll),
|
||||
src("mlp.router.layer.weight")));
|
||||
y.w_router = decl_w(b, nm.f("blk.%lld.ffn_router.weight", ll), RAD_BF16,
|
||||
{m.n_expert, E}, A, N, gl);
|
||||
/* mlp.experts.bias is not mapped (no expert bias, see the header). */
|
||||
/* Each projection is a consecutive run of expert handles: all w1 in expert order,
|
||||
* then all w2. A grouped GEMM takes the run's first handle and its length. The name
|
||||
* maps come first: declare reads a weight's planned encoding when the weight is
|
||||
* declared, and a slice mapped afterwards would be read as plain bf16. */
|
||||
for (int64_t e = 0; e < m.n_expert; ++e) {
|
||||
const long long ee = (long long)e;
|
||||
RAD_ARCH_TRY(map_slice(b, nm.f("blk.%lld.ffn_exp_w1.%lld.weight", ll, ee),
|
||||
src("mlp.experts.mlp.w1"), (int)e, g.n_ff));
|
||||
RAD_ARCH_TRY(map_transpose_slice(b, nm.f("blk.%lld.ffn_exp_w2.%lld.weight", ll, ee),
|
||||
src("mlp.experts.mlp.w2"), (int)e, g.n_ff));
|
||||
}
|
||||
y.w_w1.resize((size_t)m.n_expert);
|
||||
y.w_w2.resize((size_t)m.n_expert);
|
||||
for (int64_t e = 0; e < m.n_expert; ++e) {
|
||||
const long long ee = (long long)e;
|
||||
y.w_w1[(size_t)e] = decl_w(b, nm.f("blk.%lld.ffn_exp_w1.%lld.weight", ll, ee),
|
||||
RAD_BF16, {g.n_ff, E}, A, N,
|
||||
grp_expert_slot((int)l, (int)e, 0));
|
||||
if (!y.w_w1[(size_t)e]) return RAD_E_INVAL;
|
||||
}
|
||||
for (int64_t e = 0; e < m.n_expert; ++e) {
|
||||
const long long ee = (long long)e;
|
||||
y.w_w2[(size_t)e] = decl_w(b, nm.f("blk.%lld.ffn_exp_w2.%lld.weight", ll, ee),
|
||||
RAD_BF16, {E, g.n_ff}, A, N,
|
||||
grp_expert_slot((int)l, (int)e, 1));
|
||||
if (!y.w_w2[(size_t)e]) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
y.op_qkv = rw(b, gemm_bias_op(3 * E, E, y.w_qkv, y.b_qkv, nullptr),
|
||||
{m.b_x}, {m.b_qkv});
|
||||
y.op_rope = rw(b, RAD_OP(b, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_F64("theta", meta->rope_theta), RAD_F64("scale", 1.0),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_qkv}, {m.b_qkv});
|
||||
y.op_attn = rw(b, RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"), RAD_F64("scale", 0.125),
|
||||
RAD_INT("max_seqlen", T)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_qkv}, {m.b_att});
|
||||
y.op_out = rw(b, gemm_bias_op(E, E, y.w_out, y.b_out, nullptr),
|
||||
{m.b_att, m.b_x}, {m.b_x});
|
||||
y.op_norm1 = rw(b, layernorm_op(y.w_norm1, y.b_norm1), {m.b_x}, {m.b_h});
|
||||
|
||||
if (!y.moe) {
|
||||
y.op_fc1 = rw(b, gemm_bias_op(g.n_ff, E, y.w_fc1, y.b_fc1, "gelu"),
|
||||
{m.b_h}, {m.b_ff});
|
||||
y.op_fc2 = rw(b, gemm_bias_op(E, g.n_ff, y.w_fc2, y.b_fc2, nullptr),
|
||||
{m.b_ff, m.b_h}, {m.b_o});
|
||||
} else {
|
||||
y.op_router = rw(b, gemm_op(m.n_expert, E, y.w_router), {m.b_h}, {m.b_logits});
|
||||
y.op_topk = rw(b, RAD_OP(b, "router_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T),
|
||||
RAD_INT("n_expert", m.n_expert),
|
||||
RAD_INT("top_k", K), RAD_INT("norm", 0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_logits}, {m.b_ids, m.b_ew});
|
||||
y.op_scatter = rw(b, RAD_OP(b, "moe_scatter",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T),
|
||||
RAD_INT("n_expert", m.n_expert),
|
||||
RAD_INT("top_k", K),
|
||||
RAD_INT("expert_base", 0)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_ids}, {m.b_sorted, m.b_eoff, m.b_ecnt});
|
||||
y.op_egu = moe_gemm_op(g.n_ff, E, "token", y.w_w1, m.b_h, m.b_egu);
|
||||
y.op_gelu = rw(b, RAD_OP(b, "gelu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", g.n_ff),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_egu}, {m.b_eact});
|
||||
y.op_edn = moe_gemm_op(E, g.n_ff, "sorted", y.w_w2, m.b_eact, m.b_edn);
|
||||
y.op_gather = rw(b, RAD_OP(b, "moe_gather",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_INT("top_k", K), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("act", "none")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_edn, m.b_ew, m.b_sorted}, {m.b_emoe});
|
||||
y.op_add = add_op(m.b_h, m.b_emoe, m.b_o);
|
||||
}
|
||||
|
||||
y.op_norm2 = rw(b, layernorm_op(y.w_norm2, y.b_norm2), {m.b_o}, {m.b_x});
|
||||
|
||||
if (!y.op_qkv || !y.op_rope || !y.op_attn || !y.op_out || !y.op_norm1 || !y.op_norm2)
|
||||
return RAD_E_INVAL;
|
||||
if (y.moe && (!y.op_router || !y.op_topk || !y.op_scatter || !y.op_egu || !y.op_gelu ||
|
||||
!y.op_edn || !y.op_gather || !y.op_add))
|
||||
return RAD_E_INVAL;
|
||||
if (!y.moe && (!y.op_fc1 || !y.op_fc2)) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
m.op_mean = rw(b, RAD_OP(b, "seg_mean",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_mean});
|
||||
m.op_cast = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", E),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_mean}, {m.b_pooled});
|
||||
|
||||
int64_t n_routed = 0;
|
||||
for (const Layer& y : m.layers) n_routed += y.moe ? 1 : 0;
|
||||
rad_note(b, "embedding model: %lld layers (%lld routed, every %lld), hidden %lld, ffn %lld, "
|
||||
"%lld heads of %lld, %lld experts top %lld; post-norm, no expert bias; "
|
||||
"mean-pooled to %lld",
|
||||
(long long)g.n_layer, (long long)n_routed, (long long)every, (long long)E,
|
||||
(long long)g.n_ff, (long long)g.n_head, (long long)g.head_dim,
|
||||
(long long)m.n_expert, (long long)m.n_expert_used, (long long)E);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Model& m = g_model[rad_rank(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;
|
||||
const int64_t K = m.n_expert_used;
|
||||
const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1);
|
||||
const RadOperand pos = praw(batch->positions, RAD_I32, T);
|
||||
|
||||
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok),
|
||||
brows(m.b_o, T));
|
||||
RAD_ISSUE(c, m.op_type, brows(m.b_o, T), RAD_W(m.w_type), brows(m.b_o, T));
|
||||
RAD_ISSUE(c, m.op_emb_ln, brows(m.b_o, T), RAD_W(m.w_emb_ln), RAD_W(m.b_emb_ln),
|
||||
brows(m.b_x, T));
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const Layer& y = m.layers[(size_t)l];
|
||||
|
||||
RAD_ISSUE_N(c, y.op_qkv, T, brows(m.b_x, T), RAD_W(y.w_qkv), RAD_W(y.b_qkv),
|
||||
RAD_NONE, brows(m.b_qkv, T));
|
||||
RAD_ISSUE(c, y.op_rope, brows(m.b_qkv, T), pos);
|
||||
RAD_ISSUE(c, y.op_attn, bcol(m.b_qkv, 0, E, T), bcol(m.b_qkv, E, E, T),
|
||||
bcol(m.b_qkv, 2 * E, E, T), cu, brows(m.b_att, T));
|
||||
RAD_ISSUE_N(c, y.op_out, T, brows(m.b_att, T), RAD_W(y.w_out), RAD_W(y.b_out),
|
||||
brows(m.b_x, T), brows(m.b_x, T));
|
||||
RAD_ISSUE(c, y.op_norm1, brows(m.b_x, T), RAD_W(y.w_norm1), RAD_W(y.b_norm1),
|
||||
brows(m.b_h, T));
|
||||
|
||||
if (!y.moe) {
|
||||
RAD_ISSUE_N(c, y.op_fc1, T, brows(m.b_h, T), RAD_W(y.w_fc1), RAD_W(y.b_fc1),
|
||||
RAD_NONE, brows(m.b_ff, T));
|
||||
RAD_ISSUE_N(c, y.op_fc2, T, brows(m.b_ff, T), RAD_W(y.w_fc2),
|
||||
RAD_W(y.b_fc2), brows(m.b_h, T), brows(m.b_o, T));
|
||||
} else {
|
||||
RAD_ISSUE(c, y.op_router, brows(m.b_h, T), RAD_W(y.w_router), brows(m.b_logits, T));
|
||||
RAD_ISSUE(c, y.op_topk, brows(m.b_logits, T), brows(m.b_ids, T), brows(m.b_ew, T));
|
||||
RAD_ISSUE(c, y.op_scatter, brows(m.b_ids, T), brows(m.b_sorted, T * K),
|
||||
brows(m.b_eoff, m.n_expert + 1), brows(m.b_ecnt, m.n_expert));
|
||||
RAD_ISSUE_N(c, y.op_egu, T, brows(m.b_h, T), RAD_WTAB(y.w_w1[0], m.n_expert),
|
||||
brows(m.b_sorted, T * K), brows(m.b_eoff, m.n_expert + 1),
|
||||
brows(m.b_egu, T * K));
|
||||
RAD_ISSUE_N(c, y.op_gelu, T * K, brows(m.b_egu, T * K), brows(m.b_eact, T * K));
|
||||
RAD_ISSUE_N(c, y.op_edn, T, brows(m.b_eact, T * K), RAD_WTAB(y.w_w2[0], m.n_expert),
|
||||
brows(m.b_sorted, T * K), brows(m.b_eoff, m.n_expert + 1),
|
||||
brows(m.b_edn, T * K));
|
||||
RAD_ISSUE_N(c, y.op_gather, T, brows(m.b_edn, T * K), brows(m.b_ew, T),
|
||||
brows(m.b_sorted, T * K), RAD_NONE, RAD_NONE, brows(m.b_emoe, T));
|
||||
RAD_ISSUE(c, y.op_add, brows(m.b_h, T), brows(m.b_emoe, T), brows(m.b_o, T));
|
||||
}
|
||||
RAD_ISSUE(c, y.op_norm2, brows(m.b_o, T), RAD_W(y.w_norm2), RAD_W(y.b_norm2),
|
||||
brows(m.b_x, T));
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.op_mean, brows(m.b_x, T), cu, brows(m.b_mean, S));
|
||||
RAD_ISSUE_N(c, m.op_cast, S, brows(m.b_mean, S), brows(m.b_pooled, S));
|
||||
}
|
||||
|
||||
} /* namespace nomicbert */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
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 "
|
||||
"vector an input; bf16")
|
||||
RAD_ARCH_PROBE(nomicbert)
|
||||
#endif
|
||||
@@ -41,6 +41,7 @@
|
||||
#include <arch/rad_block_gdn.h>
|
||||
#include <arch/rad_block_mlp.h>
|
||||
#include <arch/rad_block_vit.h>
|
||||
#include <arch/rad_calib_full.h>
|
||||
|
||||
#include <vector>
|
||||
|
||||
@@ -55,6 +56,9 @@ struct Layer {
|
||||
AttnGatedBF16 attn;
|
||||
GdnBF16 gdn;
|
||||
MlpBF16 mlp;
|
||||
/* The layer's calibration inputs (rad_calib_full.h): the attention or delta net's, its output
|
||||
* projection's, the feed-forward's and down_proj's; -1 where the run does not record it. */
|
||||
int cs_in = -1, cs_o = -1, cs_mlp = -1, cs_down = -1;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
@@ -78,6 +82,12 @@ struct Model {
|
||||
|
||||
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_gather = 0, op_logits = 0;
|
||||
/* Set by a plugin built over this one whose head answers a request from its words
|
||||
* (RadBatch::plugin_words): a `fill` of the logits rows that plugin declared. A step every
|
||||
* sampled row of which carries words then skips the lm_head and leaves those zero rows for the
|
||||
* sampler, whose token the request discards. Zero, the lm_head runs as it always has, and the
|
||||
* graph this plugin declares is unchanged. */
|
||||
rad_op op_logits_fill = 0;
|
||||
|
||||
/* ---- media (arch/common/rad_block_vit.h): the vision tower and the scatter of its rows,
|
||||
* declared only when the container carries a tower and the deployment asked for media. */
|
||||
@@ -86,6 +96,10 @@ struct Model {
|
||||
MediaRows mrows{};
|
||||
|
||||
std::vector<Layer> layers;
|
||||
|
||||
/* --calib-dir: the whole Hessian of every linear's input over a --calib-corpus run. */
|
||||
CalibFull calib;
|
||||
int cs_head = -1; /* the lm_head's input, recorded with the last layer */
|
||||
};
|
||||
|
||||
/* Declare runs once per rank, in one process, on the rank's own thread (spec §1, §9), so the
|
||||
@@ -337,6 +351,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
MlpBF16::Wire mw{};
|
||||
mw.x = m.b_x; mw.h = m.b_h; mw.gate_up = m.b_gate_up; mw.ffn = m.b_ffn;
|
||||
|
||||
/* The calibration tap: the widest split input is down_proj's (the feed-forward's width), and
|
||||
* no input is wider. */
|
||||
RAD_ARCH_TRY(m.calib.begin(b, nm, g, ctx, m.n_main, g.n_ff * g.world,
|
||||
std::max({ g.n_embd, q_dim * g.world, v_dim * g.world, g.n_ff * g.world })));
|
||||
|
||||
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];
|
||||
@@ -370,6 +389,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_conv));
|
||||
RAD_ARCH_TRY(lay.gdn.declare(b, nm, g, gc, (int)l, m.kv_state, m.kv_conv, gw, gs));
|
||||
}
|
||||
if (m.calib.records(l)) {
|
||||
const std::string L = std::string(pre) + "." + std::to_string(l);
|
||||
lay.cs_in = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".input",
|
||||
lay.full ? L + ".self_attn.q_proj," + L + ".self_attn.k_proj," + L + ".self_attn.v_proj"
|
||||
: L + ".linear_attn.in_proj_qkv," + L + ".linear_attn.in_proj_z," +
|
||||
L + ".linear_attn.in_proj_a," + L + ".linear_attn.in_proj_b",
|
||||
m.b_h, g.n_embd, g.n_embd));
|
||||
lay.cs_o = (int)m.calib.sites.size();
|
||||
if (lay.full)
|
||||
RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".self_attn.o_proj.input", L + ".self_attn.o_proj",
|
||||
m.b_attn, q_dim, q_dim * g.world));
|
||||
else
|
||||
RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".linear_attn.out_proj.input", L + ".linear_attn.out_proj",
|
||||
m.b_go, v_dim, v_dim * g.world));
|
||||
}
|
||||
|
||||
MlpBF16::Src ms{};
|
||||
ms.norm = nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l);
|
||||
@@ -377,6 +412,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
ms.up = nm.ckpt("%s.%lld.mlp.up_proj.weight", pre, (long long)l);
|
||||
ms.down = nm.ckpt("%s.%lld.mlp.down_proj.weight", pre, (long long)l);
|
||||
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms));
|
||||
if (m.calib.records(l)) {
|
||||
const std::string L = std::string(pre) + "." + std::to_string(l);
|
||||
lay.cs_mlp = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".post_attention.input",
|
||||
L + ".mlp.gate_proj," + L + ".mlp.up_proj", m.b_h, g.n_embd, g.n_embd));
|
||||
lay.cs_down = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".mlp.down_proj.input", L + ".mlp.down_proj",
|
||||
m.b_ffn, g.n_ff, g.n_ff * g.world));
|
||||
}
|
||||
}
|
||||
|
||||
m.op_final_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
@@ -384,6 +428,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", final_wadd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_out_norm)),
|
||||
{m.b_x}, {m.b_h});
|
||||
/* The lm_head's input, with the run that records the last layer. */
|
||||
if (m.calib.on && m.calib.hi == m.n_main) {
|
||||
m.cs_head = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site(b, g, -1, "lm_head.input", "lm_head", m.b_h, g.n_embd, g.n_embd));
|
||||
}
|
||||
|
||||
m.op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
@@ -447,18 +496,39 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
RAD_ISSUE_N(c, m.op_embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
|
||||
brows(m.b_x, batch->n_tok), RAD_NONE);
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
for (const Layer& l : m.layers) {
|
||||
/* Under calibration a block's input norm is issued once ahead of the block, so its output
|
||||
* is read before the block overwrites `h`; the block computes it again, the same op on
|
||||
* the same bytes. */
|
||||
if (l.cs_in >= 0) {
|
||||
if (l.full) RAD_ISSUE(c, l.attn.op_norm, brows(m.b_x, T), RAD_W(l.attn.w_norm), brows(m.b_h, T));
|
||||
else RAD_ISSUE(c, l.gdn.op_norm, brows(m.b_x, T), RAD_W(l.gdn.w_norm), brows(m.b_h, T));
|
||||
m.calib.tap(c, (size_t)l.cs_in, T);
|
||||
}
|
||||
if (l.full) 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);
|
||||
if (l.cs_mlp >= 0) {
|
||||
RAD_ISSUE(c, l.mlp.op_norm, brows(m.b_x, T), RAD_W(l.mlp.w_norm), brows(m.b_h, T));
|
||||
m.calib.tap(c, (size_t)l.cs_mlp, T);
|
||||
}
|
||||
l.mlp.step(c, batch);
|
||||
if (l.cs_down >= 0) m.calib.tap(c, (size_t)l.cs_down, T);
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.op_final_norm,
|
||||
brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.b_h, batch->n_tok));
|
||||
if (m.cs_head >= 0) m.calib.tap(c, (size_t)m.cs_head, T);
|
||||
m.calib.after_step(c, T);
|
||||
|
||||
/* The lm_head runs only on the rows the sampler asked for; a mid-prompt prefill chunk has
|
||||
* n_out zero and skips it. */
|
||||
if (batch->n_out > 0) {
|
||||
if (m.op_logits_fill && plugin_words_cover_rows(batch)) {
|
||||
RAD_ISSUE_N(c, m.op_logits_fill, batch->n_out, brows(m.b_logits, batch->n_out));
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out,
|
||||
brows(m.b_h, batch->n_tok),
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out),
|
||||
|
||||
+423
-10
@@ -106,11 +106,34 @@ using Ffn = MlpFP8;
|
||||
using MtpHead = MtpFP8;
|
||||
#endif
|
||||
|
||||
/* The weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h): a weight's first
|
||||
* kPrefetchBytes, on decode steps of up to kPrefetchStepRows rows. Qwen3.8-27B MXFP4 + DFlash2, tp
|
||||
* 2 on two R9700s, no speculation: 12 MB was best, +11 % at one stream, +9 % at eight, +3 % at
|
||||
* sixteen; past ~12 MB the read outlasts the reduction and takes bandwidth from the GEMM it feeds.
|
||||
* Up to 32 rows (a verify of four sequences at speculation 7): at 32 and 64 rows the reads are a
|
||||
* wash. The drafter's reads (Dflash2::Config::prefetch) take the same size. */
|
||||
constexpr int64_t kPrefetchBytes = (int64_t)12 << 20;
|
||||
constexpr int64_t kPrefetchStepRows = 32;
|
||||
/* 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, so the whole projection (7.9 MB a rank in MXFP4; the read stops at the weight's end) is read
|
||||
* there. Qwen3.8-27B MXFP4 + DFlash2 at tp 2, production flags, 1k context, hwgrid ms/step, median of
|
||||
* five interleaved rounds, none -> whole: x1 19.40 -> 19.10, x2 20.93 -> 20.78, x4 24.26 -> 24.17
|
||||
* (every round faster), x8 25.22 -> 25.48 (four rounds of five slower: eight sequences' state traffic
|
||||
* fills the memory and the read competes with it), so up to four sequences. 4 MB read as the whole
|
||||
* (x1 19.24 / 19.10 against 19.20 / 19.06); 90k x4 and x16 (64 rows, no read) unchanged. */
|
||||
constexpr int64_t kGdnOutPrefetchBytes = (int64_t)8 << 20;
|
||||
constexpr int64_t kGdnOutPrefetchSeqs = 4;
|
||||
|
||||
struct Layer {
|
||||
int full = 0;
|
||||
AttnGatedFP8 attn;
|
||||
GdnFP8 gdn;
|
||||
Ffn mlp;
|
||||
/* gate_up's leading bytes beside the mixer's reduction, the next layer's first projection's
|
||||
* beside the feed-forward's; 0 where none is declared. */
|
||||
rad_op op_pf_gu = 0, op_pf_next = 0;
|
||||
rad_weight pf_gu_w = 0, pf_next_w = 0;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
@@ -184,6 +207,12 @@ struct Model {
|
||||
|
||||
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_gather = 0, op_logits = 0;
|
||||
/* Set by a plugin built over this one whose head answers a request from its words
|
||||
* (RadBatch::plugin_words): a `fill` of the logits rows that plugin declared. A step every
|
||||
* sampled row of which carries words then skips the lm_head and leaves those zero rows for the
|
||||
* sampler, whose token the request discards. Zero, the lm_head runs as it always has, and the
|
||||
* graph this plugin declares is unchanged. */
|
||||
rad_op op_logits_fill = 0;
|
||||
rad_op op_rope_cs = 0; /* rope_table, if the fused prologue is reachable */
|
||||
|
||||
/* ---- media (arch/common/rad_block_vit.h): the vision tower and the scatter of its rows,
|
||||
@@ -193,10 +222,28 @@ struct Model {
|
||||
MediaRows mrows{};
|
||||
|
||||
std::vector<Layer> layers;
|
||||
|
||||
/* The pipelined prefill (step_pipelined): on where declare allowed it; the bounds buffer it
|
||||
* cuts a step by, rewritten by every pipelined step from the pinned table `pipe_tbl` of
|
||||
* {0, pipe_rows(T), T} for every T, made once; and whether rank 0 has said it pipelines. */
|
||||
bool pipe_on = false;
|
||||
rad_buf b_pipe_cu = 0;
|
||||
int32_t* pipe_tbl = nullptr;
|
||||
bool pipe_tbl_tried = false;
|
||||
bool pipe_noted = false;
|
||||
bool pipe_serial_noted = false;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
#if !QWEN35_MOE
|
||||
/* The narrowest step the pipelined prefill takes, and its first piece: half the step rounded up
|
||||
* to 64 rows, so both pieces sit in one bucket band (core/runtime/ctx.h) and the second is never
|
||||
* wider than the first. */
|
||||
static const int64_t kPipeMinRows = 1024;
|
||||
static int64_t pipe_rows(int64_t T) { return ((T + 1) / 2 + 63) / 64 * 64; }
|
||||
#endif
|
||||
|
||||
/* Checks the container's statement of its format, since every mismatch is silent: a
|
||||
* `weight_block_size` of [64,64] against kernels that shift by 7 reads the right bytes with the
|
||||
* wrong gain, and e5m2 decoded as e4m3 gives merely implausible numbers. A container that states
|
||||
@@ -264,6 +311,8 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "DFlash2"));
|
||||
|
||||
Dflash2::Config dc{};
|
||||
dc.short_block = 1; /* rad_drafter_short_block below */
|
||||
dc.prefetch = kPrefetchBytes; /* reads beside the drafter's all-reduces (at tp > 1) */
|
||||
dc.n_taps = m.n_taps;
|
||||
dc.block = ctx->max_spec + 1;
|
||||
dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2);
|
||||
@@ -388,6 +437,36 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
* selector, never through the sampler's token buffer. */
|
||||
dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, dc.steps()});
|
||||
|
||||
/* --draft-coupling (RadBuildCtx::draft_coupling): the walk samples each draft from Q, its
|
||||
* scores' softmax over the best eight candidates, and the sampler couples the target's own draw
|
||||
* to it (abi/rad_spechub.h). The planes are named as the MTP head's, which is how the engine
|
||||
* finds them. Q's temperature keeps the output exact at any value and moves only acceptance;
|
||||
* 0.6 is where held-out acceptance peaked on Qwen3.8-27B MXFP4 + its DFlash2 drafter at request
|
||||
* temperature 1 (tokens a step at x4, 32 rows: ordinary rule 3.52; Q at 1.0 3.71, 0.7 3.88,
|
||||
* 0.5 3.85, 0.35 3.77): the walk's scores are flatter than the target's law, and a sharper Q
|
||||
* puts its mass where the target's is. */
|
||||
if (ctx->draft_coupling) {
|
||||
if (dc.steps() > RAD_MTP_COUPLE_MAX_ROUNDS || dc.sel_topk > RAD_DFLASH_COUPLE_MAX_K ||
|
||||
dc.sel_rank % RAD_DFLASH_EDGE_PARTS || dc.sel_rank > RAD_DFLASH_COUPLE_MAX_R) {
|
||||
rad_note(b, "--draft-coupling on: DFlash2's coupled walk takes at most %d drafts, %d "
|
||||
"candidates and a selector rank that is a multiple of %d up to %d",
|
||||
RAD_MTP_COUPLE_MAX_ROUNDS, RAD_DFLASH_COUPLE_MAX_K, RAD_DFLASH_EDGE_PARTS,
|
||||
RAD_DFLASH_COUPLE_MAX_R);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
dc.q_temp = 0.6;
|
||||
dw.couple_draws = decl_b(b, nm.f("mtp_couple_draws"), RAD_U32,
|
||||
{dg.max_seqs, RAD_MTP_COUPLE_DRAW_WORDS}, RAD_BUF_PERSIST);
|
||||
dw.couple_state = decl_b(b, nm.f("mtp_couple_state"), RAD_U32,
|
||||
{dc.steps(), dg.max_seqs, RAD_MTP_COUPLE_STATE_WORDS},
|
||||
RAD_BUF_PERSIST);
|
||||
if (!dw.couple_draws || !dw.couple_state) return RAD_E_INVAL;
|
||||
rad_note(b, "DFlash2 coupled: the walk samples x~Q (FP64 softmax of its edge scores / %g "
|
||||
"over the best eight candidates) at each of %lld positions, and the sampler "
|
||||
"couples the target's own draw to it; fixed-seed tokens are NOT preserved",
|
||||
dc.q_temp, (long long)dc.steps());
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(m.df.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft",
|
||||
nm.ckpt("lm_head.weight"), dw));
|
||||
m.have_df = true;
|
||||
@@ -414,6 +493,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
|
||||
if (m.df.block_lo > 0) RAD_ARCH_TRY(rad_drafter_short_block(b, m.df.block_lo));
|
||||
|
||||
rad_note(b, "DFlash2 drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv x %lld, "
|
||||
"ffn %lld, %s attention with a %lld-token window, %d trunk tap(s); one forward "
|
||||
@@ -430,6 +510,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (m.pipe_tbl) rad_dev_free(m.pipe_tbl, RAD_MEM_HOST_PINNED);
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -583,17 +664,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"and head instead of %lld", kvq_name, kvq == RAD_KVQ_V4 ? "E4M3" : "int6",
|
||||
(long long)(g.head_dim * row16 / 16), (long long)(2 * g.head_dim));
|
||||
|
||||
/* The SSM state cache is f32.
|
||||
/* The SSM state cache is f32, or f16 under --state-cache-dtype f16 (RadBuildCtx::state_dtype).
|
||||
*
|
||||
* State reads and writes dominate the two GDN kernels: one [128,128] state is 64 KiB at f32,
|
||||
* and a speculative step writes one per candidate token per head, since the surviving
|
||||
* candidate is unknown until after the layer. At depth 7 that is hundreds of MB per rank per
|
||||
* step; f16 would halve it. libr4d compiles both widths (`SDT`) and the f16 round-trip error is
|
||||
* ~5e-4 relative (elements are O(0.1)); vLLM's `--mamba-ssm-cache-dtype` is commonly float16.
|
||||
* It stays f32 because f16 changes the generated text. */
|
||||
* and a step reads a sequence's state and writes it back (under the anchor form once, whatever
|
||||
* the draft depth). libr4d compiles both widths (`SDT`, from the cache's dtype); the f16
|
||||
* round trip is ~5e-4 relative (elements are O(0.1)). f16 halves the state pool, its host
|
||||
* checkpoints and the state traffic, and changes the generated text, so f32 is the default. */
|
||||
RadKVGroupDecl sd{};
|
||||
sd.kind = RAD_KV_LINEAR;
|
||||
sd.dtype = RAD_F32;
|
||||
sd.dtype = ctx->state_dtype == RAD_F16 ? RAD_F16 : RAD_F32;
|
||||
if (sd.dtype == RAD_F16) rad_note(b, "GDN state cache f16 (--state-cache-dtype f16)");
|
||||
sd.n_head_kv = gc.n_head_v;
|
||||
sd.state_dim[0] = gc.head_v;
|
||||
sd.state_dim[1] = gc.head_k;
|
||||
@@ -623,7 +704,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
nm.ckpt("%s.%lld.linear_attn.in_proj_z.weight", pre, (long long)l) }));
|
||||
RadEncoding enc{};
|
||||
m.trunk_i8 = weight_enc(b, nm.f("blk.%lld.ssm_inz.weight", (long long)l), &enc) &&
|
||||
linear_is_w8h(enc);
|
||||
(linear_is_w8h(enc) || linear_is_wnh(enc));
|
||||
break;
|
||||
}
|
||||
if (!m.trunk_i8) {
|
||||
@@ -833,8 +914,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
nm.ckpt("model.language_model.embed_tokens.weight")));
|
||||
|
||||
m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
/* A table stored on the int8 grid (int8 or narrower codes and a bf16 scale per row and 128
|
||||
* columns) is declared over all its planes at the codes' dtype; the gather's layout widens it
|
||||
* to bf16 at load. */
|
||||
{
|
||||
RadEncoding te{};
|
||||
const bool q = weight_enc(b, nm.f("token_embd.weight"), &te) && !rad_enc_is(&te, "plain");
|
||||
m.w_tok = q ? decl_view(b, nm.f("token_embd.weight"), nullptr, nullptr, te.plane[0].dtype,
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model())
|
||||
: decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
}
|
||||
m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
/* Row-sharded with the vocabulary: g.n_vocab is this rank's share (rad_arch.h). */
|
||||
@@ -854,7 +944,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
|
||||
/* Always exact, not g.wire_exact: this all_reduce sums disjoint rows (each token's embedding
|
||||
* comes from one rank, the others contribute zero), so a lossy wire would only add error.
|
||||
* min_bytes stays 0 for the same reason. */
|
||||
* min_bytes stays 0 for the same reason.
|
||||
*
|
||||
* The second lane's window opens here and closes after the final norm (rad_lane1_window_begin):
|
||||
* the embedding's reduction and the pipelined prefill's boundaries are declared inside it, so
|
||||
* the concurrent buffers stay live only there and the drafter and the heads can share their
|
||||
* bytes. */
|
||||
RAD_ARCH_TRY(rad_lane1_window_begin(b));
|
||||
if (g.world > 1)
|
||||
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
@@ -862,6 +958,35 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
#if !QWEN35_MOE
|
||||
/* The pipelined prefill (step_pipelined), at two ranks wherever a step can be wide enough.
|
||||
* Its second lane needs a narrow `overlap` all-reduce beside the GEMMs; two ranks is the only
|
||||
* rank count where the step has been timed against the serial one, so elsewhere prefill stays
|
||||
* serial. The second lane touches the residual stream, the normed input in both forms and the
|
||||
* bounds, so those leave the sharing pool (Ctx::lane1_; the drafter taps are copied on the
|
||||
* first lane, pipe_taps); the bounds also because no declared op reads them, which would leave
|
||||
* a transient dead before the kernels that take them raw.
|
||||
*
|
||||
* Not on a trunk whose norms write rotated int8 codes (qwen35_w8a8 where libr4d serves the
|
||||
* `_had_quant_i8g` forms, a_h.q8_fed): the boundary norms on the second lane
|
||||
* (NormQuantFP8::step_plain) issue the E4M3 pair only, so such a trunk prefills serially. */
|
||||
if (m.a_h.q8_fed) {
|
||||
if (g.world == 2 && g.max_tok >= kPipeMinRows && ctx->rank == 0)
|
||||
fprintf(stderr, "radiance: qwen35: the pipelined prefill stays off on this trunk: its norms "
|
||||
"write rotated int8 codes, which the pipeline's boundary norms do not\n");
|
||||
} else {
|
||||
m.pipe_on = g.world == 2 && g.max_tok >= kPipeMinRows;
|
||||
}
|
||||
if (m.pipe_on) {
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_x));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.a_h.x));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.a_h.q));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.a_h.s));
|
||||
m.b_pipe_cu = decl_b(b, nm.f("pipe_cu"), RAD_I32, {4});
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_pipe_cu));
|
||||
}
|
||||
#endif
|
||||
|
||||
/* ---- the layers. */
|
||||
/* The rope table's fill, declared before the layers that read it. If it does not resolve,
|
||||
* `aw.cos_sin` is cleared and every attention block uses its unfused norm + rope pair. Its band
|
||||
@@ -904,6 +1029,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
for (int64_t l = 0; l < m.n_main; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.full = is_full_attention(l, interval) ? 1 : 0;
|
||||
#if !QWEN35_MOE
|
||||
/* The pipelined prefill runs every block's all-reduce beside the other piece's work, so
|
||||
* each declares its collective a second time at `overlap` 1, a launch that leaves the CUs
|
||||
* to that work (the lane rows of libr4d/r4d_rows.cpp); the fused all-reduce and norm
|
||||
* would hold the card while it waits on the link. */
|
||||
lay.attn.ar_overlap = lay.gdn.ar_overlap = lay.mlp.ar_overlap = m.pipe_on ? 1 : 0;
|
||||
#endif
|
||||
|
||||
const LayerFold f = layer_fold(g, l, m.n_main, m.tap_layer, m.n_taps, m.op_embed_ar != 0);
|
||||
|
||||
@@ -934,6 +1066,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
gs.out = nm.ckpt("%s.%lld.linear_attn.out_proj.weight", pre, (long long)l);
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_state));
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_conv));
|
||||
/* Lane 1 carries no collectives here (rad_block_gdn_fp8.h, ab_lane). */
|
||||
lay.gdn.ab_lane = true;
|
||||
RAD_ARCH_TRY(lay.gdn.declare(b, nm, g, gc, (int)l, m.kv_state, m.kv_conv, gw, gs,
|
||||
f.mix_fold, false, f.mix_ar_in, f.mix_ar_out));
|
||||
}
|
||||
@@ -963,11 +1097,36 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
for (int64_t l = 0; l + 1 < m.n_main; ++l) m.layers[(size_t)l].mlp.xp_next = &m.layers[(size_t)l + 1].mlp;
|
||||
#endif
|
||||
|
||||
#if !QWEN35_MOE
|
||||
/* ---- the weight reads beside the decode all-reduces. A decode-height reduction leaves the
|
||||
* card's memory idle for its round trip, so the next GEMM's leading weight bytes are read
|
||||
* into the on-die cache then: gate_up behind the mixer's, the next layer's first projection
|
||||
* behind the feed-forward's. At more than one rank; --weight-prefetch off declares none. */
|
||||
if (g.world > 1 && !ctx->weight_prefetch_off && rad_op_declared(b, "prefetch")) {
|
||||
for (int64_t l = 0; l < m.n_main; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.pf_gu_w = lay.mlp.gate_up.w;
|
||||
lay.op_pf_gu = decl_prefetch(b, lay.pf_gu_w, kPrefetchBytes);
|
||||
if (!lay.full) {
|
||||
lay.gdn.op_pf_out = decl_prefetch(b, lay.gdn.out.w, kGdnOutPrefetchBytes);
|
||||
lay.gdn.pf_out_rows = kPrefetchStepRows;
|
||||
lay.gdn.pf_out_seqs = kGdnOutPrefetchSeqs;
|
||||
}
|
||||
if (l + 1 < m.n_main) {
|
||||
const Layer& nx = m.layers[(size_t)l + 1];
|
||||
lay.pf_next_w = nx.full ? nx.attn.qg.w : nx.gdn.in.w;
|
||||
lay.op_pf_next = decl_prefetch(b, lay.pf_next_w, kPrefetchBytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
m.op_final_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", final_wadd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_out_norm)),
|
||||
{m.b_x}, {m.a_h.x});
|
||||
RAD_ARCH_TRY(rad_lane1_window_end(b));
|
||||
|
||||
m.op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
@@ -1138,6 +1297,239 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
#if !QWEN35_MOE
|
||||
/* ============================== A prefill step in two pieces ==============================
|
||||
*
|
||||
* At two ranks every layer of a prefill chunk makes two all-reduces, each folded into the next
|
||||
* block's norm (layer_fold) and each in a hard chain on one stream: block -> all-reduce + norm ->
|
||||
* block. On a 2048-token chunk they are about a fifth of the step, nearly all of it the link, with
|
||||
* nothing beside them.
|
||||
*
|
||||
* A step of one prefill sequence of at least kPipeMinRows tokens is cut into two pieces of about
|
||||
* half (pipe_rows), each the chunk a narrower batch makes. Every block runs a piece at a time on
|
||||
* the first lane, and the work between two blocks runs a piece at a time on the second: the
|
||||
* block's all-reduce at `overlap` 1 (a narrow launch that leaves the CUs to the compute beside it;
|
||||
* the fused all-reduce and norm would hold its blocks on the card while it waits on the link and
|
||||
* slow the GEMM beside it by a third), then the next block's plain norm, and after a feed-forward
|
||||
* that keeps its add, the add and the final norm (the drafter taps go on the first lane, pipe_taps).
|
||||
*
|
||||
* mixer the delta net and the dense attention run whole a piece at a time and hand the
|
||||
* first piece off behind its out projection (ArPieces), so its boundary runs beside
|
||||
* the second piece's mixer;
|
||||
* ffn its first piece runs beside the mixer's second boundary, its second beside its own
|
||||
* first boundary; the next mixer's first piece runs beside its second.
|
||||
*
|
||||
* A piece computes the bytes the narrower chunk does: every op is per row, both pieces sit in the
|
||||
* band of a whole step (pipe_rows), the all-reduce reduces within a row, the delta net carries its
|
||||
* state through the cache as between two chunks, and each attention piece sees the cache up to its
|
||||
* own end. The narrow all-reduce and the plain norm write the fused op's bytes, so a pipelined
|
||||
* step is bit for bit the serial one.
|
||||
*
|
||||
* The second lane's requirements (Ctx::lane1_) hold: every collective of the step is on it, the
|
||||
* embedding's included; none carries a device-wide arrival counter (the all-reduce's sequence
|
||||
* counters order its own launches, which one lane keeps in order); and the buffers it touches left
|
||||
* the sharing pool at declare (the drafter taps it does not touch: pipe_taps). */
|
||||
|
||||
template <class F>
|
||||
static void pipe_on1(RadCtx* c, const F& issue) {
|
||||
rad_lane(c, 1);
|
||||
rad_lane_join(c, 0, 1);
|
||||
issue();
|
||||
rad_lane(c, 0);
|
||||
}
|
||||
/* Lane 0 waits for everything issued on lane 1 so far. */
|
||||
static void pipe_wait1(RadCtx* c) { rad_lane_join(c, 1, 0); }
|
||||
|
||||
/* The work after block `s` (2l the mixer of layer l, 2l + 1 its feed-forward) for rows
|
||||
* [r0, r0 + n). */
|
||||
static void pipe_boundary(RadCtx* c, const Model& m, int64_t T, int64_t s, int64_t r0, int64_t n) {
|
||||
const Geom& g = m.g;
|
||||
const int64_t li = s / 2;
|
||||
const Layer& l = m.layers[(size_t)li];
|
||||
if (s % 2 == 0) {
|
||||
if (l.full) l.attn.issue_ar(c, r0, n);
|
||||
else l.gdn.issue_ar(c, r0, n);
|
||||
l.mlp.nq_h.step_plain(c, T, r0, n);
|
||||
return;
|
||||
}
|
||||
l.mlp.issue_ar(c, r0, n);
|
||||
if (l.mlp.op_add)
|
||||
RAD_ISSUE_N(c, l.mlp.op_add, n, brow_slice(m.b_x, r0, n, g.n_embd),
|
||||
brow_slice(m.a_h.x, r0, n, g.n_embd), brow_slice(m.b_x, r0, n, g.n_embd));
|
||||
if (li + 1 < (int64_t)m.layers.size()) {
|
||||
const Layer& nx = m.layers[(size_t)li + 1];
|
||||
(nx.full ? nx.attn.nq_h : nx.gdn.nq_h).step_plain(c, T, r0, n);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, m.op_final_norm, n, brow_slice(m.b_x, r0, n, g.n_embd), RAD_W(m.w_out_norm),
|
||||
brow_slice(m.a_h.x, r0, n, g.n_embd));
|
||||
}
|
||||
}
|
||||
|
||||
/* Layer `li`'s drafter taps of rows [r0, r0 + n), on lane 0. Issued once lane 0 has waited for that
|
||||
* piece's feed-forward boundary (its add is the last write to those rows of x before the next
|
||||
* block's boundary, which lane 1 starts only behind lane 0's next issues), so the taps buffer is
|
||||
* never touched from lane 1 and stays in the sharing pool: rad_buf_concurrent would hold its
|
||||
* [max_tok, n_taps * n_embd] for the whole program. */
|
||||
static void pipe_taps(RadCtx* c, const Model& m, int64_t li, int64_t r0, int64_t n) {
|
||||
for (int t = 0; t < m.n_taps; ++t) {
|
||||
if (m.tap_layer[t] != (int)li) continue;
|
||||
RAD_ISSUE_N(c, m.op_tap, n, brow_slice(m.b_x, r0, n, m.g.n_embd),
|
||||
bcol_at(m.b_dfsrc, r0, (int64_t)m.n_taps * m.g.n_embd, (int64_t)t * m.g.n_embd,
|
||||
m.g.n_embd, n));
|
||||
}
|
||||
}
|
||||
|
||||
/* A mixer's first piece is done (ArPieces): lane 0 takes the previous block's second boundary
|
||||
* before the second piece (and the previous layer's second-piece taps behind it), and lane 1 this
|
||||
* block's first behind it. */
|
||||
struct PipeHand {
|
||||
RadCtx* c = nullptr;
|
||||
const Model* m = nullptr;
|
||||
int64_t T = 0, s = 0;
|
||||
};
|
||||
static void pipe_hand(void* u, int64_t r0, int64_t n) {
|
||||
const PipeHand& h = *(const PipeHand*)u;
|
||||
pipe_wait1(h.c);
|
||||
if (h.s >= 2) {
|
||||
const int64_t R = pipe_rows(h.T);
|
||||
pipe_taps(h.c, *h.m, h.s / 2 - 1, R, h.T - R);
|
||||
}
|
||||
pipe_on1(h.c, [&] { pipe_boundary(h.c, *h.m, h.T, h.s, r0, n); });
|
||||
}
|
||||
|
||||
/* The bounds of this step's pieces on the card, {0, pipe_rows(T), T}, if the step is pipelined;
|
||||
* null for a serial step, and null with `failed` set when the step has been failed. Copied on the
|
||||
* step's stream ahead of every layer from the pinned table, whose rows never change, so a captured
|
||||
* step replays the same copy. */
|
||||
static const int32_t* pipe_ready(RadCtx* c, const RadBatch* batch, Model& m, bool* failed) {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (!m.pipe_on || !m.b_pipe_cu || T < kPipeMinRows || T > m.g.max_tok ||
|
||||
batch->phase != RAD_PHASE_PREFILL)
|
||||
return nullptr;
|
||||
/* A prefill step wide enough that runs serially says why, once, so a deployment that never
|
||||
* pipelines does not look like one that gains nothing from it. */
|
||||
auto serial = [&](const char* why) -> const int32_t* {
|
||||
if (!m.pipe_serial_noted && m.g.rank == 0)
|
||||
fprintf(stderr, "radiance: qwen35: a %lld-row prefill step runs serially: %s\n",
|
||||
(long long)T, why);
|
||||
m.pipe_serial_noted = true;
|
||||
return nullptr;
|
||||
};
|
||||
if (batch->n_seq != 1 || batch->n_seq_decode != 0) return serial("more than one sequence");
|
||||
if (!batch->positions) return serial("no positions");
|
||||
if (rope_mixed(batch) || batch->n_mm_rows > 0) return serial("media rows in the step");
|
||||
if (dbg_resid_on()) return serial("residual debugging is on");
|
||||
int32_t* d = (int32_t*)rad_buf_ptr(c, m.b_pipe_cu);
|
||||
if (!d) {
|
||||
/* Not a rank-local fallback to the serial step: the other rank would pipeline, and the two
|
||||
* would issue different collectives. Fail the step, as gemma3 does. */
|
||||
rad_step_fail(c, "qwen35: the pipelined prefill's bounds have no storage");
|
||||
*failed = true;
|
||||
return nullptr;
|
||||
}
|
||||
const int64_t R = pipe_rows(T);
|
||||
ArPieces pc{};
|
||||
pc.rows = R; pc.done = pipe_hand; pc.cu = d; pc.in_ready = true;
|
||||
for (const Layer& l : m.layers) {
|
||||
if (!(l.full ? l.attn.takes_pieces(batch, &pc) : l.gdn.takes_pieces(batch, &pc)))
|
||||
return serial(l.full ? "an attention block cannot run in pieces"
|
||||
: "a delta-net block cannot run in pieces");
|
||||
/* Every boundary issues its block's all-reduce itself, narrow, then the plain norm. */
|
||||
if (!(l.full ? l.attn.op_ar_ov : l.gdn.op_ar_ov) || !l.mlp.op_ar_ov)
|
||||
return serial("a block declares no overlap all-reduce");
|
||||
}
|
||||
if (!m.pipe_tbl_tried) {
|
||||
m.pipe_tbl_tried = true;
|
||||
const int64_t n = m.g.max_tok + 1;
|
||||
m.pipe_tbl = (int32_t*)rad_dev_alloc(3 * n * (int64_t)sizeof(int32_t), RAD_MEM_HOST_PINNED);
|
||||
if (m.pipe_tbl) {
|
||||
for (int64_t t = 0; t < n; ++t) {
|
||||
m.pipe_tbl[3 * t] = 0;
|
||||
m.pipe_tbl[3 * t + 1] = (int32_t)pipe_rows(t);
|
||||
m.pipe_tbl[3 * t + 2] = (int32_t)t;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Everything above depends only on the batch and the build, the same on every rank; what
|
||||
* follows is this rank's own, and falling back to the serial step here would leave the other
|
||||
* rank pipelining, the two issuing different collectives on the shared all-reduce instance
|
||||
* (a hang or a wrong sum). So it fails the step. */
|
||||
if (!m.pipe_tbl ||
|
||||
rad_memcpy_async(d, m.pipe_tbl + 3 * T, 3 * (int64_t)sizeof(int32_t), rad_stream(c)) !=
|
||||
RAD_OK) {
|
||||
rad_step_fail(c, "qwen35: the pipelined prefill's piece bounds could not be put on the card "
|
||||
"(no pinned host memory, or the copy failed)");
|
||||
*failed = true;
|
||||
return nullptr;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int32_t* pcu) {
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, R = pipe_rows(T);
|
||||
const int64_t L = (int64_t)m.layers.size();
|
||||
if (!m.pipe_noted) {
|
||||
m.pipe_noted = true;
|
||||
if (g.rank == 0)
|
||||
fprintf(stderr, "radiance: qwen35: prefill steps of one sequence from %lld rows are "
|
||||
"pipelined: two pieces, block boundaries on the second lane\n",
|
||||
(long long)kPipeMinRows);
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.op_embed,
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
|
||||
/* The embedding's reduction and layer 0's norm over the whole step, on lane 1 with every
|
||||
* other collective (the norm takes the reduction where the wire is exact). */
|
||||
pipe_on1(c, [&] {
|
||||
if (m.op_embed_ar && !ar_wire_is_exact(g, T))
|
||||
RAD_ISSUE_N(c, m.op_embed_ar, T * g.n_embd, brows(m.b_x, T), RAD_NONE);
|
||||
if (L > 0) (m.layers[0].full ? m.layers[0].attn.nq_h : m.layers[0].gdn.nq_h).step(c, T);
|
||||
});
|
||||
pipe_wait1(c);
|
||||
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));
|
||||
|
||||
for (int64_t li = 0; li < L; ++li) {
|
||||
const Layer& l = m.layers[(size_t)li];
|
||||
PipeHand h{c, &m, T, 2 * li};
|
||||
ArPieces pc{};
|
||||
pc.rows = R; pc.done = pipe_hand; pc.u = &h; pc.cu = pcu; pc.in_ready = true;
|
||||
if (l.full) l.attn.step(c, batch, false, &pc);
|
||||
else l.gdn.step(c, batch, false, &pc);
|
||||
if (pc.handed != 1) {
|
||||
rad_step_fail(c, "qwen35: a mixer did not run its two pieces in a pipelined prefill "
|
||||
"step (pipe_ready and the block's takes_pieces disagree)");
|
||||
return;
|
||||
}
|
||||
pipe_wait1(c);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, T, 2 * li, R, T - R); });
|
||||
l.mlp.body(c, T, 0, R);
|
||||
pipe_wait1(c);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, T, 2 * li + 1, 0, R); });
|
||||
l.mlp.body(c, T, R, T - R);
|
||||
pipe_wait1(c);
|
||||
pipe_taps(c, m, li, 0, R);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, T, 2 * li + 1, R, T - R); });
|
||||
}
|
||||
pipe_wait1(c);
|
||||
if (L > 0) pipe_taps(c, m, L - 1, R, T - R);
|
||||
|
||||
if (batch->n_out > 0) {
|
||||
if (m.op_logits_fill && plugin_words_cover_rows(batch)) {
|
||||
RAD_ISSUE_N(c, m.op_logits_fill, batch->n_out, brows(m.b_logits, batch->n_out));
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out,
|
||||
brows(m.a_h.x, T), praw(batch->out_ids, RAD_I32, batch->n_out),
|
||||
brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_logits, batch->n_out,
|
||||
brows(m.b_hout, batch->n_out), RAD_W(m.w_lm_head),
|
||||
brows(m.b_logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
|
||||
@@ -1176,6 +1568,15 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
return;
|
||||
}
|
||||
|
||||
#if !QWEN35_MOE
|
||||
bool pipe_failed = false;
|
||||
if (const int32_t* pcu = pipe_ready(c, batch, m, &pipe_failed)) {
|
||||
step_pipelined(c, batch, m, pcu);
|
||||
return;
|
||||
}
|
||||
if (pipe_failed) return;
|
||||
#endif
|
||||
|
||||
RAD_ISSUE(c, m.op_embed,
|
||||
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.w_tok),
|
||||
brows(m.b_x, batch->n_tok));
|
||||
@@ -1195,12 +1596,18 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
RAD_ISSUE_N(c, m.op_rope_cs, batch->n_tok,
|
||||
rope_pos1(batch, batch->n_tok), RAD_B(m.b_rope_cs));
|
||||
|
||||
/* Decode steps of up to kPrefetchStepRows rows only. This ceiling decides, not
|
||||
* prefetch_beside's own (16): it is passed a height of 1 where the step qualifies. */
|
||||
const int64_t pf_h =
|
||||
batch->phase == RAD_PHASE_DECODE && batch->n_tok <= kPrefetchStepRows ? 1 : INT64_MAX;
|
||||
for (int64_t li = 0; li < (int64_t)m.layers.size(); ++li) {
|
||||
const Layer& l = m.layers[(size_t)li];
|
||||
if (l.full) l.attn.step(c, batch);
|
||||
else l.gdn.step(c, batch);
|
||||
prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h);
|
||||
dbg_resid(c, (int)li, "mix", m.g.n_embd, m.b_x, m.a_h.x);
|
||||
l.mlp.step(c, batch);
|
||||
prefetch_beside(c, l.op_pf_next, l.pf_next_w, pf_h);
|
||||
dbg_resid(c, (int)li, "ffn", m.g.n_embd, m.b_x, m.a_h.x);
|
||||
|
||||
/* The tap, after the layer: the drafter conditions on this layer's output, which the next
|
||||
@@ -1216,6 +1623,10 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.a_h.x, batch->n_tok));
|
||||
|
||||
if (batch->n_out > 0) {
|
||||
if (m.op_logits_fill && plugin_words_cover_rows(batch)) {
|
||||
RAD_ISSUE_N(c, m.op_logits_fill, batch->n_out, brows(m.b_logits, batch->n_out));
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out,
|
||||
brows(m.a_h.x, batch->n_tok),
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out),
|
||||
@@ -1250,6 +1661,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
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;
|
||||
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);
|
||||
|
||||
@@ -174,6 +174,10 @@ struct Model {
|
||||
rad_buf b_mtp_hin = 0, b_mtp_hw = 0, b_mtp_e = 0, b_mtp_hout = 0;
|
||||
rad_buf b_mtp_dq = 0, b_mtp_ds = 0, b_mtp_dsum = 0;
|
||||
rad_buf b_mtp_dlog = 0, b_mtp_didx = 0, b_mtp_dval = 0;
|
||||
/* --draft-coupling: [max_seqs] draws staged before the serial passes and [max_spec,
|
||||
* max_seqs] states read back after them. PERSIST: the engine writes them from the host and the
|
||||
* head writes the states on the card, across a step boundary. */
|
||||
rad_buf b_mtp_couple_draws = 0, b_mtp_couple_state = 0;
|
||||
rad_buf b_mtp_dpair = 0, b_mtp_dgath = 0;
|
||||
|
||||
HcEnter enter;
|
||||
@@ -269,6 +273,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* real max_tok (RadBuildCtx::shape_probe). */
|
||||
static thread_local Model probe_model;
|
||||
Model& m = ctx->shape_probe ? probe_model : g_model[ctx->rank];
|
||||
/* 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. */
|
||||
if (m.pipe_cu_h) rad_dev_free(m.pipe_cu_h, RAD_MEM_HOST_PINNED);
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope ? ctx->scope : "");
|
||||
Names& nm = m.nm;
|
||||
@@ -1086,6 +1094,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* paths must give identical text; any difference is a defect. */
|
||||
if (m.qsaw.qk) {
|
||||
lay.attn.qsa_sel = m.qsaw.sel;
|
||||
lay.attn.qsa_nsel = m.qsaw.nsel;
|
||||
lay.attn.qsa_sequ = m.qsaw.sequ;
|
||||
lay.attn.qsa_topk = m.qsacfg.topk;
|
||||
/* The exactness bound, below which prefill issues the cheaper dense attention.
|
||||
@@ -1261,6 +1270,30 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* vocab-parallel all-gather a 16-byte row (rad_block_mtp_hc.h, kDraftTopR). */
|
||||
m.b_mtp_didx = decl_b(b, nm.f("mtp_didx"), RAD_I32, {g.max_logit_rows, kDraftTopR});
|
||||
m.b_mtp_dval = decl_b(b, nm.f("mtp_dval"), RAD_F32, {g.max_logit_rows, kDraftTopR});
|
||||
|
||||
/* --draft-coupling (RadBuildCtx::draft_coupling). Q is the law of the 2-bit candidate
|
||||
* head's reranked top-8; a plain bf16 head leaves one candidate and nothing to couple
|
||||
* over. The engine checks the drafter shape (a linear serial chain). */
|
||||
if (ctx->draft_coupling) {
|
||||
if (!m.b_mtp_didx || g.max_spec < 1 || g.max_spec > RAD_MTP_COUPLE_MAX_ROUNDS) {
|
||||
rad_note(b, "--draft-coupling on requires the 2-bit candidate head's reranked "
|
||||
"top8 and max_spec 1..%d",
|
||||
RAD_MTP_COUPLE_MAX_ROUNDS);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.b_mtp_couple_draws = decl_b(b, nm.f("mtp_couple_draws"), RAD_U32,
|
||||
{g.max_seqs, RAD_MTP_COUPLE_DRAW_WORDS},
|
||||
RAD_BUF_PERSIST);
|
||||
m.b_mtp_couple_state = decl_b(b, nm.f("mtp_couple_state"), RAD_U32,
|
||||
{g.max_spec, g.max_seqs,
|
||||
RAD_MTP_COUPLE_STATE_WORDS},
|
||||
RAD_BUF_PERSIST);
|
||||
if (!m.b_mtp_couple_draws || !m.b_mtp_couple_state) return RAD_E_INVAL;
|
||||
rad_note(b, "MTP coupled: the head samples x~Q from its reranked top8 each round "
|
||||
"(FP64), and the sampler couples the target's own draw to it; %lld "
|
||||
"round(s), fixed-seed tokens are NOT preserved",
|
||||
(long long)g.max_spec);
|
||||
}
|
||||
}
|
||||
|
||||
MtpHcBlock::Wire tw{};
|
||||
@@ -1270,6 +1303,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
tw.dq = m.b_mtp_dq; tw.ds = m.b_mtp_ds; tw.dsum = m.b_mtp_dsum;
|
||||
tw.dlog = m.b_mtp_dlog; tw.didx = m.b_mtp_didx; tw.dval = m.b_mtp_dval;
|
||||
tw.dpair = m.b_mtp_dpair; tw.dgath = m.b_mtp_dgath;
|
||||
tw.couple_draws = m.b_mtp_couple_draws; tw.couple_state = m.b_mtp_couple_state;
|
||||
/* The head reuses the trunk's working buffers, all dead by the time a draft round runs (a
|
||||
* second set would be 150 MiB). Only the wide stream and the carry are its own, since
|
||||
* they must survive the round that produced them. */
|
||||
@@ -1328,6 +1362,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.mtp.attn.kv_block = 4;
|
||||
if (m.qsaw.qk) {
|
||||
m.mtp.attn.qsa_sel = m.qsaw.sel;
|
||||
m.mtp.attn.qsa_nsel = m.qsaw.nsel;
|
||||
m.mtp.attn.qsa_sequ = m.qsaw.sequ;
|
||||
m.mtp.attn.qsa_topk = m.qsacfg.topk;
|
||||
m.mtp.attn.qsa_exact_to = m.qsacfg.budget + m.qsacfg.ratio - 1;
|
||||
@@ -1663,6 +1698,9 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
* mapped table). */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
/* The gated attention block declares the streamed store and the resolve
|
||||
* (rad_block_attn_gated_fp8.h). */
|
||||
out->kv_stream_ok = 1;
|
||||
out->draft_depth = 0;
|
||||
if (meta_int2(meta, "qwen4exp.mtp_num_hidden_layers", "mtp_num_hidden_layers", 0) > 0)
|
||||
out->draft_depth = 3;
|
||||
|
||||
+1
-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)
|
||||
lora kvstream)
|
||||
|
||||
set(RAD_CORE_SRC "")
|
||||
foreach(d ${RAD_CORE_DIRS})
|
||||
|
||||
@@ -115,6 +115,7 @@ public:
|
||||
rad_buf decl_buffer (const char* name, const RadBufDecl* d);
|
||||
rad_kvgroup decl_kv_group(const char* name, const RadKVGroupDecl* d);
|
||||
int64_t kv_block_size(rad_kvgroup g);
|
||||
int64_t kv_layer_bytes(rad_kvgroup g);
|
||||
int bind_layer_kv(int layer, rad_kvgroup g);
|
||||
rad_op decl_op (const char* op, const RadParam* p, int n_p,
|
||||
const rad_weight* w, int n_w);
|
||||
@@ -122,12 +123,16 @@ public:
|
||||
int op_declared (const char* op) const;
|
||||
int decl_name_map(const RadNameMap* m);
|
||||
int declare_logits(rad_buf b);
|
||||
int declare_scores(rad_buf hidden, rad_weight table);
|
||||
int declare_pooled(rad_buf b);
|
||||
int declare_plugin_words(int64_t max_words);
|
||||
int declare_drafter(const RadDrafterDecl* d);
|
||||
int drafter_shared_kv(int pos_offset);
|
||||
int lora_root(const char* native, const char* spellings);
|
||||
int lora_alias(const char* native, const char* from, const char* to, int64_t from_lo,
|
||||
int64_t from_hi, int64_t to_lo);
|
||||
int drafter_short_block(int64_t block);
|
||||
int drafter_tree(rad_buf parents);
|
||||
int declare_encoder(const RadEncoderDecl* d);
|
||||
int declare_generator(const RadGeneratorDecl* d);
|
||||
int declare_audio_generator(const RadAudioGenDecl* d);
|
||||
@@ -140,10 +145,12 @@ public:
|
||||
int op_reads (rad_op h, const rad_buf* b, int n);
|
||||
int op_writes(rad_op h, const rad_buf* b, int n);
|
||||
int buf_concurrent(rad_buf b);
|
||||
int lane1_window(bool end);
|
||||
int weight_shard_span(rad_weight w, int64_t lo, int64_t hi);
|
||||
int weight_shard_span_parts(rad_weight w, const int64_t* lo, const int64_t* hi,
|
||||
const int64_t* total, int n);
|
||||
int kv_group_zero(rad_kvgroup g);
|
||||
int kv_group_dense_read(rad_kvgroup g);
|
||||
int kv_group_replicated(rad_kvgroup g);
|
||||
|
||||
/* Finalise: weight first/last use, KV group geometry, buffer liveness and packing. Returns
|
||||
@@ -195,6 +202,7 @@ private:
|
||||
/* init() for every surviving instance, after the whole graph has resolved, so a failing init
|
||||
* cannot abort declare before the miss report is assembled. */
|
||||
void finish_instances();
|
||||
void fill_tune_instances();
|
||||
int32_t find_kv_consumer(rad_kvgroup g);
|
||||
void finish_layouts();
|
||||
void finish_kv_groups();
|
||||
@@ -220,6 +228,8 @@ private:
|
||||
/* Buffers touched from the second lane (rad_buf_concurrent). Their declared op range does not
|
||||
* bound when their bytes are in use, so they are live for the whole program. */
|
||||
std::set<rad_buf> concurrent_bufs_;
|
||||
/* The second lane's window (rad_lane1_window_begin), first and last op handle; -1 when none. */
|
||||
int32_t lane1_w0_ = -1, lane1_w1_ = -1;
|
||||
|
||||
/* Parallel to prog_.kv_groups: where in the op list the group was declared, and the op found
|
||||
* to consume it. Declaration order is the only link between an op and a group; see
|
||||
@@ -235,6 +245,9 @@ private:
|
||||
* per rank). */
|
||||
std::unordered_map<std::string, rad_weight> weight_by_name_;
|
||||
|
||||
/* tune_key() -> index in prog_.tune_requests: one request per kernel instantiation. */
|
||||
std::unordered_map<std::string, size_t> tune_index_;
|
||||
|
||||
/* The model's answers, cached per source: a routed model declares each expert's codes and
|
||||
* scales as two weights over one source, and a checkpoint lookup walks the name map. */
|
||||
WeightSourceFn sources_;
|
||||
|
||||
+351
-27
@@ -9,6 +9,7 @@
|
||||
* which makes fusion a selection rather than a compiler pass (spec §2.3).
|
||||
*/
|
||||
#include "rad_build.h"
|
||||
#include "kvstream/bringup.h"
|
||||
#include "lora/lora.h"
|
||||
#include "../device/device.h"
|
||||
|
||||
@@ -205,21 +206,24 @@ rad_weight Builder::decl_weight(const char* name, const RadWeightDecl* d) {
|
||||
|
||||
/* Check the declaration against the planes. One plane is declared at its own dtype and extents
|
||||
* (this rank's share under a shard); several at the codes' dtype and the logical extents. A
|
||||
* different dtype must be an exact widening the loader performs; a quantisation belongs to
|
||||
* different dtype must be an exact conversion the loader performs; a quantisation belongs to
|
||||
* rad-convert and is refused. */
|
||||
const RadEncPlane& p0 = w.enc.plane[w.sel[0]];
|
||||
if (p0.dtype != d->dtype) {
|
||||
const bool widen = w.n_sel == 1 && d->dtype == RAD_F32 &&
|
||||
(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)
|
||||
if (!widen && !narrow)
|
||||
return err(RAD_E_DTYPE, "weight '%s' is declared %s, and '%s' holds %s as %s: only an "
|
||||
"exact widening 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),
|
||||
"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 = true;
|
||||
w.widen = widen;
|
||||
w.narrow = narrow;
|
||||
}
|
||||
int64_t sr = 0, sc = 0; /* the source's logical [rows, cols] */
|
||||
if (w.enc_known) rad_enc_view(ws.rank, ws.shape, &sr, &sc);
|
||||
@@ -256,8 +260,9 @@ rad_weight Builder::decl_weight(const char* name, const RadWeightDecl* d) {
|
||||
* the resolved kernel's layout hook asks for another (spec §4.3); no hook, or
|
||||
* RAD_E_UNSUPPORTED, keeps this. */
|
||||
w.identity = true;
|
||||
w.stored_dtype = w.widen ? d->dtype : p0.dtype;
|
||||
w.stored_bytes = w.widen ? rad_dtype_bytes(d->dtype, vr * vc)
|
||||
const bool converted = w.widen || w.narrow;
|
||||
w.stored_dtype = converted ? d->dtype : p0.dtype;
|
||||
w.stored_bytes = converted ? rad_dtype_bytes(d->dtype, vr * vc)
|
||||
: vr * rad_enc_row_bytes(p0.dtype, vc);
|
||||
w.stored_rank = d->rank;
|
||||
for (uint32_t i = 0; i < RAD_MAX_RANK; ++i)
|
||||
@@ -466,20 +471,31 @@ int64_t Builder::kv_block_size(rad_kvgroup g) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* One layer's bytes of a paged group's block: what a kernel addressing one layer sees, and the
|
||||
* pitch of a streamed group's host mirror rows. */
|
||||
int64_t Builder::kv_layer_bytes(rad_kvgroup g) {
|
||||
if (g == 0 || g >= prog_.kv_groups.size()) return 0;
|
||||
KVGroupInfo& gi = prog_.kv_groups[g];
|
||||
if (gi.decl.kind != RAD_KV_FULL && gi.decl.kind != RAD_KV_WINDOW) return 0;
|
||||
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);
|
||||
}
|
||||
|
||||
/* ================================================================== ops */
|
||||
/* A kernel instantiation: (kernel, plugin, resolved input params). Keyed on geom_key, not
|
||||
* geom.str(), so tuner and selector key identically: geom_key is tunecache.h's canonical sorted
|
||||
* spelling without the tuned axes, while geom.str() keeps declaration order and includes them. */
|
||||
static std::string tune_key(const Resolved& r) {
|
||||
return r.row->info->name + std::string("\x1f") + r.row->plugin + std::string("\x1f") +
|
||||
r.geom_key;
|
||||
}
|
||||
|
||||
void Builder::record_tune_request(const Resolved& r) {
|
||||
if (!r.row || !r.row->info || r.row->info->n_tunables <= 0) return;
|
||||
/* One request per kernel instantiation: (kernel, plugin, resolved input params). The same
|
||||
* shape requested by many layers is one benchmark (spec §15).
|
||||
*
|
||||
* Keyed on geom_key, not geom.str(), so tuner and selector key identically: geom_key is
|
||||
* tunecache.h's canonical sorted spelling without the tuned axes, while geom.str() keeps
|
||||
* declaration order and includes the axes. */
|
||||
const std::string key = r.row->info->name + std::string("\x1f") + r.row->plugin +
|
||||
std::string("\x1f") + r.geom_key;
|
||||
for (auto& t : prog_.tune_requests)
|
||||
if (t.kernel + std::string("\x1f") + t.plugin + std::string("\x1f") + t.geom_key == key)
|
||||
return;
|
||||
/* The same shape requested by many layers is one benchmark (spec §15). */
|
||||
if (!tune_index_.emplace(tune_key(r), prog_.tune_requests.size()).second) return;
|
||||
|
||||
Program::TuneRequest req;
|
||||
req.kernel = r.row->info->name;
|
||||
@@ -487,6 +503,7 @@ void Builder::record_tune_request(const Resolved& r) {
|
||||
req.geom = r.geom;
|
||||
req.geom_key = r.geom_key;
|
||||
req.info = r.row->info;
|
||||
req.instance = r.instance;
|
||||
prog_.tune_requests.push_back(std::move(req));
|
||||
}
|
||||
|
||||
@@ -597,6 +614,22 @@ void Builder::finish_instances() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Hand each tune request the instance finish_instances() made for its kernel: a collective's
|
||||
* launch reaches its peer bundle (scratch, flags, sequence counters) only through the instance, so
|
||||
* the tuner forms its launches from this. */
|
||||
void Builder::fill_tune_instances() {
|
||||
if (prog_.tune_requests.empty()) return;
|
||||
for (size_t i = 1; i < prog_.ops.size(); ++i)
|
||||
for (const Band& b : prog_.ops[i].bands)
|
||||
for (int d = 0; d < RAD_N_DOMAINS; ++d) {
|
||||
const Resolved& r = b.dom[d];
|
||||
if (!r || !r.row || !r.row->info || r.row->info->n_tunables <= 0) continue;
|
||||
const auto it = tune_index_.find(tune_key(r));
|
||||
if (it != tune_index_.end()) prog_.tune_requests[it->second].instance = r.instance;
|
||||
}
|
||||
}
|
||||
|
||||
rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
|
||||
const rad_weight* w, int n_w) {
|
||||
if (finished_) return err(RAD_E_STATE, "decl_op('%s') after declare finished", opname ? opname : "");
|
||||
@@ -803,6 +836,7 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
|
||||
}
|
||||
|
||||
int Builder::op_declared(const char* op) const {
|
||||
if (kvstream_op_gated(prog_.ctx, op)) return 0; /* kvstream_op_gated */
|
||||
return op && reg_.schema(op) ? 1 : 0;
|
||||
}
|
||||
|
||||
@@ -841,6 +875,26 @@ int Builder::buf_concurrent(rad_buf b) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* See rad_lane1_window_begin. The window is the ops declared between the two calls. */
|
||||
int Builder::lane1_window(bool end) {
|
||||
if (finished_) { err(RAD_E_STATE, "rad_lane1_window after declare finished"); return RAD_E_STATE; }
|
||||
const int32_t next = (int32_t)prog_.ops.size(); /* the next op's handle */
|
||||
if (!end) {
|
||||
if (lane1_w0_ >= 0) {
|
||||
err(RAD_E_STATE, "rad_lane1_window_begin called twice: one window a program");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
lane1_w0_ = next;
|
||||
} else {
|
||||
if (lane1_w0_ < 0 || lane1_w1_ >= 0 || next - 1 < lane1_w0_) {
|
||||
err(RAD_E_STATE, "rad_lane1_window_end without a begin, twice, or around no op");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
lane1_w1_ = next - 1;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* See rad_weight_shard_span. Checked against the declaration here, where the plugin can be named;
|
||||
* the loader checks it against the container. */
|
||||
int Builder::weight_shard_span(rad_weight h, int64_t lo, int64_t hi) {
|
||||
@@ -938,6 +992,21 @@ int Builder::kv_group_zero(rad_kvgroup h) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Builder::kv_group_dense_read(rad_kvgroup h) {
|
||||
if (finished_) { err(RAD_E_STATE, "kv_group_dense_read after declare finished"); return RAD_E_STATE; }
|
||||
if (h == 0 || h >= prog_.kv_groups.size()) return RAD_E_INVAL;
|
||||
/* Full groups only: a state slot is already per sequence, and a window bounds its own
|
||||
* history. */
|
||||
const KVGroupInfo& gi = prog_.kv_groups[h];
|
||||
if (gi.decl.kind != RAD_KV_FULL) {
|
||||
err(RAD_E_INVAL, "kv group '%s': dense_read on a group that is not a full attention group",
|
||||
gi.name.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
prog_.kv_groups[h].dense_read = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Builder::kv_group_replicated(rad_kvgroup h) {
|
||||
if (finished_) {
|
||||
err(RAD_E_STATE, "kv_group_replicated after declare finished");
|
||||
@@ -1065,6 +1134,40 @@ int Builder::decl_name_map(const RadNameMap* m) {
|
||||
/* The buffer the core samples from. A second call is refused rather than winning: a target and
|
||||
* its drafter declaring into one builder (spec §10) both have logits, and keeping the second would
|
||||
* sample the draft distribution. The drafter's logits are reached through its scope. */
|
||||
int Builder::declare_scores(rad_buf hidden, rad_weight table) {
|
||||
if (finished_) { err(RAD_E_STATE, "declare_scores after declare finished"); return RAD_E_STATE; }
|
||||
if (hidden == RAD_NULL_HANDLE || (size_t)hidden >= prog_.buffers.size()) {
|
||||
err(RAD_E_INVAL, "declare_scores: %u is not a declared buffer", (unsigned)hidden);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (table == RAD_NULL_HANDLE || (size_t)table >= prog_.weights.size()) {
|
||||
err(RAD_E_INVAL, "declare_scores: %u is not a declared weight", (unsigned)table);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const RadBufDecl& h = prog_.buffers[hidden].decl;
|
||||
const auto& w = prog_.weights[table];
|
||||
if (h.dtype != RAD_BF16 || h.rank != 2 || w.decl.dtype != RAD_BF16 || w.decl.rank != 2 ||
|
||||
w.decl.shape[1] != h.shape[1]) {
|
||||
err(RAD_E_INVAL, "declare_scores: the hidden rows ('%s') and the table ('%s') must be bf16 "
|
||||
"[rows, n_embd] and [n_vocab, n_embd]", prog_.buffers[hidden].name.c_str(),
|
||||
w.name.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The table must cover the vocabulary: the scored readout indexes it by token id (the
|
||||
* scheduler bounds candidate ids by meta.n_vocab), and a table a few thousand rows short
|
||||
* would turn the last block of the vocabulary into a read off the end of a weight — a device
|
||||
* fault, not a refusal. More rows than the vocabulary is padding and reads fine. */
|
||||
if (w.decl.shape[0] < prog_.meta.n_vocab) {
|
||||
err(RAD_E_INVAL, "declare_scores: the table ('%s') has %lld rows, under the %lld-token "
|
||||
"vocabulary the scored readout indexes it by", w.name.c_str(),
|
||||
(long long)w.decl.shape[0], (long long)prog_.meta.n_vocab);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
prog_.score_hidden = hidden;
|
||||
prog_.score_table = table;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Builder::declare_logits(rad_buf b) {
|
||||
if (finished_) { err(RAD_E_STATE, "declare_logits after declare finished"); return RAD_E_STATE; }
|
||||
if (b == RAD_NULL_HANDLE || (size_t)b >= prog_.buffers.size()) {
|
||||
@@ -1150,6 +1253,19 @@ int Builder::declare_pooled(rad_buf b) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The words a request may hand the plugin (rad_declare_plugin_words). A bound, not a buffer: the
|
||||
* batch builder stages them per sequence beside the step's other arrays. */
|
||||
int Builder::declare_plugin_words(int64_t max_words) {
|
||||
if (finished_) { err(RAD_E_STATE, "declare_plugin_words after declare finished"); return RAD_E_STATE; }
|
||||
if (max_words < 0 || max_words > (1 << 20)) {
|
||||
err(RAD_E_INVAL, "declare_plugin_words: %lld words a request; the bound is 0 to %d",
|
||||
(long long)max_words, 1 << 20);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
prog_.plugin_words = max_words;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Validates the encoder at declare: it runs only when a request carries media, so a bad
|
||||
* declaration would otherwise surface on the first image as an out-of-bounds pass.
|
||||
*
|
||||
@@ -1398,7 +1514,12 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
|
||||
: prog_.generator.layout != 0 ? "an image generator" : "a video generator");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (!d->tmpl || !std::strstr(d->tmpl, "{input}") || !std::strstr(d->tmpl, "{instructions}")) {
|
||||
if (!d->tmpl && !d->tmpl_plain) {
|
||||
err(RAD_E_INVAL, "declare_audio_generator '%s': no prompt template (tmpl or tmpl_plain)",
|
||||
nm);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->tmpl && (!std::strstr(d->tmpl, "{input}") || !std::strstr(d->tmpl, "{instructions}"))) {
|
||||
err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl needs {instructions} and {input}", nm);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
@@ -1408,6 +1529,45 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
|
||||
"instructions and needs {input} alone", nm);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* References: a template with both of its slots, an item with one transcript before its one
|
||||
* clip, and the clips' geometry; read whole by one branch's prompt (an unconditional branch
|
||||
* would need references of its own). */
|
||||
if (d->tmpl_ref) {
|
||||
auto once = [](const char* t, const char* k) {
|
||||
const char* a = t ? std::strstr(t, k) : nullptr;
|
||||
return a && !std::strstr(a + 1, k);
|
||||
};
|
||||
const char* au = d->ref_item ? std::strstr(d->ref_item, "{audio}") : nullptr;
|
||||
const char* tx = d->ref_item ? std::strstr(d->ref_item, "{text}") : nullptr;
|
||||
if (!once(d->tmpl_ref, "{references}") || !once(d->tmpl_ref, "{input}") ||
|
||||
std::strstr(d->tmpl_ref, "{instructions}") || !once(d->ref_item, "{audio}") ||
|
||||
!once(d->ref_item, "{text}") || !au || !tx || tx > au) {
|
||||
err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl_ref needs {references} and "
|
||||
"{input} once each, and ref_item {text} before its one {audio}", nm);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->branches != 1 || !d->prompt_whole || d->ref_rate <= 0 || d->ref_hop <= 0 ||
|
||||
d->ref_max <= 0 || d->ref_max_samples < d->ref_hop) {
|
||||
err(RAD_E_INVAL, "declare_audio_generator '%s': references are read by a model of one "
|
||||
"branch from whole prompts, clips at a rate (%lld Hz) in frames of "
|
||||
"%lld samples, at most %d of them and %lld samples a request", nm,
|
||||
(long long)d->ref_rate, (long long)d->ref_hop, (int)d->ref_max,
|
||||
(long long)d->ref_max_samples);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
if (d->branches != 0 && d->branches != 1 && d->branches != 2) {
|
||||
err(RAD_E_INVAL, "declare_audio_generator '%s': branches is %d; a request runs 1 sequence "
|
||||
"or 2 (0 means 2)", nm, (int)d->branches);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* One branch has no unconditional prompt to render and no guidance to apply. */
|
||||
if (d->branches == 1 && (d->neg_tmpl || d->default_cfg != 1.0)) {
|
||||
err(RAD_E_INVAL, "declare_audio_generator '%s': a model of one branch has no "
|
||||
"unconditional template and no guidance (default_cfg %g)", nm,
|
||||
d->default_cfg);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->neg_tmpl && !d->prompt_whole) {
|
||||
err(RAD_E_INVAL, "declare_audio_generator '%s': an unconditional template makes branches "
|
||||
"of different lengths, which step together only as whole prompts; set "
|
||||
@@ -1485,15 +1645,24 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
|
||||
!buf_ok(d->audio_out, RAD_F32, win_samples * d->channels, "audio_out"))
|
||||
return RAD_E_INVAL;
|
||||
prog_.agen_str.name = nm;
|
||||
prog_.agen_str.tmpl = d->tmpl;
|
||||
prog_.agen_str.tmpl = d->tmpl ? d->tmpl : "";
|
||||
prog_.agen_str.tmpl_plain = d->tmpl_plain ? d->tmpl_plain : "";
|
||||
prog_.agen_str.neg_tmpl = d->neg_tmpl ? d->neg_tmpl : "";
|
||||
prog_.agen_str.tmpl_ref = d->tmpl_ref ? d->tmpl_ref : "";
|
||||
prog_.agen_str.ref_item = d->tmpl_ref && d->ref_item ? d->ref_item : "";
|
||||
prog_.audio_gen = *d;
|
||||
/* As for the image generator: the Program is moved after declare; strings live in agen_str. */
|
||||
prog_.audio_gen.name = nullptr;
|
||||
prog_.audio_gen.tmpl = nullptr;
|
||||
prog_.audio_gen.tmpl_plain = nullptr;
|
||||
prog_.audio_gen.neg_tmpl = nullptr;
|
||||
prog_.audio_gen.tmpl_ref = nullptr;
|
||||
prog_.audio_gen.ref_item = nullptr;
|
||||
/* Without references the clips' geometry is nothing: the driver stages none. */
|
||||
if (!d->tmpl_ref) {
|
||||
prog_.audio_gen.ref_rate = prog_.audio_gen.ref_hop = prog_.audio_gen.ref_max_samples = 0;
|
||||
prog_.audio_gen.ref_max = 0;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1780,6 +1949,13 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
|
||||
(long long)d->proposal_pitch);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->kind == RAD_DRAFT_BLOCK && d->proposal_pitch > 0 && d->proposal_pitch < d->depth) {
|
||||
err(RAD_E_INVAL, "declare_drafter '%s': proposal_pitch %lld under depth %d. A block pass "
|
||||
"writes each sequence's %d proposals into one row of the proposal buffer, "
|
||||
"so a row must hold them.", nm, (long long)d->proposal_pitch, d->depth,
|
||||
d->depth);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* A block pass embeds the mask id at every unfilled position, so it needs one. */
|
||||
if (d->kind == RAD_DRAFT_BLOCK && d->mask_token < 0) {
|
||||
err(RAD_E_INVAL, "declare_drafter '%s': RAD_DRAFT_BLOCK with no mask_token. Every "
|
||||
@@ -1801,7 +1977,10 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
|
||||
int64_t block = d->block;
|
||||
if (d->kind == RAD_DRAFT_BLOCK) {
|
||||
if (block == 0) block = (int64_t)d->depth + 1;
|
||||
if (block < 2 || block < (int64_t)d->depth || block > (int64_t)d->depth + 1) {
|
||||
/* A tree's (rad_drafter_tree) node count is not its block's draft count: more nodes
|
||||
* than draft positions (a wider tree) or fewer (a block longer than the tree is deep on
|
||||
* most steps). Checked at finish, once the tree is or is not declared. */
|
||||
if (block < 2) {
|
||||
err(RAD_E_INVAL, "declare_drafter '%s': block %lld rows at depth %d. The head runs "
|
||||
"over the last %d rows of the block, so the block is either %d rows "
|
||||
"(the anchor predicts nothing) or %d (it does).",
|
||||
@@ -1823,7 +2002,11 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
|
||||
prog_.drafter_name = nm;
|
||||
prog_.drafter.name = nullptr;
|
||||
prog_.drafter.block = block;
|
||||
if (prog_.drafter.proposal_pitch == 0) prog_.drafter.proposal_pitch = 1;
|
||||
/* A block drafter's proposal row holds its whole block's tokens, and the engine reads row s
|
||||
* at s * pitch (a short block fills only its front), so its pitch defaults to depth; a serial
|
||||
* one writes a token a pass, at pitch 1 by default. */
|
||||
if (prog_.drafter.proposal_pitch == 0)
|
||||
prog_.drafter.proposal_pitch = prog_.drafter.kind == RAD_DRAFT_BLOCK ? prog_.drafter.depth : 1;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1915,6 +2098,64 @@ int Builder::lora_alias(const char* native, const char* from, const char* to, in
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A block drafter's shorter block (rad_builder.h). Validated at declare: the core stages the block
|
||||
* from it, and a block the plugin did not declare its ops at would fail the step. */
|
||||
int Builder::drafter_short_block(int64_t block) {
|
||||
if (finished_) {
|
||||
err(RAD_E_STATE, "drafter_short_block after declare finished");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (prog_.drafter.kind != RAD_DRAFT_BLOCK) {
|
||||
err(RAD_E_STATE, "drafter_short_block: %s. Only a BLOCK drafter proposes a block; declare "
|
||||
"it with rad_declare_drafter first.",
|
||||
prog_.drafter.kind == RAD_DRAFT_NONE ? "no drafter is declared"
|
||||
: "the declared drafter is a SERIAL head");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const int64_t full = prog_.drafter.block > 0 ? prog_.drafter.block : prog_.drafter.depth + 1;
|
||||
const int64_t lead = full - prog_.drafter.depth; /* rows ahead of the proposing ones */
|
||||
/* A tree (rad_drafter_tree, declared first) grows a tree of its own over the shorter pass, up
|
||||
* to block - 1 nodes whatever its own node count, so it needs only two rows. */
|
||||
if (prog_.drafter_tree ? (block < 2 || block >= full) : (block >= full || block - lead < 1)) {
|
||||
err(RAD_E_INVAL, "drafter_short_block '%s': %lld rows. The short block must be shorter "
|
||||
"than the drafter's own (%lld) and still propose a token (%s %lld rows).",
|
||||
prog_.drafter_name.c_str(), (long long)block, (long long)full,
|
||||
prog_.drafter_tree ? "at least" : "more than",
|
||||
(long long)(prog_.drafter_tree ? 2 : lead));
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
prog_.drafter_short_block = block;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A block drafter whose proposal is a tree (rad_builder.h). */
|
||||
int Builder::drafter_tree(rad_buf parents) {
|
||||
if (finished_) {
|
||||
err(RAD_E_STATE, "drafter_tree after declare finished");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (prog_.drafter.kind != RAD_DRAFT_BLOCK) {
|
||||
err(RAD_E_STATE, "drafter_tree: %s. Only a BLOCK drafter's one pass proposes every node at "
|
||||
"once; declare it with rad_declare_drafter first.",
|
||||
prog_.drafter.kind == RAD_DRAFT_NONE ? "no drafter is declared"
|
||||
: "the declared drafter is a SERIAL head");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (parents == RAD_NULL_HANDLE || (size_t)parents >= prog_.buffers.size()) {
|
||||
err(RAD_E_INVAL, "drafter_tree '%s': parents buffer %u is not a declared buffer",
|
||||
prog_.drafter_name.c_str(), (unsigned)parents);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (prog_.buffers[parents].decl.dtype != RAD_I32) {
|
||||
err(RAD_E_DTYPE, "drafter_tree '%s': parents buffer '%s' is not i32",
|
||||
prog_.drafter_name.c_str(), prog_.buffers[parents].name.c_str());
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
prog_.drafter_tree = true;
|
||||
prog_.drafter_parents = parents;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void Builder::note_v(const char* f, va_list ap) {
|
||||
char msg[1024];
|
||||
vsnprintf(msg, sizeof msg, f ? f : "", ap);
|
||||
@@ -2054,12 +2295,13 @@ void Builder::finish_layouts() {
|
||||
w.source.c_str());
|
||||
continue; /* the stored defaults decl_weight set stand */
|
||||
}
|
||||
if (w.widen) {
|
||||
if (w.widen || w.narrow) {
|
||||
err(RAD_E_DTYPE, "'%s' is declared %s over a %s plane and kernel %s "
|
||||
"relayouts it; a widening and a relayout are not both "
|
||||
"relayouts it; a %s and a relayout are not both "
|
||||
"done at load", w.name.c_str(),
|
||||
rad_dtype_name(w.decl.dtype),
|
||||
rad_dtype_name(w.enc.plane[w.sel[0]].dtype), ki->name);
|
||||
rad_dtype_name(w.enc.plane[w.sel[0]].dtype), ki->name,
|
||||
w.widen ? "widening" : "narrowing");
|
||||
continue;
|
||||
}
|
||||
w.layout_tag = tag;
|
||||
@@ -2178,6 +2420,10 @@ void Builder::finish_buffer_liveness() {
|
||||
/* A second lane, signalled by any concurrent buffer, gets a second scratch region
|
||||
* (Program::scratch_regions). */
|
||||
prog_.scratch_regions = concurrent_bufs_.empty() ? 1 : 2;
|
||||
if (lane1_w0_ >= 0 && lane1_w1_ < 0)
|
||||
err(RAD_E_STATE, "rad_lane1_window_begin without rad_lane1_window_end");
|
||||
prog_.lane1_w0 = lane1_w1_ >= 0 ? lane1_w0_ : -1;
|
||||
prog_.lane1_w1 = lane1_w1_;
|
||||
|
||||
/* Each buffer's first and last declaring op, in one pass over the op lists. */
|
||||
const size_t nb = prog_.buffers.size();
|
||||
@@ -2195,11 +2441,19 @@ void Builder::finish_buffer_liveness() {
|
||||
* rule); a buffer on the second lane, whose declared range does not bound when its bytes
|
||||
* are in use; and one with no declared use, since an op may issue any handle in any
|
||||
* order (--debug-graph reports the cost). */
|
||||
if (b.decl.kind != RAD_BUF_TRANSIENT || concurrent_bufs_.count((rad_buf)i) || first[i] < 0) {
|
||||
if (b.decl.kind != RAD_BUF_TRANSIENT || first[i] < 0 ||
|
||||
(concurrent_bufs_.count((rad_buf)i) && lane1_w1_ < 0)) {
|
||||
b.first_def = 0;
|
||||
b.last_use = last_op;
|
||||
continue;
|
||||
}
|
||||
/* A concurrent buffer under a declared window (rad_lane1_window_begin): live across the
|
||||
* window, when lane 1 may touch it, and over its own uses. */
|
||||
if (concurrent_bufs_.count((rad_buf)i)) {
|
||||
b.first_def = std::min(first[i], lane1_w0_);
|
||||
b.last_use = std::max(last[i], lane1_w1_);
|
||||
continue;
|
||||
}
|
||||
b.first_def = first[i];
|
||||
b.last_use = last[i];
|
||||
|
||||
@@ -2210,6 +2464,25 @@ void Builder::finish_buffer_liveness() {
|
||||
* output likewise: the engine reads it after the last op. */
|
||||
if ((rad_buf)i == prog_.logits_buf || (rad_buf)i == prog_.pooled_buf) b.last_use = last_op;
|
||||
}
|
||||
|
||||
/* Region 1 holds what an op the second lane may issue asks for (Program::scratch_bytes_lane1):
|
||||
* every transient buffer of such an op is concurrent (Ctx::lane1_ rule 3). Ctx::issue refuses a
|
||||
* larger request on lane 1 by name, so an op that breaks the rule fails rather than overruns. */
|
||||
prog_.scratch_bytes_lane1 = 0;
|
||||
if (prog_.scratch_regions > 1)
|
||||
for (size_t o = 1; o < prog_.ops.size() && o < op_bufs_.size(); ++o) {
|
||||
bool lane1 = true;
|
||||
for (const std::vector<rad_buf>* v : { &op_bufs_[o].reads, &op_bufs_[o].writes })
|
||||
for (rad_buf h : *v)
|
||||
if (prog_.buffers[h].decl.kind == RAD_BUF_TRANSIENT && !concurrent_bufs_.count(h))
|
||||
lane1 = false;
|
||||
if (!lane1) continue;
|
||||
for (const Band& bd : prog_.ops[o].bands)
|
||||
if (bd.dom[RAD_DOMAIN_DEVICE] &&
|
||||
bd.dom[RAD_DOMAIN_DEVICE].scratch_bytes > prog_.scratch_bytes_lane1)
|
||||
prog_.scratch_bytes_lane1 = bd.dom[RAD_DOMAIN_DEVICE].scratch_bytes;
|
||||
}
|
||||
if (prog_.scratch_bytes_lane1 > prog_.scratch_bytes) prog_.scratch_bytes_lane1 = prog_.scratch_bytes;
|
||||
}
|
||||
|
||||
int Builder::finish() {
|
||||
@@ -2237,7 +2510,18 @@ int Builder::finish() {
|
||||
w.source.c_str(), rad_dtype_name(w.decl.dtype));
|
||||
}
|
||||
|
||||
if (prog_.drafter.kind == RAD_DRAFT_BLOCK && !prog_.drafter_tree &&
|
||||
(prog_.drafter.block < prog_.drafter.depth ||
|
||||
prog_.drafter.block > (int64_t)prog_.drafter.depth + 1))
|
||||
err(RAD_E_INVAL, "declare_drafter '%s': block %lld rows at depth %d. The head runs over the "
|
||||
"last %d rows of the block, so the block is either %d rows (the anchor "
|
||||
"predicts nothing) or %d (it does); only a tree (rad_drafter_tree) "
|
||||
"proposes a node count other than its block's drafts.",
|
||||
prog_.drafter_name.c_str(), (long long)prog_.drafter.block, prog_.drafter.depth,
|
||||
prog_.drafter.depth, prog_.drafter.depth + 1, prog_.drafter.depth);
|
||||
|
||||
if (instances_) finish_instances();
|
||||
fill_tune_instances();
|
||||
finish_weight_uses();
|
||||
finish_layouts();
|
||||
finish_kv_groups();
|
||||
@@ -2306,6 +2590,11 @@ int64_t rad_kv_block_size(RadBuilder* b, rad_kvgroup g) {
|
||||
return B(b)->kv_block_size(g);
|
||||
}
|
||||
|
||||
int64_t rad_kv_layer_bytes(RadBuilder* b, rad_kvgroup g) {
|
||||
if (!b) return 0;
|
||||
return B(b)->kv_layer_bytes(g);
|
||||
}
|
||||
|
||||
int rad_bind_layer_kv(RadBuilder* b, int layer, rad_kvgroup g) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->bind_layer_kv(layer, g);
|
||||
@@ -2342,6 +2631,16 @@ int rad_buf_concurrent(RadBuilder* b, rad_buf buf) {
|
||||
return B(b)->buf_concurrent(buf);
|
||||
}
|
||||
|
||||
int rad_lane1_window_begin(RadBuilder* b) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->lane1_window(false);
|
||||
}
|
||||
|
||||
int rad_lane1_window_end(RadBuilder* b) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->lane1_window(true);
|
||||
}
|
||||
|
||||
int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->weight_shard_span(w, lo, hi);
|
||||
@@ -2358,6 +2657,11 @@ int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) {
|
||||
return B(b)->kv_group_zero(g);
|
||||
}
|
||||
|
||||
int rad_kv_group_dense_read(RadBuilder* b, rad_kvgroup g) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->kv_group_dense_read(g);
|
||||
}
|
||||
|
||||
int rad_kv_group_replicated(RadBuilder* b, rad_kvgroup g) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->kv_group_replicated(g);
|
||||
@@ -2373,11 +2677,21 @@ int rad_declare_logits(RadBuilder* b, rad_buf logits) {
|
||||
return B(b)->declare_logits(logits);
|
||||
}
|
||||
|
||||
int rad_declare_scores(RadBuilder* b, rad_buf hidden, rad_weight table) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->declare_scores(hidden, table);
|
||||
}
|
||||
|
||||
int rad_declare_pooled(RadBuilder* b, rad_buf pooled) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->declare_pooled(pooled);
|
||||
}
|
||||
|
||||
int rad_declare_plugin_words(RadBuilder* b, int64_t max_words) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->declare_plugin_words(max_words);
|
||||
}
|
||||
|
||||
int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->declare_drafter(d);
|
||||
@@ -2399,8 +2713,18 @@ int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const ch
|
||||
return B(b)->lora_alias(native, from, to, from_lo, from_hi, to_lo);
|
||||
}
|
||||
|
||||
int rad_drafter_tree(RadBuilder* b, rad_buf parents) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->drafter_tree(parents);
|
||||
}
|
||||
|
||||
int rad_chain_on(void) { return rad_dev_chain_enabled(); }
|
||||
|
||||
int rad_drafter_short_block(RadBuilder* b, int64_t block) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->drafter_short_block(block);
|
||||
}
|
||||
|
||||
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->declare_encoder(d);
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <climits>
|
||||
#include <unordered_map>
|
||||
#include <cstring>
|
||||
@@ -650,7 +651,9 @@ std::string dump_graph_json(const Program& p) {
|
||||
j["geometry"] = o.base.str();
|
||||
j["ranged"] = o.ranged_key;
|
||||
if (!o.ranged_key.empty()) { j["range_lo"] = o.range_lo; j["range_hi"] = o.range_hi; }
|
||||
j["issued"] = o.issued;
|
||||
/* Read through an atomic_ref: the step path stores this flag from the engine thread
|
||||
* (Ctx::flush_issued); a plain read here would race it. */
|
||||
j["issued"] = std::atomic_ref<const bool>(o.issued).load(std::memory_order_relaxed);
|
||||
j["schema"] = schema_json(o.schema ? o.schema : reg.schema(o.op));
|
||||
|
||||
json ws = json::array();
|
||||
|
||||
+29
-5
@@ -175,8 +175,12 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
|
||||
|
||||
/* An imported quantisation is served by the family's quantised plugin (startup.h). A plugin
|
||||
* that declines imports (rad_arch_serves_imports) is left out of the family here: neither
|
||||
* counted as a second quantised plugin nor picked as the only one. */
|
||||
if (imported && !arch_id.empty() && out->arch_plugin.empty()) {
|
||||
* counted as a second quantised plugin nor picked as the only one. Block-scaled fp8 reads
|
||||
* stock weight by weight, so a family with no plugin claiming it is served the same way: the
|
||||
* plugin declares each weight at the encoding it finds (Qwen3.8-Flash-Next-FP8: fp8 routed
|
||||
* experts beside bf16 linears, served by qwen4exp_fp8). */
|
||||
const bool stock = quant == "fp8_e4m3";
|
||||
if ((imported || stock) && !arch_id.empty() && out->arch_plugin.empty()) {
|
||||
std::vector<const Plugin*> fam, quantised;
|
||||
for (const Plugin& p : r.plugins())
|
||||
if (p.kind == RAD_PLUGIN_ARCH && p.arch_id == arch_id && p.arch_serves_imports) {
|
||||
@@ -198,7 +202,7 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
|
||||
out->arch_version = pick->version;
|
||||
out->arch_id = pick->arch_id;
|
||||
out->arch_quant = pick->arch_quant;
|
||||
RAD_INFO("quantisation '%s' is imported weight by weight; '%s' serves it as %s",
|
||||
RAD_INFO("quantisation '%s' is read weight by weight; '%s' serves it as %s",
|
||||
quant.c_str(), pick->name.c_str(),
|
||||
pick->arch_quant.empty() ? "(unquantised)" : pick->arch_quant.c_str());
|
||||
}
|
||||
@@ -239,9 +243,12 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
|
||||
/* 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. */
|
||||
int rad_tools_probe(const LoadedPlugins& lp, const RadModelMeta& meta, RadArchProbe* out) {
|
||||
int rad_tools_probe(const LoadedPlugins& lp, const RadModelMeta& meta, RadArchProbe* out,
|
||||
int64_t gen_max_pixels, int64_t gen_max_refs) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = RadArchProbe{};
|
||||
out->gen_max_pixels = gen_max_pixels;
|
||||
out->gen_max_refs = gen_max_refs;
|
||||
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
|
||||
if (!ap || !ap->arch_probe) return RAD_E_UNSUPPORTED;
|
||||
const int s = ap->arch_probe(&meta, out);
|
||||
@@ -249,6 +256,8 @@ int rad_tools_probe(const LoadedPlugins& lp, const RadModelMeta& meta, RadArchPr
|
||||
RAD_WARN("%s: rad_arch_probe returned %s; the core will use its own defaults",
|
||||
lp.arch_plugin.c_str(), rad_strerror(s));
|
||||
*out = RadArchProbe{};
|
||||
out->gen_max_pixels = gen_max_pixels;
|
||||
out->gen_max_refs = gen_max_refs;
|
||||
return s;
|
||||
}
|
||||
return RAD_OK;
|
||||
@@ -270,7 +279,12 @@ int rad_tools_text_prepare(const LoadedPlugins& lp, int field, const std::string
|
||||
std::string buf(in.size() * 2 + 64, '\0');
|
||||
for (int tries = 0; tries < 2; ++tries) {
|
||||
const int64_t n = ap->arch_text_prepare(field, in.c_str(), &buf[0], (int64_t)buf.size());
|
||||
if (n < 0) return (int)n;
|
||||
if (n < 0) {
|
||||
/* The plugin's reason, when it left one in the (zeroed) buffer. */
|
||||
buf.resize(std::strlen(buf.c_str()));
|
||||
*out = std::move(buf);
|
||||
return (int)n;
|
||||
}
|
||||
if (n < (int64_t)buf.size()) {
|
||||
buf.resize((size_t)n);
|
||||
*out = std::move(buf);
|
||||
@@ -286,6 +300,16 @@ VideoPositionsFn rad_tools_video_positions(const LoadedPlugins& lp) {
|
||||
return ap ? ap->arch_video_positions : nullptr;
|
||||
}
|
||||
|
||||
VideoPackFn rad_tools_video_pack(const LoadedPlugins& lp) {
|
||||
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
|
||||
return ap ? ap->arch_video_pack : nullptr;
|
||||
}
|
||||
|
||||
EncodeGeomFn rad_tools_encode_geom(const LoadedPlugins& lp) {
|
||||
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
|
||||
return ap ? ap->arch_encode_geom : nullptr;
|
||||
}
|
||||
|
||||
const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& lp, const RadModelMeta& meta) {
|
||||
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
|
||||
if (!ap || !ap->arch_audio_format) return nullptr;
|
||||
|
||||
+15
-4
@@ -68,8 +68,9 @@ std::string rad_home_file(const std::string& home, const std::string& rel);
|
||||
* its descriptor names the producing tool and no plugin claims it. The family's quantised plugin
|
||||
* serves it: the one plugin claiming a descriptor, or the only plugin if none does. Two quantised
|
||||
* plugins are refused by name. A plugin whose rad_arch_serves_imports returns 0 is left out of
|
||||
* both counts. `out->arch_quant` is the chosen descriptor, which a container
|
||||
* converted from it records. */
|
||||
* both counts. Block-scaled fp8 (`fp8_e4m3`) that no plugin of the family claims is served the
|
||||
* same way, since its weights read stock. `out->arch_quant` is the chosen descriptor, which a
|
||||
* container converted from it records. */
|
||||
int rad_tools_load_plugins(const std::string& radiance_home,
|
||||
const std::vector<std::string>& hierarchy,
|
||||
const std::string& arch_id,
|
||||
@@ -78,7 +79,10 @@ int rad_tools_load_plugins(const std::string& radiance_home,
|
||||
bool imported = false);
|
||||
|
||||
/* The architecture plugin's rad_arch_probe answers, given before declare. */
|
||||
int rad_tools_probe(const LoadedPlugins& plugins, const RadModelMeta& meta, RadArchProbe* out);
|
||||
/* `gen_max_pixels`, `gen_max_refs`: the probe's inputs (RadArchProbe), the deployment's
|
||||
* --image-gen-max-pixels and --image-gen-max-refs; 0 the model's own. */
|
||||
int rad_tools_probe(const LoadedPlugins& plugins, const RadModelMeta& meta, RadArchProbe* out,
|
||||
int64_t gen_max_pixels = 0, int64_t gen_max_refs = 0);
|
||||
|
||||
/* The architecture plugin's declared reply format (rad_arch_chat_format), or null when it
|
||||
* declares none and the format is to be derived from the chat template. */
|
||||
@@ -93,13 +97,20 @@ const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& plugins, const
|
||||
* (rad_arch_text_prepare): RAD_OK with the result in `*out` (the text unchanged when the plugin
|
||||
* states no rewrite), or the plugin's negative status. */
|
||||
int rad_tools_text_prepare(const LoadedPlugins& plugins, int field, const std::string& in,
|
||||
std::string* out);
|
||||
std::string* out); /* on a refusal, `out` is its reason or "" */
|
||||
|
||||
/* The architecture plugin's video positions (rad_arch_video_positions), or null when it exports
|
||||
* none. */
|
||||
using VideoPositionsFn = int64_t (*)(int, const RadVideoGeom*, float*, int64_t);
|
||||
VideoPositionsFn rad_tools_video_positions(const LoadedPlugins& plugins);
|
||||
|
||||
/* Its rad_arch_video_pack and rad_arch_encode_geom, null when it does not export them. */
|
||||
using VideoPackFn = int64_t (*)(const RadVideoGeom*, const int32_t*, int32_t*, int32_t*, int32_t*,
|
||||
int32_t*, float*, int64_t);
|
||||
VideoPackFn rad_tools_video_pack(const LoadedPlugins& plugins);
|
||||
using EncodeGeomFn = int64_t (*)(int32_t, const int64_t*, int32_t*, int64_t);
|
||||
EncodeGeomFn rad_tools_encode_geom(const LoadedPlugins& plugins);
|
||||
|
||||
/* Run declare.
|
||||
*
|
||||
* `also` declares into the same builder after the architecture plugin, which is how the sampler
|
||||
|
||||
+326
-9
@@ -4,9 +4,11 @@
|
||||
* (spec §6).
|
||||
*/
|
||||
#include "rad_core.h"
|
||||
#include "kld.h"
|
||||
#include "format/rope_override.h"
|
||||
#include "sample/host_ref.h"
|
||||
#include "server/oai.h"
|
||||
#include "server/http.h"
|
||||
#include "diag/diag.h"
|
||||
#include "util/kernel_list.h"
|
||||
#include "place/planner.h"
|
||||
@@ -18,6 +20,7 @@
|
||||
#include <cerrno>
|
||||
#include <climits>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
@@ -39,7 +42,7 @@ static const std::string g_draft_window_help =
|
||||
std::string("fixed | adaptive: how many drafts each sequence carries. fixed drafts\n"
|
||||
" --num-speculative-tokens every step; adaptive makes that\n"
|
||||
" the ceiling and follows each sequence's acceptance and the\n"
|
||||
" measured step cost (a serial draft head only). Default ") +
|
||||
" measured step cost (a draft head, or prompt lookup alone). Default ") +
|
||||
draft_window_name(kDraftWindowDefault);
|
||||
|
||||
static const Flag g_flags[] = {
|
||||
@@ -47,6 +50,8 @@ static const Flag g_flags[] = {
|
||||
"Hugging Face repo id (owner/name), fetched before startup" },
|
||||
{ "--download-dir", "DIR", "where a repo id is fetched to; default\n"
|
||||
"$XDG_CACHE_HOME/radiance/hf, else ~/.cache/radiance/hf" },
|
||||
{ "--model-revision", "REV", "the hub revision -- a branch, tag, full commit sha or refs/pr/N --\n"
|
||||
"a repo id is fetched at; default the repo's moving main branch" },
|
||||
{ "--radiance-home", "DIRS", "where kernels/, architectures/ and quantizers/ live; several\n"
|
||||
"homes separated by ':' are searched in order, the first winning" },
|
||||
{ "--kernels", "LIST", "the kernel libraries to use, separated by ',' or ':', first wins; unnamed ones are not loaded. Default: every library found" },
|
||||
@@ -56,6 +61,13 @@ static const Flag g_flags[] = {
|
||||
"lossy wire: rotated 6-bit at 2 ranks, tiered int8 at 3\n"
|
||||
"and 4, none at 8" },
|
||||
{ "--tp-wire-min-kb", "N", "smallest all-reduce, in KiB, the lossy wire is used for" },
|
||||
{ "--tp-attn-split", "MODE", "heads (default) | rows -- how a prefill-sized step's\n"
|
||||
"attention splits over the ranks: rows gives each rank all\n"
|
||||
"heads of its rows, a faster prefill for the projections at\n"
|
||||
"full width on every card; not bit-identical to heads" },
|
||||
{ "--weight-prefetch", "MODE", "on (default) | off -- read a GEMM's weight into the cache\n"
|
||||
"beside the collective before it; off for an engine that\n"
|
||||
"shares its cards with another server" },
|
||||
{ "--p2p", "MODE", "how the collectives reach the other cards: auto (default)\n"
|
||||
"asks the driver, on requires peer access and stops without\n"
|
||||
"it, off exchanges through pinned host memory" },
|
||||
@@ -66,6 +78,10 @@ static const Flag g_flags[] = {
|
||||
{ "--prefill-interleave", "N", "decode-only steps after each prefill chunk while other\n"
|
||||
"sequences decode, at most 64; 0 (default) lets every step\n"
|
||||
"carry a chunk" },
|
||||
{ "--preempt-wait-ms", "N", "how long a preempted prefill may wait for the whole-\n"
|
||||
"recompute gate before reclaiming cache blocks and\n"
|
||||
"preempting the lowest-priority running request; 0\n"
|
||||
"(default 5000) falls back on the next step" },
|
||||
{ "--max-num-seqs", "N", "the largest number of sequences one step may carry" },
|
||||
{ "--max-model-len", "N", "context bound; 0 takes the model's training context" },
|
||||
{ "--rope-scaling", "SPEC", "yarn:FACTOR[:ORIG]: static YaRN over the container's own rotary\n"
|
||||
@@ -75,9 +91,17 @@ static const Flag g_flags[] = {
|
||||
{ "--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" },
|
||||
{ "--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-headroom-mib", "N", "host RAM to leave free for the system when radiance\n"
|
||||
" pins its host memory at startup (default 4096)" },
|
||||
@@ -95,14 +119,19 @@ static const Flag g_flags[] = {
|
||||
" host memory at load, pinned for the cards to read\n"
|
||||
" (locked, where only a host kernel reads it); disk reads\n"
|
||||
" its rows from the container on the host. auto takes the\n"
|
||||
" first of the three that holds it" },
|
||||
" first of the three that holds it. ram=DIR makes the\n"
|
||||
" pinned copy a file in DIR (a tmpfs) mapped shared, so\n"
|
||||
" two engines on separate cards hold one table: the\n"
|
||||
" first fills it, the last to exit deletes it" },
|
||||
{ "--weights-disk-tier", nullptr, "read weights that fit neither VRAM nor the host pool from the\n"
|
||||
" container on disk (O_DIRECT); a routed expert is read a layer\n"
|
||||
" at a time, so a step is paced by the drive" },
|
||||
" container on disk (O_DIRECT) -- the file tier, units on\n"
|
||||
" Tier::SSD; a routed expert is read a layer at\n"
|
||||
" a time, so a step is paced by the drive" },
|
||||
{ "--prefix-cache-mib", "N", "copy finished conversations' KV to host memory, up to N MiB,\n"
|
||||
" so their VRAM can go to experts and a return restores\n"
|
||||
" instead of re-prefilling. A full tier drops its least\n"
|
||||
" recently used entries. 0 is off" },
|
||||
" recently used entries. 0 is off. Off while a KV group\n"
|
||||
" streams (--kv-resident)" },
|
||||
{ "--prefix-cache-ttl", "S", "seconds a cached conversation no request uses is kept, in VRAM\n"
|
||||
" or host memory (default 3600). 0 keeps it until the memory\n"
|
||||
" is wanted" },
|
||||
@@ -151,23 +180,59 @@ static const Flag g_flags[] = {
|
||||
" one, for each of --max-num-seqs, within an eighth of host\n"
|
||||
" memory. N fixes the total; 0 keeps none" },
|
||||
{ "--no-prefix-cache", nullptr, "disable prefix caching" },
|
||||
{ "--prefix-resume", "MODE", "where a prefix hit resumes: exact (default) only where\n"
|
||||
" an idle server's cold prefill of the prompt starts a\n"
|
||||
" chunk, so the hit answers bit-identically to a cold run;\n"
|
||||
" nearest at the deepest snapshot, up to a chunk less to\n"
|
||||
" re-prefill" },
|
||||
{ "--checkpoint-policy", "NAME", "which snapshots a session retains: geometric-backoff "
|
||||
"(default), tip-only, keep-all" },
|
||||
|
||||
{ "--num-speculative-tokens", "N", "speculative window; 0 disables. Default `auto`: the drafter's\n"
|
||||
" own operating point, which the plugin states. A container\n"
|
||||
" with no draft head is unaffected -- auto resolves to 0." },
|
||||
{ "--spec-ngram", "K", "speculate by prompt lookup alone: up to K drafts a step\n"
|
||||
" copied from what followed the latest earlier occurrence of\n"
|
||||
" the sequence's last n tokens (no weights, no draft pass).\n"
|
||||
" Sets the window to K; a draft head the container carries is\n"
|
||||
" not loaded. A proposal is verified only when its record\n"
|
||||
" says it pays at the measured step cost. 0 (default) off" },
|
||||
{ "--spec-ngram-min", "N", "shortest pattern prompt lookup matches (default 2)" },
|
||||
{ "--spec-ngram-max", "N", "longest pattern prompt lookup matches, tried first\n"
|
||||
"(default 4, at most 15)" },
|
||||
{ "--draft-window", "MODE", g_draft_window_help.c_str() },
|
||||
{ "--draft-short-from", "N", "a block drafter that also serves a shorter block runs it\n"
|
||||
"from N decoding sequences on (0 never): the long block pays\n"
|
||||
"at one sequence, the short one at many. auto (the default):\n"
|
||||
"never for a chain, from 2 for a tree drafter" },
|
||||
{ "--draft-coupling", "MODE", "off (default) | on -- a linear MTP drafter or DFlash2's walk\n"
|
||||
" samples each proposal from its own shortlist and the sampler\n"
|
||||
" couples the target's draw to it: more accepted drafts on sampled\n"
|
||||
" requests, the same output law, other tokens than off for a fixed\n"
|
||||
" seed" },
|
||||
{ "--draft-model", "PATH", "NOT IMPLEMENTED -- merge the drafter at convert time" },
|
||||
|
||||
{ "--host", "ADDR", "listen address" },
|
||||
{ "--port", "N", "listen port" },
|
||||
{ "--api-key", "KEY", "require `Authorization: Bearer KEY` or `X-Api-Key: KEY` on every request but /health,\n"
|
||||
" /v1/health, /ping and the dashboard page" },
|
||||
{ "--api-key-env", "NAME", "read the API key from the named environment variable; keeps it off the\n"
|
||||
" command line, where every process on the machine can read it" },
|
||||
{ "--allow-host", "NAME", "a Host name the keyless loopback-only routes (/diagnostics,\n"
|
||||
" /admin/control-vector, the LoRA and session admin) accept besides\n"
|
||||
" localhost; repeatable" },
|
||||
{ "--trusted-proxy", "CIDR", "a network whose sockets may name the client behind them via\n"
|
||||
" X-Forwarded-For, for the log; vouching changes attribution,\n"
|
||||
" never access; repeatable" },
|
||||
{ "--served-model-name", "NAME", "the model id /v1/models lists and responses carry; default the container's name" },
|
||||
{ "--mm-max-patches", "N", "patches one encoder pass carries, and so the largest image (a patch is 16x16\n"
|
||||
"pixels). Default `auto`: 16384 when the container carries a vision tower. 0\n"
|
||||
"serves text only and keeps the tower off the card" },
|
||||
{ "--image-gen-max-pixels", "N", "an image generator's largest image, in pixels (1048576: 1024 x 1024).\n"
|
||||
" Default: the model's. Its per-image buffers, and the activation\n"
|
||||
" arena with them, are sized for it; larger requests are refused" },
|
||||
{ "--image-gen-max-refs", "N", "the reference pictures an image generator takes a request. Default: the\n"
|
||||
" model's; its conditioning buffers are sized for them" },
|
||||
{ "--generation-config", "PATH", "a generation_config.json whose sampler settings become the default\n"
|
||||
" for requests that send none. Without it a <model>.generation.json\n"
|
||||
" beside the container is used, then the container's own\n"
|
||||
@@ -257,6 +322,16 @@ static const Flag g_flags[] = {
|
||||
" mean, median, 99/99.9/99.99th percentile KL divergence and top-1\n"
|
||||
" agreement, over the positions and tokens DIR was recorded at" },
|
||||
{ "--kld-corpus", "FILE", "JSONL, one {\"prompt\", \"score_from\"?, \"source\"?} a line; --kld-record only" },
|
||||
{ "--calib-corpus", "FILE", "instead of serving, run a JSONL corpus ({\"prompt\"} a line) through\n"
|
||||
" prefill once, every token, and record the calibration statistics\n"
|
||||
" the model keeps (each linear's input Gram, GPTQ's Hessian)" },
|
||||
{ "--calib-dir", "DIR", "where --calib-corpus writes the statistics; beside --kld-record, the\n"
|
||||
" reference's run records them over the KL corpus too" },
|
||||
{ "--calib-layers", "RANGE", "LO:HI, record layers LO..HI-1 only (default every layer), for a model\n"
|
||||
" whose statistics do not fit in memory in one run" },
|
||||
{ "--kld-top", "N", "--kld-record keeps each position's N most likely tokens exactly and the\n"
|
||||
" mass of the rest, not the whole vocabulary (a corpus too large for\n"
|
||||
" full rows); 0 (default) keeps the whole vocabulary" },
|
||||
{ "--kld-out", "FILE", "the --kld-ref report as JSON, and every position's numbers in FILE.rows" },
|
||||
{ "--kld-lora", "NAME", "run --kld-record / --kld-ref through the --lora adapter NAME" },
|
||||
{ "--kld-lora-sources", "PREFIX", "--kld-lora only for documents whose source starts with PREFIX; the\n"
|
||||
@@ -265,11 +340,35 @@ static const Flag g_flags[] = {
|
||||
{ "--debug-graph", nullptr, "print the entire declared graph and exit-quality detail" },
|
||||
{ "--debug-selection", nullptr, "print the selection table" },
|
||||
{ "--debug-placement", nullptr, "print the placement plan" },
|
||||
{ "--debug-draft-oracle", "FILE", "a verify-path test, not a drafter: with --spec-ngram, prompt\n"
|
||||
" lookup proposes from the token ids in FILE (a plain greedy\n"
|
||||
" run's continuation of the one prompt the test sends), 30% of\n"
|
||||
" the drafts corrupted; the text must stay the plain run's" },
|
||||
{ "--debug-accept-reference-kernels", nullptr,
|
||||
"serve even when ops resolve only to a reference library. NOT a production configuration: the reference\n"
|
||||
" implementation is an oracle and a last resort, and falling back\n"
|
||||
" to it is orders of magnitude of speed with nothing to say so." },
|
||||
{ "--proceed-with-incompatible-configuration", nullptr,
|
||||
"start on a machine configuration radiance refuses (amdgpu CWSR off where cards serve).\n"
|
||||
" UNSUPPORTED: all guarantees are off, and the log and the startup\n"
|
||||
" report say so." },
|
||||
{ "--profile-ops", nullptr, "per-op device timing (see the caveat it prints)" },
|
||||
{ "--expert-stats", "FILE", "count the routed experts every layer selects, apart for prefill, decode,\n"
|
||||
" mixed steps and draft-head passes, and write the counts to FILE as\n"
|
||||
" JSON every 30 s and at shutdown. From the routing histograms the core\n"
|
||||
" already copies back: no device work, no synchronisation" },
|
||||
{ "--expert-profile", "FILE", "rank the expert plane by this radiance-expert-stats JSON's `decode`\n"
|
||||
" counts instead of the container's activation profile, which is\n"
|
||||
" prefill-heavy: decode-hot experts differ. The planner keeps the\n"
|
||||
" hottest resident; --expert-pin-top makes a chosen slice unmovable" },
|
||||
{ "--expert-pin-top", "F", "pin the hottest fraction F of the routed experts (0 < F <= 1) by\n"
|
||||
" --expert-profile's share: heat never demotes them, so the decode-hot\n"
|
||||
" set stays resident while the rest streams. 0 is off" },
|
||||
{ "--draft-expert-placement", "PLACEMENT", "where a draft head's (MTP/DSpark) routed experts live.\n"
|
||||
" `host` pins them in the host pool before any strategy runs, read in\n"
|
||||
" place like a pooled expert: the drafter's experts fit beside a trunk\n"
|
||||
" that already fills the card, instead of the strategy having to make\n"
|
||||
" room on the card. `auto` (the default) leaves them to the strategy" },
|
||||
{ "--live", nullptr, "the live view: cards, throughput, draft acceptance, the expert plane.\n"
|
||||
" Redirected it prints one greppable key=value line instead" },
|
||||
{ "-v", nullptr, "verbose" },
|
||||
@@ -432,6 +531,7 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
else if (S("-vv")) log_set_level(Log::Trace);
|
||||
else if (S("--model")) { if (!(v = need(i))) return RAD_E_INVAL; c->model = v; }
|
||||
else if (S("--download-dir")) { if (!(v = need(i))) return RAD_E_INVAL; c->download_dir = v; }
|
||||
else if (S("--model-revision")) { if (!(v = need(i))) return RAD_E_INVAL; c->model_revision = v; }
|
||||
else if (S("--radiance-home")) { if (!(v = need(i))) return RAD_E_INVAL; c->radiance_home = v; }
|
||||
else if (S("--kernels")) { if (!(v = need(i))) return RAD_E_INVAL; c->kernel_hierarchy = rad_split_kernel_list(v); }
|
||||
else if (S("--tp")) { if (!num(1, INT32_MAX, &c->tp)) return RAD_E_INVAL; }
|
||||
@@ -441,6 +541,18 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
else if (!std::strcmp(v, "wht6")) c->tp_wire_exact = 0;
|
||||
else { RAD_ERR("--tp-wire takes exact or wht6, not '%s'", v); return RAD_E_INVAL; }
|
||||
}
|
||||
else if (S("--tp-attn-split")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "heads")) c->tp_attn_rows = 0;
|
||||
else if (!std::strcmp(v, "rows")) c->tp_attn_rows = 1;
|
||||
else { RAD_ERR("--tp-attn-split takes heads or rows, not '%s'", v); return RAD_E_INVAL; }
|
||||
}
|
||||
else if (S("--weight-prefetch")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "on")) c->weight_prefetch = true;
|
||||
else if (!std::strcmp(v, "off")) c->weight_prefetch = false;
|
||||
else { RAD_ERR("--weight-prefetch takes on or off, not '%s'", v); return RAD_E_INVAL; }
|
||||
}
|
||||
else if (S("--p2p")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "auto")) c->p2p = RAD_P2P_AUTO;
|
||||
@@ -457,6 +569,7 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
else if (!parse_int(a.c_str(), v, 1, INT64_MAX, &c->busy_prefill_chunk)) return RAD_E_INVAL;
|
||||
}
|
||||
else if (S("--prefill-interleave")) { if (!num(0, 64, &c->prefill_interleave)) return RAD_E_INVAL; }
|
||||
else if (S("--preempt-wait-ms")) { if (!num(0, INT64_MAX, &c->preempt_wait_ms)) return RAD_E_INVAL; }
|
||||
else if (S("--max-num-seqs")) { if (!num(1, INT64_MAX, &c->max_seqs)) return RAD_E_INVAL; }
|
||||
else if (S("--max-model-len")) { if (!num(0, INT64_MAX, &c->max_ctx)) return RAD_E_INVAL; }
|
||||
else if (S("--rope-scaling")) {
|
||||
@@ -492,6 +605,14 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
c->kv_cache_dtype = v;
|
||||
}
|
||||
else if (S("--state-cache-dtype")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (std::strcmp(v, "f32") && std::strcmp(v, "f16")) {
|
||||
RAD_ERR("--state-cache-dtype takes f32 or f16, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
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;
|
||||
@@ -503,6 +624,7 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
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("--embedding-placement") || S("--ngram-placement")) {
|
||||
const bool emb = S("--embedding-placement");
|
||||
@@ -519,10 +641,20 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
RAD_ERR("--embedding-placement takes ram or vram, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!emb && !parse_table_placement(v, &p)) {
|
||||
RAD_ERR("%s takes auto, vram, ram or disk, not '%s'", a.c_str(), v);
|
||||
std::string share_dir;
|
||||
if (!emb && !std::strncmp(v, "ram=", 4)) {
|
||||
share_dir = v + 4;
|
||||
if (share_dir.empty()) {
|
||||
RAD_ERR("--ngram-placement ram= needs a directory: ram=DIR, the tmpfs that "
|
||||
"holds the shared table");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
p = TablePlacement::Ram;
|
||||
} else if (!emb && !parse_table_placement(v, &p)) {
|
||||
RAD_ERR("%s takes auto, vram, ram, ram=DIR or disk, not '%s'", a.c_str(), v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!emb) c->ngram_share_dir = share_dir;
|
||||
(emb ? c->embedding_placement : c->ngram_placement) = p;
|
||||
if (emb) c->embedding_placement_given = true;
|
||||
}
|
||||
@@ -621,6 +753,15 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
}
|
||||
else if (S("--no-prefix-cache")) c->prefix_cache = false;
|
||||
else if (S("--prefix-resume")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "exact")) c->prefix_exact = true;
|
||||
else if (!std::strcmp(v, "nearest")) c->prefix_exact = false;
|
||||
else {
|
||||
RAD_ERR("--prefix-resume '%s' is not one of exact, nearest", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--checkpoint-policy")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
/* Validated, so an unknown name does not silently fall back to the default. */
|
||||
@@ -643,6 +784,9 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
return RAD_E_INVAL;
|
||||
c->n_spec = (int)n;
|
||||
}
|
||||
else if (S("--spec-ngram")) { if (!num(0, 64, &c->spec_ngram)) return RAD_E_INVAL; }
|
||||
else if (S("--spec-ngram-min")) { if (!num(1, 15, &c->spec_ngram_min)) return RAD_E_INVAL; }
|
||||
else if (S("--spec-ngram-max")) { if (!num(1, 15, &c->spec_ngram_max)) return RAD_E_INVAL; }
|
||||
else if (S("--draft-window")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "fixed")) c->draft_window = DraftWindow::Fixed;
|
||||
@@ -652,6 +796,20 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--draft-short-from")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "auto")) c->draft_short_from = -1;
|
||||
else if (!parse_int(a.c_str(), v, 0, INT32_MAX, &c->draft_short_from)) return RAD_E_INVAL;
|
||||
}
|
||||
else if (S("--draft-coupling")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "off")) c->draft_coupling = false;
|
||||
else if (!std::strcmp(v, "on")) c->draft_coupling = true;
|
||||
else {
|
||||
RAD_ERR("--draft-coupling takes off or on, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--draft-model")) {
|
||||
/* Refused, not ignored: separate draft models are not supported (spec §10), and the
|
||||
* drafter comes from the container (rad-convert --draft-model merges one in; an MTP
|
||||
@@ -666,12 +824,58 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
else if (S("--host")) { if (!(v = need(i))) return RAD_E_INVAL; c->host = v; }
|
||||
else if (S("--port")) { if (!num(0, 65535, &c->port)) return RAD_E_INVAL; }
|
||||
else if (S("--api-key")) { if (!(v = need(i))) return RAD_E_INVAL; c->api_key = v; }
|
||||
else if (S("--api-key")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
/* An empty key is no key: --api-key "" or --api-key "$UNSET_VAR" must not start a
|
||||
* server that looks guarded and answers everything keyless. */
|
||||
if (!*v) { RAD_ERR("--api-key takes a non-empty key; an empty value guards nothing");
|
||||
return RAD_E_INVAL; }
|
||||
c->api_key = v;
|
||||
}
|
||||
else if (S("--api-key-env")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!*v) { RAD_ERR("--api-key-env takes the name of an environment variable");
|
||||
return RAD_E_INVAL; }
|
||||
const char* k = std::getenv(v);
|
||||
/* The empty --api-key refusal's sibling: a unit or compose file whose variable was
|
||||
* never set must not start a server that looks guarded and answers everything
|
||||
* keyless. The name is recorded so the config report can say where the key came
|
||||
* from without showing it. */
|
||||
if (!k || !*k) {
|
||||
RAD_ERR("--api-key-env: %s is unset or empty; refusing to serve keyless under a "
|
||||
"guarded-looking command line", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->api_key = k;
|
||||
c->api_key_env = v;
|
||||
}
|
||||
else if (S("--allow-host")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!*v) { RAD_ERR("--allow-host takes a non-empty name"); return RAD_E_INVAL; }
|
||||
c->allow_hosts.emplace_back(v);
|
||||
}
|
||||
else if (S("--trusted-proxy")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!server::cidr_valid(v)) {
|
||||
RAD_ERR("--trusted-proxy takes a numeric network with a prefix length, like "
|
||||
"127.0.0.0/8 or ::1/128 (no brackets, no bare address), got '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->trusted_proxies.emplace_back(v);
|
||||
}
|
||||
else if (S("--served-model-name")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!*v) { RAD_ERR("--served-model-name takes a non-empty name"); return RAD_E_INVAL; }
|
||||
c->served_model_name = v;
|
||||
}
|
||||
else if (S("--image-gen-max-pixels")) {
|
||||
if (!(v = need(i)) || !parse_int(a.c_str(), v, 256, INT64_MAX, &c->image_gen_max_pixels))
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
else if (S("--image-gen-max-refs")) {
|
||||
if (!(v = need(i)) || !parse_int(a.c_str(), v, 1, INT64_MAX, &c->image_gen_max_refs))
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
else if (S("--mm-max-patches")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "auto")) c->mm_max_patches = -1;
|
||||
@@ -846,14 +1050,51 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
else if (S("--kld-record")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_record = v; }
|
||||
else if (S("--kld-ref")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_ref = v; }
|
||||
else if (S("--kld-corpus")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_corpus = v; }
|
||||
else if (S("--kld-top")) { if (!num(0, kKldTopMax, &c->kld_top)) return RAD_E_INVAL; }
|
||||
else if (S("--calib-corpus")) { if (!(v = need(i))) return RAD_E_INVAL; c->calib_corpus = v; }
|
||||
else if (S("--calib-dir")) { if (!(v = need(i))) return RAD_E_INVAL; c->calib_dir = v; }
|
||||
else if (S("--calib-layers")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
int lo = -1, hi = -1, used = 0;
|
||||
if (std::sscanf(v, "%d:%d%n", &lo, &hi, &used) != 2 || v[used] != '\0' || lo < 0 || hi <= lo) {
|
||||
RAD_ERR("--calib-layers takes LO:HI with 0 <= LO < HI, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->calib_layer_lo = lo;
|
||||
c->calib_layer_hi = hi;
|
||||
}
|
||||
else if (S("--kld-out")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_out = v; }
|
||||
else if (S("--kld-lora")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_lora = v; }
|
||||
else if (S("--kld-lora-sources")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_lora_sources = v; }
|
||||
else if (S("--debug-graph")) { c->debug_graph = true; c->debug_selection = true; }
|
||||
else if (S("--debug-selection")) c->debug_selection = true;
|
||||
else if (S("--debug-placement")) c->debug_placement = true;
|
||||
else if (S("--debug-draft-oracle")) { if (!(v = need(i))) return RAD_E_INVAL; c->debug_draft_oracle = v; }
|
||||
else if (S("--debug-accept-reference-kernels")) c->accept_reference_kernels = true;
|
||||
else if (S("--proceed-with-incompatible-configuration")) c->proceed_incompatible = true;
|
||||
else if (S("--profile-ops")) c->profile_ops = true;
|
||||
else if (S("--expert-stats")) { if (!(v = need(i))) return RAD_E_INVAL; c->expert_stats = v; }
|
||||
else if (S("--expert-profile")) { if (!(v = need(i))) return RAD_E_INVAL; c->expert_profile = v; c->expert_profile_given = true; }
|
||||
else if (S("--expert-pin-top")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
char* e = nullptr;
|
||||
const double d = strtod(v, &e);
|
||||
if (e == v || *e != '\0' || d < 0.0 || d > 1.0) {
|
||||
RAD_ERR("--expert-pin-top: '%s' is not a fraction in [0, 1]", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->expert_pin_top = (float)d;
|
||||
c->expert_pin_top_given = true;
|
||||
}
|
||||
else if (S("--draft-expert-placement")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (std::strcmp(v, "auto") != 0 && std::strcmp(v, "host") != 0) {
|
||||
RAD_ERR("--draft-expert-placement: '%s' is not auto or host", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->draft_expert_placement = v;
|
||||
c->draft_expert_placement_given = true;
|
||||
}
|
||||
else if (S("--live")) c->live_view = true;
|
||||
else {
|
||||
RAD_ERR("unknown option '%s'", a.c_str());
|
||||
@@ -889,6 +1130,22 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* Prompt lookup alone: the window is its K, stated once. */
|
||||
if (c->spec_ngram_min > c->spec_ngram_max) {
|
||||
RAD_ERR("--spec-ngram-min %d is longer than --spec-ngram-max %d", c->spec_ngram_min,
|
||||
c->spec_ngram_max);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c->spec_ngram > 0) {
|
||||
if (c->given.count("--num-speculative-tokens") && c->n_spec != c->spec_ngram) {
|
||||
RAD_ERR("--spec-ngram %d sets the speculative window to %d, and "
|
||||
"--num-speculative-tokens asks for %s; give one", c->spec_ngram,
|
||||
c->spec_ngram, c->n_spec < 0 ? "auto" : std::to_string(c->n_spec).c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->n_spec = c->spec_ngram;
|
||||
}
|
||||
|
||||
/* KL mode: exactly one direction, each with the inputs it reads. */
|
||||
if (!c->kld_record.empty() && !c->kld_ref.empty()) {
|
||||
RAD_ERR("--kld-record writes a reference and --kld-ref scores against one; give one");
|
||||
@@ -903,6 +1160,26 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
"--kld-corpus");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c->calib() && c->calib_dir.empty()) {
|
||||
RAD_ERR("--calib-corpus records into --calib-dir; give one");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if ((!c->calib_dir.empty() || c->calib_layer_hi) && !c->calib() && c->kld_record.empty()) {
|
||||
RAD_ERR("--calib-dir and --calib-layers belong to a --calib-corpus or --kld-record run");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c->calib_layer_hi && c->calib_dir.empty()) {
|
||||
RAD_ERR("--calib-layers chooses what --calib-dir records; give one");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c->calib() && c->kld()) {
|
||||
RAD_ERR("--calib-corpus and the KL mode each replace the server; give one");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c->kld_top && c->kld_record.empty()) {
|
||||
RAD_ERR("--kld-top is how --kld-record stores a reference; --kld-ref reads the form from it");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!c->kld_out.empty() && c->kld_ref.empty()) {
|
||||
RAD_ERR("--kld-out is the --kld-ref report");
|
||||
return RAD_E_INVAL;
|
||||
@@ -1027,6 +1304,7 @@ struct ShowRow { const char* flag; Show show; };
|
||||
const ShowRow kShow[] = {
|
||||
{ "--model", [](const Config& c) { return c.model; } },
|
||||
{ "--download-dir", [](const Config& c) { return or_none(c.download_dir, "the XDG cache (~/.cache/radiance/hf)"); } },
|
||||
{ "--model-revision", [](const Config& c) { return or_none(c.model_revision, "the repo's main branch"); } },
|
||||
{ "--radiance-home", [](const Config& c) { return c.radiance_home; } },
|
||||
{ "--kernels", [](const Config& c) {
|
||||
std::string s;
|
||||
@@ -1034,6 +1312,8 @@ const ShowRow kShow[] = {
|
||||
return or_none(s, "every library found"); } },
|
||||
{ "--tp", [](const Config& c) { return num(c.tp); } },
|
||||
{ "--tp-wire", [](const Config& c) { return std::string(c.tp_wire_exact ? "exact" : "wht6"); } },
|
||||
{ "--tp-attn-split", [](const Config& c) { return std::string(c.tp_attn_rows ? "rows" : "heads"); } },
|
||||
{ "--weight-prefetch", [](const Config& c) { return onoff(c.weight_prefetch); } },
|
||||
{ "--tp-wire-min-kb", [](const Config& c) { return num(c.tp_wire_min_kb); } },
|
||||
{ "--p2p", [](const Config& c) {
|
||||
return std::string(c.p2p == RAD_P2P_ON ? "on" : c.p2p == RAD_P2P_OFF ? "off" : "auto"); } },
|
||||
@@ -1043,18 +1323,24 @@ const ShowRow kShow[] = {
|
||||
: c.busy_prefill_chunk == 0 ? std::string("off") : num(c.busy_prefill_chunk); } },
|
||||
{ "--prefill-interleave", [](const Config& c) {
|
||||
return c.prefill_interleave > 0 ? num(c.prefill_interleave) : std::string("off"); } },
|
||||
{ "--preempt-wait-ms", [](const Config& c) { return num(c.preempt_wait_ms); } },
|
||||
{ "--max-num-seqs", [](const Config& c) { return num(c.max_seqs); } },
|
||||
{ "--max-model-len", [](const Config& c) {
|
||||
return c.max_ctx ? num(c.max_ctx) : std::string("0 (the model's training context)"); } },
|
||||
{ "--rope-scaling", [](const Config& c) { return or_none(c.rope_scaling, "the checkpoint's own"); } },
|
||||
{ "--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-headroom-mib", [](const Config& c) { return num(c.host_headroom_mib); } },
|
||||
{ "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } },
|
||||
{ "--ngram-placement", [](const Config& c) { return std::string(table_placement_name(c.ngram_placement)); } },
|
||||
{ "--ngram-placement", [](const Config& c) {
|
||||
std::string v = table_placement_name(c.ngram_placement);
|
||||
return c.ngram_share_dir.empty() ? v : v + "=" + c.ngram_share_dir; } },
|
||||
{ "--vision-tower-placement", [](const Config& c) { return std::string(table_placement_name(c.tower_placement)); } },
|
||||
{ "--weights-disk-tier", [](const Config& c) { return onoff(c.weights_disk_tier); } },
|
||||
{ "--prefix-cache-mib", [](const Config& c) {
|
||||
@@ -1084,16 +1370,37 @@ const ShowRow kShow[] = {
|
||||
return c.checkpoint_slots < 0 ? std::string("auto") : num(c.checkpoint_slots); } },
|
||||
{ "--no-prefix-cache", [](const Config& c) {
|
||||
return std::string(c.prefix_cache ? "not given: prefix caching on" : "prefix caching off"); } },
|
||||
{ "--prefix-resume", [](const Config& c) {
|
||||
return std::string(c.prefix_exact ? "exact" : "nearest"); } },
|
||||
{ "--checkpoint-policy", [](const Config& c) { return c.checkpoint_policy; } },
|
||||
{ "--num-speculative-tokens", [](const Config& c) { return c.n_spec < 0 ? std::string("auto") : num(c.n_spec); } },
|
||||
{ "--spec-ngram", [](const Config& c) {
|
||||
return c.spec_ngram > 0 ? num(c.spec_ngram) : std::string("0 (off)"); } },
|
||||
{ "--spec-ngram-min", [](const Config& c) { return num(c.spec_ngram_min); } },
|
||||
{ "--spec-ngram-max", [](const Config& c) { return num(c.spec_ngram_max); } },
|
||||
{ "--draft-window", [](const Config& c) { return std::string(draft_window_name(c.draft_window)); } },
|
||||
{ "--draft-short-from", [](const Config& c) {
|
||||
return c.draft_short_from < 0 ? std::string("auto")
|
||||
: c.draft_short_from > 0 ? num(c.draft_short_from) : std::string("0 (never)"); } },
|
||||
{ "--draft-coupling", [](const Config& c) { return onoff(c.draft_coupling); } },
|
||||
{ "--draft-model", [](const Config&) { return std::string("not implemented (the container's own drafter)"); } },
|
||||
{ "--host", [](const Config& c) { return c.host; } },
|
||||
{ "--port", [](const Config& c) { return num(c.port); } },
|
||||
/* Never print the secret, only whether it is set. */
|
||||
{ "--api-key", [](const Config& c) { return std::string(c.api_key.empty() ? "not set" : "set"); } },
|
||||
{ "--api-key-env", [](const Config& c) { return or_none(c.api_key_env, "not used"); } },
|
||||
{ "--allow-host", [](const Config& c) {
|
||||
std::string o;
|
||||
for (const std::string& h : c.allow_hosts) o += (o.empty() ? "" : ",") + h;
|
||||
return o.empty() ? std::string("the loopback names only") : o; } },
|
||||
{ "--trusted-proxy", [](const Config& c) {
|
||||
std::string o;
|
||||
for (const std::string& p : c.trusted_proxies) o += (o.empty() ? "" : ",") + p;
|
||||
return o.empty() ? std::string("no socket vouches for a caller") : o; } },
|
||||
{ "--served-model-name", [](const Config& c) { return or_none(c.served_model_name, "the container's name"); } },
|
||||
{ "--mm-max-patches", [](const Config& c) { return c.mm_max_patches < 0 ? std::string("auto") : num(c.mm_max_patches); } },
|
||||
{ "--image-gen-max-pixels", [](const Config& c) { return c.image_gen_max_pixels > 0 ? num(c.image_gen_max_pixels) : std::string("the model's"); } },
|
||||
{ "--image-gen-max-refs", [](const Config& c) { return c.image_gen_max_refs > 0 ? num(c.image_gen_max_refs) : std::string("the model's"); } },
|
||||
{ "--generation-config", [](const Config& c) { return or_none(c.generation_config, "none"); } },
|
||||
{ "--override-chat-template", [](const Config& c) { return or_none(c.override_chat_template, "none (the container's)"); } },
|
||||
{ "--temp", [](const Config& c) { return c.sample_temp < 0 ? std::string("unset") : fnum(c.sample_temp); } },
|
||||
@@ -1158,14 +1465,24 @@ const ShowRow kShow[] = {
|
||||
{ "--kld-record", [](const Config& c) { return or_none(c.kld_record, "none"); } },
|
||||
{ "--kld-ref", [](const Config& c) { return or_none(c.kld_ref, "none"); } },
|
||||
{ "--kld-corpus", [](const Config& c) { return or_none(c.kld_corpus, "none"); } },
|
||||
{ "--kld-top", [](const Config& c) { return c.kld_top ? num(c.kld_top) : std::string("0 (the whole vocabulary)"); } },
|
||||
{ "--calib-corpus", [](const Config& c) { return or_none(c.calib_corpus, "none"); } },
|
||||
{ "--calib-dir", [](const Config& c) { return or_none(c.calib_dir, "none"); } },
|
||||
{ "--calib-layers", [](const Config& c) { return c.calib_layer_hi ? num(c.calib_layer_lo) + ":" + num(c.calib_layer_hi) : std::string("every layer"); } },
|
||||
{ "--kld-out", [](const Config& c) { return or_none(c.kld_out, "none"); } },
|
||||
{ "--kld-lora", [](const Config& c) { return or_none(c.kld_lora, "none (the base)"); } },
|
||||
{ "--kld-lora-sources", [](const Config& c) { return or_none(c.kld_lora_sources, "every document"); } },
|
||||
{ "--debug-graph", [](const Config& c) { return onoff(c.debug_graph); } },
|
||||
{ "--debug-selection", [](const Config& c) { return onoff(c.debug_selection); } },
|
||||
{ "--debug-placement", [](const Config& c) { return onoff(c.debug_placement); } },
|
||||
{ "--debug-draft-oracle", [](const Config& c) { return or_none(c.debug_draft_oracle, "none"); } },
|
||||
{ "--debug-accept-reference-kernels", [](const Config& c) { return onoff(c.accept_reference_kernels); } },
|
||||
{ "--proceed-with-incompatible-configuration", [](const Config& c) { return onoff(c.proceed_incompatible); } },
|
||||
{ "--profile-ops", [](const Config& c) { return onoff(c.profile_ops); } },
|
||||
{ "--expert-stats", [](const Config& c) { return or_none(c.expert_stats, "off"); } },
|
||||
{ "--expert-profile", [](const Config& c) { return or_none(c.expert_profile, "off"); } },
|
||||
{ "--expert-pin-top", [](const Config& c) { return fmt("%.4g", c.expert_pin_top); } },
|
||||
{ "--draft-expert-placement", [](const Config& c) { return c.draft_expert_placement; } },
|
||||
{ "--live", [](const Config& c) { return onoff(c.live_view); } },
|
||||
{ "-v", [](const Config& c) { return onoff(c.given.count("-v") > 0); } },
|
||||
{ "-vv", [](const Config& c) { return onoff(c.given.count("-vv") > 0); } },
|
||||
|
||||
+544
-81
@@ -64,6 +64,7 @@
|
||||
#include <vector>
|
||||
|
||||
#include "aql.h"
|
||||
#include "directio.h"
|
||||
#include "rad_format.h"
|
||||
#include "../rad_internal.h"
|
||||
|
||||
@@ -77,6 +78,10 @@ namespace rad {
|
||||
|
||||
int aql_vmem_device_of(const void* addr, int* dev);
|
||||
|
||||
namespace {
|
||||
void stamp_hold(hsa_signal_t h, bool on);
|
||||
}
|
||||
|
||||
namespace aql {
|
||||
namespace {
|
||||
|
||||
@@ -598,8 +603,6 @@ struct Stream {
|
||||
bool agent_only = false; /* rad_xp_stream_create: never a system-scope acquire */
|
||||
std::atomic<int> gates{0}; /* closed gates (rad_stream_gate) on this queue */
|
||||
std::atomic<int> fault{0};
|
||||
int unordered_run = 0; /* played packets in a row without the barrier bit */
|
||||
bool unordered_warned = false;
|
||||
char* bounce = nullptr; /* pinned, for pageable copies */
|
||||
std::mutex bounce_mu;
|
||||
/* Chained launches (RadKernelChainFn): the completion counter every block of a chained kernel
|
||||
@@ -633,11 +636,25 @@ inline Stream* ours(const void* s) {
|
||||
return p->magic == kStreamMagic ? const_cast<Stream*>(p) : nullptr;
|
||||
}
|
||||
|
||||
/* The device's stuck state, for dev_stuck_ms, in steady-clock ns (0: none). `g_stuck_at` is the
|
||||
* last moment anything advanced, set by the stall verdict (Stall::check) with the read-progress sum
|
||||
* it saw in `g_stuck_progress`; `g_fault_at` is when the first queue faulted. */
|
||||
std::atomic<uint64_t> g_stuck_at{0};
|
||||
std::atomic<uint64_t> g_stuck_progress{0};
|
||||
std::atomic<uint64_t> g_fault_at{0};
|
||||
|
||||
inline uint64_t steady_ns() {
|
||||
return (uint64_t)std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
void on_queue_error(hsa_status_t st, hsa_queue_t*, void* data) {
|
||||
Stream* s = static_cast<Stream*>(data);
|
||||
const char* m = nullptr;
|
||||
hsa_status_string(st, &m);
|
||||
s->fault.store((int)st, std::memory_order_release);
|
||||
uint64_t none = 0;
|
||||
g_fault_at.compare_exchange_strong(none, steady_ns(), std::memory_order_acq_rel);
|
||||
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 : "?");
|
||||
@@ -648,12 +665,19 @@ void on_queue_error(hsa_status_t st, hsa_queue_t*, void* data) {
|
||||
* nothing will decrement, or a kernel that faulted silently); the packet at the read index says
|
||||
* which. */
|
||||
/* Sum of every queue's read index. It only grows, so an unchanged sum means no queue moved. */
|
||||
/* How long a host wait may see no queue advance before it reports the queues; see dump_queues. */
|
||||
/* How long a host wait may see no progress before it reports the queues; see dump_queues. The
|
||||
* watchdog is progress-aware -- read_progress counts the drive reader's bytes beside the queues'
|
||||
* read indices -- so a period that moves nothing anywhere is a hang however slow the model's
|
||||
* drives are, and the threshold needs no tuning per deployment. */
|
||||
constexpr uint32_t kStallMs = 5000;
|
||||
|
||||
uint64_t read_progress() {
|
||||
/* Queue read indices plus the drive reader's byte count: the file tier's reads legitimately
|
||||
* park every queue for seconds at a time (one rank spins at the all-reduce while the other is
|
||||
* still reading its layer off the drive), and the bytes coming back are the progress that
|
||||
* makes such a wait not a stall. */
|
||||
uint64_t n = rad::dio_progress.load(std::memory_order_relaxed);
|
||||
std::lock_guard<std::mutex> lk(G().streams_mu);
|
||||
uint64_t n = 0;
|
||||
for (Stream* s : G().streams) n += hsa_queue_load_read_index_scacquire(s->q);
|
||||
return n;
|
||||
}
|
||||
@@ -869,7 +893,8 @@ hsa_status_t on_system_event(const hsa_amd_event_t* e, void*) {
|
||||
* video generator's denoising pass for tens of them. So the queues' read indices are sampled once
|
||||
* every stall period and only a period in which none advanced reports, with the packet each queue
|
||||
* is on: a hung kernel, or a queue the driver evicted and could not restore. A wait that keeps
|
||||
* moving says nothing. */
|
||||
* moving says nothing. The drive reader's byte count is progress too (read_progress), so a wait
|
||||
* parked on the file tier's drive reads never reports. */
|
||||
struct Stall {
|
||||
const char* where;
|
||||
uint32_t n = 0;
|
||||
@@ -892,8 +917,11 @@ struct Stall {
|
||||
const uint64_t p = read_progress();
|
||||
if (sampled && p == progress) {
|
||||
told = true;
|
||||
/* Nothing has advanced since the previous sample, a stall period ago. */
|
||||
g_stuck_progress.store(p, std::memory_order_relaxed);
|
||||
g_stuck_at.store(steady_ns() - (uint64_t)kStallMs * 1000000u, std::memory_order_release);
|
||||
dump_queues(where);
|
||||
RAD_ERR("device: no queue has advanced in the %u s since: the GPU is not running the "
|
||||
RAD_ERR("device: nothing has advanced in the %u s since: the GPU is not running the "
|
||||
"packet named above -- a hung kernel, or a queue the driver evicted and could "
|
||||
"not restore (amdgpu cwsr_enable=0 is one cause)", kStallMs / 1000);
|
||||
return;
|
||||
@@ -903,6 +931,22 @@ struct Stall {
|
||||
}
|
||||
};
|
||||
|
||||
/* dev_stuck_ms. A standing verdict is dropped as soon as the read progress moves again. */
|
||||
int64_t stuck_ms() {
|
||||
const uint64_t now = steady_ns();
|
||||
if (G().faulted.load(std::memory_order_acquire)) {
|
||||
const uint64_t f = g_fault_at.load(std::memory_order_acquire);
|
||||
return f && now > f ? (int64_t)((now - f) / 1000000u) : 0;
|
||||
}
|
||||
uint64_t at = g_stuck_at.load(std::memory_order_acquire);
|
||||
if (!at) return 0;
|
||||
if (read_progress() != g_stuck_progress.load(std::memory_order_relaxed)) {
|
||||
g_stuck_at.compare_exchange_strong(at, 0, std::memory_order_acq_rel);
|
||||
return 0;
|
||||
}
|
||||
return now > at ? (int64_t)((now - at) / 1000000u) : 0;
|
||||
}
|
||||
|
||||
/* Reserves packet `idx` once the packet processor has consumed far enough that its slot is free.
|
||||
* A launched barrier-bit packet means every packet before it has completed, which a kernel
|
||||
* argument slot (read for the kernel's whole run) needs. A played tape clears the bit on at most
|
||||
@@ -935,18 +979,12 @@ inline int reserve(Stream* s, uint64_t* out) {
|
||||
|
||||
inline void publish(Stream* s, uint64_t idx, uint16_t header, uint16_t setup) {
|
||||
s->wr = idx + 1;
|
||||
s->unordered_run = 0; /* an offered packet: every reclamation proof holds */
|
||||
_mm_sfence(); /* the packet body and the argument slot are write-combined
|
||||
VRAM: globally visible before the index below exposes
|
||||
the packet to the GPU (a torn kernarg read faults on the
|
||||
device with a stripped high pointer bit) */
|
||||
hsa_queue_store_write_index_relaxed(s->q, idx + 1);
|
||||
_mm_sfence(); /* the argument slot, written before the header */
|
||||
__atomic_store_n(reinterpret_cast<uint32_t*>(
|
||||
static_cast<hsa_kernel_dispatch_packet_t*>(s->q->base_address) +
|
||||
(idx & s->mask)),
|
||||
(uint32_t)header | ((uint32_t)setup << 16), __ATOMIC_RELEASE);
|
||||
/* The index is what exposes the packet to the GPU: only after the fence and the
|
||||
* header, or the packet processor can read a half-written argument block. */
|
||||
hsa_queue_store_write_index_relaxed(s->q, idx + 1);
|
||||
hsa_signal_store_relaxed(s->q->doorbell_signal, (hsa_signal_value_t)idx);
|
||||
}
|
||||
|
||||
@@ -1165,23 +1203,21 @@ struct PlayLeft { uint32_t q = UINT32_MAX; uint64_t wr = 0; };
|
||||
constexpr int kPlayLeft = 8;
|
||||
thread_local PlayLeft t_left[kPlayLeft];
|
||||
|
||||
/* A dispatch played under RADIANCE_AQL_STAMP (see "dispatch timestamps"). `sig` goes in as the
|
||||
* stamp's own signal and comes out as the packet's completion signal, which is a record's or a
|
||||
* ride's where one rides on the dispatch. */
|
||||
struct PlayStamp {
|
||||
hsa_signal_t sig{};
|
||||
bool ordered = false;
|
||||
bool chained = false;
|
||||
};
|
||||
|
||||
struct PlayRun {
|
||||
const Tape* tape = nullptr; /* the tape played, for a chained record's argument bytes */
|
||||
Stream* s = nullptr;
|
||||
uint64_t next = 0; /* the write index after the last packet written */
|
||||
int unrung = 0;
|
||||
bool foreign = true; /* the next packet's queue has packets this thread did not play */
|
||||
uint32_t seen[4] = {UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX};
|
||||
int n_seen = 0;
|
||||
/* True for the first dispatch this play writes on each queue, whatever its record says.
|
||||
* reserve()'s argument-slot proof needs an ordered packet after any the reuse may race:
|
||||
* a slot is reused once the read index passes the packet that held it, and only an
|
||||
* ordered packet after that one makes the index mean "it completed". */
|
||||
bool first_on(const Stream* q) {
|
||||
for (int i = 0; i < n_seen; ++i) if (seen[i] == q->id) return false;
|
||||
if (n_seen < 4) seen[n_seen++] = q->id;
|
||||
return true;
|
||||
}
|
||||
|
||||
void ring() {
|
||||
if (!unrung) return;
|
||||
@@ -1210,7 +1246,7 @@ struct PlayRun {
|
||||
/* `done`, when set, is the packet's completion signal and `rel_min` its minimum release
|
||||
* scope, for a record riding on this dispatch (see a_tape_play). */
|
||||
int put(const TapeRec& r, uint64_t* out_idx, hsa_signal_t done = hsa_signal_t{0},
|
||||
int rel_min = HSA_FENCE_SCOPE_NONE) {
|
||||
int rel_min = HSA_FENCE_SCOPE_NONE, PlayStamp* stamp = nullptr) {
|
||||
if (s != r.s) {
|
||||
end();
|
||||
s = r.s;
|
||||
@@ -1235,6 +1271,12 @@ struct PlayRun {
|
||||
s->ride.handle = 0;
|
||||
}
|
||||
if (done.handle) p->completion_signal = done;
|
||||
if (stamp) {
|
||||
/* Before the header: once the packet completes, the signal may return to the pool. */
|
||||
if (done.handle) stamp_hold(done, true);
|
||||
else p->completion_signal = stamp->sig;
|
||||
stamp->sig = p->completion_signal;
|
||||
}
|
||||
/* 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. */
|
||||
@@ -1254,21 +1296,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 = first_on(s) || foreign || !r.overlap || done.handle;
|
||||
bool ordered = foreign || !r.overlap || done.handle;
|
||||
/* Not while a plain packet may still run: a played plain kernel the overlap analysis let
|
||||
* start early (it touched nothing in flight) adds nothing to the counter, so a chained
|
||||
* kernel that reads its output and sits behind a chained one (a cache read beside a
|
||||
* collective, say) would wait for the chained blocks only. */
|
||||
if (chain && s->prev_chained && !s->plain_inflight && !foreign && !done.handle) ordered = false;
|
||||
/* The bound the slot proof rests on. Say so once if it is ever crossed, rather than tear
|
||||
* an argument block silently. */
|
||||
if (ordered) {
|
||||
s->unordered_run = 0;
|
||||
} else if (++s->unordered_run > kTapeOverlapRun && !s->unordered_warned) {
|
||||
s->unordered_warned = true;
|
||||
RAD_WARN("queue %u: %d played packets in a row carry no barrier bit, past the %d the "
|
||||
"argument-slot proof tolerates; a kernarg block may be reused while a kernel "
|
||||
"still reads it", s->id, s->unordered_run, kTapeOverlapRun);
|
||||
if (stamp) {
|
||||
stamp->ordered = ordered;
|
||||
stamp->chained = chain;
|
||||
}
|
||||
const uint16_t h = header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel, ordered);
|
||||
__atomic_store_n(reinterpret_cast<uint32_t*>(p), (uint32_t)h | ((uint32_t)r.pkt.setup << 16),
|
||||
@@ -1612,12 +1648,19 @@ struct Sig {
|
||||
bool irq = false; /* an interrupt signal */
|
||||
hsa_agent_t agent{}; /* where it was recorded */
|
||||
std::vector<std::pair<uint32_t, uint64_t>> waiters; /* queue id, packet index */
|
||||
bool stamped = false; /* its times not read yet (stamp_hold) */
|
||||
/* A prefetch DMA queue's list polls it (a_xp_list): the card whose queue, -1 for none, and the
|
||||
* list number the queue writes to its finish word once the engine is past the poll. A DMA
|
||||
* poll is no queue packet, so `waiters` cannot hold it. */
|
||||
std::atomic<int32_t> xp_dev{-1};
|
||||
std::atomic<uint32_t> xp_list{0};
|
||||
};
|
||||
|
||||
struct SigPool {
|
||||
std::mutex mu;
|
||||
std::vector<Sig*> free[2]; /* by irq */
|
||||
std::deque<Sig*> retiring; /* in the order they were retired */
|
||||
std::unordered_map<uint64_t, Sig*> by_handle;
|
||||
};
|
||||
|
||||
SigPool& pool() {
|
||||
@@ -1625,15 +1668,29 @@ SigPool& pool() {
|
||||
return *p;
|
||||
}
|
||||
|
||||
bool xp_list_finished(int ord, uint32_t k);
|
||||
|
||||
/* A signal at 0 can still be awaited: by a queue packet not yet consumed (`waiters`), or by a
|
||||
* prefetch DMA list that has not yet read it (`xp_dev`). Reused then, its next user's 1 would be
|
||||
* what that wait sees, and the wait would hang behind work that waits for it. */
|
||||
bool reusable(const Sig* g) {
|
||||
if (hsa_signal_load_relaxed(g->h) != 0) return false;
|
||||
if (g->stamped || hsa_signal_load_relaxed(g->h) != 0) return false;
|
||||
for (const auto& w : g->waiters) {
|
||||
hsa_queue_t* q = g_queue_by_id[w.first].load(std::memory_order_acquire);
|
||||
if (q && hsa_queue_load_read_index_relaxed(q) <= w.second) return false;
|
||||
}
|
||||
const int32_t xd = g->xp_dev.load(std::memory_order_acquire);
|
||||
if (xd >= 0 && !xp_list_finished(xd, g->xp_list.load(std::memory_order_relaxed))) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Back to the free list: what held it is over. */
|
||||
void sig_free(SigPool& p, Sig* g) {
|
||||
g->waiters.clear();
|
||||
g->xp_dev.store(-1, std::memory_order_relaxed);
|
||||
p.free[g->irq].push_back(g);
|
||||
}
|
||||
|
||||
/* A signal for one record: an interrupt signal if the host waits on the event, else GPU_ONLY.
|
||||
* Only interrupt signals can end a host wait (see "host waits"), but each costs a driver event (a
|
||||
* process has a few thousand) and an interrupt per completion, wasted on events recorded dozens
|
||||
@@ -1648,8 +1705,7 @@ Sig* sig_get(bool irq) {
|
||||
while (p.free[irq].empty() && !p.retiring.empty() && reusable(p.retiring.front())) {
|
||||
Sig* g = p.retiring.front();
|
||||
p.retiring.pop_front();
|
||||
g->waiters.clear();
|
||||
p.free[g->irq].push_back(g);
|
||||
sig_free(p, g);
|
||||
}
|
||||
if (p.free[irq].empty()) {
|
||||
/* In place and in order, so the front stays the oldest. */
|
||||
@@ -1657,8 +1713,7 @@ Sig* sig_get(bool irq) {
|
||||
for (size_t i = 0; i < p.retiring.size(); ++i) {
|
||||
Sig* g = p.retiring[i];
|
||||
if (reusable(g)) {
|
||||
g->waiters.clear();
|
||||
p.free[g->irq].push_back(g);
|
||||
sig_free(p, g);
|
||||
} else {
|
||||
p.retiring[kept++] = g;
|
||||
}
|
||||
@@ -1675,9 +1730,19 @@ Sig* sig_get(bool irq) {
|
||||
const hsa_status_t st = irq ? hsa_signal_create(0, 0, nullptr, &g->h)
|
||||
: hsa_amd_signal_create(0, 0, nullptr, HSA_AMD_SIGNAL_AMD_GPU_ONLY, &g->h);
|
||||
if (st != HSA_STATUS_SUCCESS || (irq && !interrupts(g->h))) return nullptr;
|
||||
p.by_handle[g->h.handle] = g.get();
|
||||
return g.release();
|
||||
}
|
||||
|
||||
/* A stamp's times live in the signal until a reuse overwrites them, so a record's or a ride's
|
||||
* signal a stamp shares stays out of the free list until they are read. */
|
||||
void stamp_hold(hsa_signal_t h, bool on) {
|
||||
SigPool& p = pool();
|
||||
std::lock_guard<std::mutex> lk(p.mu);
|
||||
auto it = p.by_handle.find(h.handle);
|
||||
if (it != p.by_handle.end()) it->second->stamped = on;
|
||||
}
|
||||
|
||||
void sig_retire(Sig* g) {
|
||||
SigPool& p = pool();
|
||||
std::lock_guard<std::mutex> lk(p.mu);
|
||||
@@ -1951,6 +2016,228 @@ int a_tape_set_overlap(RadTape rt, int i, int on) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- dispatch timestamps (RADIANCE_AQL_STAMP)
|
||||
*
|
||||
* RADIANCE_AQL_STAMP=N gives every dispatch of every Nth pass played on card 0 a completion signal,
|
||||
* into which the packet processor writes the dispatch's start and end (profiling is on on every
|
||||
* queue). Nothing else changes: PlayRun::put decides the barrier bit and the chain as without the
|
||||
* signal, so the queues run the pass as unstamped. A pass is the plays of one tape from its record
|
||||
* 0 on: Ctx::play_pass plays a pass in stretches between its host ops, and counting plays would
|
||||
* time stretches rather than passes. A dispatch a record or a ride already rides on is stamped
|
||||
* from that signal, held out of the pool until its times are read (stamp_hold).
|
||||
*
|
||||
* Nothing waits for the card: a later play on card 0 reads the signals that reached 0, in issue
|
||||
* order, and appends a line per dispatch to RADIANCE_AQL_STAMP_OUT (default
|
||||
* /tmp/radiance-stamps-<pid>.csv); exit waits briefly for the rest. */
|
||||
constexpr size_t kStampSignals = 8192;
|
||||
|
||||
struct StampRow {
|
||||
hsa_signal_t h{};
|
||||
bool own = false; /* the stamp's signal, not a record's or a ride's */
|
||||
bool ordered = false;
|
||||
bool chained = false;
|
||||
uint32_t queue = 0;
|
||||
int seq = 0; /* its record in the tape */
|
||||
uint32_t play = 0; /* the play of the pass that issued it */
|
||||
uint32_t records = 0; /* the tape's length, which tells kinds of pass apart */
|
||||
uint64_t pass = 0;
|
||||
uint64_t kernel = 0;
|
||||
};
|
||||
|
||||
struct Stamps {
|
||||
std::mutex mu;
|
||||
int every = 0;
|
||||
std::string path;
|
||||
FILE* out = nullptr;
|
||||
bool out_failed = false;
|
||||
bool full_told = false;
|
||||
uint64_t passes = 0; /* begun on card 0 */
|
||||
const Tape* tape = nullptr; /* the pass being stamped, if one is */
|
||||
uint32_t play = 0;
|
||||
std::vector<hsa_signal_t> free;
|
||||
size_t made = 0;
|
||||
std::deque<StampRow> rows; /* issued, times not read yet */
|
||||
std::unordered_map<uint64_t, std::string> names;
|
||||
};
|
||||
|
||||
void stamps_at_exit();
|
||||
|
||||
Stamps& stamps() {
|
||||
static Stamps* st = [] {
|
||||
Stamps* x = new Stamps();
|
||||
const char* n = std::getenv("RADIANCE_AQL_STAMP");
|
||||
x->every = n ? std::max(0, std::atoi(n)) : 0;
|
||||
const char* o = std::getenv("RADIANCE_AQL_STAMP_OUT");
|
||||
x->path = o && *o ? std::string(o) : fmt("/tmp/radiance-stamps-%d.csv", (int)getpid());
|
||||
if (x->every) {
|
||||
RAD_WARN("device: RADIANCE_AQL_STAMP times every dispatch of one pass in %d on card 0, "
|
||||
"into %s", x->every, x->path.c_str());
|
||||
std::atexit(stamps_at_exit);
|
||||
}
|
||||
return x;
|
||||
}();
|
||||
return *st;
|
||||
}
|
||||
|
||||
bool stamps_file(Stamps& st) {
|
||||
if (st.out) return true;
|
||||
if (st.out_failed) return false;
|
||||
st.out = std::fopen(st.path.c_str(), "a");
|
||||
if (!st.out) {
|
||||
st.out_failed = true;
|
||||
RAD_WARN("device: RADIANCE_AQL_STAMP: %s cannot be opened (%s); the times are dropped",
|
||||
st.path.c_str(), std::strerror(errno));
|
||||
return false;
|
||||
}
|
||||
std::fseek(st.out, 0, SEEK_END);
|
||||
if (std::ftell(st.out) == 0)
|
||||
std::fputs("pass,seq,queue,kernel,ordered,chained,start_ns,end_ns,play,records\n", st.out);
|
||||
return true;
|
||||
}
|
||||
|
||||
const std::string& stamps_kernel(Stamps& st, uint64_t obj) {
|
||||
auto it = st.names.find(obj);
|
||||
if (it != st.names.end()) return it->second;
|
||||
std::string n;
|
||||
{
|
||||
std::lock_guard<std::mutex> nl(g_names_mu);
|
||||
auto k = g_names.find(obj);
|
||||
n = k != g_names.end() ? k->second : fmt("%#" PRIx64, obj);
|
||||
}
|
||||
if (n.find_first_of(",\"") != std::string::npos) {
|
||||
std::string q = "\"";
|
||||
for (char c : n) {
|
||||
if (c == '"') q += '"';
|
||||
q += c;
|
||||
}
|
||||
n = q + "\"";
|
||||
}
|
||||
return st.names.emplace(obj, std::move(n)).first->second;
|
||||
}
|
||||
|
||||
uint64_t stamps_ns(uint64_t t) {
|
||||
return (uint64_t)((unsigned __int128)t * 1000000000u / G().ts_freq);
|
||||
}
|
||||
|
||||
/* With st.mu held. Rows are read in issue order, so one still running holds back the rows after
|
||||
* it, which a later call reads. */
|
||||
void stamps_read(Stamps& st, bool wait) {
|
||||
bool wrote = false;
|
||||
while (!st.rows.empty()) {
|
||||
const StampRow w = st.rows.front();
|
||||
if (hsa_signal_load_scacquire(w.h) != 0 &&
|
||||
(!wait || G().faulted.load(std::memory_order_acquire) ||
|
||||
hsa_signal_wait_scacquire(w.h, HSA_SIGNAL_CONDITION_EQ, 0, G().ts_freq / 10,
|
||||
HSA_WAIT_STATE_ACTIVE) != 0))
|
||||
break;
|
||||
hsa_amd_profiling_dispatch_time_t t{};
|
||||
const bool timed = hsa_amd_profiling_get_dispatch_time(G().dev[0].agent, w.h, &t) ==
|
||||
HSA_STATUS_SUCCESS;
|
||||
if (w.own) st.free.push_back(w.h);
|
||||
else stamp_hold(w.h, false);
|
||||
st.rows.pop_front();
|
||||
if (!stamps_file(st)) continue;
|
||||
std::fprintf(st.out, "%" PRIu64 ",%d,%u,%s,%d,%d,", w.pass, w.seq, w.queue,
|
||||
stamps_kernel(st, w.kernel).c_str(), (int)w.ordered, (int)w.chained);
|
||||
if (timed) std::fprintf(st.out, "%" PRIu64 ",%" PRIu64, stamps_ns(t.start), stamps_ns(t.end));
|
||||
else std::fputc(',', st.out);
|
||||
std::fprintf(st.out, ",%u,%u\n", w.play, w.records);
|
||||
wrote = true;
|
||||
}
|
||||
if (wrote) std::fflush(st.out);
|
||||
}
|
||||
|
||||
void stamps_at_exit() {
|
||||
Stamps& st = stamps();
|
||||
std::lock_guard<std::mutex> lk(st.mu);
|
||||
stamps_read(st, true);
|
||||
if (st.out) std::fclose(st.out);
|
||||
st.out = nullptr;
|
||||
st.out_failed = true;
|
||||
}
|
||||
|
||||
/* The stamping of one play: a signal for each of its dispatches, taken up front so the play
|
||||
* takes the lock twice rather than once a dispatch. */
|
||||
struct StampRun {
|
||||
bool on = false;
|
||||
uint64_t pass = 0;
|
||||
uint32_t play = 0;
|
||||
uint32_t records = 0;
|
||||
std::vector<hsa_signal_t> sig;
|
||||
size_t used = 0;
|
||||
std::vector<StampRow> rows;
|
||||
|
||||
void begin(const Tape* t, int from, int to) {
|
||||
Stamps& st = stamps();
|
||||
if (!st.every || from >= to || t->rec[(size_t)from].s->ord != 0) return;
|
||||
std::lock_guard<std::mutex> lk(st.mu);
|
||||
stamps_read(st, false);
|
||||
if (from == 0) {
|
||||
st.tape = ++st.passes % (uint64_t)st.every == 0 ? t : nullptr;
|
||||
st.play = 0;
|
||||
}
|
||||
if (!st.tape || st.tape != t) return;
|
||||
size_t n = 0;
|
||||
for (int i = from; i < to; ++i) n += t->rec[(size_t)i].kind == kTapeDispatch;
|
||||
while (sig.size() < n) {
|
||||
hsa_signal_t h{};
|
||||
if (!st.free.empty()) {
|
||||
h = st.free.back();
|
||||
st.free.pop_back();
|
||||
} else if (st.made < kStampSignals &&
|
||||
hsa_amd_signal_create(1, 0, nullptr, HSA_AMD_SIGNAL_AMD_GPU_ONLY, &h) ==
|
||||
HSA_STATUS_SUCCESS) {
|
||||
++st.made;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
hsa_signal_silent_store_relaxed(h, 1);
|
||||
sig.push_back(h);
|
||||
}
|
||||
if (sig.size() < n) {
|
||||
st.tape = nullptr;
|
||||
if (!st.full_told) {
|
||||
st.full_told = true;
|
||||
RAD_WARN("device: RADIANCE_AQL_STAMP: %zu signals are in flight, pass %" PRIu64
|
||||
" and any pass that finds them so are stamped in part", st.made, st.passes);
|
||||
}
|
||||
}
|
||||
on = true;
|
||||
pass = st.passes;
|
||||
play = st.play++;
|
||||
records = (uint32_t)t->rec.size();
|
||||
}
|
||||
PlayStamp* take(PlayStamp& ps) {
|
||||
if (!on || used == sig.size()) return nullptr;
|
||||
ps = PlayStamp{};
|
||||
ps.sig = sig[used++];
|
||||
return &ps;
|
||||
}
|
||||
void drop() { --used; }
|
||||
void note(const TapeRec& r, int seq, const PlayStamp& ps) {
|
||||
StampRow w;
|
||||
w.h = ps.sig;
|
||||
w.own = ps.sig.handle == sig[used - 1].handle;
|
||||
if (!w.own) --used;
|
||||
w.ordered = ps.ordered;
|
||||
w.chained = ps.chained;
|
||||
w.queue = r.s->id;
|
||||
w.seq = seq;
|
||||
w.play = play;
|
||||
w.records = records;
|
||||
w.pass = pass;
|
||||
w.kernel = r.pkt.kernel_object;
|
||||
rows.push_back(w);
|
||||
}
|
||||
void end() {
|
||||
if (sig.empty()) return;
|
||||
Stamps& st = stamps();
|
||||
std::lock_guard<std::mutex> lk(st.mu);
|
||||
st.free.insert(st.free.end(), sig.begin() + (std::ptrdiff_t)used, sig.end());
|
||||
st.rows.insert(st.rows.end(), rows.begin(), rows.end());
|
||||
}
|
||||
};
|
||||
|
||||
int a_tape_play(RadTape rt, int from, int to) {
|
||||
Tape* t = tape_of(rt);
|
||||
if (!t || from < 0 || to > (int)t->rec.size() || from > to) {
|
||||
@@ -1961,6 +2248,8 @@ int a_tape_play(RadTape rt, int from, int to) {
|
||||
int rc = RAD_OK;
|
||||
PlayRun run;
|
||||
run.tape = t;
|
||||
StampRun stamp;
|
||||
stamp.begin(t, from, to);
|
||||
for (int i = from; i < to && rc >= 0; ++i) {
|
||||
const TapeRec& r = t->rec[(size_t)i];
|
||||
if (r.kind == kTapeDispatch) {
|
||||
@@ -1979,8 +2268,14 @@ int a_tape_play(RadTape rt, int from, int to) {
|
||||
break;
|
||||
}
|
||||
uint64_t idx = 0;
|
||||
rc = run.put(r, &idx, g ? g->h : hsa_signal_t{0}, rel);
|
||||
if (rc < 0) break;
|
||||
PlayStamp ps;
|
||||
PlayStamp* sp = stamp.take(ps);
|
||||
rc = run.put(r, &idx, g ? g->h : hsa_signal_t{0}, rel, sp);
|
||||
if (rc < 0) {
|
||||
if (sp) stamp.drop();
|
||||
break;
|
||||
}
|
||||
if (sp) stamp.note(r, i, ps);
|
||||
bool found = false;
|
||||
for (auto& l : t->last)
|
||||
if (l.first == r.s->id) { l.second = idx; found = true; break; }
|
||||
@@ -2001,6 +2296,7 @@ int a_tape_play(RadTape rt, int from, int to) {
|
||||
: a_event_wait((RadStream)r.s, r.ev);
|
||||
}
|
||||
run.end();
|
||||
stamp.end();
|
||||
--t_tape_pause;
|
||||
return rc;
|
||||
}
|
||||
@@ -2272,10 +2568,10 @@ struct DmaQueue {
|
||||
bool ever_held = false; /* a stream has held this card's link at least once */
|
||||
std::atomic<bool> tried{false}; /* dma_open has run, for the startup report */
|
||||
std::string why; /* why it failed */
|
||||
/* For a queue whose lists each end by writing their number to `fin` (the expert prefetch's),
|
||||
* the room check uses the end of the last finished list as a lower bound on what the engine
|
||||
* has read. The engine's written-back read pointer can stop moving on such a queue while the
|
||||
* engine runs on, and a ring the host thinks full would wait forever. */
|
||||
/* For a queue whose lists each end by writing their number to `fin` (the lane's and the
|
||||
* expert prefetch's), the room check uses the end of the last finished list as a lower bound
|
||||
* on what the engine has read. The engine's written-back read pointer can stop moving on such
|
||||
* a queue while the engine runs on, and a ring the host thinks full would wait forever. */
|
||||
volatile uint32_t* fin = nullptr;
|
||||
uint32_t lists = 0; /* lists handed over; list k ends at ends[k % kDmaEnds] */
|
||||
std::unique_ptr<uint64_t[]> ends;
|
||||
@@ -2462,8 +2758,9 @@ void dump_dma_lanes() {
|
||||
for (int c = 0; c < kMaxDevices; ++c) {
|
||||
DmaQueue& q = g_dma[c];
|
||||
if (!q.tried.load(std::memory_order_acquire) || !q.ok) continue;
|
||||
RAD_ERR(" device %d DMA lane: ring written %" PRIu64 " B, read %" PRIu64 " B; link gate %"
|
||||
PRId64 " (%s), last hold issued %s", c, (uint64_t)q.w, (uint64_t)*q.rptr,
|
||||
RAD_ERR(" device %d DMA lane: ring written %" PRIu64 " B, read %" PRIu64 " B; %u lists handed "
|
||||
"over, %" PRIu32 " finished; link gate %" PRId64 " (%s), last hold issued %s",
|
||||
c, (uint64_t)q.w, dma_read(&q), q.lists, q.fin ? *q.fin : 0u,
|
||||
(int64_t)hsa_signal_load_relaxed(q.gate),
|
||||
(hsa_signal_load_relaxed(q.gate) & 1) ? "held" : "free", q.held ? "on" : "off");
|
||||
}
|
||||
@@ -2475,6 +2772,11 @@ void dump_dma_lanes() {
|
||||
}
|
||||
}
|
||||
|
||||
/* Where the engine reads and writes a signal's value: the 64-bit word the CP decrements and polls. */
|
||||
inline uint64_t sig_value_addr(const Sig* g) {
|
||||
return (uint64_t)g->h.handle + offsetof(amd_signal_t, value);
|
||||
}
|
||||
|
||||
/* The card's queue, opened on first use; null (after one warning) if the driver refuses. */
|
||||
DmaQueue* dma_queue(int ord) {
|
||||
if (ord < 0 || ord >= kMaxDevices || ord >= (int)G().dev.size()) return nullptr;
|
||||
@@ -2486,6 +2788,18 @@ DmaQueue* dma_queue(int ord) {
|
||||
q.why = why;
|
||||
q.tried.store(true, std::memory_order_release);
|
||||
if (q.ok) aql::g_dump_lanes = dump_dma_lanes;
|
||||
if (q.ok) {
|
||||
/* The engine's written-back read pointer can stop moving while the engine runs on (the
|
||||
* expert prefetch's queue has the same quirk), and a ring the host thinks full would
|
||||
* wait forever -- a large pool's load fill wedged exactly there. So every list ends by
|
||||
* writing its number to a word the engine keeps advancing, which bounds the engine's
|
||||
* progress from below without trusting the read pointer (dma_read). */
|
||||
if (Sig* f = sig_get(false)) {
|
||||
hsa_signal_silent_store_relaxed(f->h, 0);
|
||||
q.ends.reset(new uint64_t[kDmaEnds]());
|
||||
q.fin = (volatile uint32_t*)(uintptr_t)sig_value_addr(f);
|
||||
}
|
||||
}
|
||||
if (q.ok)
|
||||
RAD_INFO("device: card %d copy lists go to DMA engine 0 on a queue of this process's own "
|
||||
"(%.1f ms to open)", ord,
|
||||
@@ -2543,11 +2857,6 @@ void dma_kick(DmaQueue* q) {
|
||||
*q->db = q->w;
|
||||
}
|
||||
|
||||
/* Where the engine reads and writes a signal's value: the 64-bit word the CP decrements and polls. */
|
||||
inline uint64_t sig_value_addr(const Sig* g) {
|
||||
return (uint64_t)g->h.handle + offsetof(amd_signal_t, value);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------- the expert prefetch's device half (rad_xp_*) */
|
||||
|
||||
/* The card's prefetch queue on its second DMA engine (the lane has the first), opened on first
|
||||
@@ -2576,6 +2885,15 @@ DmaQueue* xp_queue(int ord) {
|
||||
return q.ok ? &q : nullptr;
|
||||
}
|
||||
|
||||
/* Whether card `ord`'s prefetch queue has finished list `k`, or a later one: its lists finish in
|
||||
* order, so the engine is then past every packet list `k` holds. */
|
||||
bool xp_list_finished(int ord, uint32_t k) {
|
||||
if (ord < 0 || ord >= kMaxDevices) return true;
|
||||
const DmaQueue& q = g_dma_xp[ord];
|
||||
if (!q.fin) return true;
|
||||
return (int32_t)(*q.fin - k) >= 0;
|
||||
}
|
||||
|
||||
int a_xp_supported(int device) { return xp_queue(device) != nullptr; }
|
||||
|
||||
int a_xp_stream_create(RadStream* out) {
|
||||
@@ -2697,9 +3015,9 @@ int64_t a_gate_room(RadStream rs) {
|
||||
|
||||
/* Waits for the mark, then for the card's link gate if a collective has ever held it (under TP
|
||||
* the all-reduce shares the link and the step waits on it, not on these copies), copies, writes
|
||||
* `done`, then the list's number. */
|
||||
* `done`, then the list's number. RAD_XP_NO_YIELD skips the gate (rad_xp_list). */
|
||||
int a_xp_list(int ord, void* mark, int n, const uint64_t* src, const uint64_t* dst, const uint64_t* bytes,
|
||||
uint32_t* done, uint32_t done_val) {
|
||||
uint32_t* done, uint32_t done_val, unsigned flags) {
|
||||
DmaQueue* dq = xp_queue(ord);
|
||||
if (!dq) return RAD_E_UNSUPPORTED;
|
||||
Sig* in = (Sig*)mark;
|
||||
@@ -2712,8 +3030,18 @@ int a_xp_list(int ord, void* mark, int n, const uint64_t* src, const uint64_t* d
|
||||
(uint32_t)ia, (uint32_t)(ia >> 32), 0u, 0xffffffffu,
|
||||
10u /* interval */ | (0xfffu << 16) /* retry forever */ };
|
||||
rc = dma_put(dq, poll, 6);
|
||||
/* The mark stays out of the pool until the engine is past this poll: the finish word
|
||||
* reaches lists + 1 only behind it, whether this list's own fence writes it or, if the
|
||||
* list below fails, the next list's. Returned earlier, a mark at 0 can be handed out and
|
||||
* set to 1 before the engine reads it, and the list then waits for whatever completes
|
||||
* the next use, which can sit behind the stream's wait for this list. */
|
||||
if (rc == RAD_OK) {
|
||||
in->xp_list.store(dq->lists + 1, std::memory_order_relaxed);
|
||||
in->xp_dev.store(ord, std::memory_order_release);
|
||||
}
|
||||
if (rc == RAD_OK && n > 0 && lane && lane->ever_held && lane->gate.handle) {
|
||||
}
|
||||
if (rc == RAD_OK && n > 0 && lane && lane->ever_held && lane->gate.handle &&
|
||||
!(flags & RAD_XP_NO_YIELD)) {
|
||||
const uint64_t ga = (uint64_t)lane->gate.handle + offsetof(amd_signal_t, value);
|
||||
const uint32_t gate[6] = { kSdmaPoll | (3u << 28) /* equal */ | (1u << 31) /* memory */,
|
||||
(uint32_t)ga, (uint32_t)(ga >> 32), 0u, 1u /* the low bit */,
|
||||
@@ -2748,6 +3076,29 @@ int a_xp_list(int ord, void* mark, int n, const uint64_t* src, const uint64_t* d
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* rad_event_dma: a fresh signal for the event, at 0. The caller arms it with a 1 written in stream
|
||||
* order: a host store could land ahead of a wait still queued for the previous copy, and an event
|
||||
* record completes by reaching 0, the value the wait looks for. A fresh signal each time keeps two
|
||||
* uses from sharing one word. */
|
||||
int a_event_dma(RadEvent re, RadStream rs, uint32_t** word) {
|
||||
if (!word) { device_set_error("rad_event_dma: null word"); return RAD_E_INVAL; }
|
||||
if (capturing()) {
|
||||
device_set_error("rad_event_dma: a tape cannot record a DMA list; the caller must re-run "
|
||||
"this call with the tape paused");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
Event* e = ev_of(re);
|
||||
Stream* s = ours(rs);
|
||||
if (!e || !s) { device_set_error("rad_event_dma: null or foreign argument"); return RAD_E_INVAL; }
|
||||
Sig* g = sig_get(e->host);
|
||||
if (!g) { device_set_error("rad_event_dma: no signal could be made"); return RAD_E_DEVICE; }
|
||||
hsa_signal_silent_store_relaxed(g->h, 0);
|
||||
g->agent = s->agent;
|
||||
record_adopt(e, g);
|
||||
*word = (uint32_t*)(uintptr_t)sig_value_addr(g);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int64_t a_xp_behind(int ord) {
|
||||
DmaQueue* dq = (ord >= 0 && ord < kMaxDevices) ? &g_dma_xp[ord] : nullptr;
|
||||
if (!dq || !dq->tried.load(std::memory_order_acquire) || !dq->ok) return 0;
|
||||
@@ -2864,6 +3215,19 @@ int a_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream
|
||||
(uint32_t)oa, (uint32_t)(oa >> 32), 0u };
|
||||
rc = dma_put(dq, fence, 4);
|
||||
}
|
||||
if (rc == RAD_OK && dq->fin) {
|
||||
/* Name the list: the engine writes the number when everything before it is done,
|
||||
* which the room check trusts over the read pointer (see dma_read). */
|
||||
const uint32_t k = dq->lists + 1;
|
||||
const uint64_t fa = (uint64_t)(uintptr_t)dq->fin;
|
||||
const uint32_t finf[4] = { kSdmaFence | (3u << 16) /* uncached */,
|
||||
(uint32_t)fa, (uint32_t)(fa >> 32), k };
|
||||
rc = dma_put(dq, finf, 4);
|
||||
if (rc == RAD_OK) {
|
||||
dq->ends[k % kDmaEnds] = dq->w;
|
||||
dq->lists = k;
|
||||
}
|
||||
}
|
||||
dma_kick(dq);
|
||||
}
|
||||
/* If the ring refused the list, release `out` so the stream does not wait on it forever. */
|
||||
@@ -3383,6 +3747,43 @@ void* pin_whole(int64_t bytes, const std::vector<hsa_agent_t>& cards) {
|
||||
return p;
|
||||
}
|
||||
|
||||
/* Locks [p, p + len) in pieces of at most kPinPiece for every card, each mapped on the cards at
|
||||
* its host address. On failure sets the device error for `who` (asked for `bytes`), unlocks what
|
||||
* was locked and returns false; the mapping stays the caller's to unmap. */
|
||||
bool lock_pieces(char* p, int64_t len, int64_t bytes, std::vector<hsa_agent_t>& cards,
|
||||
const char* who) {
|
||||
const int pieces = (int)((len + kPinPiece - 1) / kPinPiece);
|
||||
int done = 0;
|
||||
for (; done < pieces; ++done) {
|
||||
const int64_t off = (int64_t)done * kPinPiece;
|
||||
const int64_t n = std::min(kPinPiece, len - off);
|
||||
void* on_card = nullptr;
|
||||
const hsa_status_t st = hsa_amd_memory_lock_to_pool(p + off, (size_t)n, cards.data(),
|
||||
(int)cards.size(), G().host_fine, 0,
|
||||
&on_card);
|
||||
if (st != HSA_STATUS_SUCCESS) {
|
||||
device_set_error("%s(%s): locking piece %d of %d (%s at +%s): %s", who,
|
||||
humanb(bytes).c_str(), done + 1, pieces, humanb(n).c_str(),
|
||||
humanb(off).c_str(), hsa_why(st));
|
||||
break;
|
||||
}
|
||||
if (on_card != p + off) {
|
||||
++done;
|
||||
device_set_error("%s(%s): piece %d of %d is mapped on the cards at %p, not "
|
||||
"at its host address %p, so the pieces are not one range there, "
|
||||
"although the kernel driver reports the SVM API that maps a lock in "
|
||||
"place",
|
||||
who, humanb(bytes).c_str(), done, pieces, on_card, (void*)(p + off));
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (done < pieces) {
|
||||
for (int i = 0; i < done; ++i) (void)hsa_amd_memory_unlock(p + (int64_t)i * kPinPiece);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void* pin_pieces(int64_t bytes) {
|
||||
std::vector<hsa_agent_t> cards;
|
||||
for (const Dev& d : G().dev) cards.push_back(d.agent);
|
||||
@@ -3411,33 +3812,61 @@ void* pin_pieces(int64_t bytes) {
|
||||
}
|
||||
(void)::madvise(p, (size_t)len, MADV_DONTFORK);
|
||||
|
||||
const int pieces = (int)((len + kPinPiece - 1) / kPinPiece);
|
||||
int done = 0;
|
||||
for (; done < pieces; ++done) {
|
||||
const int64_t off = (int64_t)done * kPinPiece;
|
||||
const int64_t n = std::min(kPinPiece, len - off);
|
||||
void* on_card = nullptr;
|
||||
const hsa_status_t st = hsa_amd_memory_lock_to_pool(p + off, (size_t)n, cards.data(),
|
||||
(int)cards.size(), G().host_fine, 0,
|
||||
&on_card);
|
||||
if (st != HSA_STATUS_SUCCESS) {
|
||||
device_set_error("rad_dev_alloc(%s): locking piece %d of %d (%s at +%s): %s",
|
||||
humanb(bytes).c_str(), done + 1, pieces, humanb(n).c_str(),
|
||||
humanb(off).c_str(), hsa_why(st));
|
||||
break;
|
||||
if (!lock_pieces(p, len, bytes, cards, "rad_dev_alloc")) {
|
||||
::munmap(p, (size_t)len);
|
||||
return nullptr;
|
||||
}
|
||||
if (on_card != p + off) {
|
||||
++done;
|
||||
device_set_error("rad_dev_alloc(%s): piece %d of %d is mapped on the cards at %p, not "
|
||||
"at its host address %p, so the pieces are not one range there, "
|
||||
"although the kernel driver reports the SVM API that maps a lock in "
|
||||
"place",
|
||||
humanb(bytes).c_str(), done, pieces, on_card, (void*)(p + off));
|
||||
break;
|
||||
std::lock_guard<std::mutex> lk(g_pinned_mu);
|
||||
g_pinned.emplace((uintptr_t)p, Pinned{len, nullptr});
|
||||
return p;
|
||||
}
|
||||
|
||||
/* pin_pieces over a shared file mapping instead of private anonymous memory: the pages are the
|
||||
* file's (a tmpfs file other processes map too) and the lock takes them in place. The file maps
|
||||
* onto a 2 MiB boundary inside a reservation made with one alignment extra, then the ends are
|
||||
* trimmed. MADV_HUGEPAGE is advised but shmem follows shmem_enabled, not it. A tmpfs page is
|
||||
* swappable until the lock pins it, so MLOCK_ONFAULT keeps the pages in memory meanwhile; a
|
||||
* refusal (the memlock limit) costs only that. */
|
||||
void* pin_pieces_file(int64_t bytes, int fd, int64_t foff) {
|
||||
std::vector<hsa_agent_t> cards;
|
||||
for (const Dev& d : G().dev) cards.push_back(d.agent);
|
||||
if (!svm_in_place()) {
|
||||
device_set_error("rad_dev_map_file(%s): a file range is pinned in place only through the "
|
||||
"kernel driver's SVM API, which this host lacks, so ram=DIR needs it",
|
||||
humanb(bytes).c_str());
|
||||
return nullptr;
|
||||
}
|
||||
if (done < pieces) {
|
||||
for (int i = 0; i < done; ++i) (void)hsa_amd_memory_unlock(p + (int64_t)i * kPinPiece);
|
||||
|
||||
const int64_t align = RAD_ALIGN_POOL;
|
||||
const int64_t len = align_up(bytes, 4096);
|
||||
void* m = ::mmap(nullptr, (size_t)(len + align), PROT_NONE,
|
||||
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
|
||||
if (m == MAP_FAILED) {
|
||||
device_set_error("rad_dev_map_file(%s): mmap: %s", humanb(bytes).c_str(),
|
||||
std::strerror(errno));
|
||||
return nullptr;
|
||||
}
|
||||
const uintptr_t lo = (uintptr_t)m;
|
||||
const uintptr_t at = (lo + (uintptr_t)align - 1) & ~((uintptr_t)align - 1);
|
||||
if (::mmap((void*)at, (size_t)len, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd,
|
||||
(off_t)foff) == MAP_FAILED) {
|
||||
device_set_error("rad_dev_map_file(%s): mmap of the file at +%s: %s", humanb(bytes).c_str(),
|
||||
humanb(foff).c_str(), std::strerror(errno));
|
||||
::munmap(m, (size_t)(len + align));
|
||||
return nullptr;
|
||||
}
|
||||
if (at > lo) ::munmap(m, at - lo);
|
||||
if (lo + (uintptr_t)align > at) ::munmap((void*)(at + (uintptr_t)len), lo + (uintptr_t)align - at);
|
||||
char* const p = (char*)at;
|
||||
|
||||
if (len >= ((int64_t)2 << 20)) (void)::madvise(p, (size_t)len, MADV_HUGEPAGE);
|
||||
(void)::madvise(p, (size_t)len, MADV_DONTFORK);
|
||||
if (::mlock2(p, (size_t)len, MLOCK_ONFAULT) != 0)
|
||||
RAD_WARN("device: the shared file range %p (%s) could not be locked against swap (mlock2: "
|
||||
"%s)", (void*)p, humanb(len).c_str(), std::strerror(errno));
|
||||
prefer_numa_node(p, len, current_card_numa_node());
|
||||
|
||||
if (!lock_pieces(p, len, bytes, cards, "rad_dev_map_file")) {
|
||||
::munmap(p, (size_t)len);
|
||||
return nullptr;
|
||||
}
|
||||
@@ -3501,6 +3930,17 @@ void* a_alloc(int64_t bytes, int kind) {
|
||||
return p;
|
||||
}
|
||||
|
||||
void* a_map_file(int fd, int64_t foff, int64_t bytes) {
|
||||
if (fd < 0 || foff < 0 || bytes <= 0) {
|
||||
device_set_error("rad_dev_map_file(%d, %lld, %lld): a file, a non-negative offset and a "
|
||||
"positive size are needed", fd, (long long)foff, (long long)bytes);
|
||||
return nullptr;
|
||||
}
|
||||
void* p = pin_pieces_file(bytes, fd, foff);
|
||||
note_alloc(p, bytes, RAD_MEM_HOST_MAPPED);
|
||||
return p;
|
||||
}
|
||||
|
||||
/* Every free invalidates locate()'s cache first. */
|
||||
void (*g_hip_free)(void*, int) = nullptr;
|
||||
void a_free(void* p, int kind) {
|
||||
@@ -3553,6 +3993,15 @@ DeviceBackend g_aql;
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace aql {
|
||||
bool ride_reusable(void* token) {
|
||||
Sig* g = static_cast<Sig*>(token);
|
||||
if (!g) return false;
|
||||
std::lock_guard<std::mutex> lk(pool().mu);
|
||||
return reusable(g);
|
||||
}
|
||||
} // namespace aql
|
||||
|
||||
size_t aql_code_registered(void) { return a_code_mark(); }
|
||||
|
||||
const DeviceBackend* aql_backend_if_present(void) {
|
||||
@@ -3581,6 +4030,7 @@ const DeviceBackend* aql_backend_if_present(void) {
|
||||
g_hip_host_ptr = hip->host_ptr;
|
||||
g_hip_device_ptr = hip->device_ptr;
|
||||
g_aql.alloc = a_alloc;
|
||||
g_aql.map_file = a_map_file;
|
||||
g_aql.free = a_free;
|
||||
g_aql.host_ptr = a_host_ptr;
|
||||
g_aql.device_ptr = a_device_ptr;
|
||||
@@ -3612,6 +4062,7 @@ const DeviceBackend* aql_backend_if_present(void) {
|
||||
g_aql.alloc_uncached = a_alloc_uncached;
|
||||
g_aql.free_uncached = a_free_uncached;
|
||||
g_aql.dma_lane = a_dma_lane;
|
||||
g_aql.stuck_ms = stuck_ms;
|
||||
g_aql.vmem_granularity = a_vmem_granularity;
|
||||
g_aql.vmem_reserve = a_vmem_reserve;
|
||||
g_aql.vmem_release = a_vmem_release;
|
||||
@@ -3633,6 +4084,7 @@ const DeviceBackend* aql_backend_if_present(void) {
|
||||
g_aql.stream_gate = a_stream_gate;
|
||||
g_aql.gate_open = a_gate_open;
|
||||
g_aql.gate_room = a_gate_room;
|
||||
g_aql.event_dma = a_event_dma;
|
||||
return &g_aql;
|
||||
}();
|
||||
return b;
|
||||
@@ -3834,4 +4286,15 @@ hipError_t hipPeekAtLastError(void) {
|
||||
|
||||
} // extern "C"
|
||||
|
||||
#else
|
||||
|
||||
#include "aql.h"
|
||||
|
||||
namespace rad {
|
||||
namespace aql {
|
||||
/* A build without the AQL backend hands out no ride. */
|
||||
bool ride_reusable(void*) { return false; }
|
||||
} // namespace aql
|
||||
} // namespace rad
|
||||
|
||||
#endif /* RAD_HAVE_HIP */
|
||||
@@ -67,6 +67,11 @@ bool code_object_kernels(const void* elf, size_t size, std::vector<KernelMeta>*
|
||||
enum : uint8_t { kFenceAcquireSystem = 1, kFenceReleaseSystem = 2 };
|
||||
void set_next_fence(uint8_t f);
|
||||
|
||||
/* ------------------------------------------------------------------ test hooks */
|
||||
|
||||
/* Whether the signal behind a rad_ride token could be handed out again now (tests/device_test.cpp). */
|
||||
bool ride_reusable(void* token);
|
||||
|
||||
} // namespace aql
|
||||
} // namespace rad
|
||||
|
||||
|
||||
+41
-5
@@ -104,26 +104,47 @@ extern "C" void* rad_link_gate(RadStream s);
|
||||
* A ride is a signal completed by the next dispatch on a stream, instead of a separate barrier
|
||||
* packet. That dispatch keeps its ordering bit, so the signal covers everything before it.
|
||||
* rad_ride_wait puts a barrier waiting on it onto another stream and recycles the signal behind
|
||||
* that barrier. A ride polled by the DMA engine is returned with rad_ride_release once nothing can
|
||||
* poll it: immediately (`after` null) when the polling list has finished, else once `after` is
|
||||
* `packets` dispatches further on.
|
||||
* that barrier. A ride handed to rad_xp_list as its mark is returned with rad_ride_release once
|
||||
* the caller is done with it, `after` null; the backend keeps it out of reuse until the list's
|
||||
* engine is past its poll. One never handed to a list (a dropped request's) is returned with
|
||||
* `after` and `packets` reaching past the dispatch it rides on: the signal is reused only once
|
||||
* `after` has consumed `packets` more packets.
|
||||
*
|
||||
* rad_xp_list gives the card's prefetch DMA queue a list: wait for `mark` (a ride, or null), copy
|
||||
* the `n` ranges, then write `done_val` to `done` (pinned host memory, or null). rad_xp_behind
|
||||
* counts lists handed over and not yet finished. The prefetch ring is uncached device memory
|
||||
* (rad_dev_alloc_uncached): the engine writes it and kernels read it, so no cache may hold a
|
||||
* slot's previous contents. */
|
||||
/* An event a DMA list completes instead of a dispatch. `*word` is its completion word, for
|
||||
* rad_xp_list to write 0 to as the list's `done`; the caller arms it with a 1 in stream order (the
|
||||
* weight table's patch dispatch). `rad_event_wait(s, ev)` then holds `s` on the device until the
|
||||
* copy has landed. The caller waits for the previous copy before arming the next, so an older 0
|
||||
* cannot release a later wait. RAD_E_STATE while a tape records: the caller re-runs it with the
|
||||
* tape paused (core/kvstream/stage.cpp). */
|
||||
extern "C" int rad_event_dma(RadEvent ev, RadStream s, uint32_t** word);
|
||||
extern "C" int rad_xp_supported(int device);
|
||||
extern "C" int rad_xp_stream_create(RadStream* out);
|
||||
extern "C" int rad_ride(RadStream s, void** token);
|
||||
extern "C" int rad_ride_wait(RadStream s, void* token);
|
||||
extern "C" void rad_ride_release(void* token, RadStream after, int64_t packets);
|
||||
/* `flags` RAD_XP_NO_YIELD: the list does not yield the link to a hold by a stream of this card. A
|
||||
* copy the compute stream waits on must set it, since the hold's release is behind that wait. */
|
||||
#define RAD_XP_NO_YIELD 1u
|
||||
extern "C" int rad_xp_list(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst,
|
||||
const uint64_t* bytes, uint32_t* done, uint32_t done_val);
|
||||
const uint64_t* bytes, uint32_t* done, uint32_t done_val,
|
||||
unsigned flags);
|
||||
extern "C" int64_t rad_xp_behind(int device);
|
||||
extern "C" void* rad_dev_alloc_uncached(int64_t bytes);
|
||||
extern "C" void rad_dev_free_uncached(void* p);
|
||||
|
||||
/* [foff, foff + bytes) of the open file `fd`, mapped MAP_SHARED and pinned for every card as a
|
||||
* RAD_MEM_HOST_MAPPED allocation is: one range at the same address on host and cards. For a table
|
||||
* that engines on separate cards share through a tmpfs file (format/table_share.h). `foff` is a
|
||||
* multiple of 2 MiB and the file holds the whole range. Freed with rad_dev_free(p,
|
||||
* RAD_MEM_HOST_MAPPED), which unpins and unmaps and leaves the file alone. Null with the reason in
|
||||
* rad_dev_last_error() on a backend without it or a failure. */
|
||||
extern "C" void* rad_dev_map_file(int fd, int64_t foff, int64_t bytes);
|
||||
|
||||
/* A gate on a stream: the stream stops at the point rad_stream_gate enqueues and goes on once the
|
||||
* host calls rad_gate_open. Everything enqueued behind the gate meanwhile is then ready at once, so
|
||||
* the device runs it back to back however long the host took to submit it. For timing a batch of
|
||||
@@ -316,7 +337,7 @@ struct DeviceBackend {
|
||||
int (*ride_wait)(RadStream s, void* token);
|
||||
void (*ride_release)(void* token, RadStream after, int64_t packets);
|
||||
int (*xp_list)(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst,
|
||||
const uint64_t* bytes, uint32_t* done, uint32_t done_val);
|
||||
const uint64_t* bytes, uint32_t* done, uint32_t done_val, unsigned flags);
|
||||
int64_t (*xp_behind)(int device);
|
||||
void* (*alloc_uncached)(int64_t bytes);
|
||||
void (*free_uncached)(void* p);
|
||||
@@ -325,6 +346,15 @@ struct DeviceBackend {
|
||||
int (*stream_gate)(RadStream s, void** gate);
|
||||
int (*gate_open)(void* gate);
|
||||
int64_t (*gate_room)(RadStream s);
|
||||
|
||||
/* ---- rad_event_dma; null on a backend with no DMA queue. */
|
||||
int (*event_dma)(RadEvent e, RadStream s, uint32_t** word);
|
||||
|
||||
/* ---- see rad_dev_map_file. Null on a backend with no pinned host memory to map a file into. */
|
||||
void* (*map_file)(int fd, int64_t foff, int64_t bytes);
|
||||
|
||||
/* ---- see dev_stuck_ms. Null on a backend that cannot tell. */
|
||||
int64_t (*stuck_ms)(void);
|
||||
};
|
||||
|
||||
|
||||
@@ -363,6 +393,12 @@ std::string dev_runtime_version();
|
||||
/* The current backend's DeviceBackend::dma_lane, "" where it has none. */
|
||||
std::string dev_dma_lane(int device);
|
||||
|
||||
/* How long the device has been stuck, in ms, or 0: since the last moment anything advanced, once a
|
||||
* host wait has seen nothing advance for its stall period and named the stuck packet (the queue
|
||||
* dump), or since a queue faulted. Anything advancing again clears it. 0 where the backend cannot
|
||||
* tell. */
|
||||
int64_t dev_stuck_ms();
|
||||
|
||||
/* Longest run of dispatches a played tape leaves unordered. Of any kTapeOverlapRun + 1
|
||||
* consecutive packets on a queue one carries the barrier bit, so a launched packet still proves
|
||||
* that everything more than that many packets earlier has completed. Argument slots and tape
|
||||
|
||||
@@ -40,7 +40,9 @@ int64_t pread_some(int fd, void* dst, int64_t bytes, int64_t off) {
|
||||
int pread_exact(int fd, void* dst, int64_t bytes, int64_t off) {
|
||||
const int64_t got = pread_some(fd, dst, bytes, off);
|
||||
if (got < 0) return (int)got;
|
||||
return got == bytes ? RAD_OK : RAD_E_IO;
|
||||
if (got != bytes) return RAD_E_IO;
|
||||
dio_progress.fetch_add((uint64_t)bytes, std::memory_order_relaxed);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int pwrite_exact(int fd, const void* src, int64_t bytes, int64_t off) {
|
||||
|
||||
@@ -11,10 +11,17 @@
|
||||
* (rad_format.h), so every mover read takes the unbounced path. The bounce is for other callers.
|
||||
*/
|
||||
#pragma once
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Bytes the drive has returned through this reader, monotonically. The stall
|
||||
* watchdog (aql.cpp) counts this alongside the queues' read indices: a host wait
|
||||
* that moves nothing anywhere -- no queue advanced, no read came back -- is the
|
||||
* only one that reports a stall. */
|
||||
inline std::atomic<uint64_t> dio_progress{0};
|
||||
|
||||
enum {
|
||||
RAD_DIO_READ = 1,
|
||||
RAD_DIO_WRITE = 2, /* implies read: a partial block is a read-modify-write */
|
||||
|
||||
@@ -538,6 +538,10 @@ std::string dev_pci_address(int device) {
|
||||
if (!dev()->pci_address) return std::string();
|
||||
return dev_string(64, [&](char* b, int n) { return dev()->pci_address(device, b, n); });
|
||||
}
|
||||
int64_t dev_stuck_ms() {
|
||||
const auto f = dev()->stuck_ms;
|
||||
return f ? f() : 0;
|
||||
}
|
||||
std::string dev_dma_lane(int device) {
|
||||
if (!dev()->dma_lane) return std::string();
|
||||
return dev_string(256, [&](char* b, int n) { return dev()->dma_lane(device, b, n); });
|
||||
@@ -564,6 +568,7 @@ int dev_code_runs(size_t from, size_t to, int device, std::string* why) {
|
||||
|
||||
extern "C" {
|
||||
|
||||
int rad_dev_peer_access(int self, int peer) { return rad::dev_peer_access(self, peer); }
|
||||
|
||||
int rad_event_create_as(RadEvent* out, unsigned flags) {
|
||||
const int s = dev()->event_create(out, flags);
|
||||
@@ -578,6 +583,11 @@ void rad_event_destroy(RadEvent e) {
|
||||
dev()->event_destroy(e);
|
||||
}
|
||||
int rad_event_record(RadEvent e, RadStream s) { return dev()->event_record(e, s); }
|
||||
int rad_event_dma(RadEvent e, RadStream s, uint32_t** w) {
|
||||
if (const auto f = dev()->event_dma) return f(e, s, w);
|
||||
rad::device_set_error("rad_event_dma: the device backend has no DMA queue to complete an event");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
int rad_event_wait(RadStream s, RadEvent e) { return dev()->event_wait(s, e); }
|
||||
int rad_event_query(RadEvent e) { return dev()->event_query(e); }
|
||||
int rad_event_sync(RadEvent e) {
|
||||
@@ -612,10 +622,14 @@ int rad_event_elapsed_ms(RadEvent a, RadEvent b, float* out) {
|
||||
}
|
||||
|
||||
int rad_memcpy_async(void* dst, const void* src, int64_t bytes, RadStream s) {
|
||||
/* One address space (unified memory, or a host view of a device allocation): a copy
|
||||
* onto itself is already done. */
|
||||
if (dst == src) return RAD_OK;
|
||||
return dev()->memcpy_async(dst, src, bytes, s);
|
||||
}
|
||||
int rad_memcpy_2d_async(void* dst, int64_t dpitch, const void* src, int64_t spitch,
|
||||
int64_t width, int64_t height, RadStream s) {
|
||||
if (dst == src && dpitch == spitch) return RAD_OK;
|
||||
return dev()->memcpy_2d_async(dst, dpitch, src, spitch, width, height, s);
|
||||
}
|
||||
int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s) {
|
||||
@@ -659,8 +673,8 @@ void rad_ride_release(void* token, RadStream after, int64_t packets) {
|
||||
if (const auto f = dev()->ride_release) f(token, after, packets);
|
||||
}
|
||||
int rad_xp_list(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst, const uint64_t* bytes,
|
||||
uint32_t* done, uint32_t done_val) {
|
||||
if (const auto f = dev()->xp_list) return f(device, mark, n, src, dst, bytes, done, done_val);
|
||||
uint32_t* done, uint32_t done_val, unsigned flags) {
|
||||
if (const auto f = dev()->xp_list) return f(device, mark, n, src, dst, bytes, done, done_val, flags);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
int64_t rad_xp_behind(int device) {
|
||||
@@ -671,6 +685,20 @@ void* rad_dev_alloc_uncached(int64_t bytes) {
|
||||
if (const auto f = dev()->alloc_uncached) return f(bytes);
|
||||
return nullptr;
|
||||
}
|
||||
void* rad_dev_map_file(int fd, int64_t foff, int64_t bytes) {
|
||||
const auto f = dev()->map_file;
|
||||
if (!f) {
|
||||
rad::device_set_error("rad_dev_map_file: the %s backend has no pinned host memory to map a "
|
||||
"file into", dev()->name);
|
||||
return nullptr;
|
||||
}
|
||||
void* p = f(fd, foff, bytes);
|
||||
if (p) {
|
||||
rad::g_ledger[RAD_MEM_HOST_MAPPED].bytes.fetch_add(bytes, std::memory_order_relaxed);
|
||||
rad::g_ledger[RAD_MEM_HOST_MAPPED].count.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
void rad_dev_free_uncached(void* p) {
|
||||
if (const auto f = dev()->free_uncached) f(p);
|
||||
}
|
||||
|
||||
@@ -182,6 +182,7 @@ int d_props(int device, RadDeviceProps* out) {
|
||||
out->vram_bytes = (int64_t)p.totalGlobalMem;
|
||||
out->lds_bytes = (int64_t)p.sharedMemPerBlock;
|
||||
out->is_host_backend = 0;
|
||||
out->unified = d_integrated(device);
|
||||
|
||||
/* hipMemGetInfo reports the current device, so switch to `device` and back. props is not
|
||||
* called per step. */
|
||||
|
||||
@@ -816,6 +816,7 @@ const DeviceBackend g_host = {
|
||||
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
|
||||
|
||||
h_stream_gate, h_gate_open, h_gate_room,
|
||||
nullptr, /* event_dma: no DMA queue */
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
+36
-5
@@ -4,7 +4,9 @@
|
||||
* Each check is a pure function of the facts (no file or device access), so tests pass a machine
|
||||
* described in a struct. A finding states what was seen with numbers, why it matters, and a fix.
|
||||
*
|
||||
* Warn: a cost or risk to act on. Note: a trade-off, or worth knowing when reading a benchmark.
|
||||
* Incompatible: a machine setting startup refuses (incompatible()), unless
|
||||
* --proceed-with-incompatible-configuration starts it anyway. Warn: a cost or risk to act on. Note:
|
||||
* a trade-off, or worth knowing when reading a benchmark.
|
||||
* Load-dependent findings (a parked link) are raised only when the card was busy, since an idle
|
||||
* PCIe link parks at its lowest speed by design.
|
||||
*/
|
||||
@@ -13,6 +15,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <set>
|
||||
|
||||
@@ -232,9 +235,12 @@ void check_od_runtime_pm(const Facts& f, std::vector<Finding>* out) {
|
||||
|
||||
/* ---- the host ------------------------------------------------------------------------------- */
|
||||
|
||||
/* Incompatible where cards serve (#42's class of hang); a host-backend run beside a loaded driver is
|
||||
* only told. */
|
||||
void check_cwsr(const Facts& f, std::vector<Finding>* out) {
|
||||
if (f.host.cwsr_enable != 0) return;
|
||||
add(out, Finding::Warn, "cwsr-off", "amdgpu cwsr_enable is 0",
|
||||
add(out, served(f).empty() ? Finding::Warn : Finding::Incompatible, "cwsr-off",
|
||||
"amdgpu cwsr_enable is 0",
|
||||
"the driver cannot preempt a running queue: any queue eviction (host memory the card maps, "
|
||||
"moved under memory pressure) waits for a queue a serve never lets drain, and ends in a "
|
||||
"GPU hang and reset",
|
||||
@@ -400,8 +406,34 @@ void check_engine(const Facts& f, const RunFacts& r, std::vector<Finding>* out)
|
||||
|
||||
} /* namespace */
|
||||
|
||||
std::vector<Finding> check(const Facts& f, const RunFacts& r) {
|
||||
std::vector<Finding> incompatible(const Facts& f) {
|
||||
std::vector<Finding> out;
|
||||
check_cwsr(f, &out);
|
||||
std::stable_sort(out.begin(), out.end(),
|
||||
[](const Finding& a, const Finding& b) { return a.level > b.level; });
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<std::string> unsupported_banner() {
|
||||
const char* text[] = {
|
||||
"UNSUPPORTED CONFIGURATION -- started with --proceed-with-incompatible-configuration.",
|
||||
"This machine is set up in a way radiance refuses to run on, and it was started anyway.",
|
||||
"ALL GUARANTEES ARE OFF: correctness, speed and stability are not tested here, and",
|
||||
"problems seen on this configuration are not supported. The startup report lists what",
|
||||
"is incompatible and how to fix it.",
|
||||
};
|
||||
size_t w = 0;
|
||||
for (const char* t : text) w = std::max(w, std::strlen(t));
|
||||
const std::string bar(w + 8, '!');
|
||||
std::vector<std::string> out{ bar };
|
||||
for (const char* t : text)
|
||||
out.push_back("!! " + std::string(t) + std::string(w - std::strlen(t), ' ') + " !!");
|
||||
out.push_back(bar);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<Finding> check(const Facts& f, const RunFacts& r) {
|
||||
std::vector<Finding> out = incompatible(f);
|
||||
check_engine(f, r, &out);
|
||||
check_link_under_load(f, &out);
|
||||
check_cards_differ(f, &out);
|
||||
@@ -409,13 +441,12 @@ std::vector<Finding> check(const Facts& f, const RunFacts& r) {
|
||||
check_small_bar(f, &out);
|
||||
check_power_cap(f, &out);
|
||||
check_od_runtime_pm(f, &out);
|
||||
check_cwsr(f, &out);
|
||||
check_memory(f, r, &out);
|
||||
check_huge_pages(f, r, &out);
|
||||
check_iommu(f, r, &out);
|
||||
check_memlock(f, r, &out);
|
||||
check_cpu(f, &out);
|
||||
/* Warnings first; stable, so each group keeps the order above. */
|
||||
/* Refusals, then warnings, then notes; stable, so each group keeps the order above. */
|
||||
std::stable_sort(out.begin(), out.end(),
|
||||
[](const Finding& a, const Finding& b) { return a.level > b.level; });
|
||||
return out;
|
||||
|
||||
+18
-1
@@ -109,6 +109,7 @@ struct HostFacts {
|
||||
std::string io_uring; /* available | refused (why) | unknown */
|
||||
std::string cpu_governor, cpu_epp, cpu_driver;
|
||||
std::string runtime; /* the device runtime's version, "" for none */
|
||||
std::string media; /* "libavformat <v>" / "absent (built without libav*)" */
|
||||
};
|
||||
|
||||
struct Facts {
|
||||
@@ -160,14 +161,22 @@ struct RunFacts {
|
||||
bool reference_kernels = false;
|
||||
bool profile_ops = false;
|
||||
bool deterministic = false;
|
||||
/* Started with --proceed-with-incompatible-configuration: the report opens with
|
||||
* unsupported_banner() and marks each incompatible finding as started anyway. */
|
||||
bool unsupported = false;
|
||||
/* -v: the CONFIGURATION section lists every option; without it, the options not at their
|
||||
* default and a count of the rest (/diagnostics always carries every one). */
|
||||
bool all_options = false;
|
||||
/* Names of the RADIANCE_* variables set (env_names): settings outside the option table,
|
||||
* such as the log level, a pinned tuning or an instrument left on. */
|
||||
std::vector<std::string> environment;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ findings */
|
||||
/* Incompatible: a machine setting known to break radiance; startup stops on it with the fix unless
|
||||
* --proceed-with-incompatible-configuration starts it anyway (incompatible()). */
|
||||
struct Finding {
|
||||
enum Level { Note = 0, Warn = 1 };
|
||||
enum Level { Note = 0, Warn = 1, Incompatible = 2 };
|
||||
Level level = Note;
|
||||
std::string id; /* stable, for a test or a grep: "link-below-max" */
|
||||
std::string what; /* what was seen, with the numbers */
|
||||
@@ -177,6 +186,14 @@ struct Finding {
|
||||
|
||||
std::vector<Finding> check(const Facts& f, const RunFacts& r);
|
||||
|
||||
/* The incompatible findings alone, from the machine only, so startup can refuse before it loads
|
||||
* anything: the serving cards (rank >= 0) and their host. check() includes them. */
|
||||
std::vector<Finding> incompatible(const Facts& f);
|
||||
|
||||
/* The box --proceed-with-incompatible-configuration puts at the top of the log and the startup
|
||||
* report, one log line an element. */
|
||||
std::vector<std::string> unsupported_banner();
|
||||
|
||||
/* ------------------------------------------------------------------ the report */
|
||||
std::string render(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
|
||||
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings);
|
||||
|
||||
+31
-7
@@ -89,9 +89,19 @@ std::string host_lines(const HostFacts& h, const RunFacts& r) {
|
||||
o += fmt(" runtime %s | backend %s\n",
|
||||
h.runtime.empty() ? "no device runtime" : h.runtime.c_str(),
|
||||
r.host_backend ? "host (CPU)" : "device");
|
||||
if (!h.media.empty())
|
||||
o += fmt(" media decoders %s\n", h.media.c_str());
|
||||
return o;
|
||||
}
|
||||
|
||||
const char* level_tag(Finding::Level l) {
|
||||
return l == Finding::Incompatible ? "INCOMPATIBLE" : l == Finding::Warn ? "WARN" : "note";
|
||||
}
|
||||
|
||||
const char* level_json(Finding::Level l) {
|
||||
return l == Finding::Incompatible ? "incompatible" : l == Finding::Warn ? "warn" : "note";
|
||||
}
|
||||
|
||||
std::string card_lines(const CardFacts& c) {
|
||||
std::string o;
|
||||
std::string who = c.rank >= 0 ? fmt("rank %d (device %d)", c.rank, c.device)
|
||||
@@ -135,13 +145,20 @@ std::string card_lines(const CardFacts& c) {
|
||||
std::string render(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
|
||||
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings) {
|
||||
std::string o;
|
||||
if (r.unsupported)
|
||||
for (const std::string& l : unsupported_banner()) o += l + "\n";
|
||||
o += "STARTUP REPORT" + (r.version.empty() ? std::string() : " -- radiance " + r.version) +
|
||||
(r.failed ? " -- STARTUP STOPPED; this is what it had resolved when it did\n" : "\n");
|
||||
o += "CONFIGURATION -- every option, the value in force, and where it came from\n";
|
||||
o += r.all_options
|
||||
? "CONFIGURATION -- every option, the value in force, and where it came from\n"
|
||||
: "CONFIGURATION -- every option not at its default, the value in force, and where it "
|
||||
"came from\n";
|
||||
size_t w = 0;
|
||||
for (const ConfigRow& c : config) w = std::max(w, c.flag.size());
|
||||
w = std::min<size_t>(w + 2, 34);
|
||||
int defaults = 0;
|
||||
for (const ConfigRow& c : config) {
|
||||
if (!r.all_options && c.source == "default") { ++defaults; continue; }
|
||||
const std::string v = c.value.empty() ? "\"\"" : c.value;
|
||||
const std::string first = v.substr(0, v.find('\n'));
|
||||
std::string l = fmt(" %-*s %s", (int)w, c.flag.c_str(), first.c_str());
|
||||
@@ -151,6 +168,9 @@ std::string render(const std::vector<ConfigRow>& config, const std::vector<Decis
|
||||
if (first.size() != v.size()) indented(&o, v.substr(first.size() + 1), (int)(3 + w));
|
||||
if (!c.why.empty()) indented(&o, c.why, (int)(5 + w));
|
||||
}
|
||||
if (defaults)
|
||||
o += fmt(" %d option%s at %s default (-v lists every option; /diagnostics carries them "
|
||||
"all)\n", defaults, defaults == 1 ? "" : "s", defaults == 1 ? "its" : "their");
|
||||
o += "ENVIRONMENT -- the RADIANCE_* variables set, by name; their values are not shown\n";
|
||||
if (r.environment.empty()) o += " none\n";
|
||||
for (const std::string& n : r.environment) o += " " + n + "\n";
|
||||
@@ -165,13 +185,15 @@ std::string render(const std::vector<ConfigRow>& config, const std::vector<Decis
|
||||
o += host_lines(f.host, r);
|
||||
for (const CardFacts& c : f.cards) o += card_lines(c);
|
||||
if (f.cards.empty()) o += " no display-class PCI device is visible\n";
|
||||
int nw = 0, nn = 0;
|
||||
for (const Finding& x : findings) (x.level == Finding::Warn ? nw : nn)++;
|
||||
o += fmt("FINDINGS -- %d warning%s, %d note%s\n", nw, nw == 1 ? "" : "s", nn, nn == 1 ? "" : "s");
|
||||
int ni = 0, nw = 0, nn = 0;
|
||||
for (const Finding& x : findings)
|
||||
(x.level == Finding::Incompatible ? ni : x.level == Finding::Warn ? nw : nn)++;
|
||||
o += fmt("FINDINGS -- %s%d warning%s, %d note%s\n",
|
||||
ni ? fmt("%d incompatible%s, ", ni, r.unsupported ? " (started anyway)" : "").c_str() : "",
|
||||
nw, nw == 1 ? "" : "s", nn, nn == 1 ? "" : "s");
|
||||
if (findings.empty()) o += " nothing found that costs speed or correctness\n";
|
||||
for (const Finding& x : findings) {
|
||||
o += fmt(" %s %s: %s\n", x.level == Finding::Warn ? "WARN" : "note", x.id.c_str(),
|
||||
x.what.c_str());
|
||||
o += fmt(" %s %s: %s\n", level_tag(x.level), x.id.c_str(), x.what.c_str());
|
||||
o += " why: " + x.why + "\n";
|
||||
o += " fix: " + x.fix + "\n";
|
||||
}
|
||||
@@ -183,6 +205,7 @@ std::string to_json(const std::vector<ConfigRow>& config, const std::vector<Deci
|
||||
using J = nlohmann::ordered_json;
|
||||
J o;
|
||||
o["startup_failed"] = r.failed;
|
||||
o["unsupported_configuration"] = r.unsupported;
|
||||
J cfg = J::array();
|
||||
for (const ConfigRow& c : config) {
|
||||
J e;
|
||||
@@ -224,6 +247,7 @@ std::string to_json(const std::vector<ConfigRow>& config, const std::vector<Deci
|
||||
host["cpu_epp"] = h.cpu_epp;
|
||||
host["cpu_driver"] = h.cpu_driver;
|
||||
host["runtime"] = h.runtime;
|
||||
host["media"] = h.media;
|
||||
J cards = J::array();
|
||||
for (const CardFacts& c : f.cards) {
|
||||
J e;
|
||||
@@ -274,7 +298,7 @@ std::string to_json(const std::vector<ConfigRow>& config, const std::vector<Deci
|
||||
o["hardware"] = { { "host", std::move(host) }, { "cards", std::move(cards) }, { "run", std::move(run) } };
|
||||
J fs = J::array();
|
||||
for (const Finding& x : findings)
|
||||
fs.push_back({ { "level", x.level == Finding::Warn ? "warn" : "note" }, { "id", x.id },
|
||||
fs.push_back({ { "level", level_json(x.level) }, { "id", x.id },
|
||||
{ "what", x.what }, { "why", x.why }, { "fix", x.fix } });
|
||||
o["findings"] = std::move(fs);
|
||||
/* Replace invalid UTF-8 instead of throwing: paths, boot parameters and product names are
|
||||
|
||||
+655
-102
File diff suppressed because it is too large.
Load diff
+151
-7
@@ -19,12 +19,14 @@
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
#include "rad_spechub.h" /* RadMtpCoupleDraw/State: the coupled MTP wire rows */
|
||||
#include "cvec.h"
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include "build/startup.h"
|
||||
#include "diag/diag.h"
|
||||
#include "mem/hostarena.h"
|
||||
#include "runtime/ctx.h" /* KVStageRun */
|
||||
#include "sched/mem_iface.h"
|
||||
#include "sched/scheduler.h"
|
||||
#include "sample/vocab_view.h"
|
||||
@@ -32,12 +34,14 @@
|
||||
#include "text/tokenizer.h"
|
||||
#include "format/radfile.h"
|
||||
#include "format/table_copy.h"
|
||||
#include "format/table_share.h"
|
||||
#include "lora/adapter.h"
|
||||
#include "lora/slots.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
@@ -47,9 +51,12 @@ namespace rad {
|
||||
class Kld;
|
||||
class StallWatch;
|
||||
namespace gen { class Driver; class AudioDriver; class VideoDriver; struct IPassDriver; }
|
||||
namespace server { class Sink; }
|
||||
struct TierPump;
|
||||
struct TierJob;
|
||||
struct StepSlot;
|
||||
class ExpertStats; /* place/xstats.h */
|
||||
class XsTally;
|
||||
|
||||
struct VramFacts; /* mem/vram_budget.h */
|
||||
struct WeightFootprint; /* place/planner.h */
|
||||
@@ -88,6 +95,9 @@ public:
|
||||
* serving cards' power-management files (hardware_facts). */
|
||||
std::string diagnostics_json() const;
|
||||
bool startup_report_printed() const { return report_printed_; }
|
||||
/* --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();
|
||||
|
||||
/* ---- the control vector's public surface (core/cvec.h).
|
||||
*
|
||||
@@ -113,6 +123,12 @@ private:
|
||||
* than broadcast (spec §1). */
|
||||
struct Rank;
|
||||
std::vector<std::unique_ptr<Rank>> ranks_;
|
||||
/* Per rank and KV group, that rank's stream view or null; the batch builder takes these, since it
|
||||
* cannot reach each rank's manager. */
|
||||
std::vector<std::vector<const RadKVStream*>> rank_stream_views_;
|
||||
/* Per KV group, the ranges a staged pass of the next step copies (kvstream_step_runs), refilled
|
||||
* in place each step. */
|
||||
std::vector<std::vector<KVStageRun>> stage_runs_;
|
||||
/* The tiers' work in flight: the host-memory copies the transfer streams are running. */
|
||||
std::unique_ptr<TierPump> pump_;
|
||||
/* serve()'s startup stall watch, released when the server listens (run_server) or the KL
|
||||
@@ -141,6 +157,9 @@ private:
|
||||
/* The source rad_weight_encoding answers from: container entries or checkpoint tensors. */
|
||||
WeightSourceFn sources() const;
|
||||
|
||||
/* --expert-stats FILE (place/xstats.h); null without the flag. */
|
||||
std::unique_ptr<ExpertStats> xstats_;
|
||||
|
||||
RadModelMeta meta_{};
|
||||
LoadedPlugins plugins_;
|
||||
|
||||
@@ -221,7 +240,7 @@ private:
|
||||
int64_t host_late);
|
||||
/* --ngram-placement ram: one copy of the container's [src, src + n) at file offset `foff`,
|
||||
* shared by every rank. Locked for the host gather, or pinned for a device kernel to read
|
||||
* over the link (`card`). */
|
||||
* over the link (`card`); with ram=DIR the pinned copy is a file other engines map too. */
|
||||
int copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, void** out,
|
||||
std::string* why);
|
||||
/* An auto-chosen pinned copy failed: move every rank's n-gram gather to the host. */
|
||||
@@ -231,7 +250,13 @@ private:
|
||||
* the ranks that read them are gone. */
|
||||
std::vector<TableCopy> table_copies_;
|
||||
std::vector<void*> card_copies_;
|
||||
/* The files behind the card copies made under --ngram-placement ram=DIR. Closed after the
|
||||
* copies are freed, because the holder that leaves last deletes the file. */
|
||||
std::vector<TableShare> table_shares_;
|
||||
std::vector<std::pair<const void*, void*>> table_copy_of_;
|
||||
/* --expert-profile: the decode ranking loaded once, before any rank plans, and handed to every
|
||||
* rank's planner in place of the container's activation profile. */
|
||||
std::vector<RadFileProfile> expert_profile_;
|
||||
int load_weights();
|
||||
int configure_kv();
|
||||
/* Resolves --checkpoint-slots auto for snapshots of `slot` bytes (`what` names their kind). */
|
||||
@@ -253,6 +278,12 @@ private:
|
||||
/* [n_rows] each sampled row's logprobs, for the rows of requests that asked for them;
|
||||
* empty on a step with none. */
|
||||
std::vector<TokenLogprobs> lp;
|
||||
/* The ids' copy recorded tok_end_ ahead of the drafter's passes: collect_step waits for
|
||||
* it alone, and the step loop for step_end_ after the commit. */
|
||||
bool early = false;
|
||||
/* [n_seq][RAD_SCHED_MAX_SPEC] on a tree step (StepPlan::spec_is_tree): each entry's
|
||||
* accepted nodes in commit order (accept_tree's path). Empty on a chain step. */
|
||||
std::vector<int32_t> path;
|
||||
};
|
||||
|
||||
/* The text frontend, loaded from the container. The sampler's grammars walk `vocab_view_`,
|
||||
@@ -293,7 +324,13 @@ private:
|
||||
* Written by the scheduler thread while the ranks are parked, read by them during the step,
|
||||
* consumed by collect_step. */
|
||||
std::vector<std::pair<int32_t, TokenScores*>> score_rows_;
|
||||
int stage_scored_rows(const StepPlan& plan, const StepOut& so);
|
||||
/* A scored step (RadBatch::score_only): the plugin ran no lm_head, and the candidates' logits
|
||||
* come from the hidden rows and the head table's rows at `score_ids_` (every scored row's
|
||||
* candidates, sorted and unique), both read back into `score_host`. */
|
||||
bool score_only_ = false;
|
||||
std::vector<int32_t> score_ids_;
|
||||
int64_t score_embd_ = 0;
|
||||
int stage_scored_rows(const StepPlan& plan, const StepOut& so, std::vector<uint64_t>& cancel);
|
||||
int issue_scored_rows(Rank& r);
|
||||
int collect_scored_rows();
|
||||
|
||||
@@ -322,22 +359,52 @@ private:
|
||||
void probe_arena_levels();
|
||||
int step_loop();
|
||||
/* Issue the copy of the step's sampled ids to the host, then wait for and interpret them.
|
||||
* Split so the copy is issued before draft passes overwrite the ids, and the wait comes after
|
||||
* them. */
|
||||
int collect_issue(StepOut& so);
|
||||
* Split so the copy is issued before draft passes overwrite the ids. With `fence` the copy
|
||||
* records tok_end_, so the wait for the ids skips the passes (StepOut::early). */
|
||||
int collect_issue(StepOut& so, bool fence = false);
|
||||
int collect_step(const RadBatch* b, StepOut& so);
|
||||
int row_logprobs(StepOut& so, int32_t row, int32_t token);
|
||||
/* `row`'s logprobs for `token`, filed at `at` (default `row`): a tree verify emits a token from
|
||||
* its parent node's row but files it as the entry's j-th emitted token. */
|
||||
int row_logprobs(StepOut& so, int32_t row, int32_t token, int32_t at = -1);
|
||||
/* The step's end on the card: after its last draft pass and the host readbacks, before the
|
||||
* step issued ahead. collect_step waits on this event, not the stream, so the card runs the
|
||||
* step issued ahead. The engine waits on this event, not the stream, so the card runs the
|
||||
* next step while the host commits this one. */
|
||||
int mark_step_end(const RadBatch* b, StepOut& so);
|
||||
RadEvent step_end_ = nullptr;
|
||||
/* The sampled ids' copy, ahead of the drafter's passes (collect_issue's `fence`). */
|
||||
RadEvent tok_end_ = nullptr;
|
||||
/* Whether the ids may be read before the drafter's passes end: not in KL mode, whose scored
|
||||
* rows are read from the logits after collection, nor for an embedding program. */
|
||||
bool early_ids_ = false;
|
||||
|
||||
/* ---- KV streaming's counters (engine.cpp, "KV streaming's counters"). Pinned, because a
|
||||
* device-to-host copy into pageable memory blocks the stream. */
|
||||
struct StreamRead {
|
||||
int64_t resolves = 0, lookups = 0, misses = 0;
|
||||
int64_t max_union = 0, max_misses = 0, max_claims = 0;
|
||||
int64_t slots = 0, block_bytes = 0;
|
||||
bool overflow = false;
|
||||
int32_t group = -1;
|
||||
};
|
||||
std::vector<StreamRead> stream_prev_; /* what metrics have already been charged */
|
||||
/* Pinned landing area for the copies: [n_kv_groups][16] i32, grown on first use. */
|
||||
int32_t* stream_ctl_p_ = nullptr;
|
||||
size_t stream_ctl_n_ = 0;
|
||||
int stream_probe_issue(const RadBatch* b);
|
||||
int stream_probe_take(const RadBatch* b, bool prefill_done, bool request_end);
|
||||
void stream_report(const char* when, const StreamRead& r, const StreamRead& prev);
|
||||
|
||||
/* The draft head as declared (rad_declare_drafter), zeroed when no speculative window was
|
||||
* asked for. `kind` selects which of the two drivers below runs. `drafter_name_` owns the
|
||||
* string because RadDrafterDecl::name points into the Program. */
|
||||
RadDrafterDecl drafter_{};
|
||||
std::string drafter_name_;
|
||||
/* The block drafter's shorter block (rad_drafter_short_block), 0 when it has none or will not
|
||||
* run it (--draft-short-from 0, or auto for a chain). */
|
||||
int64_t drafter_short_ = 0;
|
||||
bool short_on_ = false; /* the short block runs now (block_shape) */
|
||||
/* --draft-short-from resolved at bring-up (auto: 0 for a chain, 2 for a tree). */
|
||||
int64_t short_from_ = 0;
|
||||
|
||||
/* Serial driver (spec §10): `depth` dependent passes after the step commits, each embedding
|
||||
* the previous proposal. MTP, EAGLE and Medusa-serial have this shape. */
|
||||
@@ -373,6 +440,9 @@ private:
|
||||
gen::AudioDriver* aud_gen_ = nullptr;
|
||||
gen::VideoDriver* vid_gen_ = nullptr;
|
||||
int gen_loop();
|
||||
/* Zeroes the state slots the KV manager granted since the last step, on every rank's stream,
|
||||
* before the step or pass that first reads them. */
|
||||
void clear_fresh_states();
|
||||
bool serial_drafting() const;
|
||||
int advance_all(int mode, int round, bool from_proposal, int rows = -1);
|
||||
int issue_serial_drafter(int step, StepOut& so);
|
||||
@@ -395,6 +465,27 @@ private:
|
||||
void step_state_fini();
|
||||
StepSlot* slots_host_ = nullptr;
|
||||
|
||||
/* --draft-coupling (engine_draft.cpp). The head declares `mtp_couple_draws` and
|
||||
* `mtp_couple_state`; the engine stages one draw per drafting row before the serial passes and
|
||||
* reads the states back once, then binds each to the verify row it will be coupled at. */
|
||||
bool mtp_couple_ = false;
|
||||
rad_buf couple_draws_buf_ = 0, couple_state_buf_ = 0;
|
||||
int64_t couple_rows_ = 0; /* the state plane's rows per round */
|
||||
RadMtpCoupleDraw* couple_draw_stage_ = nullptr; /* pinned [max_seqs] */
|
||||
RadMtpCoupleState* couple_readback_ = nullptr; /* pinned [rounds, couple_rows_] */
|
||||
std::vector<RadMtpCoupleDraw> couple_by_card_; /* the plan's draw per card slot */
|
||||
RadMtpCoupleState couple_bound_[RAD_MTP_COUPLE_MAX_ROUNDS] = {};
|
||||
bool couple_evidence_ = false; /* the completed-verify line was written (once a process) */
|
||||
bool couple_host_note_ = false; /* the host-domain counterpart was written (once) */
|
||||
bool couple_malformed_note_ = false; /* a status -1 round was reported (once) */
|
||||
/* `rows` are serial_row_ or block_row_ (Scheduler::SerialRow / BlockRow). */
|
||||
template <class Row> int stage_couple_draws(const Row* rows, int n);
|
||||
int bind_couple(uint64_t seq, int i, int done, bool drafted, int32_t card);
|
||||
/* One INFO line at the first coupled verify that completed: the step, the live requests whose
|
||||
* rows carried a bound state, the kernel and its domain. Read from the sampler's build
|
||||
* snapshot after collect_step's wait, so it reports a finished verify, not an enqueue. */
|
||||
void couple_verify_evidence(int step);
|
||||
|
||||
/* Step-time attribution, Debug only (see the barrier in step_loop): time per scheduler phase.
|
||||
* The nine phases sum to the whole step, including the readback, commit and drafter after the
|
||||
* join. */
|
||||
@@ -410,13 +501,41 @@ private:
|
||||
* both behind the step before its readback and finish_block_drafter publishes the proposals
|
||||
* after the commit, so the step can be issued ahead. */
|
||||
bool block_drafting() const;
|
||||
/* RadBuildCtx::draft_tree for every declare: decided once in declare() from the plugin's probe
|
||||
* (RadArchProbe::tree_pays). */
|
||||
bool draft_tree_ = false;
|
||||
int block_pass(const RadBatch* db, const char* what, int step);
|
||||
/* A program's block drafter rides its window in the window snapshot: it stores its context
|
||||
* in the context pass right behind the trunk step, and the snapshot is saved after that. Only
|
||||
* where the trunk's window is snapshotted at all (window_snapshots): a full-attention trunk
|
||||
* takes no snapshot for a drafter's window alone. */
|
||||
bool drafter_window_snap(const Program& p) const {
|
||||
return cfg_.n_spec > 0 && p.drafter.kind == RAD_DRAFT_BLOCK && p.drafter.depth > 0 &&
|
||||
window_snapshots(p, cfg_);
|
||||
}
|
||||
/* The drafter's window rides in the window snapshot (KVManager::drafter_window_snapshot), so
|
||||
* the checkpoint save waits for its context pass (save_checkpoints). */
|
||||
bool drafter_snap_ = false;
|
||||
int save_checkpoints();
|
||||
/* A tree drafter (rad_drafter_tree), driven on the card only: ADV_BTAKE takes its parents,
|
||||
* ADV_COMPACT moves the accepted path's K and V after the acceptance, and ADV_CTXTREE stages
|
||||
* the context pass by that path. */
|
||||
bool tree_ = false;
|
||||
rad_buf tree_parents_ = 0;
|
||||
int tree_compact(int rows);
|
||||
int issue_block_drafter(int step, StepOut& so);
|
||||
int finish_block_drafter(const StepOut& so);
|
||||
/* The block and proposal count this step's query pass runs at: the drafter's own, or its short
|
||||
* block once --draft-short-from sequences decode, back to its own two below or at one sequence
|
||||
* (Scheduler::short_block_on). */
|
||||
void block_shape(int* block, int* steps);
|
||||
/* Handed from issue_block_drafter to finish_block_drafter and issue_ahead: the drafting rows,
|
||||
* in the query pass's order, and how many there are (0 when no query pass ran). */
|
||||
std::vector<Scheduler::BlockRow> block_row_;
|
||||
int block_rows_ = 0;
|
||||
/* The proposals a row of the query pass took (block_shape), for finish_block_drafter and
|
||||
* issue_ahead's expect_draft. */
|
||||
int block_steps_ = 0;
|
||||
/* Encoder driver (spec §11, core/engine_mm.cpp): encodes every media item the scheduler waits
|
||||
* on, in passes of whole segments, and reads it back into the item. Runs between steps, never
|
||||
* inside one. */
|
||||
@@ -472,10 +591,20 @@ private:
|
||||
* requests and hands every step's scored rows, copied to the host, to `kld_`. One pinned
|
||||
* block per rank, holding a step's tokens of that rank's logits columns. */
|
||||
int run_kld();
|
||||
int run_docs(std::vector<std::unique_ptr<Request>>& reqs,
|
||||
std::vector<std::unique_ptr<server::Sink>>& sinks, bool fit_pool,
|
||||
const char* tag, int every_s,
|
||||
const std::function<void(size_t, double)>& progress, int* bad);
|
||||
int score_rows(const RadBatch* b, const StepOut& so);
|
||||
std::unique_ptr<Kld> kld_;
|
||||
std::vector<float*> kld_host_;
|
||||
std::vector<int64_t> kld_vocab0_, kld_width_; /* per rank read: its logits columns */
|
||||
/* --calib-corpus, replacing run_server: the corpus, loaded before declare so the plugin is told
|
||||
* its token count (RadBuildCtx::calib_tokens), submitted as plain prefill requests. */
|
||||
int run_calib();
|
||||
std::unique_ptr<Kld> calib_;
|
||||
/* --kld-record beside --calib-dir: the KL corpus's tokens, which the plugins record over. */
|
||||
long long calib_tokens_ = 0;
|
||||
/* The engine half of /server_info, as a JSON object. See the definition in engine.cpp. */
|
||||
std::string engine_info() const;
|
||||
|
||||
@@ -485,6 +614,9 @@ private:
|
||||
void decide(const std::string& key, const std::string& value, const std::string& why) {
|
||||
diag::decide(&decisions_, key, value, why);
|
||||
}
|
||||
/* The architecture's RadArchProbe, asked once in declare(): a property of the model, so every
|
||||
* RadBuildCtx carries the same answer (RadBuildCtx::kv_stream_ok). */
|
||||
RadArchProbe arch_probe_{};
|
||||
std::string devnote_; /* the devices usable_devices left out, and why */
|
||||
int p2p_measured_ = -1; /* 1 peer to peer, 0 through host memory, -1 not asked */
|
||||
std::string p2p_blocked_;
|
||||
@@ -514,6 +646,10 @@ private:
|
||||
std::vector<DevId> dev_ids_;
|
||||
std::string runtime_version_;
|
||||
void identify_devices(const std::vector<std::string>& names);
|
||||
/* The machine settings startup refuses (diag::incompatible) for the cards the ranks take, asked
|
||||
* before anything loads: RAD_E_UNSUPPORTED with each one and its fix on an E line, or under
|
||||
* --proceed-with-incompatible-configuration each on a W line and the start goes on. */
|
||||
int check_configuration(const std::vector<int>& devs);
|
||||
/* Syscall-only facts (diag::probe_process), read once at the first report: the memlock limit
|
||||
* cannot change under a running process, and the io_uring probe need not repeat per
|
||||
* /diagnostics request. */
|
||||
@@ -535,6 +671,14 @@ private:
|
||||
* what the heat engine proposes. A member because Rank is private; a no-op on a static plan.
|
||||
* The definition explains why a step is the unit. */
|
||||
void tiering_dispatch(Rank& r, int step);
|
||||
/* The routing histograms landed since the last drain (tiering_dispatch), and the drain alone
|
||||
* for --expert-stats where the heat engine is off. */
|
||||
void find_histograms(Rank& r, int before_step);
|
||||
void xstats_drain(Rank& r, XsTally* xs, int before_step);
|
||||
/* --expert-stats: the map and the file, opened before the rank threads start; closed after they
|
||||
* stop, crediting what the ring still holds once the streams are drained. */
|
||||
int xstats_open();
|
||||
void xstats_close();
|
||||
void rank_loop(int rank);
|
||||
};
|
||||
|
||||
|
||||
+472
-65
@@ -7,6 +7,7 @@
|
||||
#include "engine_priv.h"
|
||||
#include "rad_internal.h"
|
||||
#include "engine_hostmem.h"
|
||||
#include "kld.h"
|
||||
#include "gen/driver.h"
|
||||
#include "gen/audio_driver.h"
|
||||
#include "gen/video_driver.h"
|
||||
@@ -19,8 +20,11 @@
|
||||
#include "format/rope_override.h"
|
||||
#include "format/share.h"
|
||||
#include "format/table_copy.h"
|
||||
#include "format/table_share.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "mem/vram_budget.h"
|
||||
#include "kvstream/bringup.h"
|
||||
#include "kvstream/plan.h"
|
||||
#include "runtime/arena.h"
|
||||
#include "runtime/kvbind.h"
|
||||
#include "runtime/xprefetch.h"
|
||||
@@ -35,6 +39,7 @@
|
||||
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <numeric>
|
||||
#include <sstream>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
@@ -329,13 +334,8 @@ static void memory_cgroups(const std::function<bool(const std::string&, int64_t)
|
||||
}
|
||||
}
|
||||
|
||||
/* Whether `need` more bytes fit in host memory after `still` more this process will allocate
|
||||
* first and `margin` (--host-headroom-mib) stays free, or why not. Checks MemAvailable; every
|
||||
* memory cgroup from the process's own up to the visible root (Docker's --memory, enforced by
|
||||
* the OOM killer); and, for an mlock()ed copy (`mlocks`), RLIMIT_MEMLOCK unless the process has
|
||||
* CAP_IPC_LOCK. Pinned memory a card reads is a driver userptr mapping, which RLIMIT_MEMLOCK
|
||||
* does not count. An unreadable limit is ignored, never guessed. */
|
||||
static bool lockable_room(int64_t need, int64_t still, int64_t margin, bool mlocks,
|
||||
/* See engine_hostmem.h. */
|
||||
bool lockable_room(int64_t need, int64_t still, int64_t margin, bool mlocks,
|
||||
std::string* why) {
|
||||
long long locked_kb = 0;
|
||||
unsigned long long caps = 0;
|
||||
@@ -401,15 +401,59 @@ static int64_t lockable_bytes(int64_t still, int64_t margin, std::string* limit)
|
||||
}
|
||||
|
||||
/* The copy is table_copy_make's (core/format/table_copy.h), or for a card, table_copy_fill into
|
||||
* pinned memory every card maps (rad_dev_alloc RAD_MEM_HOST_MAPPED, locked in pieces). One copy
|
||||
* per container address, shared by every rank; freed in ~Engine. */
|
||||
* pinned memory every card maps (rad_dev_alloc RAD_MEM_HOST_MAPPED, locked in pieces). With
|
||||
* --ngram-placement ram=DIR the pinned memory is a file in DIR mapped shared (core/format/
|
||||
* table_share.h): this engine fills it or, if another engine did, checks samples of it against the
|
||||
* container, and pins it either way. Only a table of kTableShareMin or more is shared: the gather's
|
||||
* scale is an n-gram weight too, since it moves with the table between gather sites, and as a file
|
||||
* its two bytes would cost the 2 MiB header and a 2 MiB page. One copy per container address,
|
||||
* shared by every rank; freed in ~Engine. */
|
||||
int Engine::copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, void** out,
|
||||
std::string* why) {
|
||||
for (const auto& c : table_copy_of_)
|
||||
if (c.first == src) { *out = c.second; return RAD_OK; }
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
auto since = [&] {
|
||||
return std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
|
||||
};
|
||||
void* base = nullptr;
|
||||
if (card) {
|
||||
if (card && !cfg_.ngram_share_dir.empty() && n >= kTableShareMin) {
|
||||
const std::string id = table_share_id(file_->path(), foff, n);
|
||||
if (id.empty()) {
|
||||
*why = fmt("the container %s cannot be stat'ed, which names the shared table",
|
||||
file_->path());
|
||||
return RAD_E_IO;
|
||||
}
|
||||
TableShare s;
|
||||
int rc = table_share_open(cfg_.ngram_share_dir, id, n, &s, why);
|
||||
if (rc != RAD_OK) return rc;
|
||||
base = rad_dev_map_file(s.fd, kTableShareHeader, n);
|
||||
if (!base) {
|
||||
*why = fmt("pinning %s of %s: %s", humanb(n).c_str(), s.path.c_str(),
|
||||
rad_dev_last_error());
|
||||
table_share_close(&s);
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
if (s.filler) {
|
||||
rc = table_copy_fill(*file_, src, n, foff, static_cast<uint8_t*>(base), why);
|
||||
if (rc == RAD_OK) rc = table_share_mark_ready(&s, n, id, why);
|
||||
} else {
|
||||
rc = table_copy_check(src, n, static_cast<const uint8_t*>(base), why);
|
||||
if (rc != RAD_OK)
|
||||
*why = fmt("the shared file %s does not match the container (%s)", s.path.c_str(),
|
||||
why->c_str());
|
||||
}
|
||||
if (rc != RAD_OK) {
|
||||
rad_dev_free(base, RAD_MEM_HOST_MAPPED);
|
||||
table_share_close(&s);
|
||||
return rc;
|
||||
}
|
||||
card_copies_.push_back(base);
|
||||
table_shares_.push_back(s);
|
||||
RAD_INFO("placement: n-gram table in pinned memory the cards read, %s in shared file %s, "
|
||||
"%s in %.1f s", humanb(n).c_str(), s.path.c_str(),
|
||||
s.filler ? "filled" : "reused (probes match)", since());
|
||||
} else if (card) {
|
||||
base = rad_dev_alloc(n, RAD_MEM_HOST_MAPPED);
|
||||
if (!base) {
|
||||
*why = fmt("pinning %s: %s", humanb(n).c_str(), rad_dev_last_error());
|
||||
@@ -421,16 +465,17 @@ int Engine::copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, v
|
||||
return rc;
|
||||
}
|
||||
card_copies_.push_back(base);
|
||||
RAD_INFO("placement: n-gram table copied into pinned memory the cards read, %s in %.1f s",
|
||||
humanb(n).c_str(), since());
|
||||
} else {
|
||||
TableCopy tc;
|
||||
const int rc = table_copy_make(*file_, src, n, foff, &tc, why);
|
||||
if (rc != RAD_OK) return rc;
|
||||
table_copies_.push_back(tc);
|
||||
base = tc.base;
|
||||
RAD_INFO("placement: n-gram table copied into locked memory, %s in %.1f s",
|
||||
humanb(n).c_str(), since());
|
||||
}
|
||||
RAD_INFO("placement: n-gram table copied into %s, %s in %.1f s",
|
||||
card ? "pinned memory the cards read" : "locked memory", humanb(n).c_str(),
|
||||
std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count());
|
||||
table_copy_of_.push_back({ src, base });
|
||||
*out = base;
|
||||
return RAD_OK;
|
||||
@@ -566,8 +611,43 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
* then the container. */
|
||||
const int64_t still = (int64_t)cfg_.tp * cfg_.host_pool_total_mib() * MiB +
|
||||
cfg_.prefix_cache_mib * MiB + host_late;
|
||||
const int64_t need = align_up(ngram_bytes, (int64_t)2 << 20);
|
||||
int64_t need = align_up(ngram_bytes, (int64_t)2 << 20);
|
||||
const char* copy = ngram_device ? "a pinned copy the card reads" : "a locked copy";
|
||||
/* ram=DIR: the copy is a file other engines map too. One already complete costs this engine
|
||||
* no host memory for the table; a weight under kTableShareMin beside it (the scale) is a
|
||||
* private copy either way. */
|
||||
std::string share_note;
|
||||
if (!cfg_.ngram_share_dir.empty() && ngram_bytes > 0) {
|
||||
if (!ngram_device) {
|
||||
RAD_ERR("--ngram-placement ram=%s: only the pinned copy a card reads is shared, and no "
|
||||
"loaded kernel plugin reads an n-gram table on a card (embed_lookup_q has host "
|
||||
"kernels only), so the host gather would read a private locked copy. Use ram "
|
||||
"or disk.", cfg_.ngram_share_dir.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
share_note = fmt("a file in %s that other engines share", cfg_.ngram_share_dir.c_str());
|
||||
if (file_ && !ranks_.empty()) {
|
||||
const Program& prog = ranks_.front()->program;
|
||||
for (size_t i = 1; i < prog.weights.size(); ++i) {
|
||||
const WeightInfo& w = prog.weights[i];
|
||||
if (!is_ngram_table(prog, (rad_weight)i) || w.n_sel < 1) continue;
|
||||
const RadFileEntry* e = file_->find(w.source);
|
||||
if (!e) continue;
|
||||
const RadFilePlane& p0 = file_->plane(*e, w.sel[0]);
|
||||
if ((int64_t)p0.bytes < kTableShareMin) continue;
|
||||
const std::string id =
|
||||
table_share_id(file_->path(), (int64_t)p0.offset, (int64_t)p0.bytes);
|
||||
if (table_share_is_ready(cfg_.ngram_share_dir, id, (int64_t)p0.bytes)) {
|
||||
need = align_up(std::max<int64_t>(ngram_bytes - (int64_t)p0.bytes, 0),
|
||||
(int64_t)2 << 20);
|
||||
share_note = fmt("a complete shared file in %s already holds it, which "
|
||||
"takes no memory of this engine's own for the table",
|
||||
cfg_.ngram_share_dir.c_str());
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
auto card_holds = [&](std::string* why) {
|
||||
std::vector<VramFacts> with = facts;
|
||||
int64_t fixed = 0;
|
||||
@@ -642,7 +722,7 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
"%s: %s", humanb(ngram_bytes).c_str(), copy, ram_why.c_str());
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
ng_why = "as asked";
|
||||
ng_why = share_note.empty() ? std::string("as asked") : "as asked, as " + share_note;
|
||||
} else if (card) {
|
||||
ng = TablePlacement::Vram;
|
||||
ng_why = "the card holds it beside the other weights and a KV pool for one "
|
||||
@@ -898,6 +978,7 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
|
||||
bc.max_seqs = cfg_.max_seqs;
|
||||
bc.max_ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
|
||||
bc.max_spec = cfg_.n_spec;
|
||||
bc.draft_tree = draft_tree_ ? 1 : 0;
|
||||
bc.tp_wire_lossy = cfg_.tp_wire_exact ? 0 : 1;
|
||||
/* The engine always states the KV dtype. RAD_DT_INVALID (zero) remains valid in the ABI for
|
||||
* other callers and means the plugin's default. */
|
||||
@@ -905,6 +986,16 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
|
||||
bc.kv_quant = cfg_.kv_cache_dtype == "fp8_v4" ? RAD_KVQ_V4
|
||||
: cfg_.kv_cache_dtype == "k6_v4" ? RAD_KVQ_K6V4 : RAD_KVQ_NONE;
|
||||
bc.attn_prefill_fp8 = cfg_.attn_prefill_fp8;
|
||||
bc.tp_attn_rows = cfg_.tp_attn_rows;
|
||||
bc.weight_prefetch_off = cfg_.weight_prefetch ? 0 : 1;
|
||||
bc.calib_dir = cfg_.calib_dir.empty() ? nullptr : cfg_.calib_dir.c_str();
|
||||
bc.calib_layer_lo = cfg_.calib_layer_lo;
|
||||
bc.calib_layer_hi = cfg_.calib_layer_hi;
|
||||
bc.calib_tokens = calib_ ? calib_->n_tokens() : calib_tokens_;
|
||||
bc.gen_max_pixels = cfg_.image_gen_max_pixels;
|
||||
bc.gen_max_refs = cfg_.image_gen_max_refs;
|
||||
bc.state_dtype = cfg_.state_cache_dtype == "f16" ? RAD_F16 : 0;
|
||||
bc.draft_coupling = cfg_.draft_coupling ? 1 : 0;
|
||||
bc.tp_wire_min_bytes = cfg_.tp_wire_min_kb * 1024;
|
||||
bc.scope = "";
|
||||
bc.max_enc_patches = cfg_.mm_max_patches > 0 ? cfg_.mm_max_patches : 0;
|
||||
@@ -915,6 +1006,15 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
|
||||
/* Under --prefill-span every step but a lone prefill is planned at the shared budget
|
||||
* (Scheduler::step), so a wider step is one sequence; 0 without a span. */
|
||||
bc.max_mixed_tok = cfg_.prefill_span > 1 ? std::min(max_tok, prefill_shared_tok(cfg_)) : 0;
|
||||
/* --kv-resident in tokens, raised to kStreamFloorTokens as kvstream_ring_shape raises it: the
|
||||
* arch declares kv_resolve's ring depth from this, and the kernel refuses a carve deeper than
|
||||
* the declared table. */
|
||||
bc.kv_resident_blocks = cfg_.kv_resident > 0 && cfg_.kv_resident < kStreamFloorTokens
|
||||
? kStreamFloorTokens
|
||||
: cfg_.kv_resident;
|
||||
/* A streamed-only op is declared only when the architecture streams and the flag asks
|
||||
* (kvstream_op_gated). */
|
||||
bc.kv_stream_ok = arch_probe_.kv_stream_ok;
|
||||
/* The control vector, when one is loaded: this rank's view, or null. A plugin reads it at
|
||||
* declare only (the direction table never changes); the per-request switch rides the derived
|
||||
* mask, not this struct. */
|
||||
@@ -925,6 +1025,15 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
|
||||
}
|
||||
|
||||
int Engine::declare() {
|
||||
/* An architecture that declares no streamed ops cannot stream, so with --kv-resident set on one
|
||||
* the flag is turned off here, with the decision named, before anything is planned for it. */
|
||||
(void)rad_tools_probe(plugins_, meta_, &arch_probe_, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
|
||||
if (cfg_.kv_resident > 0 && arch_probe_.kv_stream_ok == 0) {
|
||||
cfg_.kv_resident = 0;
|
||||
decide("--kv-resident", "0",
|
||||
std::string("architecture '") + (meta_.arch_id ? meta_.arch_id : "?") +
|
||||
"' has no streamed KV path");
|
||||
}
|
||||
RAD_TRY(lora_targets());
|
||||
/* KL mode measures the trunk (core/kld.h): a drafter writes no scored rows and a prefix hit
|
||||
* would skip positions the reference holds, so both are off, and an explicit depth is refused
|
||||
@@ -943,13 +1052,43 @@ int Engine::declare() {
|
||||
"the KL mode: a prefix hit would start a document past positions the reference holds";
|
||||
decide("--no-prefix-cache", "prefix caching off", prefix_off_why_);
|
||||
}
|
||||
/* --calib-corpus: every token of the corpus through prefill exactly once, so no prefix hit
|
||||
* skips any and no drafter adds rows; the corpus is loaded here, before the plugins declare,
|
||||
* because they are told its size. */
|
||||
if (cfg_.calib()) {
|
||||
if (cfg_.n_spec > 0) {
|
||||
RAD_ERR("--num-speculative-tokens %d: a calibration run drafts nothing; leave it at "
|
||||
"auto or 0", cfg_.n_spec);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
cfg_.n_spec = 0;
|
||||
cfg_.prefix_cache = false;
|
||||
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
|
||||
decide("--num-speculative-tokens", "0", "a calibration run records the trunk's rows only");
|
||||
prefix_off_why_ = "a calibration run: a prefix hit would skip tokens the statistics must count";
|
||||
decide("--no-prefix-cache", "prefix caching off", prefix_off_why_);
|
||||
calib_ = std::make_unique<Kld>();
|
||||
RAD_TRY(calib_->load(cfg_.calib_corpus, vocab_));
|
||||
RAD_INFO("calib: %zu documents, %lld tokens from %s", calib_->n_docs(),
|
||||
(long long)calib_->n_tokens(), cfg_.calib_corpus.c_str());
|
||||
}
|
||||
/* --kld-record beside --calib-dir: the reference's run records the statistics too, over the
|
||||
* KL corpus, whose size the plugins are told here; run_kld then feeds the documents so that
|
||||
* none is preempted. */
|
||||
if (!cfg_.kld_record.empty() && !cfg_.calib_dir.empty()) {
|
||||
Kld count;
|
||||
RAD_TRY(count.load(cfg_.kld_corpus, vocab_));
|
||||
calib_tokens_ = count.n_tokens();
|
||||
RAD_INFO("calib: recorded beside the reference, %zu documents, %lld tokens from %s",
|
||||
count.n_docs(), (long long)calib_tokens_, cfg_.kld_corpus.c_str());
|
||||
}
|
||||
/* An image generator sizes the step itself (RadArchProbe::gen_rows): a denoise pass carries all
|
||||
* of an image's latent rows (twice with guidance), and a conditioning pass encodes every
|
||||
* reference picture of a request. Operator-given values are kept. No drafting (no tokens) and
|
||||
* no prefix cache (a conditioning is read only by its own request). */
|
||||
{
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
|
||||
if (pb.gen_rows > 0 && pb.gen_audio) {
|
||||
if (!cfg_.given.count("--max-num-batched-tokens")) {
|
||||
cfg_.max_tok = pb.gen_rows;
|
||||
@@ -987,7 +1126,14 @@ int Engine::declare() {
|
||||
decide("--max-model-len", std::to_string(cfg_.max_ctx),
|
||||
"a video generator: a step's rows");
|
||||
}
|
||||
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
|
||||
/* A video generator with a vision tower takes a pass of its patches, the size its
|
||||
* plugin states. */
|
||||
if (cfg_.mm_max_patches < 0 && pb.gen_patches > 0) {
|
||||
cfg_.mm_max_patches = pb.gen_patches;
|
||||
decide("--mm-max-patches", std::to_string(cfg_.mm_max_patches),
|
||||
"a video generator: every reference media patch of one conditioning, "
|
||||
"the pass size the plugin states");
|
||||
}
|
||||
if (cfg_.n_spec < 0) cfg_.n_spec = 0;
|
||||
cfg_.prefix_cache = false;
|
||||
} else if (pb.gen_rows > 0) {
|
||||
@@ -1022,20 +1168,54 @@ int Engine::declare() {
|
||||
if (cfg_.kv_cache_dtype == "fp8_v4" || cfg_.kv_cache_dtype == "k6_v4") {
|
||||
const int q = cfg_.kv_cache_dtype == "fp8_v4" ? RAD_KVQ_V4 : RAD_KVQ_K6V4;
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
|
||||
if (!(pb.kv_quant_ok & (1 << q))) {
|
||||
RAD_ERR("--kv-cache-dtype %s: the '%s' plugin does not serve it for this model "
|
||||
"(fp8 does)", cfg_.kv_cache_dtype.c_str(), plugins_.arch_plugin.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
/* The row split is a graph only the plugin can declare, and it splits over ranks. A plugin
|
||||
* that does not say it serves it (RadArchProbe::tp_attn_rows_ok), or a single rank, would
|
||||
* serve the head split under a name that promised the other, so the flag is refused rather
|
||||
* than ignored. */
|
||||
if (cfg_.tp_attn_rows) {
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
|
||||
if (!pb.tp_attn_rows_ok) {
|
||||
RAD_ERR("--tp-attn-split rows: the '%s' plugin does not split attention by rows for "
|
||||
"this model (heads does)", plugins_.arch_plugin.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (cfg_.tp < 2) {
|
||||
RAD_ERR("--tp-attn-split rows splits a prefill's attention over tensor-parallel ranks, "
|
||||
"and --tp %d has none to split over (heads does)", cfg_.tp);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_WARN("attention: a prefill-sized step splits by rows over the %d ranks "
|
||||
"(--tp-attn-split rows): every card holds the attention's projections at full "
|
||||
"width, and the result is not bit-identical to the head split", cfg_.tp);
|
||||
}
|
||||
/* Likewise an f16 recurrent state: a plugin that does not say it declares one would keep f32
|
||||
* under a flag that promised half the state memory. */
|
||||
if (cfg_.state_cache_dtype == "f16") {
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
|
||||
if (!pb.state_f16_ok) {
|
||||
RAD_ERR("--state-cache-dtype f16: the '%s' plugin does not declare its recurrent state "
|
||||
"at f16 for this model (f32 does)", plugins_.arch_plugin.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RAD_INFO("recurrent state cache: f16 (--state-cache-dtype), half the state memory; lossy, "
|
||||
"the generated text differs from f32");
|
||||
}
|
||||
/* Resolved here, not at argument parsing: the plugin states its drafter's depth, and it is
|
||||
* selected only once the container is open. Every consumer of `n_spec` (buffer sizing, kernel
|
||||
* bands, the scheduler's window) runs after this. rad_arch_probe is the core's only source of
|
||||
* drafter configuration. */
|
||||
if (cfg_.n_spec < 0) {
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
|
||||
cfg_.n_spec = pb.draft_depth > 0 ? pb.draft_depth : 0;
|
||||
if (cfg_.n_spec > 0)
|
||||
RAD_INFO("speculation: depth %d, this drafter's own operating point "
|
||||
@@ -1053,7 +1233,7 @@ int Engine::declare() {
|
||||
* speculatively. */
|
||||
{
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
|
||||
const bool pays = cfg_.n_spec > 0 && pb.chain_pays;
|
||||
rad_dev_chain_infer(pays);
|
||||
const bool on = rad_dev_chain_enabled() != 0;
|
||||
@@ -1064,13 +1244,29 @@ int Engine::declare() {
|
||||
RAD_INFO("chained launches: %s -- %s", on ? "on" : "off", why);
|
||||
decide("chained launches", on ? "on" : "off", why);
|
||||
}
|
||||
/* Trees: a block drafter's proposals verified as a tree, where the model's plugin measured a
|
||||
* gain with one (RadArchProbe::tree_pays; the Gemma 4 31B with DFlash2: +7% single-stream
|
||||
* decode, +6-9% aggregate at 1-16 users on 4x R9700) and the drafter decodes speculatively.
|
||||
* A tree changes no token, only how many drafts land a step. */
|
||||
{
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
|
||||
/* A tree is verified only behind a step issued ahead (step_loop). The KL mode, which issues
|
||||
* none, drafts nothing either (n_spec is 0 there by now), so this never runs under it. */
|
||||
draft_tree_ = cfg_.n_spec > 0 && pb.tree_pays != 0;
|
||||
if (draft_tree_) {
|
||||
const char* why = "the model's plugin measured a gain with them";
|
||||
RAD_INFO("draft trees: asked -- %s", why);
|
||||
decide("draft trees", "asked", why);
|
||||
}
|
||||
}
|
||||
/* The audio encoder's pass: the plugin's longest clip, when the model file carries an audio
|
||||
* encoder (`radiance.encoder` names one) and the deployment is not text-only. */
|
||||
if (cfg_.mm_audio_frames < 0) {
|
||||
const char* enc = rad_meta_gets(&meta_, "radiance.encoder", "");
|
||||
const bool named = enc && std::strstr(enc, "audio") != nullptr;
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
|
||||
const bool text_only = cfg_.mm_max_patches == 0;
|
||||
cfg_.mm_audio_frames = !text_only && pb.audio_frames > 0 && (named || !file_)
|
||||
? pb.audio_frames : 0;
|
||||
@@ -1088,7 +1284,7 @@ int Engine::declare() {
|
||||
cfg_.mm_max_patches = (enc && *enc) || (!file_ && tower) ? 16384 : 0;
|
||||
/* Whole output rows a pass: the plugin's merge, when it states one. */
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
|
||||
if (cfg_.mm_max_patches > 0 && pb.enc_merge > 1)
|
||||
cfg_.mm_max_patches -= cfg_.mm_max_patches % pb.enc_merge;
|
||||
if (cfg_.mm_max_patches == 0 && tower)
|
||||
@@ -1114,7 +1310,7 @@ int Engine::declare() {
|
||||
"refused");
|
||||
} else {
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
|
||||
if (!pb.control_vector_ok) {
|
||||
RAD_ERR("--control-vector %s: the '%s' plugin does not apply control vectors for this "
|
||||
"model", cfg_.control_vector.c_str(), plugins_.arch_plugin.c_str());
|
||||
@@ -1318,6 +1514,46 @@ int Engine::declare() {
|
||||
drafter_name_ = p0.drafter_name;
|
||||
drafter_.name = drafter_name_.c_str();
|
||||
if (cfg_.n_spec <= 0) drafter_ = RadDrafterDecl{};
|
||||
/* A tree drafter (rad_drafter_tree): its parents plane rides with the proposal. */
|
||||
tree_ = drafter_.kind == RAD_DRAFT_BLOCK && drafter_.depth > 0 && p0.drafter_tree;
|
||||
tree_parents_ = tree_ ? p0.drafter_parents : 0;
|
||||
/* --draft-short-from auto: a chain keeps its own block, a tree runs its short block from two
|
||||
* decoding sequences on. Its nodes are verify rows every drafting sequence pays for, which a
|
||||
* wide tree's extra nodes repay at one sequence and not at many. */
|
||||
short_from_ = cfg_.draft_short_from >= 0 ? cfg_.draft_short_from : (tree_ ? 2 : 0);
|
||||
drafter_short_ = drafter_.kind == RAD_DRAFT_BLOCK && short_from_ > 0
|
||||
? p0.drafter_short_block : 0;
|
||||
if (cfg_.draft_short_from > 0 && drafter_.kind == RAD_DRAFT_NONE)
|
||||
RAD_WARN("--draft-short-from %lld: this deployment runs no drafter, so there is no block "
|
||||
"to shorten", (long long)cfg_.draft_short_from);
|
||||
else if (cfg_.draft_short_from > 0 && !drafter_short_)
|
||||
RAD_WARN("--draft-short-from %lld: '%s' %s", (long long)cfg_.draft_short_from,
|
||||
drafter_name_.c_str(),
|
||||
drafter_.kind == RAD_DRAFT_BLOCK ? "declares no shorter block, so it keeps its own"
|
||||
: "is a serial head, which proposes no block");
|
||||
if (drafter_short_ && tree_)
|
||||
RAD_INFO("speculation: from %lld decoding sequences on, '%s' runs its short block of %lld "
|
||||
"row(s), a tree of %lld node(s) over it", (long long)short_from_,
|
||||
drafter_name_.c_str(), (long long)drafter_short_,
|
||||
(long long)std::min<int64_t>(drafter_.depth, drafter_short_ - 1));
|
||||
else if (drafter_short_)
|
||||
RAD_INFO("speculation: from %lld decoding sequences on, '%s' runs its short block of %lld "
|
||||
"row(s), %lld token(s)", (long long)short_from_,
|
||||
drafter_name_.c_str(),
|
||||
(long long)drafter_short_,
|
||||
(long long)(drafter_short_ - ((drafter_.block > 0 ? drafter_.block
|
||||
: drafter_.depth + 1) -
|
||||
drafter_.depth)));
|
||||
if (tree_)
|
||||
RAD_INFO("speculation: '%s' proposes a tree of %d node(s); each verify follows the deepest "
|
||||
"path the target agrees with, and that path's K and V move into place",
|
||||
drafter_.name, drafter_.depth);
|
||||
if (cfg_.spec_ngram > 0 && drafter_.kind != RAD_DRAFT_NONE) {
|
||||
RAD_ERR("--spec-ngram drafts by prompt lookup alone, and this container declares the draft "
|
||||
"head '%s'; serve it with --num-speculative-tokens N, where prompt lookup fills in "
|
||||
"for the sequences the head declines", drafter_.name);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (drafter_.kind != RAD_DRAFT_NONE) {
|
||||
/* A zero proposal handle means the sampler's token buffer: the head's logits go through
|
||||
* the ordinary sampler chain. */
|
||||
@@ -1362,7 +1598,7 @@ static constexpr int64_t kArenaGuard = 1ll << 20;
|
||||
void Engine::probe_arena_levels() {
|
||||
for (auto& r : ranks_) r->arena_levels.clear();
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
|
||||
if (!pb.shape_probe_ok) {
|
||||
RAD_INFO("activation arena: not lent -- the '%s' plugin does not declare at a smaller step "
|
||||
"size (RadArchProbe::shape_probe_ok)", plugins_.arch_plugin.c_str());
|
||||
@@ -1520,6 +1756,10 @@ int Engine::plan() {
|
||||
rad_dev_props(r->device, &props);
|
||||
f.capacity = props.vram_bytes;
|
||||
f.free = props.vram_free;
|
||||
/* Unified memory: the pinned host pool is the same RAM as the card, so the
|
||||
* budget charges it against the one ledger. */
|
||||
f.unified = props.unified != 0;
|
||||
f.host_pinned = f.unified ? cfg_.host_pool_mib * ((int64_t)1 << 20) : 0;
|
||||
/* On integrated graphics an eighth of host memory stays the host's, on top of the free
|
||||
* figure's own bound (core/device/hip.cpp), so the OS is not driven to reclaim and
|
||||
* kill. */
|
||||
@@ -1546,9 +1786,22 @@ int Engine::plan() {
|
||||
* memory, and the real pool does not exist yet. */
|
||||
KVManager probe;
|
||||
host_arenas += arena_host_bytes(r->program);
|
||||
probe.set_drafter_window_snapshot(drafter_window_snap(r->program));
|
||||
if (declare_ring_windows(probe, r->program) == RAD_OK &&
|
||||
probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) {
|
||||
ck_slot += probe.checkpoint_bytes();
|
||||
/* The budget must see the streamed plan before it sizes the pool: a streamed group's
|
||||
* ceiling is max(ring, one layer of its context), not its whole cache
|
||||
* (docs/KV-STREAMING.md §4.1). */
|
||||
RAD_TRY(kvstream_cap_probe(probe, cfg_, r->program, ctx));
|
||||
/* No prefix-cache entry holding a streamed group can be demoted (its mirror is its only
|
||||
* cold copy), so the host tier would be pinned and never used: turned off before
|
||||
* the tables and the checkpoint store are sized. */
|
||||
if (const int64_t off = kvstream_prefix_host_off(cfg_)) {
|
||||
RAD_INFO("a streamed KV group has no host cache: --prefix-cache-mib %lld is off, "
|
||||
"since no entry holding the group could be demoted",
|
||||
(long long)off);
|
||||
}
|
||||
f.kv_ceiling = probe.ceiling(ctx);
|
||||
f.kv_fixed = probe.fixed_bytes();
|
||||
/* One --max-model-len sequence's pool, as the inverse of the real plan: its
|
||||
@@ -1577,16 +1830,21 @@ int Engine::plan() {
|
||||
int64_t lazy = r->program.scratch_regions > 1 ? f.queue_bytes : 0;
|
||||
/* The KV tiers' copy staging, built by TierExec::device_init on the first copy out.
|
||||
* The cached groups are settled later, so every paged group is counted (an upper
|
||||
* bound). */
|
||||
* bound), each with the blocks an entry at the lcm of their block sizes holds
|
||||
* (PrefixCache::entry_groups). */
|
||||
if (cfg_.prefix_cache_mib > 0) {
|
||||
int64_t entry = 0, bs = 0;
|
||||
int ng = 0;
|
||||
for (size_t g = 0; g < r->program.kv_groups.size(); ++g) {
|
||||
const KVGroupPlan* p = probe.plan((int32_t)g);
|
||||
if (!p || !p->paged() || p->bytes_per_block <= 0) continue;
|
||||
entry += p->bytes_per_block;
|
||||
bs = bs > 0 ? std::min<int64_t>(bs, p->block_size) : p->block_size;
|
||||
++ng;
|
||||
if (!p || !p->paged() || p->bytes_per_block <= 0 || p->block_size <= 0) continue;
|
||||
bs = bs > 0 ? std::lcm<int64_t>(bs, p->block_size) : p->block_size;
|
||||
}
|
||||
for (size_t g = 0; g < r->program.kv_groups.size() && bs > 0; ++g) {
|
||||
const KVGroupPlan* p = probe.plan((int32_t)g);
|
||||
if (!p || !p->paged() || p->bytes_per_block <= 0 || p->block_size <= 0) continue;
|
||||
entry += p->bytes_per_block * (bs / p->block_size);
|
||||
ng += (int)(bs / p->block_size);
|
||||
}
|
||||
const int64_t tier = TierExec::device_bytes(entry, ng, TierExec::sizes(entry, ctx, bs));
|
||||
f.staging += tier;
|
||||
@@ -1620,6 +1878,38 @@ int Engine::plan() {
|
||||
for (VramFacts& f : facts) f.held_out = cvec_bytes;
|
||||
RAD_TRY(resolve_table_placement(facts, emb_bytes, wfs, kv_floor, ngram_bytes,
|
||||
ngram_device, ngram_host, ck_store + host_arenas));
|
||||
/* --draft-expert-placement host: the drafter's experts are pinned in the host pool before
|
||||
* the strategy runs, so they leave the elastic plane the card must hold and the pool must
|
||||
* have room for them on top of the trunk's spill. The pool grows here, before the split,
|
||||
* so a drafter fits beside a trunk that already fills the card. */
|
||||
if (cfg_.draft_expert_placement == "host") {
|
||||
const int64_t MiB = (int64_t)1 << 20;
|
||||
int64_t draft_max = 0;
|
||||
for (const WeightFootprint& wf : wfs) draft_max = std::max(draft_max, wf.draft_experts);
|
||||
if (draft_max == 0 && cfg_.draft_expert_placement_given) {
|
||||
RAD_ERR("--draft-expert-placement host: this model declares no draft head with "
|
||||
"routed experts");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (draft_max > 0) {
|
||||
/* The pool grows by the drafter's bytes, and each rank's floor is recomputed
|
||||
* against that room with the drafter out of the plane the card places. */
|
||||
const int64_t add = align_up(draft_max, MiB) / MiB;
|
||||
cfg_.host_pool_mib += add;
|
||||
for (size_t i = 0; i < facts.size(); ++i) {
|
||||
int64_t room = cfg_.host_pool_mib * MiB;
|
||||
if (cfg_.weights_disk_tier)
|
||||
room -= file_stage_reserve(wfs[i].layer_unit_max, wfs[i].routed);
|
||||
facts[i].expert_floor = expert_vram_floor_draft_hosted(
|
||||
wfs[i], std::max<int64_t>(room - align_up(wfs[i].draft_experts, MiB), 0));
|
||||
facts[i].experts = std::max<int64_t>(wfs[i].experts - wfs[i].draft_experts, 0);
|
||||
}
|
||||
RAD_INFO("placement: --draft-expert-placement host pins %s of drafter experts a "
|
||||
"rank in the host pool; --host-pool-mib grows by %lld to hold them, and "
|
||||
"the card places only the trunk's experts",
|
||||
humanb(draft_max).c_str(), (long long)add);
|
||||
}
|
||||
}
|
||||
/* The n-gram table was counted off the card; on it, every rank holds the whole table. */
|
||||
if (cfg_.ngram_resolved == TablePlacement::Vram)
|
||||
for (VramFacts& f : facts) f.statics += ngram_bytes;
|
||||
@@ -1683,6 +1973,7 @@ int Engine::plan() {
|
||||
* its carve). */
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
probes[i] = std::make_unique<KVManager>();
|
||||
probes[i]->set_drafter_window_snapshot(drafter_window_snap(ranks_[i]->program));
|
||||
if (declare_ring_windows(*probes[i], ranks_[i]->program) != RAD_OK ||
|
||||
probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) {
|
||||
kept = fmt("rank %d's KV groups did not plan", ranks_[i]->index);
|
||||
@@ -1768,6 +2059,28 @@ int Engine::plan() {
|
||||
in.profile = file_->profile();
|
||||
in.n_profile = (int64_t)file_->header().prof_count;
|
||||
}
|
||||
/* --expert-profile replaces the container's activation profile, which is prefill-heavy
|
||||
* while decode-hot experts differ (--expert-pin-top keeps them resident). Loaded once, at
|
||||
* the first rank's plan, so every rank ranks the same way. */
|
||||
if (!cfg_.expert_profile.empty()) {
|
||||
if (expert_profile_.empty() && ri == 0) {
|
||||
int32_t trunk = -1;
|
||||
const int pr = xs_profile_load(cfg_.expert_profile, &expert_profile_, &trunk);
|
||||
if (pr < 0) return pr;
|
||||
/* A profile from another model would rank its layers onto this one's. */
|
||||
if (trunk >= 0 && trunk != (int32_t)meta_.n_layers) {
|
||||
RAD_ERR("--expert-profile: %s counts %d trunk layers and this model has %d: "
|
||||
"it was recorded on another model", cfg_.expert_profile.c_str(),
|
||||
(int)trunk, (int)meta_.n_layers);
|
||||
expert_profile_.clear();
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
if (!expert_profile_.empty()) {
|
||||
in.profile = expert_profile_.data();
|
||||
in.n_profile = (int64_t)expert_profile_.size();
|
||||
}
|
||||
}
|
||||
in.container = file_ != nullptr;
|
||||
in.host_backend = device_is_host();
|
||||
Planner planner(in);
|
||||
@@ -1789,7 +2102,8 @@ int Engine::plan() {
|
||||
humanb(r->plan.totals.bytes[(int)Tier::Mapped]).c_str()),
|
||||
r->plan.forced_host_used > 0
|
||||
? fmt("the host pool holds the %s the placement flags put there (the token "
|
||||
"embedding, the encoder towers) beside the weights placed in it",
|
||||
"embedding, the encoder towers, the drafter's experts) beside the "
|
||||
"weights placed in it",
|
||||
humanb(r->plan.forced_host_used).c_str())
|
||||
: std::string());
|
||||
}
|
||||
@@ -1833,10 +2147,10 @@ struct LoadRun {
|
||||
/* ================================================================== the relayout pool
|
||||
*
|
||||
* Weights the loader must rearrange (spec §4.3): the resolved kernel stores something other than
|
||||
* the canonical planes (a fragment order, a per-row scale tail), or the declaration widens bf16 to
|
||||
* f32. The sweep copies the weight's planes into a host input; once all bytes arrive, a worker
|
||||
* produces the stored form, directly into its host pool slot or, for VRAM, through the worker's
|
||||
* pinned bounce buffers.
|
||||
* the canonical planes (a fragment order, a per-row scale tail), or the declaration converts bf16
|
||||
* to f32, or f32 to bf16. The sweep copies the weight's planes into a host input; once all bytes
|
||||
* arrive, a worker produces the stored form, directly into its host pool slot or, for VRAM,
|
||||
* through the worker's pinned bounce buffers.
|
||||
*
|
||||
* It must keep pace with the disk (Qwen3.8-27B-FP8 rearranges 24 GiB of 29 per load; one thread
|
||||
* runs at a fraction of 7 GB/s), so it is a thread pool and the sweep only reads. The copies out
|
||||
@@ -2173,8 +2487,8 @@ private:
|
||||
const int fs = s.fill(s.in);
|
||||
if (fs < 0) return fs;
|
||||
}
|
||||
/* Stored as read (only reached by a weight with no sweep). */
|
||||
if (w.identity && !w.widen) {
|
||||
/* Stored as read (only reached by a weight with no sweep, no dtype conversion). */
|
||||
if (w.identity && !w.widen && !w.narrow) {
|
||||
const int64_t n = w.stored_bytes;
|
||||
if (!s.dev) { std::memcpy(s.dst, s.in, (size_t)n); return RAD_OK; }
|
||||
const int us = b.upload(s.dst, s.in, n, s.device);
|
||||
@@ -2202,11 +2516,15 @@ private:
|
||||
|
||||
int st = RAD_OK;
|
||||
const char* who = "the loader";
|
||||
if (w.widen) {
|
||||
/* Exact: every bf16 and f16 value is representable in f32. */
|
||||
if (w.widen || w.narrow) {
|
||||
/* Exact: every bf16 and f16 value is representable in f32, and f32 rounds to bf16 to
|
||||
* nearest even. */
|
||||
const int64_t cnt = w.sel_rows[0] * w.sel_cols[0];
|
||||
if (cnt * 4 != n) st = RAD_E_SHAPE;
|
||||
else for (int64_t e = 0; e < cnt; ++e) ((float*)out)[e] = rad_load_f32(pt[0].data, pt[0].dtype, e);
|
||||
const int64_t esz = (int64_t)rad_dtype_bytes(w.stored_dtype, 1);
|
||||
if (cnt * esz != n) st = RAD_E_SHAPE;
|
||||
else for (int64_t e = 0; e < cnt; ++e)
|
||||
rad_store_f32(out, w.stored_dtype, e,
|
||||
rad_load_f32(pt[0].data, pt[0].dtype, e));
|
||||
} else {
|
||||
const Resolved& r = s.prog->ops[(size_t)w.lay_op].bands[(size_t)w.lay_band].dom[w.lay_dom];
|
||||
const RadKernelInfo* ki = r.row->info;
|
||||
@@ -2669,7 +2987,9 @@ int Engine::load_weights() {
|
||||
RAD_ERR("rank %d: '%s' was placed on the %s tier, which reads the container where "
|
||||
"it lies, and its stored form is not the container's (%s)", r->index,
|
||||
w.name.c_str(), tier_name(w.tier),
|
||||
w.widen ? "widened at load" : w.identity ? "a shard of it"
|
||||
w.widen ? "widened at load"
|
||||
: w.narrow ? "narrowed at load"
|
||||
: w.identity ? "a shard of it"
|
||||
: w.layout_tag.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
@@ -2787,7 +3107,8 @@ int Engine::load_weights() {
|
||||
total += sh[k].dense_bytes();
|
||||
}
|
||||
sw.in_bytes = in_bytes;
|
||||
if (w.identity && !w.widen && sh[0].dense_bytes() != w.stored_bytes) {
|
||||
if (w.identity && !w.widen && !w.narrow &&
|
||||
sh[0].dense_bytes() != w.stored_bytes) {
|
||||
RAD_ERR("rank %d: '%s': this rank's share is %lld bytes and the slot %lld",
|
||||
r->index, w.name.c_str(), (long long)sh[0].dense_bytes(),
|
||||
(long long)w.stored_bytes);
|
||||
@@ -2809,7 +3130,7 @@ int Engine::load_weights() {
|
||||
* by plane for the relayout pool, which writes the slot. */
|
||||
int32_t stage = -1;
|
||||
int64_t in_bytes = 0;
|
||||
if (!w.identity || w.widen) {
|
||||
if (!w.identity || w.widen || w.narrow) {
|
||||
stage = (int32_t)staged.size();
|
||||
staged.emplace_back();
|
||||
StagedWeight& sw = staged.back();
|
||||
@@ -2951,8 +3272,23 @@ int Engine::size_checkpoint_store(int64_t slot, const char* what) {
|
||||
|
||||
int64_t still = cfg_.prefix_cache_mib * ((int64_t)1 << 20);
|
||||
for (const auto& r : ranks_) still += arena_host_bytes(r->program);
|
||||
std::string limit;
|
||||
int64_t room = lockable_bytes(still, host_headroom_bytes(), &limit);
|
||||
/* The fewest snapshots the store means to hold, in bytes: the count below which prefix reuse
|
||||
* is not worth the pinning. It is what the reserve below must not decide away, and it scales
|
||||
* with the model's own state -- any hybrid's linear layers, any KV encoding's mirror -- since
|
||||
* it is measured from this rank's slot and the host's own spare memory. */
|
||||
const int64_t floor_slots =
|
||||
std::min<int64_t>(checkpoint_slots_want(*pol, cfg_.max_seqs, ctx, interval),
|
||||
kCheckpointSlotsFloor);
|
||||
const int64_t floor_bytes =
|
||||
slot > INT64_MAX / std::max<int64_t>(floor_slots, 1) ? INT64_MAX : floor_slots * slot;
|
||||
const int64_t asked = host_headroom_bytes();
|
||||
int64_t margin = asked;
|
||||
std::string limit, gave_way;
|
||||
/* What the host can pin with `marg` held free: spare memory (MemAvailable and every memory
|
||||
* cgroup), then the driver's own pin cap. Both are the host's own measurement, so a wider
|
||||
* mirror, a bigger pool or a larger slot never needs a second rule here. */
|
||||
auto room_with = [&](int64_t marg, std::string* why) {
|
||||
int64_t r = lockable_bytes(still, marg, why);
|
||||
if (!device_is_host()) {
|
||||
bool lifted = false;
|
||||
if (const int64_t cap = amdgpu_pin_cap(&lifted); cap > 0) {
|
||||
@@ -2960,14 +3296,27 @@ int Engine::size_checkpoint_store(int64_t slot, const char* what) {
|
||||
rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, nullptr);
|
||||
rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, nullptr);
|
||||
const int64_t left = std::max<int64_t>(cap - pinned - mapped - still, 0);
|
||||
if (left < room) {
|
||||
room = left;
|
||||
limit = fmt("the amdgpu driver's pin cap of %s, of which this process holds %s "
|
||||
if (left < r) {
|
||||
r = left;
|
||||
*why = fmt("the amdgpu driver's pin cap of %s, of which this process holds %s "
|
||||
"and still pins %s", humanb(cap).c_str(),
|
||||
humanb(pinned + mapped).c_str(), humanb(still).c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
return r;
|
||||
};
|
||||
int64_t room = room_with(margin, &limit);
|
||||
if (const int64_t keep = host_reserve_for_floor(floor_bytes, room, margin); keep < margin) {
|
||||
/* The host has the bytes, but the reserve stood between them and a store that works.
|
||||
* Take back exactly the shortfall and say so; a host that cannot pin the floor even
|
||||
* then still gets the honest warning below. */
|
||||
const int64_t wider = room_with(keep, &limit);
|
||||
gave_way = fmt("; the host reserve gave back %s of its %s for the floor of %lld "
|
||||
"snapshot(s), holding %s", humanb(margin - keep).c_str(),
|
||||
humanb(asked).c_str(), (long long)floor_slots, humanb(keep).c_str());
|
||||
room = wider;
|
||||
}
|
||||
const int64_t total = meminfo_bytes("MemTotal");
|
||||
const int64_t share = total > 0 ? total / 8 : room;
|
||||
const CheckpointSlots c = checkpoint_slots_auto(*pol, cfg_.max_seqs, ctx, interval, slot,
|
||||
@@ -2986,19 +3335,19 @@ int Engine::size_checkpoint_store(int64_t slot, const char* what) {
|
||||
else if (c.bound == CheckpointSlots::Bound::Room)
|
||||
bound = fmt("; %lld wanted, held to what the host can pin: %s", (long long)c.want,
|
||||
limit.c_str());
|
||||
decide("--checkpoint-slots", std::to_string(c.slots), need + bound);
|
||||
decide("--checkpoint-slots", std::to_string(c.slots), need + bound + gave_way);
|
||||
if (c.slots == 0) {
|
||||
RAD_WARN("checkpoint slots: auto finds no room for one %s snapshot of %s (%s), so every "
|
||||
"prefix hit on this model prefills from the start. Free host memory, or lower "
|
||||
"--host-pool-mib or --prefix-cache-mib", what, humanb(slot).c_str(),
|
||||
limit.c_str());
|
||||
RAD_WARN("checkpoint slots: the host cannot pin one %s snapshot of %s: %s%s. Every prefix "
|
||||
"hit on this model prefills from the start. Free host memory, or lower "
|
||||
"--host-pool-mib, --prefix-cache-mib or --host-headroom-mib", what,
|
||||
humanb(slot).c_str(), limit.c_str(), gave_way.c_str());
|
||||
return RAD_OK;
|
||||
}
|
||||
const std::string line =
|
||||
fmt("checkpoint slots: auto: %lld %s snapshot(s) of %s in pinned host memory (%s), none of "
|
||||
"it on the card; %s%s", (long long)c.slots, what, humanb(slot).c_str(),
|
||||
humanb(slot * c.slots).c_str(), need.c_str(), bound.c_str());
|
||||
if (c.bound == CheckpointSlots::Bound::Room) RAD_WARN("%s", line.c_str());
|
||||
"it on the card; %s%s%s", (long long)c.slots, what, humanb(slot).c_str(),
|
||||
humanb(slot * c.slots).c_str(), need.c_str(), bound.c_str(), gave_way.c_str());
|
||||
if (c.slots < floor_slots || c.bound == CheckpointSlots::Bound::Room) RAD_WARN("%s", line.c_str());
|
||||
else RAD_INFO("%s", line.c_str());
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -3014,6 +3363,14 @@ int Engine::configure_kv() {
|
||||
"block and the linear-state chunk), so a checkpoint is a legal chunk split",
|
||||
(long long)geo_.quantum)
|
||||
: std::string("the model keeps no linear state to checkpoint"));
|
||||
/* KV streaming's policy, refusals and ring (kvstream/bringup.h), decided once from rank 0's
|
||||
* declarations: a streamed group must be the same group on every rank. */
|
||||
KVStreamSetup stream;
|
||||
if (!ranks_.empty())
|
||||
RAD_TRY(kvstream_configure(cfg_, cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train,
|
||||
ranks_[0]->program.kv_groups, ranks_[0]->program, &stream));
|
||||
if (stream.group >= 0)
|
||||
for (auto& r : ranks_) r->kv.cap_resident_tokens(stream.group, stream.ring_tokens);
|
||||
/* One block table serves every rank (serve() checks it), so every rank carves the same number
|
||||
* of paged blocks. Under an uneven split the pools differ (more delta-net heads, or zero
|
||||
* attention weights), so each rank is planned first and all are capped at the least before
|
||||
@@ -3023,7 +3380,9 @@ int Engine::configure_kv() {
|
||||
auto& r = ranks_[i];
|
||||
LogRank lr(r->index);
|
||||
RAD_TRY(declare_ring_windows(r->kv, r->program));
|
||||
r->kv.set_drafter_window_snapshot(drafter_window_snap(r->program));
|
||||
RAD_TRY(r->kv.plan_groups(r->program.kv_groups, cfg_));
|
||||
if (i == 0) drafter_snap_ = r->kv.drafter_window_snapshot();
|
||||
const int64_t t = r->kv.paged_tokens(r->pools.kv().avail());
|
||||
/* A rank plan() re-sized for the common token count must page at least that count (same
|
||||
* plan, same bytes); anything less is a broken invariant. */
|
||||
@@ -3037,6 +3396,22 @@ int Engine::configure_kv() {
|
||||
if (t == KVManager::kUnboundedTokens) continue; /* holds no cache; limits nobody */
|
||||
if (least < 0 || t < least) least = t;
|
||||
}
|
||||
/* The mirrors are checked once, before any rank pins one, against the host tiers still to be
|
||||
* pinned after them: the prefix cache's, the activation arenas and, when sized already, the
|
||||
* checkpoint store. */
|
||||
KVStreamHostUse stream_host;
|
||||
for (auto& r : ranks_) kvstream_host_add(&stream_host, r->kv);
|
||||
if (stream_host.sum.host_bytes > 0) {
|
||||
const int64_t MiB = (int64_t)1 << 20;
|
||||
int64_t still = cfg_.prefix_cache_mib * MiB;
|
||||
for (auto& r : ranks_) still += arena_host_bytes(r->program);
|
||||
if (cfg_.checkpoint_slots > 0) {
|
||||
int64_t slot = 0;
|
||||
for (auto& r : ranks_) slot += r->kv.checkpoint_bytes();
|
||||
still += slot * cfg_.checkpoint_slots;
|
||||
}
|
||||
RAD_TRY(kvstream_host_gate(stream_host, (int)ranks_.size(), still, host_headroom_bytes()));
|
||||
}
|
||||
for (auto& r : ranks_) {
|
||||
LogRank lr(r->index);
|
||||
RAD_TRY(rad_dev_set(r->device)); /* allocates on the current device; see plan() */
|
||||
@@ -3048,7 +3423,13 @@ int Engine::configure_kv() {
|
||||
(long long)least);
|
||||
r->kv.cap_paged_tokens(least);
|
||||
}
|
||||
/* Before the carve, which refuses a streamed plan with no mirror and maps. The maps come out
|
||||
* of this rank's KV pool, so the paged split sees them taken. */
|
||||
const KVManager::StreamCost sc = r->kv.stream_cost();
|
||||
if (sc.groups > 0)
|
||||
RAD_TRY(r->kv.alloc_stream(rad_device_allocator(), r->pools.kv()));
|
||||
RAD_TRY(r->kv.carve(r->pools.kv()));
|
||||
if (sc.groups > 0) RAD_TRY(kvstream_fill(r->kv)); /* the maps, after the elastic pool */
|
||||
/* Without virtual memory management the cache cannot lend: everything still works, but
|
||||
* the expert slab never grows, which no counter shows, so log it once. */
|
||||
if (r->index == 0 && !r->pools.kv().elastic())
|
||||
@@ -3072,8 +3453,12 @@ int Engine::configure_kv() {
|
||||
shard_off[i] = slot;
|
||||
slot += ranks_[i]->kv.checkpoint_bytes();
|
||||
}
|
||||
/* A slot holds linear state or a trunk's window, never both (KVGroupPlan::win_snap). */
|
||||
const char* what = ranks_[0]->kv.has_window_snapshot() ? "sliding-window" : "linear-state";
|
||||
/* A slot holds linear state, a trunk's window (KVGroupPlan::win_snap), or both; a block
|
||||
* drafter's window rides beside a trunk's window where the engine snapshots it. */
|
||||
bool linear = false;
|
||||
for (const KVGroupPlan& p : ranks_[0]->kv.plans()) linear = linear || p.stateful();
|
||||
const char* what = !ranks_[0]->kv.has_window_snapshot() ? "linear-state"
|
||||
: linear ? "linear-state + sliding-window" : "sliding-window";
|
||||
const bool sized_auto = cfg_.checkpoint_slots < 0;
|
||||
if (sized_auto) RAD_TRY(size_checkpoint_store(slot, what));
|
||||
const int64_t n = cfg_.checkpoint_slots > 0 ? cfg_.checkpoint_slots : 0;
|
||||
@@ -3096,7 +3481,14 @@ int Engine::configure_kv() {
|
||||
};
|
||||
if (!sized) return refuse("no host has");
|
||||
std::string why;
|
||||
if (!lockable_room(slot * n, 0, host_headroom_bytes(), false, &why))
|
||||
/* The same reserve rule the sizing used, or a count that auto could fit by giving the
|
||||
* reserve back would be refused a few lines after it was chosen. */
|
||||
std::string guard_why;
|
||||
const int64_t want_bytes = slot * n;
|
||||
const int64_t marg = host_reserve_for_floor(
|
||||
want_bytes, lockable_bytes(0, host_headroom_bytes(), &guard_why),
|
||||
host_headroom_bytes());
|
||||
if (!lockable_room(want_bytes, 0, marg, false, &why))
|
||||
return refuse("does not fit: " + why);
|
||||
if (ck_store_.open(slot, slot * n) != RAD_OK)
|
||||
return refuse(std::string("the host did not pin: ") + rad_dev_last_error());
|
||||
@@ -3123,7 +3515,9 @@ int Engine::configure_kv() {
|
||||
* sessions view reads. The flags gate only the mover, below. */
|
||||
{
|
||||
const bool tier_asked = cfg_.prefix_cache_mib > 0;
|
||||
const std::vector<int32_t>& cg = ranks_[0]->prefix.cached_groups();
|
||||
/* An entry's blocks, one group per block: a cached group whose blocks are shorter than
|
||||
* the entry appears once for each of its blocks (PrefixCache::entry_groups). */
|
||||
const std::vector<int32_t>& cg = ranks_[0]->prefix.entry_groups();
|
||||
/* One slot holds the whole engine's entry: the groups every rank holds alike
|
||||
* (rad_kv_group_replicated) once, at the front, then every rank's own shard in its own
|
||||
* window. Shards can differ or be empty (uneven heads, rad_kv_group_zero). The layout is
|
||||
@@ -3146,7 +3540,11 @@ int Engine::configure_kv() {
|
||||
"to move. --prefix-cache-mib does nothing here.");
|
||||
} else {
|
||||
IdleTiers::Config tc;
|
||||
tc.host_cap_bytes = cfg_.prefix_cache_mib << 20;
|
||||
/* Unified memory: the host tier is the same RAM as the device tier, so the
|
||||
* tiers collapse to resident -- no capacity on the host side, nothing moves. */
|
||||
RadDeviceProps tprops{};
|
||||
rad_dev_props(ranks_[0]->device, &tprops);
|
||||
tc.host_cap_bytes = tprops.unified ? 0 : (cfg_.prefix_cache_mib << 20);
|
||||
tc.entry_bytes = slot_bytes;
|
||||
tc.ckpt_bytes = ck_slot_bytes;
|
||||
tc.ckpt_slots = ck_store_.capacity();
|
||||
@@ -3249,6 +3647,7 @@ int Engine::configure_kv() {
|
||||
}
|
||||
|
||||
RAD_INFO("kv: %s", ranks_[0]->kv.report().c_str());
|
||||
kvstream_report(stream, stream_host, (int)ranks_.size());
|
||||
/* The prefix cache's report: on or off, groups covered and skipped. It names the two things
|
||||
* that silently disable caching on a hybrid model: a windowed group cannot be served a prefix,
|
||||
* and a linear model with no checkpoint interval replays from zero. */
|
||||
@@ -3334,6 +3733,9 @@ int Engine::start() {
|
||||
cfg_.tp, cfg_.tp, devs.size(), inventory.c_str());
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
/* The machine before the model: a refusal here costs a second, after the load it costs the
|
||||
* load. */
|
||||
RAD_TRY(check_configuration(devs));
|
||||
|
||||
RAD_TRY(read_metadata());
|
||||
if (cfg_.max_ctx == 0)
|
||||
@@ -3503,8 +3905,13 @@ int Engine::start() {
|
||||
r->stager.n_layers(), (int)PrefillStager::lead());
|
||||
}
|
||||
/* The file stager, wherever a routed expert is on the file tier (static or dynamic plan;
|
||||
* such a unit has no other address). */
|
||||
RAD_TRY(r->fstager.init(r->program, r->plan, &r->mover));
|
||||
* such a unit has no other address). Routing-aware reads take this
|
||||
* rank's routing reports: the trigger runs after the layer's router on the same stream. */
|
||||
RAD_TRY(r->fstager.init(r->program, r->plan, &r->mover,
|
||||
[](void* ud, int32_t layer, int64_t* n) -> const int32_t* {
|
||||
return ((Ctx*)ud)->route_counts_device(layer, n);
|
||||
},
|
||||
&r->ctx));
|
||||
if (r->fstager.enabled() && r->index == 0)
|
||||
RAD_INFO("file stager: %zu routed layers hold experts read from the container; each "
|
||||
"pass reads a layer's (up to %s) into one of two VRAM buffers before its "
|
||||
@@ -3539,8 +3946,8 @@ int Engine::start() {
|
||||
const int64_t lbpb = p.layer_bytes_per_block(), stripe = p.layer_stride();
|
||||
for (int64_t L = 0; L < p.n_layers; ++L) {
|
||||
LoanStrip st;
|
||||
st.top = (char*)p.base + L * stripe + p.n_blocks * lbpb;
|
||||
st.bytes = p.n_blocks * lbpb;
|
||||
st.top = (char*)p.base + L * stripe + p.pool_blocks() * lbpb;
|
||||
st.bytes = p.pool_blocks() * lbpb;
|
||||
st.unit_bytes = lbpb;
|
||||
st.unit_tokens = p.block_size;
|
||||
strips.push_back(st);
|
||||
|
||||
+40
-1
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
#include "engine_priv.h"
|
||||
#include "device/device.h"
|
||||
#include "mm/media.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
@@ -30,6 +31,33 @@ void Engine::identify_devices(const std::vector<std::string>& names) {
|
||||
}
|
||||
}
|
||||
|
||||
void Engine::print_unsupported_banner() {
|
||||
for (const std::string& l : diag::unsupported_banner()) RAD_WARN("%s", l.c_str());
|
||||
}
|
||||
|
||||
int Engine::check_configuration(const std::vector<int>& devs) {
|
||||
diag::Facts f = hardware_facts(false);
|
||||
for (int i = 0; i < cfg_.tp && i < (int)devs.size(); ++i)
|
||||
for (diag::CardFacts& c : f.cards)
|
||||
if (c.device == devs[(size_t)i]) c.rank = i;
|
||||
int found = 0;
|
||||
for (const diag::Finding& x : diag::incompatible(f)) {
|
||||
if (x.level != diag::Finding::Incompatible) continue;
|
||||
++found;
|
||||
if (cfg_.proceed_incompatible)
|
||||
RAD_WARN("incompatible configuration, started anyway: %s: %s. Fix: %s", x.id.c_str(),
|
||||
x.what.c_str(), x.fix.c_str());
|
||||
else
|
||||
RAD_ERR("incompatible configuration: %s: %s -- %s. Fix: %s", x.id.c_str(),
|
||||
x.what.c_str(), x.why.c_str(), x.fix.c_str());
|
||||
}
|
||||
if (!found || cfg_.proceed_incompatible) return RAD_OK;
|
||||
RAD_ERR("radiance does not start on a configuration it does not support: the fix for each is "
|
||||
"said above. --proceed-with-incompatible-configuration starts it anyway, unsupported "
|
||||
"and without any guarantee");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
diag::Facts Engine::hardware_facts(bool serving) const {
|
||||
std::vector<std::string> mine;
|
||||
for (const DevId& id : dev_ids_)
|
||||
@@ -37,6 +65,7 @@ diag::Facts Engine::hardware_facts(bool serving) const {
|
||||
if (r->device == id.device) mine.push_back(id.bdf);
|
||||
diag::Facts f = diag::collect("", serving ? &mine : nullptr);
|
||||
f.host.runtime = runtime_version_;
|
||||
f.host.media = mm::decoder_version();
|
||||
if (probed_) {
|
||||
f.host.memlock_soft = memlock_soft_;
|
||||
f.host.io_uring = io_uring_;
|
||||
@@ -95,6 +124,8 @@ diag::RunFacts Engine::run_facts(bool failed) const {
|
||||
r.reference_kernels = cfg_.accept_reference_kernels;
|
||||
r.profile_ops = cfg_.profile_ops;
|
||||
r.deterministic = cfg_.deterministic;
|
||||
r.unsupported = cfg_.proceed_incompatible;
|
||||
r.all_options = cfg_.given.count("-v") > 0;
|
||||
r.environment = env_set_;
|
||||
return r;
|
||||
}
|
||||
@@ -125,9 +156,17 @@ void Engine::print_startup_report(int status) {
|
||||
at = nl + 1;
|
||||
}
|
||||
/* Each warning also on its own W line, for readers filtering a log by level. */
|
||||
for (const diag::Finding& x : found)
|
||||
for (const diag::Finding& x : found) {
|
||||
if (x.level == diag::Finding::Warn)
|
||||
RAD_WARN("startup report: %s: %s. Fix: %s", x.id.c_str(), x.what.c_str(), x.fix.c_str());
|
||||
/* A refusal is an E line; started anyway it is a W line, which the banner explains. */
|
||||
else if (x.level == diag::Finding::Incompatible && cfg_.proceed_incompatible)
|
||||
RAD_WARN("startup report: INCOMPATIBLE, started anyway: %s: %s. Fix: %s", x.id.c_str(),
|
||||
x.what.c_str(), x.fix.c_str());
|
||||
else if (x.level == diag::Finding::Incompatible)
|
||||
RAD_ERR("startup report: INCOMPATIBLE: %s: %s. Fix: %s", x.id.c_str(), x.what.c_str(),
|
||||
x.fix.c_str());
|
||||
}
|
||||
/* Repeat the failure last, since the original error line is now above the report. */
|
||||
if (status < 0)
|
||||
RAD_ERR("startup stopped: %s (the reason is said above the startup report)",
|
||||
|
||||
+304
-14
@@ -6,6 +6,9 @@
|
||||
*/
|
||||
#include "engine_priv.h"
|
||||
|
||||
#include "sample/mtp_couple_evidence.h"
|
||||
#include "sched/mtp_couple_bind.h"
|
||||
#include "sched/mtp_couple_plan.h"
|
||||
#include "sched/scheduler.h"
|
||||
#include "device/device.h"
|
||||
|
||||
@@ -13,6 +16,7 @@
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -26,6 +30,8 @@ int Engine::step_state_init() {
|
||||
if (vocab_) eog = vocab_->eog();
|
||||
std::sort(eog.begin(), eog.end());
|
||||
eog.erase(std::unique(eog.begin(), eog.end()), eog.end());
|
||||
/* Scheduler::ends_every_request reads the same ids. */
|
||||
sched_.set_eog(eog);
|
||||
const int64_t n_slot = cfg_.max_seqs > 0 ? cfg_.max_seqs : 1;
|
||||
const int64_t slot_bytes = n_slot * (int64_t)sizeof(StepSlot);
|
||||
for (auto& rk : ranks_) {
|
||||
@@ -48,7 +54,66 @@ int Engine::step_state_init() {
|
||||
if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0]->device));
|
||||
slots_host_ = static_cast<StepSlot*>(rad_dev_alloc(slot_bytes, RAD_MEM_HOST_PINNED));
|
||||
if (!slots_host_) return RAD_E_NOMEM;
|
||||
|
||||
/* --draft-coupling: the head's two planes, found by name in the declared program, and the
|
||||
* pinned staging beside them. A program without them is refused rather than served
|
||||
* uncoupled. */
|
||||
mtp_couple_ = cfg_.draft_coupling;
|
||||
if (mtp_couple_) {
|
||||
/* Coupling is defined on a linear chain of drafts: a serial head's rounds, or a block
|
||||
* drafter whose walk samples each position in turn (DFlash2, dflash_couple_propose), its
|
||||
* position l standing for round l + 1. Either way one draw a drafting row and one state a
|
||||
* (round, row). */
|
||||
if ((drafter_.kind != RAD_DRAFT_SERIAL && drafter_.kind != RAD_DRAFT_BLOCK) ||
|
||||
drafter_.depth <= 0) {
|
||||
RAD_ERR("--draft-coupling on requires a linear draft chain (a serial head or a block "
|
||||
"drafter with a coupled walk, depth > 0); this model declares drafter '%s' "
|
||||
"kind %d depth %d, which has no per-round draw to couple",
|
||||
drafter_.name ? drafter_.name : "(none)", drafter_.kind, drafter_.depth);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const Program& prog = ranks_[0]->program;
|
||||
for (size_t i = 0; i < prog.buffers.size(); ++i) {
|
||||
const std::string& name = prog.buffers[i].name;
|
||||
auto ends = [&](const char* suffix) {
|
||||
const size_t n = std::strlen(suffix);
|
||||
return name.size() >= n && name.compare(name.size() - n, n, suffix) == 0;
|
||||
};
|
||||
if (ends("mtp_couple_draws")) couple_draws_buf_ = (rad_buf)i;
|
||||
if (ends("mtp_couple_state")) couple_state_buf_ = (rad_buf)i;
|
||||
}
|
||||
if (!couple_draws_buf_ || !couple_state_buf_) {
|
||||
RAD_ERR("--draft-coupling on, but the architecture declared no coupled MTP planes; "
|
||||
"this model's drafter cannot couple");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const RadBufDecl& sd = prog.buffers[couple_state_buf_].decl;
|
||||
if (sd.rank != 3 || sd.shape[2] != (int64_t)RAD_MTP_COUPLE_STATE_WORDS ||
|
||||
sd.shape[0] < (int64_t)drafter_.depth) {
|
||||
RAD_ERR("--draft-coupling: 'mtp_couple_state' is not the [rounds, rows, %d]-word "
|
||||
"plane the coupling reads", (int)RAD_MTP_COUPLE_STATE_WORDS);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
couple_rows_ = sd.shape[1];
|
||||
/* One entry per card slot, indexed by StepEntry::card as slots_host_ is. */
|
||||
couple_by_card_.assign((size_t)n_slot, RadMtpCoupleDraw{});
|
||||
couple_draw_stage_ = static_cast<RadMtpCoupleDraw*>(
|
||||
rad_dev_alloc(n_slot * (int64_t)sizeof(RadMtpCoupleDraw), RAD_MEM_HOST_PINNED));
|
||||
couple_readback_ = static_cast<RadMtpCoupleState*>(rad_dev_alloc(
|
||||
(int64_t)drafter_.depth * couple_rows_ * (int64_t)sizeof(RadMtpCoupleState),
|
||||
RAD_MEM_HOST_PINNED));
|
||||
if (!couple_draw_stage_ || !couple_readback_) return RAD_E_NOMEM;
|
||||
if (drafter_.kind == RAD_DRAFT_BLOCK)
|
||||
RAD_INFO("DFlash coupled LIVE: %d position(s), x~Q along the candidate walk, maximal "
|
||||
"coupling at the verify; fixed-seed tokens are NOT preserved", drafter_.depth);
|
||||
else
|
||||
RAD_INFO("MTP coupled LIVE: %d linear round(s), x~Q from the final reranked top8, "
|
||||
"maximal coupling at the verify; fixed-seed tokens are NOT preserved",
|
||||
drafter_.depth);
|
||||
}
|
||||
|
||||
RAD_TRY(rad_event_create_as(&step_end_, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT));
|
||||
RAD_TRY(rad_event_create_as(&tok_end_, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -62,8 +127,14 @@ void Engine::step_state_fini() {
|
||||
}
|
||||
if (slots_host_) rad_dev_free(slots_host_, RAD_MEM_HOST_PINNED);
|
||||
slots_host_ = nullptr;
|
||||
if (couple_draw_stage_) rad_dev_free(couple_draw_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (couple_readback_) rad_dev_free(couple_readback_, RAD_MEM_HOST_PINNED);
|
||||
couple_draw_stage_ = nullptr;
|
||||
couple_readback_ = nullptr;
|
||||
if (step_end_) rad_event_destroy(step_end_);
|
||||
step_end_ = nullptr;
|
||||
if (tok_end_) rad_event_destroy(tok_end_);
|
||||
tok_end_ = nullptr;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the serial driver
|
||||
@@ -104,6 +175,14 @@ int Engine::advance_all(int mode, int round, bool from_proposal, int rows) {
|
||||
: rk.ctx.buf_ptr(rk.tok_buf));
|
||||
a.src_pitch = (drafter_.proposal && drafter_.proposal_pitch > 0)
|
||||
? drafter_.proposal_pitch : 1;
|
||||
/* A tree drafter's parents, at the proposal's pitch (rad_drafter_tree). */
|
||||
if (tree_ && mode == ADV_BTAKE) {
|
||||
a.par = static_cast<const int32_t*>(rk.ctx.buf_ptr(tree_parents_));
|
||||
if (!a.par) {
|
||||
RAD_ERR("drafter '%s': rank %zu has no parents buffer", drafter_.name, i);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
a.src = static_cast<const int32_t*>(rk.ctx.buf_ptr(rk.tok_buf));
|
||||
}
|
||||
@@ -117,10 +196,54 @@ int Engine::advance_all(int mode, int round, bool from_proposal, int rows) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ADV_COMPACT on every rank, against the scheduler's latest build (the tree step just accepted):
|
||||
* the accepted paths' K and V into place in every paged group. Each rank's pools are its own. */
|
||||
int Engine::tree_compact(int rows) {
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
Rank& rk = *ranks_[i];
|
||||
AdvanceArgs a = sched_.advance_args((int)i);
|
||||
if (rows >= 0 && rows < a.n_seq) a.n_seq = rows;
|
||||
a.mode = 0;
|
||||
a.st = rk.step_slots;
|
||||
const Program& p = rk.program;
|
||||
for (size_t g = 1; g < p.kv_groups.size() && (int)g < a.n_groups; ++g) {
|
||||
const int kind = p.kv_groups[g].decl.kind;
|
||||
if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW) continue;
|
||||
const KVPoolBinding* b = rk.ctx.kv_binding((uint32_t)g);
|
||||
if (!b || !b->base || b->rank != 4) continue; /* a zero group on this rank */
|
||||
const int bits = rad_dtype_bits(b->dtype);
|
||||
const int64_t row = bits > 0 ? b->shape[3] * bits / 8 : 0;
|
||||
int32_t layers = 0;
|
||||
for (int32_t s : b->layer_slot) layers += s >= 0;
|
||||
if (row <= 0 || row % 16 || (bits != 8 && bits != 16 && bits != 32) ||
|
||||
(b->bytes && (int64_t)layers * b->layer_stride > b->bytes)) {
|
||||
RAD_ERR("speculation: KV group %zu's cache (%s, %lld-byte rows) is not one a tree's "
|
||||
"acceptance can move", g, rad_dtype_name(b->dtype), (long long)row);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (a.n_pool >= kAdvMaxPools) {
|
||||
RAD_ERR("speculation: more than %d paged KV groups for a tree's acceptance",
|
||||
(int)kAdvMaxPools);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
AdvPool& q = a.pool[a.n_pool++];
|
||||
q.base = static_cast<char*>(b->base);
|
||||
q.layer_stride = b->layer_stride;
|
||||
q.n_layers = layers;
|
||||
q.n_head = (int32_t)b->shape[1];
|
||||
q.row_bytes = (int32_t)row;
|
||||
q.grp = (int32_t)g;
|
||||
}
|
||||
RAD_TRY(step_compact(a, rk.ctx.stream()));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Issue the step's draft passes behind it, without waiting. After the trunk's ranks join: the
|
||||
* acceptance on every rank, the sampled-id readback (before a round can overwrite them), the
|
||||
* history pass and every round, then the final proposal into the slots and their readback.
|
||||
* Nothing synchronises here; collect_step has the step's one wait. */
|
||||
* Nothing synchronises here: collect_step waits for the ids alone, and the step loop for the
|
||||
* passes after the commit, before finish_serial_drafter reads the slots. */
|
||||
int Engine::issue_serial_drafter(int step, StepOut& so) {
|
||||
serial_rounds_ = 0;
|
||||
serial_rows_ = 0;
|
||||
@@ -132,7 +255,7 @@ int Engine::issue_serial_drafter(int step, StepOut& so) {
|
||||
}
|
||||
|
||||
RAD_TRY(advance_all(ADV_ACCEPT, 0, false));
|
||||
RAD_TRY(collect_issue(so));
|
||||
RAD_TRY(collect_issue(so, /*fence=*/true));
|
||||
|
||||
int rounds = drafter_.depth;
|
||||
serial_row_.resize((size_t)cfg_.max_seqs);
|
||||
@@ -142,6 +265,8 @@ int Engine::issue_serial_drafter(int step, StepOut& so) {
|
||||
if (rounds <= 0) return RAD_OK;
|
||||
serial_rounds_ = rounds;
|
||||
serial_rows_ = n;
|
||||
/* Before any serial pass reads a draw; round 1 is the history pass below. */
|
||||
if (mtp_couple_ && n > 0) RAD_TRY(stage_couple_draws(serial_row_.data(), n));
|
||||
|
||||
/* RADIANCE_DEBUG_STAGE: running means of a draft pass's host time: batch + advance, greedy
|
||||
* sampler chain, barrier release and issue. They cost the step nothing until their sum exceeds
|
||||
@@ -213,6 +338,15 @@ int Engine::issue_serial_drafter(int step, StepOut& so) {
|
||||
* history (Scheduler::serial_batch). */
|
||||
RAD_TRY(advance_all(ADV_TAKE, serial_done_, true, n));
|
||||
Rank& r0 = *ranks_[0];
|
||||
if (mtp_couple_) {
|
||||
/* Rounds 1..done of the drafting rows, on the same stream as the slots below. */
|
||||
const void* state = r0.ctx.buf_ptr(couple_state_buf_);
|
||||
if (!state || serial_done_ > (int)drafter_.depth) return RAD_E_STATE;
|
||||
const int64_t pitch = couple_rows_ * (int64_t)sizeof(RadMtpCoupleState);
|
||||
RAD_TRY(rad_memcpy_2d_async(couple_readback_, pitch, state, pitch,
|
||||
(int64_t)n * (int64_t)sizeof(RadMtpCoupleState), serial_done_,
|
||||
r0.ctx.stream()));
|
||||
}
|
||||
RAD_TRY(rad_memcpy_async(slots_host_, r0.step_slots,
|
||||
(int64_t)cfg_.max_seqs * (int64_t)sizeof(StepSlot), r0.ctx.stream()));
|
||||
return RAD_OK;
|
||||
@@ -253,8 +387,98 @@ int Engine::finish_serial_drafter(const StepOut& so) {
|
||||
/* No draft for a request the sampler will not speculate on (a constraining grammar that
|
||||
* cannot snapshot its state); the sampler would refuse the next step otherwise. */
|
||||
if (!r0.sampler.allows_speculation(serial_row_[(size_t)i].seq)) continue;
|
||||
sched_.set_draft(serial_row_[(size_t)i].seq,
|
||||
&draft_out_[(size_t)i * (size_t)rounds], done);
|
||||
const uint64_t seq = serial_row_[(size_t)i].seq;
|
||||
const int rc = sched_.set_draft(seq, &draft_out_[(size_t)i * (size_t)rounds], done);
|
||||
if (mtp_couple_)
|
||||
RAD_TRY(bind_couple(seq, i, done, rc == RAD_OK, serial_row_[(size_t)i].card));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* --draft-coupling, after the commit: bind drafting row `i`'s `done` states (its readback column)
|
||||
* to the positions the next build samples, and hand them to every rank's sampler.
|
||||
*
|
||||
* Bound only for a request still running: one this commit finished, or whose draft the scheduler
|
||||
* refused (`drafted` false), binds nothing, and set_mtp_couple(..., 0) clears an earlier step's
|
||||
* states (RAD_E_NOTFOUND for a request the sampler already dropped).
|
||||
*
|
||||
* The position is the committed output length after this commit, the n_out the next build_step
|
||||
* reads. It comes from the scheduler's commit snapshot, not the plan's Request pointer, which
|
||||
* reap() may already have freed (sched/mtp_couple_bind.h). */
|
||||
int Engine::bind_couple(uint64_t seq, int i, int done, bool drafted, int32_t card) {
|
||||
MtpCoupleBindPoint bp;
|
||||
bp.found = sched_.committed_seq(seq, &bp.n_out, &bp.live);
|
||||
if (!bp.found)
|
||||
RAD_WARN("coupled draft: row for sequence %llu is not in the committed step; clearing its "
|
||||
"coupling", (unsigned long long)seq);
|
||||
int n_bound = 0, n_malformed = 0;
|
||||
std::string why;
|
||||
const int bs = mtp_couple_bind_rounds(bp, couple_draw_stage_[(size_t)i],
|
||||
&couple_readback_[(size_t)i], (int)couple_rows_, done,
|
||||
slots_host_[card], meta_.n_vocab, couple_bound_,
|
||||
&n_bound, &why, &n_malformed);
|
||||
if (bs < 0) { RAD_ERR("%s", why.c_str()); return bs; }
|
||||
if (n_malformed > 0 && !couple_malformed_note_) {
|
||||
couple_malformed_note_ = true;
|
||||
RAD_WARN("coupled draft: sequence %llu: %d draft position(s) had a shortlist with no valid "
|
||||
"Q (non-finite score, duplicate id or no live entry); those keep the greedy "
|
||||
"proposal and the ordinary verify (logged once)",
|
||||
(unsigned long long)seq, n_malformed);
|
||||
}
|
||||
for (auto& rk : ranks_) {
|
||||
const int st = rk->sampler.set_mtp_couple(seq, couple_bound_, drafted ? n_bound : 0);
|
||||
if (st < 0 && st != RAD_E_NOTFOUND) return st;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One line, once, at the first coupled verify that completed. It reads the snapshot build_step
|
||||
* froze for the step whose wait just returned (sample/mtp_couple_evidence.h), which the
|
||||
* drafter's build_greedy does not clear, and checks that run() issued the verify for that build.
|
||||
* Sequences are re-checked as Running after the wait. Request numbers, the row count and the
|
||||
* kernel name only; a host-domain row is labelled as such. */
|
||||
void Engine::couple_verify_evidence(int step) {
|
||||
if (!mtp_couple_ || couple_evidence_) return;
|
||||
Sampler& smp = ranks_[0]->sampler;
|
||||
const rad_op op = smp.staged_couple_op();
|
||||
const MtpCoupleEvidence ev = mtp_couple_evidence(
|
||||
smp.couple_build(), step, ranks_[0]->ctx.op_domain(op),
|
||||
[this](uint64_t seq) { return sched_.running(seq); });
|
||||
if (ev.rows <= 0 || smp.staged_couple_issued_step() != step) return;
|
||||
const char* kernel = ranks_[0]->ctx.ip_kernel_name(op);
|
||||
if (ev.device) {
|
||||
couple_evidence_ = true;
|
||||
RAD_INFO("MTP coupled verify completed: step %d, %lld bound row(s) over request(s) [%s], "
|
||||
"kernel %s, domain device", step, (long long)ev.rows, ev.seqs.c_str(), kernel);
|
||||
} else if (!couple_host_note_) {
|
||||
couple_host_note_ = true;
|
||||
RAD_INFO("MTP coupled verify completed on the host domain: step %d, %lld bound row(s) over "
|
||||
"request(s) [%s], kernel %s -- not device evidence", step, (long long)ev.rows,
|
||||
ev.seqs.c_str(), kernel);
|
||||
}
|
||||
}
|
||||
|
||||
/* --draft-coupling: the draw for every drafting row, before any draft pass reads it.
|
||||
*
|
||||
* The coordinate is the pre-commit output size, which strictly grows between two steps that draft
|
||||
* one request, so (base, round) never repeats a draft stream. The card is the slot the advance
|
||||
* writes; the propose op keeps the greedy proposal for a row whose draw names another card. The
|
||||
* rule is sched/mtp_couple_plan.h. */
|
||||
template <class Row>
|
||||
int Engine::stage_couple_draws(const Row* rows, int n) {
|
||||
std::string why;
|
||||
const int stg = mtp_couple_plan_stage(sched_.plan(),
|
||||
(int)(cfg_.max_seqs > 0 ? cfg_.max_seqs : 1),
|
||||
rows, n, &couple_by_card_, couple_draw_stage_, &why);
|
||||
if (stg < 0) {
|
||||
RAD_ERR("MTP coupled: %s", why.c_str());
|
||||
return stg;
|
||||
}
|
||||
for (auto& rk : ranks_) {
|
||||
void* dst = rk->ctx.buf_ptr(couple_draws_buf_);
|
||||
if (!dst) return RAD_E_STATE;
|
||||
RAD_TRY(rad_memcpy_async(dst, couple_draw_stage_,
|
||||
n * (int64_t)sizeof(RadMtpCoupleDraw), rk->ctx.stream()));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -312,24 +536,65 @@ bool Engine::block_drafting() const {
|
||||
* The query pass's rows are device rows that the card positions at the committed end (ADV_BLOCK),
|
||||
* and its proposals go into the slots behind the anchor (ADV_BTAKE): exactly the token row the
|
||||
* next verify reads (ADV_TRUNK), so the step issued ahead verifies them with no host round trip.
|
||||
* collect_step's wait covers both passes and the slots' readback. */
|
||||
* collect_step waits for the sampled ids alone, so the commit streams the tokens while the card
|
||||
* runs both passes; the step loop waits for them (step_end_) before finish_block_drafter reads the
|
||||
* slots. */
|
||||
void Engine::block_shape(int* block, int* steps) {
|
||||
*steps = drafter_.depth;
|
||||
/* The row count is the drafter's (defaulted and checked by declare_drafter). */
|
||||
*block = drafter_.block > 0 ? (int)drafter_.block : drafter_.depth + 1;
|
||||
/* Its short block under load (rad_drafter_short_block): the same anchor convention, so as many
|
||||
* fewer proposals as rows. The load is the step just run's, which the next step, the one these
|
||||
* proposals are for, mostly repeats (Scheduler::short_block_on). */
|
||||
if (drafter_short_ <= 0) return;
|
||||
short_on_ = Scheduler::short_block_on(short_on_, sched_.decoded_seqs(), short_from_);
|
||||
if (short_on_) {
|
||||
/* A tree (rad_drafter_tree) grows a tree of its own over the shorter pass, at most its
|
||||
* draft positions of nodes (DFlash2 attends across its block, so the short pass is not the
|
||||
* full pass's prefix); the verify takes that many. */
|
||||
if (tree_) *steps = std::min(*steps, (int)drafter_short_ - 1);
|
||||
else *steps -= *block - (int)drafter_short_;
|
||||
*block = (int)drafter_short_;
|
||||
}
|
||||
}
|
||||
|
||||
int Engine::issue_block_drafter(int step, StepOut& so) {
|
||||
block_rows_ = 0;
|
||||
if (!block_drafting()) return RAD_OK;
|
||||
|
||||
RAD_TRY(advance_all(ADV_ACCEPT, 0, false));
|
||||
/* A tree's accepted path into place in the trunk's cache, against the same build (the step
|
||||
* just accepted), before any later pass reads it. */
|
||||
if (tree_) RAD_TRY(tree_compact(-1));
|
||||
/* The sampled ids before either pass, as the serial driver reads them. */
|
||||
RAD_TRY(collect_issue(so));
|
||||
RAD_TRY(collect_issue(so, /*fence=*/true));
|
||||
|
||||
const int steps = drafter_.depth;
|
||||
const int block = drafter_.block > 0 ? (int)drafter_.block : drafter_.depth + 1;
|
||||
/* The short block too (block_shape): its query pass is a shorter batch the card positions
|
||||
* the same way, its proposals the front of each row at the drafter's pitch (ADV_BTAKE), and
|
||||
* the step issued ahead verifies that many (issue_ahead). */
|
||||
int block = 0, steps = 0;
|
||||
block_shape(&block, &steps);
|
||||
block_steps_ = steps;
|
||||
block_row_.resize((size_t)cfg_.max_seqs);
|
||||
const int n = sched_.block_begin(block, steps, (int)drafter_.window, drafter_.mask_token,
|
||||
/* The head reads the block's draft rows. A tree (rad_drafter_tree; DFlash2's convention, the
|
||||
* anchor predicts nothing) reads all block - 1 of them whatever its node count. */
|
||||
const int head = tree_ ? block - 1 : steps;
|
||||
const int n = sched_.block_begin(block, head, (int)drafter_.window, drafter_.mask_token,
|
||||
block_row_.data(), (int)block_row_.size(), /*on_card=*/true);
|
||||
|
||||
/* --draft-coupling: the draws before the query pass reads them (stage_couple_draws). */
|
||||
if (mtp_couple_ && n > 0) RAD_TRY(stage_couple_draws(block_row_.data(), n));
|
||||
|
||||
/* The context pass runs even when nothing drafts: a mid-prompt sequence has hidden states the
|
||||
* drafter will need, and skipping would leave a permanent hole in its cache. */
|
||||
if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(block_pass(cb, "context", step));
|
||||
* drafter will need, and skipping would leave a permanent hole in its cache. A tree verify's
|
||||
* context rows store only the accepted path, at its committed positions (ADV_CTXTREE). */
|
||||
if (const RadBatch* cb = sched_.block_context(step)) {
|
||||
if (tree_) RAD_TRY(advance_all(ADV_CTXTREE, 0, false));
|
||||
RAD_TRY(block_pass(cb, "context", step));
|
||||
}
|
||||
/* A snapshot carrying the drafter's window is saved now, with the step's context rows stored
|
||||
* and before the query pass and the step issued ahead (save_checkpoints). */
|
||||
if (drafter_snap_) RAD_TRY(save_checkpoints());
|
||||
if (n <= 0) return RAD_OK;
|
||||
const RadBatch* qb = sched_.block_query(step);
|
||||
if (!qb) return RAD_OK;
|
||||
@@ -337,6 +602,15 @@ int Engine::issue_block_drafter(int step, StepOut& so) {
|
||||
RAD_TRY(block_pass(qb, "query", step));
|
||||
RAD_TRY(advance_all(ADV_BTAKE, steps, true, n));
|
||||
Rank& r0 = *ranks_[0];
|
||||
if (mtp_couple_) {
|
||||
/* Positions 1..steps of the drafting rows, on the stream of the slots below. */
|
||||
const void* state = r0.ctx.buf_ptr(couple_state_buf_);
|
||||
if (!state || steps > (int)drafter_.depth) return RAD_E_STATE;
|
||||
const int64_t pitch = couple_rows_ * (int64_t)sizeof(RadMtpCoupleState);
|
||||
RAD_TRY(rad_memcpy_2d_async(couple_readback_, pitch, state, pitch,
|
||||
(int64_t)n * (int64_t)sizeof(RadMtpCoupleState), steps,
|
||||
r0.ctx.stream()));
|
||||
}
|
||||
RAD_TRY(rad_memcpy_async(slots_host_, r0.step_slots,
|
||||
(int64_t)cfg_.max_seqs * (int64_t)sizeof(StepSlot), r0.ctx.stream()));
|
||||
block_rows_ = n;
|
||||
@@ -368,18 +642,34 @@ int Engine::finish_block_drafter(const StepOut& so) {
|
||||
if (block_rows_ <= 0) return RAD_OK;
|
||||
|
||||
Rank& r0 = *ranks_[0];
|
||||
const int steps = drafter_.depth;
|
||||
const int steps = block_steps_;
|
||||
draft_out_.assign((size_t)block_rows_ * (size_t)steps, 0);
|
||||
for (int i = 0; i < block_rows_; ++i) {
|
||||
const StepSlot& S = slots_host_[block_row_[(size_t)i].card];
|
||||
for (int j = 0; j < steps; ++j)
|
||||
draft_out_[(size_t)i * (size_t)steps + (size_t)j] = S.tok[1 + j];
|
||||
}
|
||||
/* -v: what each block pass proposed, a line a sequence, so two runs can be compared draft by
|
||||
* draft where acceptance alone cannot tell them apart (a drafter whose context is wrong still
|
||||
* drafts, and its rejected drafts change no token). */
|
||||
const bool show = (int)log_level() >= (int)Log::Debug;
|
||||
for (int i = 0; i < block_rows_; ++i) {
|
||||
const int32_t* d = &draft_out_[(size_t)i * (size_t)steps];
|
||||
if (show) {
|
||||
std::string t;
|
||||
for (int j = 0; j < steps; ++j) t += fmt(" %d", (int)d[j]);
|
||||
RAD_DEBUG("drafter '%s': sequence %llu proposes%s", drafter_.name,
|
||||
(unsigned long long)block_row_[(size_t)i].seq, t.c_str());
|
||||
}
|
||||
/* As in finish_serial_drafter: the step issued ahead only carries a request whose answer
|
||||
* is fixed (Scheduler::step_next_locked), so this agrees with the count it verifies. */
|
||||
* is fixed (Scheduler::step_next_locked), so this agrees with the count it verifies. A
|
||||
* tree's parents come from the same slot, as ADV_BTAKE took them. */
|
||||
if (!r0.sampler.allows_speculation(block_row_[(size_t)i].seq)) continue;
|
||||
sched_.set_draft(block_row_[(size_t)i].seq, &draft_out_[(size_t)i * (size_t)steps], steps);
|
||||
const uint64_t seq = block_row_[(size_t)i].seq;
|
||||
const StepSlot& S = slots_host_[block_row_[(size_t)i].card];
|
||||
const int rc = sched_.set_draft(seq, d, steps, tree_ ? S.par : nullptr);
|
||||
if (mtp_couple_)
|
||||
RAD_TRY(bind_couple(seq, i, steps, rc == RAD_OK, block_row_[(size_t)i].card));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -53,6 +53,8 @@ int Engine::gen_loop() {
|
||||
continue;
|
||||
}
|
||||
idle = 0;
|
||||
/* A hybrid model's recurrent state: the slots a newly admitted request was granted. */
|
||||
clear_fresh_states();
|
||||
if (const int ps = prepare_release(b); ps < 0) return stop(ps);
|
||||
for (auto& rk : ranks_) rk->ctx.set_gen_lora_slot(gen_->lora_slot());
|
||||
issue_what_.store(kIssueModel, std::memory_order_release);
|
||||
|
||||
@@ -19,4 +19,12 @@ 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);
|
||||
|
||||
/* 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
|
||||
* OOM killer); and, for an mlock()ed copy (`mlocks`), RLIMIT_MEMLOCK unless the process has
|
||||
* CAP_IPC_LOCK. Pinned memory a card reads is a driver userptr mapping, which RLIMIT_MEMLOCK does
|
||||
* not count. An unreadable limit is ignored, never guessed. */
|
||||
bool lockable_room(int64_t need, int64_t still, int64_t margin, bool mlocks, std::string* why);
|
||||
|
||||
} /* namespace rad */
|
||||
Loaded 100 of 937 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user