radiance 1.8.0

- video: MiniMax-H3 and FastVideo's FastH3 8-Step V2, a video with its stereo soundtrack from text
  on OpenAI's /v1/videos, block fp8 on two cards
- music: MiniMax-Music3, songs from lyrics and a description on /v1/audio/speech
- speech: Breeze-TTS-2 on /v1/audio/speech and vLLM-Omni's realtime WebSocket
- runtime LoRA adapters beside the base model, picked per request by `model` (baKon, #105)
- several agent streams keep their cached history: --checkpoint-slots auto, the new default, sizes
  the snapshot store by --max-num-seqs (#108)
- the Swift 1.5 27B W4 releases convert and serve: compressed-tensors AWQ and GPTQ int4, AutoRound,
  ModelOpt NVFP4 (#110)
- the image's host tests pass where perf_event_open is refused, as in BuildKit's sandbox (#106)
- plugin ABI 21: out-of-tree plugins must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-18 11:38:37 +02:00
1 parent 91127395ee
commit 7a7707a955
179 files changed
+37542 -1892

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.21)
# VERSION is the server release that /version reports. The plugin ABI version is separate and is
# read from abi/rad_abi.h below.
project(radiance VERSION 1.7.0 LANGUAGES C CXX)
project(radiance VERSION 1.8.0 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
+14 -11
View File
@@ -51,15 +51,17 @@ ARG JOBS=
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
build-essential nasm pkg-config ca-certificates curl xz-utils zlib1g-dev libdav1d-dev \
libwebp-dev \
libwebp-dev libopenh264-dev \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /tmp
# Demuxers: media.cpp's kFormats whitelist. Decoders: what those containers carry -- still
# images, H.264 and HEVC (MP4, MOV, HEIF), VP8 and VP9 (WebM, WebP), AV1 through dav1d (WebM, MP4,
# AVIF), MPEG-1/2/4, Theora and the FLV/H.263 family. JPEG XL is recognised and refused by name
# (its only decoder is libjxl's). Encoders: the image output formats of media.cpp encode_image
# (png, jpeg as mjpeg, webp through libwebp). No protocols: media.cpp reads from memory through its
# own I/O context.
# (png, jpeg as mjpeg, webp through libwebp), and a generated video's MP4 (core/mm/mp4.cpp): H.264
# through libopenh264 (BSD-licensed, so the build stays LGPL) and FFmpeg's own AAC, in the mp4
# muxer. No protocols: media.cpp and mp4.cpp read and write memory through their own I/O
# contexts.
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
curl -fsSL "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" -o ffmpeg.tar.xz \
&& echo "${FFMPEG_SHA256} ffmpeg.tar.xz" | sha256sum -c - \
@@ -70,7 +72,7 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
--enable-zlib --enable-libdav1d --enable-libwebp \
--enable-demuxer=mov,matroska,avi,mpegts,flv,ogg,gif,apng,image2pipe,image_png_pipe,image_jpeg_pipe,image_jpegls_pipe,image_jpegxl_pipe,image_webp_pipe,image_bmp_pipe,image_tiff_pipe,image_qoi_pipe,image_pgm_pipe,image_ppm_pipe,image_pbm_pipe,image_pam_pipe,image_gif_pipe,wav,w64,mp3,flac,aac,aiff \
--enable-decoder=h264,hevc,vp8,vp9,libdav1d,mpeg4,mpeg1video,mpeg2video,mjpeg,jpegls,png,apng,gif,webp,bmp,tiff,qoi,pgm,ppm,pbm,pam,pgmyuv,theora,vp3,flv,h263,pcm_u8,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,pcm_s32le,pcm_s32be,pcm_f32le,pcm_f32be,pcm_f64le,pcm_alaw,pcm_mulaw,mp3float,mp2float,flac,vorbis,opus,aac \
--enable-encoder=png,mjpeg,libwebp \
--enable-encoder=png,mjpeg,libwebp,libopenh264,aac --enable-muxer=mp4 --enable-libopenh264 \
--enable-parser=h264,hevc,vp8,vp9,av1,mpeg4video,mpegvideo,mjpeg,png,gif,bmp,webp,vp3,qoi,pnm,h263,jpegxl,mpegaudio,flac,aac,vorbis,opus \
&& make -j"${JOBS:-$(nproc)}" \
&& make install \
@@ -136,11 +138,11 @@ ARG JOBS=
# g++-14 rather than the default 13: hipcc compiles device-side translation units against its
# libstdc++, which is also the runtime image's. gawk: tools/ops_doc_check.sh uses gensub, which
# mawk lacks. libdav1d7 and libwebp7 are the runtime libraries of the ffmpeg stage's AV1 decoder
# and WebP encoder; busybox-static goes into the runtime image.
# 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.
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 busybox-static \
cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 libopenh264-7 busybox-static \
&& rm -rf /var/lib/apt/lists/*
COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg
@@ -207,10 +209,11 @@ ARG JOBS=
# ctest --test-dir /build -L gpu --output-on-failure
# Tests run JOBS at a time (default one per two hardware threads, about one per core on an SMT
# machine: the per-binary CPU budgets in tests/CMakeLists.txt hold for tests that do not share a
# core); the `perf` entries, which assert wall-clock costs, run alone (RUN_SERIAL). The build sandbox forbids io_uring, so avx_check skips its
# file-backed gather case. The `oot` suite (every shipped plugin rebuilt against the installed
# package) repeats this stage's whole compile, so it runs from the development tree instead
# (tests/oot_plugins.sh).
# core); the `perf` entries, which assert wall-clock costs, run alone (RUN_SERIAL). The build
# sandbox forbids io_uring, so avx_check skips its file-backed gather case, and perf_event_open, so
# the tests that bound work count CPU time rather than instructions (tests/work_counter.h). The
# `oot` suite (every shipped plugin rebuilt against the installed package) repeats this stage's
# whole compile, so it runs from the development tree instead (tests/oot_plugins.sh).
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
bash /src/docker/llvm-check.sh /build \
&& ctest --test-dir /build -LE 'gpu|oot' -j"${JOBS:-$(( ($(nproc) + 1) / 2 ))}" --output-on-failure \
+2 -2
View File
@@ -22,8 +22,8 @@ Written by Deadcode, with contributions from:
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, and
--prefill-interleave
jq and a CA bundle in the image with hfget.sh under its busybox, rad-export, --prefill-interleave,
and runtime LoRA adapters served beside the base model and picked per request
- 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
+33 -8
View File
@@ -1,10 +1,10 @@
# radiance
An LLM and image-generation inference server for AMD GPUs, in C++ and HIP. Its HTTP API speaks
OpenAI's chat, completions, Responses and images APIs, Anthropic's Messages API and llama-server's
native one, so their clients and SDKs work unchanged. Model architectures, kernel libraries and
quantisers are `.so` plugins; the ones in this tree are built and loaded the same way a third
party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)).
An inference server for AMD GPUs, in C++ and HIP: language models, and image, video, speech and
music generation. Its HTTP API speaks OpenAI's chat, completions, Responses, images, audio and video
APIs, Anthropic's Messages API and llama-server's native one, so their clients and SDKs work
unchanged. Model architectures, kernel libraries and quantisers are `.so` plugins; the ones in this
tree are built and loaded the same way a third party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)).
The bundled device kernels (`libr4d`) target AMD RDNA4 (`gfx1200`, `gfx1201`). The serve flags
below are for two 32 GB cards (Radeon AI PRO R9700). The engine starts on any AMD GPU family;
@@ -28,6 +28,10 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC
| 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` |
| 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` |
| MiniMax-H3 FP8: video with its stereo soundtrack from text | `minimax-h3-fp8.rad` (60 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-fp8) | `minimax-h3.yaml` |
| FastH3 8-Step V2 FP8: the same in eight steps | `fasth3-8-step-v2-fp8.rad` (62 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-fp8) | `fasth3.yaml` |
| MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `minimax-music3.yaml` |
| Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `breeze-tts2.yaml` |
| Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.yaml` |
| Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` |
| Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` |
@@ -63,6 +67,19 @@ On two R9700s a 2048x2048 picture takes 61 s at the base model's 40 steps and 13
12 s with `--tp-wire wht6`); 1024x1024 takes 6 s and 2.6 s. Qwen-Image 2.1 is under Qwen's research
license, which is non-commercial.
The MiniMax-H3 containers serve OpenAI's video jobs (`/v1/videos`): a video with its stereo
soundtrack from a prompt, 5 to 14 s, up to 1344x768. On two R9700s a 5.17 s clip at 1344x768 takes
about 68 s with FastH3 and 8.8 minutes at MiniMax-H3's 50 steps; both read about 39 GiB of pinned
host memory. 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.
## Run with Docker
The host needs Docker and an `amdgpu` driver that supports ROCm 10.1; it does not need ROCm. The
@@ -141,6 +158,9 @@ four-rank rows have no compose file. The other models' flags are in their compos
| MiniCPM5-2B FP8 and bf16 | `--tp 2 --max-num-seqs 32 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512` |
| Qwen3.8-Flash-Next bf16 | `--tp 2 --max-model-len 32768 --placement expert_tiered --weights-disk-tier --host-pool-mib 12288 --gpu-headroom-mib 768 --deterministic --max-num-seqs 32 --max-num-batched-tokens 32768 --num-speculative-tokens 0` |
| Qwen-Image 2.1 and 2.1 Turbo | `--tp 2 --tp-wire wht6` |
| MiniMax-H3 and FastH3 | `--tp 2 --vision-tower-placement ram` |
| MiniMax-Music3 | `--tp 2` |
| Breeze-TTS-2 | `--tp 1` |
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
@@ -204,15 +224,20 @@ build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-w4a8.ra
build/bin/rad-convert /srv/models/hf/z-lab/Qwen3.8-27B-PARO -o qwen3.8-27b-paro-int4.rad \
--recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe \
--draft-model /srv/models/hf/z-lab/Qwen3.8-27B-DFlash2
build/bin/rad-convert /srv/models/hf/ukisai/Swift-1.5-Qwen3.8-27b-W4A16-AWQ -o swift15-27b-w4a16.rad \
--recipe data/recipes/q38-27b-w4a16.recipe
```
With Docker, use `docker run --rm -v /srv/models:/models --entrypoint rad-convert stilldeadcode/radiance ...`.
In the image the recipes are in `/opt/radiance/share/radiance/recipes/`. A checkpoint served at its
own precision needs no container: `radiance --model /srv/models/hf/Qwen/Qwen3.8-27B-FP8`. A release
someone else quantised is read as it ships when the engine serves its form (block-scaled FP8,
Quark's MXFP4) and converted from its exact dequantisation when it does not: compressed-tensors'
NVFP4 to the MXFP4 kernels, AutoRound and GPTQ int4 to int8. [docs/GUIDE.md](docs/GUIDE.md) names
the recipes of record with their `rad-convert` commands.
Quark's MXFP4), written at its own numbers when the kernels read them in another spelling (an int4
W4A16 release, compressed-tensors' AWQ and GPTQ or AutoRound's, on the 4-bit GEMMs with
`data/recipes/q38-27b-w4a16.recipe`), and converted from its exact dequantisation when no kernel
reads it: NVFP4 (compressed-tensors' and NVIDIA ModelOpt's) to the MXFP4 kernels, an AutoRound
Flash-Next's int4 block projections to int8. [docs/GUIDE.md](docs/GUIDE.md) names the recipes of record
with their `rad-convert` commands.
## Test
+1 -1
View File
@@ -17,7 +17,7 @@ extern "C" {
* kind of plugin reports it, and a plugin that does not report exactly this version is refused at
* load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a
* change of shape: a plugin without it gets the default. */
#define RAD_ABI_VERSION 18u
#define RAD_ABI_VERSION 21u
/* ================================================================== plugin identity */
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
+269 -7
View File
@@ -395,7 +395,8 @@ int rad_op_declared(RadBuilder* b, const char* op);
/* The plugin owns the map from checkpoint tensor names to declared weight names, including
* convert-time fusions (q/k/v into one qkv, gate and up into gate_up). It is the only component
* that knows both sides, and rad-convert reads the map from it (spec §2.4). */
enum { RAD_MAP_COPY = 0, RAD_MAP_CONCAT = 1 };
enum { RAD_MAP_COPY = 0, RAD_MAP_CONCAT = 1, RAD_MAP_WNORM = 2, RAD_MAP_ROWS = 3,
RAD_MAP_TRANSPOSE = 4, RAD_MAP_EMA = 5 };
typedef struct RadNameMap {
const char* declared; /* the name given to rad_decl_weight */
@@ -409,12 +410,37 @@ typedef struct RadNameMap {
* declared weight per expert; this carries the expert index so rad-convert need not parse it
* out of the declared name. */
int src_index[8];
/* RAD_MAP_ROWS only: piece i is rows [src_index[i], src_index[i] + src_rows[i]) of the 2-D (or
* higher, rows along dim 0) tensor src[i]; the pieces join along dim 0. */
int64_t src_rows[8];
} RadNameMap;
/* RAD_MAP_COPY with n_src > 1: the first source present in the container wins. This expresses a
* tied lm_head (output.weight if present, else token_embd.weight), so one plugin covers family
* members that differ only in tying. RAD_MAP_CONCAT with n_src > 1 concatenates all sources along
* concat_dim and requires every one. */
* concat_dim and requires every one.
*
* RAD_MAP_WNORM folds a weight-normalised tensor (torch.nn.utils.weight_norm) into the plain
* weight it stands for: src[0] is the magnitude `weight_g` ([d0, 1, ...]), src[1] the direction
* `weight_v` ([d0, ...]), and the result is g * v / ||v||, the norm taken over every dimension but
* the first. Folded in f32 and stored as the recipe says. A model that applies the
* parametrisation at every forward computes the same weight each time; doing it once at convert
* leaves the plugin an ordinary weight.
*
* RAD_MAP_ROWS keeps only row ranges of its sources (see src_rows), joined: a head read over a
* fraction of a vocabulary (an audio model's codes, a few rows of a text model's 200K) stores that
* fraction rather than the whole table.
*
* 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).
*
* 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
* divided by max(usage, 1e-5), in f32. Successive EMA maps for one name stack their codebooks
* along dim 0, as CONCAT maps extend (a residual quantiser's codebooks as one table).
*
* TRANSPOSE and EMA are computed at convert in f32, like WNORM, and stored as the recipe says. */
int rad_decl_name_map(RadBuilder* b, const RadNameMap* m);
@@ -580,7 +606,7 @@ int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d);
* against its conditioning's KV.
* RAD_GEN_PASS_DECODE one image's latent to pixels, in `image_out`, which the core reads back.
*
* A program declares exactly one of this, logits or pooled vectors.
* A program declares exactly one of this, the other generators, logits or pooled vectors.
*
* The fields are the model's contract with a client: the prompt it was trained on, the sizes it
* makes, its sampler's schedule. The core turns a request into passes from them without naming
@@ -662,6 +688,202 @@ typedef struct RadGeneratorDecl {
int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d);
/* ================================================================== the audio generator */
/* A program that makes audio from text: an autoregressive language model writes the piece frame by
* frame, with classifier-free guidance (each request runs a conditional and an unconditional
* branch in step), and either a denoiser turns the frames' hidden states into audio latents window
* by window, which a vocoder turns into samples, or (`voc_chunk` > 0) a vocoder plays the frames
* themselves a few at a time as they are made. The core drives the passes (RadBatch::gen,
* RadAudioGenBatch):
*
* RAD_GEN_PASS_PROMPT the prompt of one or more requests, both branches, as an ordinary causal
* prefill into the KV group: two sequences a request, the conditional one
* first. A long prompt takes several passes, each a chunk of both branches,
* unless the declaration asks for whole prompts (`prompt_whole`). The pass
* that ends a prompt leaves the branches' last hidden states in the
* request's lane.
* RAD_GEN_PASS_FRAME one frame of every request in its autoregressive stage: the plugin samples
* the frame from the lane's last hidden states, keeps what the denoiser
* conditions on, and runs the language model over the frame's embedding
* (one row a branch, appended to that branch's KV). It writes `status` for
* each lane: >= 0 a frame was made, -1 the model ended the piece instead.
* RAD_GEN_PASS_WINDOW one denoising step of one or more windows, each a run of a request's frames
* (two entries a window with guidance, conditional and unconditional).
* RAD_GEN_PASS_VOCODE one finished window's latents to samples, in `audio_out`, which the core
* reads back; with `voc_chunk`, the frames [voc_frame0, voc_frame0 +
* voc_latents) of one lane, of which the first `voc_left` are context and
* only the rest are played.
*
* Windows overlap: window k covers frames [k win_hop, k win_hop + win_frames) and is stepped once
* the language model has made all of them, or ended. A window joins its predecessor through the
* latents they share, so a request's windows run in order, and window k + 1 does not start before
* window k is vocoded. The last window ends at the last frame; there is a window k >= 1 only while
* frames remain past k win_hop + (win_frames - win_hop), so no window is all overlap.
*
* A program declares exactly one of this, the other generators, logits or pooled vectors. */
enum { RAD_GEN_PASS_PROMPT = 4, RAD_GEN_PASS_FRAME = 5, RAD_GEN_PASS_WINDOW = 6,
RAD_GEN_PASS_VOCODE = 7 };
typedef struct RadAudioGenDecl {
const char* name; /* "minimax-music3" -- the served model id and messages */
/* 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. */
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
* are the same length and step together. */
int32_t neg_token;
int32_t neg_keep_head, neg_keep_tail;
/* The longest prompt in tokens, and the most frames a request makes. */
int64_t max_prompt;
int64_t max_frames;
/* frame_rate_num / frame_rate_den frames a second. */
int64_t frame_rate_num, frame_rate_den;
/* Windows: `win_frames` frames, a new one every `win_hop`. A window of n frames has
* floor(n * lat_num / lat_den) latents of `latent_channels`, and each latent is
* `samples_per_latent` samples of `channels` channels at `sample_rate`. Where two windows meet,
* the earlier one's last `win_crop_right` latents and the later one's first `win_crop_left` are
* not played; the first window keeps its start and the last its end. */
int64_t win_frames, win_hop;
/* Rows the denoiser puts ahead of a window's latents in each entry of a WINDOW pass (a
* timestep token); the core counts them into the pass's rows. */
int64_t win_lead;
int64_t lat_num, lat_den;
int64_t latent_channels;
int64_t win_crop_left, win_crop_right;
int64_t samples_per_latent;
int64_t sample_rate;
int64_t channels;
/* The denoiser's sampler: `default_steps` Euler steps of flow matching from t = 0 (noise) to
* t = 1 (data), t_i = i / steps; guidance `default_cfg` (1 is off), v = u + cfg (c - u). */
int64_t default_steps;
double default_cfg;
/* `max_lanes` requests may be in flight at once, each in a lane of the plugin's state.
* `status` is [>= max_lanes] i32 on the device, indexed by lane (see FRAME above); `audio_out`
* is [>= the samples of the longest window, channels] f32 on the device, interleaved, in
* [-1, 1]: what a VOCODE pass plays, its crops already applied. */
int64_t max_lanes;
rad_buf status;
rad_buf audio_out;
/* The prompt of a request without instructions, `{input}` its only slot; NULL makes the
* instructions required. */
const char* tmpl_plain;
/* The unconditional branch's own template, rendered from the request's texts as `tmpl` is;
* NULL derives it from the conditional prompt by `neg_token` as above. With it the branches
* may differ in length, and a request whose guidance is 1 runs the conditional prompt in both
* (the guided logits are then the conditional ones). */
const char* neg_tmpl;
/* Nonzero: a prompt is never split across PROMPT passes (an encoder that reads it at once);
* the pass rows must hold both branches of the longest. Required with `neg_tmpl`. */
int32_t prompt_whole;
/* The first frame a request keeps: frames before it only move the model past the prompt. */
int32_t first_frame;
/* Nonzero: no denoiser and no windows. The vocoder plays the kept frames as they are made, at
* most `voc_chunk` a VOCODE pass, reading `voc_context` frames before them again (and not
* playing them) so that a causal vocoder needs no state between passes. A frame is then one
* latent: `lat_num` = `lat_den` = 1, `samples_per_latent` samples a frame. */
int64_t voc_chunk;
int64_t voc_context;
} RadAudioGenDecl;
int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d);
/* ================================================================== the video generator */
/* A program that makes a video and its soundtrack from text: a text encoder reads the prompt, one
* denoiser steps a packed sequence holding the prompt's rows, the soundtrack's latents and the
* video's latents together (flow matching, one forward a step, no guidance), and two decoders turn
* the latents into frames and samples. The core drives the passes (RadBatch::gen,
* RadVideoGenBatch), one request a pass:
*
* RAD_GEN_PASS_VCOND the request's prompt, an ordinary non-paged pass over its tokens: the
* text encoder, and what the denoiser reads of the prompt at every step,
* into the request's lane. It carries the request's whole schedule, so
* what depends only on a step's timesteps can be computed once here.
* RAD_GEN_PASS_VSTEP one denoising step of one lane over the packed sequence
* [text | audio | video]: the prompt's rows, then the soundtrack's
* `audio_channels` blocks of latents (channel-major, one row a latent),
* then the video's patches (frame-major, then row-major). The first step
* draws the lane's noise.
* RAD_GEN_PASS_ADECODE the lane's soundtrack to samples in `audio_out`, which the core reads
* back. Runs once, after the last step.
* RAD_GEN_PASS_VDECODE one chunk of the lane's video latents to frames in `frames_out`, which
* the core reads back. Chunks run in order after the soundtrack; each joins
* its predecessor through state the plugin keeps in the lane.
*
* Geometry. A video of n chunks has `frames_per_chunk n + frames_tail` frames at
* `fps_num / fps_den` a second and `latents_per_chunk n + latents_tail` latent frames, each of
* (height / latent_scale) x (width / latent_scale) latents of `latent_channels`; the denoiser
* reads them in `patch` x `patch` patches. Chunk c of n is `frames_per_chunk` frames, the last
* `frames_per_chunk + frames_tail`. A side is a multiple of `size_multiple` pixels, at least
* `min_side`, the area at most `max_area`, and the long side over the short at most `max_aspect`.
* The soundtrack has round(frames / fps * audio_rate) latents a channel, each
* `sample_rate / audio_rate` samples.
*
* The rotary positions of a pass's rows are the plugin's (rad_arch_video_positions), which a video
* generator must export.
*
* The sampler: a request's `steps` are sigma grid points, the terminal 0 included, as diffusers'
* MiniMax-H3 counts them: sigma_i = shift s / (1 + (shift - 1) s) over s = linspace(1, 0, steps)
* in f32 (consecutive duplicates dropped), and a model evaluation at each timestep
* t_i = 1 - sigma_i but the last; one schedule for the video (`shift_video`) and one for the
* soundtrack (`shift_audio`), stepped together. A few-step (distilled) checkpoint instead declares
* the base times it was trained on (`rungs`, below): s = rungs then 0, each taken to f32, the same
* shifts applied, and the step count fixed at n_rungs + 1.
*
* 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 };
typedef struct RadVideoGenDecl {
const char* name; /* "minimax-h3" -- the served model id and messages */
/* The prompt as text the core tokenises, `{prompt}` replaced by the request's; special tokens
* are spelled as text. No beginning-of-sequence token is added. */
const char* tmpl;
int64_t max_text; /* the longest prompt, in tokens */
/* Geometry (above). */
int64_t fps_num, fps_den;
int64_t frames_per_chunk, frames_tail;
int64_t latents_per_chunk, latents_tail, dec_latents;
int64_t min_chunks, max_chunks;
int64_t latent_scale, latent_channels, patch;
int64_t size_multiple, min_side, max_area, max_aspect;
/* The size and length a request that names none is made at. */
int64_t default_width, default_height, default_chunks;
/* The soundtrack. */
int64_t sample_rate, audio_rate, audio_channels, audio_latent_channels;
/* The sampler (above). */
int64_t default_steps, max_steps;
double shift_video, shift_audio;
/* `max_lanes` requests may hold state at once. `frames_out` is [>= the frames of the largest
* chunk, height, width, 3] u8 on the device, the frames a VDECODE pass made, row-major RGB;
* `audio_out` is [>= the samples of the longest soundtrack, audio_channels] f32, interleaved,
* what an ADECODE pass made. */
int64_t max_lanes;
rad_buf frames_out;
rad_buf audio_out;
/* A trained schedule when `n_rungs` > 0: base times strictly decreasing in (0, 1] (a
* trainer's timesteps over its 1000-step clock), each modality's sigmas their shifts as above.
* `default_steps` and `max_steps` are then both n_rungs + 1 and a request may not name another
* count. 0 is the linspace schedule. */
int32_t n_rungs;
const double* rungs;
} RadVideoGenDecl;
int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d);
/* ================================================================== diagnostics */
/* A plugin may annotate the graph dump. Free-form, printed under --debug-graph. */
void rad_note(RadBuilder* b, const char* fmt, ...);
@@ -721,15 +943,26 @@ typedef struct RadArchProbe {
* the engine sizes the audio pass with it (RadBuildCtx::max_audio_frames). 0 is no audio. */
int64_t audio_frames;
/* Nonzero for an image generator (rad_declare_generator): the rows its largest pass carries.
* The engine sizes the step for it before declare (a denoise pass carries all of an image's
* latent rows at once, twice with guidance) and turns off what a generator does not use. 0 is
* a program that generates text or embeds. */
/* Nonzero for a generator (rad_declare_generator, rad_declare_audio_generator): the rows its
* largest pass carries. The engine sizes the step for it before declare (an image's denoise
* pass carries all of its latent rows at once, twice with guidance; an audio window's step all
* of the window's) and turns off what a generator does not use. 0 is a program that
* generates text or embeds. */
int64_t gen_rows;
/* The most patches the generator's conditioning pass encodes: every reference picture a
* request may carry, at the model's resize target. This is the encoder's pass size
* (max_enc_patches). */
int64_t gen_patches;
/* Nonzero for an audio generator, which the engine sizes before declare as it does an image
* generator, with these differences: two sequences a request (its branches), and `gen_ctx`
* the longest a sequence grows (the whole prompt and every frame), which is the context the
* KV group is sized for. */
int32_t gen_audio;
int64_t gen_ctx;
/* Nonzero for a video generator, which the engine sizes as it does an image generator from
* `gen_rows` (its largest pass: a step's packed sequence at the largest size and length). It
* keeps no KV. */
int32_t gen_video;
} RadArchProbe;
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
@@ -900,6 +1133,35 @@ typedef struct RadAudioFormat {
/* Return the format, or NULL when this model serves no speech route. Called once at startup. */
const RadAudioFormat* rad_arch_audio_format(const RadModelMeta* meta);
/* A request's free text rewritten into the form the model was trained on, before it goes into the
* audio generator's prompt template (RadAudioGenDecl::tmpl). Optional: absent, the text goes in
* 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 };
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
* knows. `which` names the pass: RAD_VPOS_STEP, the packed sequence of every VSTEP pass of a
* request of geometry `g` -- its rows, and their rotary positions written to `pos` (f32 [3, rows]
* component-major) when it is non-null and `cap` rows hold them; RAD_VPOS_DECODE, the rows of one
* of its VDECODE passes, whose positions the plugin makes itself (`pos` is not written). Returns
* the rows, or a negative status for a geometry the model cannot take. Called on any thread, so it
* keeps no state. Required of a video generator. */
typedef struct RadVideoGeom {
int32_t n_text; /* the prompt's tokens */
int32_t frames; /* the video's frames */
int32_t lat_frames; /* its latent frames */
int32_t lat_h, lat_w; /* latents a frame, down and across */
int32_t n_audio; /* the soundtrack's latents a channel */
} 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);
int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx);
/* Forward declaration; the signature is in rad_runtime.h. */
struct RadCtx;
+26
View File
@@ -46,4 +46,30 @@ RAD_PHILOX_HD float rad_philox_normal(uint64_t seed, uint64_t e) {
return (j & 1) ? r * sinf(t) : r * cosf(t);
}
/* Element `e` of the standard-normal stream (seed, stream): the counter's upper half is `stream`,
* so stream 0 is rad_philox_normal and each other value an independent stream of the same seed
* (an audio window's noise is stream 1 + its index). */
RAD_PHILOX_HD float rad_philox_normal_s(uint64_t seed, uint64_t stream, uint64_t e) {
const uint64_t g = e >> 2;
uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), (uint32_t)stream, (uint32_t)(stream >> 32) };
rad_philox4x32_10(c, (uint32_t)seed, (uint32_t)(seed >> 32));
const int j = (int)(e & 3u);
const uint32_t wa = c[(j >> 1) * 2], wb = c[(j >> 1) * 2 + 1];
const float ua = ((float)(wa >> 8) + 0.5f) * (1.0f / 16777216.0f);
const float ub = ((float)(wb >> 8) + 0.5f) * (1.0f / 16777216.0f);
const float r = sqrtf(-2.0f * logf(ua));
const float t = 6.28318530717958647692f * ub;
return (j & 1) ? r * sinf(t) : r * cosf(t);
}
/* Element `e` of the uniform stream (seed, stream), in (0, 1): word e % 4 of the counter
* (e / 4, stream) made uniform as the normal stream's words are. A sampler draws its pick from
* it. */
RAD_PHILOX_HD float rad_philox_uniform_s(uint64_t seed, uint64_t stream, uint64_t e) {
const uint64_t g = e >> 2;
uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), (uint32_t)stream, (uint32_t)(stream >> 32) };
rad_philox4x32_10(c, (uint32_t)seed, (uint32_t)(seed >> 32));
return ((float)(c[e & 3u] >> 8) + 0.5f) * (1.0f / 16777216.0f);
}
#endif /* RAD_PHILOX_H */
+166 -4
View File
@@ -55,10 +55,11 @@ typedef struct RadBatch {
* row of a sequence carries its request's slot, fixed when the request was admitted, so a step
* that mixes adapters and the base needs nothing else.
*
* Null when the engine serves no adapters (no --lora and no --max-loras). The core issues the
* adapter ops itself and reads it there; a block with an adapter epilogue of its own reads it
* too. Like every array above it sits at one address per rank for the engine's life and is
* rewritten every step, so a recorded pass replays it. */
* Null on a step with no adapter row, so always when the engine serves no adapters (no --lora
* and no --max-loras). The core issues the adapter ops itself, only when this is set; a block
* with an adapter epilogue of its own reads it too. Like every array above it sits at one
* address per rank for the engine's life and is rewritten every step, so a recorded pass
* replays it. */
const int32_t* lora_slot;
/* The tokens the sampler wants logits for: indices into this step's tokens, [n_out].
@@ -230,6 +231,18 @@ typedef struct RadBatch {
* every step of a program that declared no generator. */
int32_t gen;
const struct RadGenBatch* gen_b;
/* ================================================ audio generation */
/* An audio generator's pass (rad_declare_audio_generator; `gen` is one of its
* RAD_GEN_PASS_*): its payload. Null on every other step. */
const struct RadAudioGenBatch* agen_b;
/* ================================================ video generation */
/* A video generator's pass (rad_declare_video_generator; `gen` is one of its
* RAD_GEN_PASS_*): its payload. Null on every other step. */
const struct RadVideoGenBatch* vgen_b;
} RadBatch;
/* What a generator pass carries beside the step batch's own fields, which keep their meanings:
@@ -312,6 +325,155 @@ enum {
RAD_GEN_F_PREVIEW = 4 /* write the step's estimate of the clean latent to the lane's preview */
};
/* What an audio generator's pass carries beside the step batch's own fields (rad_builder.h,
* RadAudioGenDecl, describes the passes):
*
* PROMPT an ordinary causal prefill: `token_ids`, `positions`, `cu_seqlens` and the KV group's
* slot mapping, block table and seqused, two sequences a lane (2i conditional, 2i + 1
* unconditional). A chunk of a longer prompt is the same with positions that start
* past zero.
* FRAME one row a sequence, two sequences a lane, ordered as PROMPT's: the frame's embedding
* is the plugin's (it samples the frame first), so `token_ids` are zero; `positions`,
* the slot mapping and seqused place the row after its sequence's earlier ones.
* WINDOW one entry per (window, branch): `cu_seqlens` bounds each entry's rows, `win_lead`
* rows of the plugin's own (RadAudioGenDecl::win_lead) and then the window's latent
* rows; positions count from 0 in each entry.
* VOCODE one window, no rows.
*
* Every pointer is device memory unless the name ends in _h. */
typedef struct RadAudioGenBatch {
/* ---- PROMPT and FRAME: the lanes of the pass's requests, in entry order */
int64_t n_lane;
const int32_t* lane; /* [n_lane] */
const int32_t* lane_h;
/* PROMPT: 1 where this pass holds the end of the lane's prompt, so the last rows' hidden
* states are the ones the first frame is sampled from. [n_lane] */
const int32_t* last;
const int32_t* last_h;
/* FRAME: the frame each lane makes, from 0; frames before RadAudioGenDecl::first_frame only
* move the model past the prompt. [n_lane] */
const int32_t* frame;
const int32_t* frame_h;
/* PROMPT, FRAME and WINDOW: each lane's (WINDOW: each entry's) request seed, [n, 2] low word
* first. */
const uint32_t* seed;
/* PROMPT and FRAME, one value per entry ([n_seq]): the entry's row in a state of two rows a
* lane, 2 lane + branch, and the entry's last row in the pass (a prompt chunk's, or a frame's
* one row). */
const int32_t* slot;
const int32_t* last_row;
/* PROMPT: each entry's rows already in the KV before this pass ([n_seq]), the prefix a chunk's
* rows attend to beside their own. */
const int32_t* prefix;
/* ---- WINDOW, one value per entry ([n_seq]) */
const float* t; /* where the entry's latent is, in [0, 1) */
const float* t_next; /* where this step takes it */
const float* cfg; /* v = u + cfg (c - u); 1 without a pair. FRAME: each lane's
* guidance, [n_lane] */
/* The entry holding this window's unconditional branch, or -1 for none; -2 marks an entry
* that is one, whose rows serve another entry's step and which does not move its lane. */
const int32_t* pair;
const int32_t* win_lane; /* the lane the window's request runs in */
const int32_t* win_lane_h;
/* RAD_AGEN_F_*, device and host. */
const int32_t* flags;
const int32_t* flags_h;
/* The window: its index in the request, its first frame and its frames, host and device. */
const int32_t* win_index;
const int32_t* win_index_h;
const int32_t* win_frame0;
const int32_t* win_frame0_h;
const int32_t* win_frames;
const int32_t* win_frames_h;
/* The latent rows apart from the lead rows: [n_seq + 1] offsets over them, and for each the
* row of the pass it is (`lat_rows` of them). */
int64_t lat_rows;
const int32_t* lat_cu;
const int32_t* lat_cu_h;
const int32_t* lat_src;
/* ---- VOCODE */
int32_t voc_lane;
int32_t voc_window;
int32_t voc_latents; /* the window's latents */
int32_t voc_left; /* latents at its start not played */
int32_t voc_right; /* latents at its end not played */
/* 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;
} RadAudioGenBatch;
/* A window entry's flags on a WINDOW pass. FIRST is RAD_GEN_F_FIRST's bit and the others are clear
* of RAD_GEN_F_*'s, so one flags array serves the image generator's sampler ops as well. */
enum {
RAD_AGEN_F_FIRST = 1, /* the window's first step: its latent is the noise its seed draws and
* its conditioning is built from the request's frames */
RAD_AGEN_F_LAST = 8, /* the window's last step: after it the latent is final */
RAD_AGEN_F_JOIN = 16 /* the window has a predecessor whose end it overlaps */
};
/* What a video generator's pass carries beside the step batch's own fields (rad_builder.h,
* RadVideoGenDecl, describes the passes). Every pass is one request's, in lane `lane`:
*
* VCOND `token_ids`, `positions` and `cu_seqlens` are the prompt, one sequence of `n_tok`
* rows, attended causally, nothing paged.
* VSTEP `n_tok` rows: the packed sequence, n_text + audio_channels n_audio + the video's
* patches. No token ids.
* ADECODE no rows of the pass's own.
* VDECODE `dec_rows` rows of the decoder's own (rad_arch_video_positions, RAD_VPOS_DECODE).
*
* Every pointer is device memory unless the name ends in _h. */
typedef struct RadVideoGenBatch {
int32_t lane;
RadVideoGeom geom; /* the request's geometry */
/* The geometry again for ops that read it from an operand, i32 [RAD_VGEOM_N] (below). */
const int32_t* geom_d;
/* 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. */
const int32_t* seg_cu;
const int32_t* lat_cu;
/* ---- VCOND: every step the request takes, the video's timestep and the soundtrack's */
int32_t n_steps;
const float* t_video; /* [n_steps] */
const float* t_audio; /* [n_steps] */
/* ---- 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. */
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. */
const uint32_t* seed;
/* ---- VDECODE */
int32_t chunk; /* from 0, of n_chunks */
int32_t n_chunks;
int64_t dec_rows; /* RAD_VPOS_DECODE */
int32_t n_frames_out; /* frames the pass writes to frames_out */
/* ---- ADECODE */
int64_t n_samples; /* samples a channel the pass writes to audio_out */
} RadVideoGenBatch;
/* 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. */
enum {
RAD_VGEOM_LAT_FRAMES = 0, RAD_VGEOM_LAT_H = 1, RAD_VGEOM_LAT_W = 2, RAD_VGEOM_N_TEXT = 3,
RAD_VGEOM_N_AUDIO = 4, RAD_VGEOM_CHUNK_LAT0 = 5,
RAD_VGEOM_CHUNK_FRAMES = 6, RAD_VGEOM_CHUNK_H = 7, RAD_VGEOM_CHUNK_W = 8,
RAD_VGEOM_CHUNK_FIRST = 9, RAD_VGEOM_CHUNK_LAST = 10,
RAD_VGEOM_PATCH_FRAMES = 11, RAD_VGEOM_PATCH_H = 12, RAD_VGEOM_PATCH_W = 13,
RAD_VGEOM_N = 16
};
/* ================================================================== operands */
/* RAD_OPK_KV names a KV group's pool rather than a buffer: attention and kv_store take the cache
* as an operand, and RadKVGroupBatch carries the slot mapping and block table but not the pool
+52
View File
@@ -51,6 +51,41 @@ inline bool rad_yarn_valid(const RadYarn& y) {
y.high >= y.low && std::isfinite(y.magnitude) && y.magnitude > 0.0f));
}
/* Llama 3's frequency scaling (transformers' rope_type "llama3"), the other static scaling a
* checkpoint may name: a frequency whose wavelength 2 pi / inv is shorter than orig / high is
* kept, one longer than orig / low is divided by `factor`, and those between are blended,
* s = (orig / wavelength - low) / (high - low), (1 - s) inv / factor + s inv. f32 throughout, as
* transformers computes it. `factor` zero is off. */
struct RadLlama3 {
float factor = 0.0f;
float low = 0.0f; /* low_freq_factor */
float high = 0.0f; /* high_freq_factor */
float orig = 0.0f; /* original_max_position_embeddings */
RAD_YARN_HD float frequency(float inv) const {
if (factor == 0.0f) return inv;
const float wavelen = 6.28318530717958647692f / inv;
if (wavelen < orig / high) return inv;
if (wavelen > orig / low) return inv / factor;
const float sm = (orig / wavelen - low) / (high - low);
return (1.0f - sm) * inv / factor + sm * inv;
}
};
inline RadLlama3 rad_llama3_args(const RadArgs* a) {
const float factor = (float)rad_args_getf_or(a, "llama3_factor", 0.0);
if (factor == 0.0f) return {};
return { factor, (float)rad_args_getf_or(a, "llama3_low", 0.0),
(float)rad_args_getf_or(a, "llama3_high", 0.0),
(float)rad_args_getf_or(a, "llama3_orig", 0.0) };
}
inline bool rad_llama3_valid(const RadLlama3& l) {
return std::isfinite(l.factor) &&
(l.factor == 0.0f || (l.factor >= 1.0f && l.low > 0.0f && l.high > l.low &&
std::isfinite(l.high) && l.orig > 0.0f && std::isfinite(l.orig)));
}
#undef RAD_YARN_HD
#else /* C */
@@ -82,6 +117,23 @@ static inline RadYarn rad_yarn_args(const RadArgs* a) {
return y;
}
typedef struct RadLlama3 {
float factor; /* zero: off */
float low;
float high;
float orig;
} RadLlama3;
static inline float rad_llama3_frequency(const RadLlama3* l, float inv) {
float wavelen, sm;
if (l->factor == 0.0f) return inv;
wavelen = 6.28318530717958647692f / inv;
if (wavelen < l->orig / l->high) return inv;
if (wavelen > l->orig / l->low) return inv / l->factor;
sm = (l->orig / wavelen - l->low) / (l->high - l->low);
return (1.0f - sm) * inv / l->factor + sm * inv;
}
static inline int rad_yarn_valid(const RadYarn* y) {
return isfinite(y->factor) && (y->factor == 0.0f ||
(y->factor >= 1.0f && isfinite(y->low) && isfinite(y->high) && y->high >= y->low &&
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/breeze -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(breeze LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(breeze architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/breeze.cpp)
File diff suppressed because it is too large. Load diff
+42
View File
@@ -417,6 +417,48 @@ inline RadNameMap map_base(const char* declared, int mode) {
return m;
}
/* Row ranges of checkpoint tensors joined along dim 0 (RAD_MAP_ROWS): each piece is (source,
* first row, rows). */
struct RowPiece { const char* src; int first; int64_t rows; };
inline int map_rows(RadBuilder* b, const char* declared, std::initializer_list<RowPiece> pieces) {
RadNameMap m = map_base(declared, RAD_MAP_ROWS);
for (const RowPiece& p : pieces) {
if (m.n_src >= 8) return RAD_E_INVAL;
m.src[m.n_src] = p.src;
m.src_index[m.n_src] = p.first;
m.src_rows[m.n_src] = p.rows;
++m.n_src;
}
return rad_decl_name_map(b, &m);
}
/* A weight-normalised checkpoint tensor folded into its plain weight (RAD_MAP_WNORM). */
inline int map_wnorm(RadBuilder* b, const char* declared, const char* g, const char* v) {
RadNameMap m = map_base(declared, RAD_MAP_WNORM);
m.n_src = 2;
m.src[0] = g;
m.src[1] = v;
return rad_decl_name_map(b, &m);
}
/* A linear the checkpoint keeps as (in, out), read as (out, in): src's last two dimensions
* swapped (RAD_MAP_TRANSPOSE). */
inline int map_transpose(RadBuilder* b, const char* declared, const char* src) {
RadNameMap m = map_base(declared, RAD_MAP_TRANSPOSE);
m.n_src = 1;
m.src[0] = src;
return rad_decl_name_map(b, &m);
}
/* An EMA codebook: the embedding sums over max(cluster usage, 1e-5), row by row (RAD_MAP_EMA). */
inline int map_ema(RadBuilder* b, const char* declared, const char* sums, const char* usage) {
RadNameMap m = map_base(declared, RAD_MAP_EMA);
m.n_src = 2;
m.src[0] = sums;
m.src[1] = usage;
return rad_decl_name_map(b, &m);
}
/* A checkpoint tensor copied through unchanged. */
inline int map_copy(RadBuilder* b, const char* declared, const char* src) {
RadNameMap m = map_base(declared, RAD_MAP_COPY);
+3 -3
View File
@@ -98,9 +98,9 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
RAD_ARCH_TRY(down.probe(b, nm, g, down_base, { src.down }));
RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0, down.reads_x));
/* The fold (decl_gated_fold), an fp8a8 tile, so bf16, MXFP4 and rotated 5-bit gate_up weights
* take the pair. */
if (!gate_up.bf16 && !gate_up.mx && !gate_up.paro5)
/* The fold (decl_gated_fold), an fp8a8 tile, so bf16, MXFP4, rotated 5-bit and 4-bit gate_up
* weights take the pair. */
if (!gate_up.bf16 && !gate_up.mx && !gate_up.paro5 && !gate_up.w4)
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
+139 -13
View File
@@ -631,6 +631,14 @@ struct LinearFP8 {
/* The 5-bit sibling: the same rotation to f16 (`rot_q` is the f16 plane, no `rot_s`), then
* 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)
* (`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;
/* 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` /
@@ -650,6 +658,10 @@ struct LinearFP8 {
* 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 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(). */
int access = RAD_ACCESS_PER_TOKEN;
/* Declares the name map and reads the weight's format (reads_x, probed_i8). `base` and `src`
* are the same as for declare(). */
@@ -778,6 +790,19 @@ inline bool linear_is_paro_mxfp4(const RadEncoding& e) {
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->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. */
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");
return e.plane[0].dtype == RAD_U4 && 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_U4 || zp->dtype == RAD_U8) && zp->block[0] == 1 &&
zp->block[1] == RAD_FP8_BLOCK;
}
/* A rotated weight with ParoQuant int5 (u5) or z-lab int4 (u4) asymmetric codes: an f16 scale and
* u8 zero point per 128 of K. Read by gemm_nt_q at w5a16 / w4a16_asym over an f16 activation, or
* w5a8i8 / w4a8i8_asym over an int8 one. */
@@ -799,9 +824,10 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char*
const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
enc.plane[0].dtype == RAD_BF16;
probed_i8 = known && linear_is_w8(enc);
/* A rotated weight rotates and quantises the bf16 plane itself. */
/* 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));
reads_x = g.w_bf16 || plain || probed_i8 || rotated;
reads_x = g.w_bf16 || plain || probed_i8 || rotated || (known && linear_is_w4(enc));
return RAD_OK;
}
@@ -941,7 +967,7 @@ 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"));
w = decl_w_n(b, wn, RAD_BF16, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, 0, rp.w, rp.n);
w = decl_w_n(b, wn, RAD_BF16, { N, K }, access, shard, grp, 0, rp.w, rp.n);
if (!w) return RAD_E_INVAL;
if (span_hi > 0) RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi));
op = rw(b, RAD_OP(b, "gemm_nt",
@@ -973,9 +999,9 @@ 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 }, RAD_ACCESS_PER_TOKEN, shard, grp,
w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, access, shard, grp,
rp.w, rp.n);
ws = decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, RAD_ACCESS_PER_TOKEN,
ws = 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) {
@@ -1042,10 +1068,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
if (!rot_q) return RAD_E_INVAL;
op_rot = decl_rot_op(b, g, a, 1, f16_hi, { rot_q });
if (!op_rot) return RAD_E_INVAL;
w = decl_view(b, wn, nullptr, "codes", enc.plane[0].dtype, { N, K }, RAD_ACCESS_PER_TOKEN,
w = decl_view(b, wn, nullptr, "codes", enc.plane[0].dtype, { N, K }, access,
shard, grp);
ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K },
RAD_ACCESS_PER_TOKEN, shard, grp);
access, shard, grp);
if (!w || !ws) return RAD_E_INVAL;
op = decl_gemm_q(b, 1, f16_hi, RAD_FP8_BLOCK, bits5 ? "w5a16" : "w4a16_asym",
pb1, pb2, { w, ws }, { rot_q }, y);
@@ -1067,6 +1093,71 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
return RAD_OK;
}
/* ---- 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
* (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 (!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);
return RAD_E_DTYPE;
}
if (N % 16 || K % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; a 4-bit weight takes rows in "
"16s and K in whole %d-column groups\n",
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
RowParts rp;
RAD_ARCH_TRY(rp.set(row_parts, 1, 1, base, "rows"));
w = decl_view(b, wn, nullptr, "codes", RAD_U4, { N, K }, access, shard, grp, rp.w, rp.n);
ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K }, access,
shard, grp, rp.w, rp.n);
if (!w || !ws) return RAD_E_INVAL;
if (span_hi > 0) {
if (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, w, span_lo, span_hi));
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, span_lo, span_hi));
}
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;
if (hi > kSplit) {
w4_split = kSplit;
a8q = decl_b(b, nm.f("%s.a8q", base), RAD_I8, { hi, K });
a8s = decl_b(b, nm.f("%s.a8s", base), RAD_F32, { hi, K / RAD_FP8_BLOCK });
if (!a8q || !a8s) return RAD_E_INVAL;
op_q = rw(b, RAD_OP(b, "quant_act_i8g",
RAD_PARAMS(RAD_RANGE("M", kSplit + 1, hi), RAD_INT("n", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ a.x }, { a8q, a8s });
op2 = decl_gemm_q(b, kSplit + 1, hi, RAD_FP8_BLOCK, "w4a8i8_asym", 0, 0, { w, ws },
{ a8q, a8s }, y);
if (!op_q || !op2) return RAD_E_INVAL;
}
return RAD_OK;
}
/* The remaining formats read the E4M3 pair, which an int8-fed input lacks (a trunk mixing
* formats that the model's probe did not detect). */
if (a.q8_fed) {
@@ -1125,12 +1216,12 @@ 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 }, RAD_ACCESS_PER_TOKEN,
w = decl_view(b, wn, nullptr, "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 },
RAD_ACCESS_PER_TOKEN, shard, grp, rp.w, rp.n);
access, shard, grp, rp.w, rp.n);
wref = decl_view(b, rn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
RAD_ACCESS_PER_TOKEN, shard, grp, rp.w, rp.n);
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;
@@ -1152,6 +1243,23 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
return op ? RAD_OK : RAD_E_INVAL;
}
/* Block fp8 is the last form; any other encoding is refused by name with the ones read. */
if (known) {
const RadEncPlane* sc = rad_enc_plane(&enc, "scale");
if (!rad_enc_is(&enc, "affine") || enc.n_planes != 2 || enc.transform[0] ||
enc.plane[0].dtype != RAD_F8E4M3 || !sc || sc->dtype != RAD_BF16 ||
sc->block[0] != RAD_FP8_BLOCK || sc->block[1] != RAD_FP8_BLOCK) {
char en[256];
rad_enc_format(&enc, en, sizeof en);
fprintf(stderr, "radiance: '%s' is %s, which this model's linears do not read; they "
"read bf16, fp8_e4m3*bf16[128x128], i8*bf16[1x128], "
"fp4_e2m1*e8m0[1x32], u4*f16[1x128]-u4[1x128] (or a u8 zero) and the "
"ParoQuant forms. A recipe rule stores the weight in one of them "
"(docs/TOOLS.md, the import rule for a shipped int4 grid)\n", wn, en);
return RAD_E_DTYPE;
}
}
/* Block fp8: per-rank extents must be whole scale blocks, checked here to name the weight (this
* also catches a tensor-parallel width that cuts a block). */
if (N % RAD_FP8_BLOCK || K % RAD_FP8_BLOCK) {
@@ -1173,10 +1281,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
/* 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 },
RAD_ACCESS_PER_TOKEN, shard, grp, rp.w, rp.n);
access, shard, grp, rp.w, rp.n);
ws_row_div = RAD_FP8_BLOCK;
ws = decl_view(b, sn, wn, "scale", RAD_BF16, { fp8_blocks(N), fp8_blocks(K) },
RAD_ACCESS_PER_TOKEN, shard, grp, rp.s, rp.n);
access, shard, grp, rp.s, rp.n);
if (!w || !ws) return RAD_E_INVAL;
/* An uneven slice; the scale plane takes the same slice in blocks. */
if (span_hi > 0) {
@@ -1222,6 +1330,22 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
RAD_W(w), RAD_W(ws), brow_slice(y, r0, 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
* between the two ops issued here. */
if (w4 && w4_split && rows > w4_split) {
RAD_ISSUE_N(c, op_q, rows, brow_slice(a.x, r0, rows, K), brow_slice(a8q, 0, rows, K),
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);
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);
return;
}
if (paro5 && rot_split && rows > rot_split) {
RAD_ISSUE_N(c, op_rot2, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_dense),
RAD_W(rot_scale), brow_slice(rot_q2, r0, rows, rot_parts * K),
@@ -1275,6 +1399,8 @@ struct DenseFP8 {
* works against the same E4M3 activation pair. */
rad_weight ref = 0;
bool mx = false;
/* The caller made the name map (a row range of a checkpoint tensor); declare() does not. */
bool mapped = false;
int declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K,
int access, int shard, RadWeightGroup grp,
@@ -1309,7 +1435,7 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
* 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);
RAD_ARCH_TRY(map_linear(b, wn, src));
if (!mapped) RAD_ARCH_TRY(map_linear(b, wn, src));
RadEncoding enc{};
mx = weight_enc(b, wn, &enc) && linear_is_mxfp4(enc);
if (mx) {
+5 -3
View File
@@ -443,11 +443,12 @@ struct Audio {
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_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_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));
@@ -477,7 +478,8 @@ struct Audio {
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_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);
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/minimaxh3 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(minimaxh3 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(minimaxh3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/minimaxh3.cpp)
File diff suppressed because it is too large. Load diff
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/minimaxmusic3 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(minimaxmusic3 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(minimaxmusic3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/minimaxmusic3.cpp)
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -1399,12 +1399,13 @@ static void step_blocks(RadCtx* c, const Model& m, int64_t R, int64_t S, const R
brows(m.b_ks, R));
RAD_ISSUE(c, L.op_attn_q, bcol(m.b_qkv, 0, qd, R), bcol(m.b_qkv, qd, qd, R),
bcol(m.b_qkv, 2 * qd, qd, R), kv_cache(m.kv, (int)l), bt, used, cu, RAD_NONE,
RAD_NONE, brows(m.b_k8, R), brows(m.b_ks, R), brows(m.a_attn.x, R));
RAD_NONE, brows(m.b_k8, R), brows(m.b_ks, R), brows(m.a_attn.x, R),
RAD_NONE);
} else {
RAD_ISSUE(c, causal ? L.op_attn_c : L.op_attn_b, bcol(m.b_qkv, 0, qd, R),
bcol(m.b_qkv, qd, qd, R), bcol(m.b_qkv, 2 * qd, qd, R),
kv_cache(m.kv, (int)l), bt, used, cu, RAD_NONE, RAD_NONE, RAD_NONE, RAD_NONE,
brows(m.a_attn.x, R));
brows(m.a_attn.x, R), RAD_NONE);
}
/* Each wait below is for the all-reduce lane 1 holds last, which is the one lane 0 reads
* next: the second half's projection runs under the first half's reduction, the first
+8 -6
View File
@@ -127,6 +127,8 @@ public:
int drafter_shared_kv(int pos_offset);
int declare_encoder(const RadEncoderDecl* d);
int declare_generator(const RadGeneratorDecl* d);
int declare_audio_generator(const RadAudioGenDecl* d);
int declare_video_generator(const RadVideoGenDecl* d);
void note_v (const char* f, va_list ap);
/* An op's buffer operands (rad_op_reads/rad_op_writes in rad_builder.h), which give the
@@ -159,13 +161,13 @@ public:
* an io_uring ring, which must not stop a sandboxed conversion. */
void set_instances(bool on) { instances_ = on; }
/* RUNTIME LoRA (core/lora/): the HF module leaves an adapter may target. Set before the
* plugin declares, so a FUSED GEMM over a targeted weight -- a GEMM no adapter delta can ride
* on, the gated gate_up fold -- is declined as it is declared and the plugin emits the unfused
* chain it already has for a library without the fused kernel. Null: nothing is declined. */
/* Runtime LoRA (core/lora/): the HF module leaves an adapter may target. Set before the plugin
* declares, so a fused GEMM over a targeted weight (the gated gate_up fold), which leaves no
* output for the delta, is declined as it is declared and the plugin emits the unfused chain it
* has for a library without the fused kernel. Null: nothing is declined. */
void set_lora_targets(const std::set<std::string>* t) { lora_targets_ = t; }
/* The read and write sets an op declared (rad_op_reads / rad_op_writes), for the LoRA declare,
* which needs the dtypes of the activation and the output a targeted GEMM was declared over. */
/* The read and write sets an op declared (rad_op_reads / rad_op_writes): the LoRA declare reads
* the dtypes of a targeted GEMM's activation and output from them. */
const std::vector<rad_buf>& op_read_set (rad_op h) const { return op_bufs_[h].reads; }
const std::vector<rad_buf>& op_write_set(rad_op h) const { return op_bufs_[h].writes; }
+331 -21
View File
@@ -703,12 +703,12 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
}
}
/* RUNTIME LoRA: A FUSED GEMM OVER A TARGETED WEIGHT IS DECLINED. Every `gemm_*` op other than
* the four an adapter delta can follow (lora::op_is_site) fuses something into its epilogue --
* the gated fold quantises the SiLU product in place -- so the delta has no y to land in. The
* op is recorded resolved to nothing, exactly as a library without the kernel would leave it,
* and the plugin falls back to the unfused chain it emits for that library. The decision reads
* only the weight's own declaration and name map, so the sizing declare makes the same one. */
/* Runtime LoRA: a fused GEMM over a targeted weight is declined. Every `gemm_*` op other than
* the four an adapter delta can follow (lora::op_is_site) fuses something into its epilogue
* (the gated fold quantises the SiLU product in place), so the delta has no y to land in. The
* op is recorded unresolved, as a library without the kernel would leave it, and the plugin
* runs its unfused chain. The decision reads only the weight's own declaration and name map,
* so the sizing declare makes the same one. */
bool lora_declined = false;
if (lora_targets_ && n_w > 0 && oi.op.rfind("gemm_", 0) == 0 && oi.op != "gemm_nt" &&
oi.op != "gemm_nt_bias" && oi.op != "gemm_nt_q" && oi.op != "gemm_nt_q_bias") {
@@ -726,10 +726,10 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
"output for the adapter's delta (the plugin runs the unfused chain)";
oi.bands.assign(1, none);
oi.lora_declined = true;
/* AND IT OWNS NO WEIGHT. The planner, the layout pass and the weight-use bookkeeping all
* read an op's weights, and an op with no kernel anywhere would tell the planner the weight
* cannot be read on the card -- moving the gate_up the unfused chain multiplies on the card
* off it. The op stays in the list, by name, so the sizing declare lines up. */
/* It owns no weight: the planner reads an op's weights, and an op with no kernel anywhere
* would tell it the weight cannot be read on the card, moving the gate_up the unfused
* chain multiplies off the card. The op stays in the list by name so the sizing declare
* lines up. */
oi.weights.clear();
oi.weight_opd.clear();
prog_.ops.push_back(std::move(oi));
@@ -939,10 +939,23 @@ int Builder::decl_name_map(const RadNameMap* m) {
err(RAD_E_INVAL, "name map for '%s': %d source tensors, 1..8 allowed", m->declared, m->n_src);
return RAD_E_INVAL;
}
if (m->mode != RAD_MAP_COPY && m->mode != RAD_MAP_CONCAT) {
if (m->mode != RAD_MAP_COPY && m->mode != RAD_MAP_CONCAT && m->mode != RAD_MAP_WNORM &&
m->mode != RAD_MAP_ROWS && m->mode != RAD_MAP_TRANSPOSE && m->mode != RAD_MAP_EMA) {
err(RAD_E_INVAL, "name map for '%s': unknown mode %d", m->declared, m->mode);
return RAD_E_INVAL;
}
if ((m->mode == RAD_MAP_WNORM || m->mode == RAD_MAP_EMA) && m->n_src != 2) {
err(RAD_E_INVAL, "name map for '%s': a %s map names two sources (%s), not %d",
m->declared, m->mode == RAD_MAP_EMA ? "codebook" : "weight-norm",
m->mode == RAD_MAP_EMA ? "the embedding sums and the cluster usage"
: "the magnitude and the direction", m->n_src);
return RAD_E_INVAL;
}
if (m->mode == RAD_MAP_TRANSPOSE && m->n_src != 1) {
err(RAD_E_INVAL, "name map for '%s': a transpose map names one source, not %d",
m->declared, m->n_src);
return RAD_E_INVAL;
}
RadNameMap c{};
c.declared = intern(scoped(m->declared));
@@ -961,6 +974,14 @@ int Builder::decl_name_map(const RadNameMap* m) {
* also map_base() in arch/common/rad_arch.h), so every map would ask for slice 0. */
for (int i = 0; i < m->n_src; ++i) c.src_index[i] = m->src_index[i];
for (int i = m->n_src; i < 8; ++i) c.src_index[i] = -1;
for (int i = 0; i < 8; ++i) c.src_rows[i] = i < m->n_src ? m->src_rows[i] : 0;
if (m->mode == RAD_MAP_ROWS)
for (int i = 0; i < m->n_src; ++i)
if (m->src_index[i] < 0 || m->src_rows[i] <= 0) {
err(RAD_E_INVAL, "name map for '%s': row piece %d starts at %d and holds %lld rows",
m->declared, i, m->src_index[i], (long long)m->src_rows[i]);
return RAD_E_INVAL;
}
/* A CONCAT map may be declared in pieces; any other repeat is an error.
*
@@ -975,10 +996,12 @@ int Builder::decl_name_map(const RadNameMap* m) {
auto seen = name_map_first_.find(c.declared);
if (seen != name_map_first_.end()) {
const RadNameMap& first = prog_.name_map[seen->second];
if (c.mode != RAD_MAP_CONCAT || first.mode != RAD_MAP_CONCAT) {
err(RAD_E_INVAL, "name map for '%s': declared twice, and only a CONCAT map may be "
"extended -- a repeated COPY map means two sources for one weight, and "
"which one wins is not something a declaration can express",
const bool joins = (c.mode == RAD_MAP_CONCAT && first.mode == RAD_MAP_CONCAT) ||
(c.mode == RAD_MAP_EMA && first.mode == RAD_MAP_EMA);
if (!joins) {
err(RAD_E_INVAL, "name map for '%s': declared twice, and only a CONCAT or EMA map may "
"be extended -- a repeated COPY map means two sources for one weight, "
"and which one wins is not something a declaration can express",
c.declared);
return RAD_E_INVAL;
}
@@ -1022,6 +1045,16 @@ int Builder::declare_logits(rad_buf b) {
prog_.gen_str.name.c_str());
return RAD_E_STATE;
}
if (prog_.is_audio_generator()) {
err(RAD_E_STATE, "declare_logits: this program already declared the audio generator '%s'",
prog_.agen_str.name.c_str());
return RAD_E_STATE;
}
if (prog_.is_video_generator()) {
err(RAD_E_STATE, "declare_logits: this program already declared the video generator '%s'",
prog_.vgen_str.name.c_str());
return RAD_E_STATE;
}
prog_.logits_buf = b;
return RAD_OK;
}
@@ -1052,6 +1085,16 @@ int Builder::declare_pooled(rad_buf b) {
prog_.gen_str.name.c_str());
return RAD_E_STATE;
}
if (prog_.is_audio_generator()) {
err(RAD_E_STATE, "declare_pooled: this program already declared the audio generator '%s'",
prog_.agen_str.name.c_str());
return RAD_E_STATE;
}
if (prog_.is_video_generator()) {
err(RAD_E_STATE, "declare_pooled: this program already declared the video generator '%s'",
prog_.vgen_str.name.c_str());
return RAD_E_STATE;
}
const RadBufDecl& d = prog_.buffers[b].decl;
if (d.dtype != RAD_F32 || d.domain != RAD_DOMAIN_DEVICE || d.rank != 2 ||
d.shape[0] < prog_.ctx.max_seqs || d.shape[1] <= 0) {
@@ -1140,10 +1183,13 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
prog_.gen_str.name.c_str(), nm);
return RAD_E_STATE;
}
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE) {
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
prog_.is_audio_generator() || prog_.is_video_generator()) {
err(RAD_E_STATE, "declare_generator '%s': this program already declared %s; a program "
"generates text, embeds or makes images -- one of the three", nm,
prog_.logits_buf != RAD_NULL_HANDLE ? "logits" : "a pooled output");
"generates text, embeds, makes images, audio or video -- one of the five",
nm, prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
: prog_.is_audio_generator() ? "an audio generator" : "a video generator");
return RAD_E_STATE;
}
if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID) {
@@ -1224,6 +1270,258 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
return RAD_OK;
}
/* Validated at declare for the reason the image generator is: a buffer too small for the longest
* window, or a window that never ends, would otherwise show at the first request. */
int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
if (finished_) {
err(RAD_E_STATE, "declare_audio_generator after declare finished");
return RAD_E_STATE;
}
if (!d) { err(RAD_E_INVAL, "declare_audio_generator: null declaration"); return RAD_E_INVAL; }
const char* nm = d->name && *d->name ? d->name : "(unnamed)";
if (prog_.is_audio_generator()) {
err(RAD_E_STATE, "declare_audio_generator: '%s' was already declared; '%s' is a second one",
prog_.agen_str.name.c_str(), nm);
return RAD_E_STATE;
}
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
prog_.generator.layout != 0 || prog_.is_video_generator()) {
err(RAD_E_STATE, "declare_audio_generator '%s': this program already declared %s; a "
"program generates text, embeds, makes images, audio or video -- one of "
"the five", nm,
prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
: 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}")) {
err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl needs {instructions} and {input}", nm);
return RAD_E_INVAL;
}
if (d->tmpl_plain &&
(!std::strstr(d->tmpl_plain, "{input}") || std::strstr(d->tmpl_plain, "{instructions}"))) {
err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl_plain is the prompt without "
"instructions and needs {input} alone", nm);
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 "
"prompt_whole", nm);
return RAD_E_INVAL;
}
if (d->max_prompt <= 0 || d->first_frame < 0 ||
(!d->neg_tmpl && (d->neg_keep_head < 0 || d->neg_keep_tail < 0 || d->neg_token < 0 ||
d->neg_keep_head + d->neg_keep_tail >= d->max_prompt))) {
err(RAD_E_INVAL, "declare_audio_generator '%s': the prompt is out of range (at most %lld "
"tokens, unconditional branch token %d keeping %d + %d)", nm,
(long long)d->max_prompt, (int)d->neg_token, (int)d->neg_keep_head,
(int)d->neg_keep_tail);
return RAD_E_INVAL;
}
const bool chunked = d->voc_chunk > 0;
if (chunked && (d->voc_context < 0 || d->lat_num != 1 || d->lat_den != 1)) {
err(RAD_E_INVAL, "declare_audio_generator '%s': a vocoder that plays frames as they are "
"made reads a frame as one latent (lat_num = lat_den = 1) and a context "
"of >= 0 frames; got %lld/%lld and %lld", nm, (long long)d->lat_num,
(long long)d->lat_den, (long long)d->voc_context);
return RAD_E_INVAL;
}
if (d->max_frames <= 0 || d->frame_rate_num <= 0 || d->frame_rate_den <= 0 ||
(!chunked && (d->win_frames <= 0 || d->win_hop <= 0 || d->win_hop > d->win_frames ||
d->win_lead < 0 || d->latent_channels <= 0 || d->win_crop_left < 0 ||
d->win_crop_right < 0)) ||
d->lat_num <= 0 || d->lat_den <= 0 || d->samples_per_latent <= 0 || d->sample_rate <= 0 ||
d->channels <= 0 || d->max_lanes <= 0) {
err(RAD_E_INVAL, "declare_audio_generator '%s': a geometry field is out of range (%lld "
"frames at %lld/%lld a second, windows of %lld every %lld, %lld lead "
"rows, %lld/%lld latents a frame of %lld channels, crops %lld + %lld, "
"%lld samples a latent at %lld Hz x %lld, %lld lanes)", nm,
(long long)d->max_frames, (long long)d->frame_rate_num, (long long)d->frame_rate_den,
(long long)d->win_frames, (long long)d->win_hop, (long long)d->win_lead,
(long long)d->lat_num, (long long)d->lat_den, (long long)d->latent_channels,
(long long)d->win_crop_left, (long long)d->win_crop_right,
(long long)d->samples_per_latent, (long long)d->sample_rate, (long long)d->channels,
(long long)d->max_lanes);
return RAD_E_INVAL;
}
/* A middle window plays what is left after both crops, so they must leave some of it. */
if (!chunked &&
d->win_crop_left + d->win_crop_right >= d->win_frames * d->lat_num / d->lat_den) {
err(RAD_E_INVAL, "declare_audio_generator '%s': the crops (%lld + %lld latents) leave a "
"window of %lld latents nothing to play", nm, (long long)d->win_crop_left,
(long long)d->win_crop_right, (long long)(d->win_frames * d->lat_num / d->lat_den));
return RAD_E_INVAL;
}
if ((!chunked && d->default_steps <= 0) || !(d->default_cfg >= 1.0)) {
err(RAD_E_INVAL, "declare_audio_generator '%s': the sampler is incomplete (%lld default "
"steps, guidance %g)", nm, (long long)d->default_steps, d->default_cfg);
return RAD_E_INVAL;
}
auto buf_ok = [&](rad_buf h, uint32_t dtype, int64_t numel, const char* what) {
if (h == RAD_NULL_HANDLE || (size_t)h >= prog_.buffers.size()) {
err(RAD_E_INVAL, "declare_audio_generator '%s': %s %u is not a declared buffer", nm,
what, (unsigned)h);
return false;
}
const RadBufDecl& ob = prog_.buffers[h].decl;
if (ob.dtype != dtype || ob.domain != RAD_DOMAIN_DEVICE ||
decl_numel(ob.rank, ob.shape) < numel) {
err(RAD_E_INVAL, "declare_audio_generator '%s': %s '%s' must be a device %s buffer of "
"at least %lld elements", nm, what, prog_.buffers[h].name.c_str(),
dtype == RAD_I32 ? "i32" : "f32", (long long)numel);
return false;
}
return true;
};
/* audio_out holds what one VOCODE pass plays: a window, or a chunk of frames. */
const int64_t win_samples = (chunked ? d->voc_chunk : d->win_frames * d->lat_num / d->lat_den) *
d->samples_per_latent;
if (!buf_ok(d->status, RAD_I32, d->max_lanes, "status") ||
!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_plain = d->tmpl_plain ? d->tmpl_plain : "";
prog_.agen_str.neg_tmpl = d->neg_tmpl ? d->neg_tmpl : "";
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;
return RAD_OK;
}
/* Validated at declare for the reasons the other generators are: an output buffer too small for
* the largest chunk or the longest soundtrack, or a geometry whose frame count does not follow
* from its chunks, would otherwise show at the first request. */
int Builder::declare_video_generator(const RadVideoGenDecl* d) {
if (finished_) {
err(RAD_E_STATE, "declare_video_generator after declare finished");
return RAD_E_STATE;
}
if (!d) { err(RAD_E_INVAL, "declare_video_generator: null declaration"); return RAD_E_INVAL; }
const char* nm = d->name && *d->name ? d->name : "(unnamed)";
if (prog_.is_video_generator()) {
err(RAD_E_STATE, "declare_video_generator: '%s' was already declared; '%s' is a second one",
prog_.vgen_str.name.c_str(), nm);
return RAD_E_STATE;
}
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
prog_.generator.layout != 0 || prog_.is_audio_generator()) {
err(RAD_E_STATE, "declare_video_generator '%s': this program already declared %s; a "
"program generates text, embeds, makes images, audio or video -- one of "
"the five", nm,
prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
: prog_.generator.layout != 0 ? "an image generator" : "an audio generator");
return RAD_E_STATE;
}
if (!d->tmpl || !std::strstr(d->tmpl, "{prompt}") || d->max_text <= 0) {
err(RAD_E_INVAL, "declare_video_generator '%s': tmpl needs {prompt} and max_text a "
"length (%lld)", nm, (long long)d->max_text);
return RAD_E_INVAL;
}
if (d->fps_num <= 0 || d->fps_den <= 0 || d->frames_per_chunk <= 0 || d->frames_tail < 0 ||
d->latents_per_chunk <= 0 || d->latents_tail < 0 || d->dec_latents < d->latents_per_chunk ||
d->min_chunks <= 0 || d->max_chunks < d->min_chunks || d->default_chunks < d->min_chunks ||
d->default_chunks > d->max_chunks ||
d->latents_per_chunk * (d->max_chunks - 1) + d->dec_latents >
d->latents_per_chunk * d->max_chunks + d->latents_tail) {
err(RAD_E_INVAL, "declare_video_generator '%s': the temporal geometry is out of range "
"(%lld/%lld fps, %lld n + %lld frames over %lld n + %lld latents, chunks of "
"%lld latents, %lld..%lld chunks, %lld by default)", nm,
(long long)d->fps_num, (long long)d->fps_den, (long long)d->frames_per_chunk,
(long long)d->frames_tail, (long long)d->latents_per_chunk, (long long)d->latents_tail,
(long long)d->dec_latents, (long long)d->min_chunks, (long long)d->max_chunks,
(long long)d->default_chunks);
return RAD_E_INVAL;
}
const int64_t unit = d->latent_scale * d->patch;
if (d->latent_scale <= 0 || d->latent_channels <= 0 || d->patch <= 0 ||
d->size_multiple <= 0 || d->size_multiple % unit != 0 || d->min_side < d->size_multiple ||
d->max_area < d->min_side * d->min_side || d->max_aspect < 1 ||
d->default_width % d->size_multiple != 0 || d->default_height % d->size_multiple != 0 ||
d->default_width < d->min_side || d->default_height < d->min_side ||
d->default_width * d->default_height > d->max_area) {
err(RAD_E_INVAL, "declare_video_generator '%s': the spatial geometry is out of range "
"(latents of %lld px in %lld x %lld patches, sides multiples of %lld from "
"%lld, area to %lld, aspect to %lld, %lld x %lld by default)", nm,
(long long)d->latent_scale, (long long)d->patch, (long long)d->patch,
(long long)d->size_multiple, (long long)d->min_side, (long long)d->max_area,
(long long)d->max_aspect, (long long)d->default_width, (long long)d->default_height);
return RAD_E_INVAL;
}
if (d->sample_rate <= 0 || d->audio_rate <= 0 || d->sample_rate % d->audio_rate != 0 ||
d->audio_channels <= 0 || d->audio_latent_channels <= 0) {
err(RAD_E_INVAL, "declare_video_generator '%s': the soundtrack is out of range (%lld Hz "
"at %lld latents a second, %lld channels of %lld)", nm,
(long long)d->sample_rate, (long long)d->audio_rate, (long long)d->audio_channels,
(long long)d->audio_latent_channels);
return RAD_E_INVAL;
}
if (d->default_steps <= 0 || d->max_steps < d->default_steps || !(d->shift_video > 0.0) ||
!(d->shift_audio > 0.0) || d->max_lanes <= 0) {
err(RAD_E_INVAL, "declare_video_generator '%s': the sampler is incomplete (%lld steps by "
"default, %lld at most, shifts %g and %g, %lld lanes)", nm,
(long long)d->default_steps, (long long)d->max_steps, d->shift_video, d->shift_audio,
(long long)d->max_lanes);
return RAD_E_INVAL;
}
if (d->n_rungs < 0 || (d->n_rungs > 0 && !d->rungs) ||
(d->n_rungs > 0 && (d->default_steps != d->n_rungs + 1 || d->max_steps != d->n_rungs + 1))) {
err(RAD_E_INVAL, "declare_video_generator '%s': a trained schedule of %d rungs runs %d grid "
"points, which default_steps and max_steps must both be (%lld, %lld)", nm,
(int)d->n_rungs, (int)d->n_rungs + 1, (long long)d->default_steps,
(long long)d->max_steps);
return RAD_E_INVAL;
}
for (int i = 0; i < d->n_rungs; ++i)
if (!(d->rungs[i] > 0.0 && d->rungs[i] <= 1.0) ||
(i > 0 && !(d->rungs[i] < d->rungs[i - 1]))) {
err(RAD_E_INVAL, "declare_video_generator '%s': rung %d (%g) is outside (0, 1] or not "
"below the one before it", nm, i, d->rungs[i]);
return RAD_E_INVAL;
}
auto buf_ok = [&](rad_buf h, uint32_t dtype, int64_t numel, const char* what) {
if (h == RAD_NULL_HANDLE || (size_t)h >= prog_.buffers.size()) {
err(RAD_E_INVAL, "declare_video_generator '%s': %s %u is not a declared buffer", nm,
what, (unsigned)h);
return false;
}
const RadBufDecl& ob = prog_.buffers[h].decl;
if (ob.dtype != dtype || ob.domain != RAD_DOMAIN_DEVICE ||
decl_numel(ob.rank, ob.shape) < numel) {
err(RAD_E_INVAL, "declare_video_generator '%s': %s '%s' must be a device %s buffer of "
"at least %lld elements", nm, what, prog_.buffers[h].name.c_str(),
dtype == RAD_U8 ? "u8" : "f32", (long long)numel);
return false;
}
return true;
};
/* frames_out holds the last chunk, the largest, at the largest area; audio_out the longest
* soundtrack. */
const int64_t chunk_px = (d->frames_per_chunk + d->frames_tail) * d->max_area * 3;
const int64_t max_frames = d->frames_per_chunk * d->max_chunks + d->frames_tail;
const int64_t max_lat = (max_frames * d->fps_den * d->audio_rate * 2 + d->fps_num) /
(2 * d->fps_num) + 1;
const int64_t max_samples = max_lat * (d->sample_rate / d->audio_rate);
if (!buf_ok(d->frames_out, RAD_U8, chunk_px, "frames_out") ||
!buf_ok(d->audio_out, RAD_F32, max_samples * d->audio_channels, "audio_out"))
return RAD_E_INVAL;
prog_.vgen_str.name = nm;
prog_.vgen_str.tmpl = d->tmpl;
prog_.vgen_str.rungs.assign(d->rungs, d->rungs + d->n_rungs);
prog_.video_gen = *d;
/* As for the other generators: the Program is moved after declare; strings and the rungs live
* in vgen_str. */
prog_.video_gen.name = nullptr;
prog_.video_gen.tmpl = nullptr;
prog_.video_gen.rungs = nullptr;
return RAD_OK;
}
/* Validates the draft head at declare rather than at the first draft pass, where a bad decl would
* only show as zero acceptance. `depth` must equal RadBuildCtx::max_spec, which the plugin sized
* its buffers with. */
@@ -1524,10 +1822,12 @@ void Builder::finish_layouts() {
for (size_t h = 1; h < prog_.weights.size(); ++h) {
const WeightInfo& w = prog_.weights[h];
if (w.n_sel <= 1 || !w.identity || !claimant[h].empty()) continue;
char en[256];
rad_enc_format(&w.enc, en, sizeof en);
if (unjoined[h].empty())
err(RAD_E_SHAPE, "'%s' takes %d planes of '%s' as one weight and no op reads it, so "
"nothing says how they are stored", w.name.c_str(), w.n_sel,
w.source.c_str());
err(RAD_E_SHAPE, "'%s' takes %d planes of '%s' (%s) as one weight and no op reads it, "
"so nothing says how they are stored", w.name.c_str(), w.n_sel,
w.source.c_str(), en);
else
err(RAD_E_SHAPE, "'%s' takes %d planes of '%s' as one weight, and the host kernels "
"reading it (%s) have no layout that joins them (abi/rad_planes.h)",
@@ -1814,6 +2114,16 @@ int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d) {
return B(b)->declare_generator(d);
}
int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d) {
if (!b) return RAD_E_INVAL;
return B(b)->declare_audio_generator(d);
}
int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d) {
if (!b) return RAD_E_INVAL;
return B(b)->declare_video_generator(d);
}
void rad_note(RadBuilder* b, const char* f, ...) {
if (!b) return;
va_list ap;
+31 -5
View File
@@ -258,6 +258,32 @@ const RadChatFormat* rad_tools_chat_format(const LoadedPlugins& lp, const RadMod
return ap->arch_chat_format(&meta);
}
int rad_tools_text_prepare(const LoadedPlugins& lp, int field, const std::string& in,
std::string* out) {
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
if (!ap || !ap->arch_text_prepare) {
*out = in;
return RAD_OK;
}
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 < (int64_t)buf.size()) {
buf.resize((size_t)n);
*out = std::move(buf);
return RAD_OK;
}
buf.assign((size_t)n + 1, '\0');
}
return RAD_E_STATE;
}
VideoPositionsFn rad_tools_video_positions(const LoadedPlugins& lp) {
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
return ap ? ap->arch_video_positions : 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;
@@ -368,8 +394,8 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
return s;
}
/* RUNTIME LoRA, after the plugin and before the sampler: the sites read the plugin's finished
* graph, and the appended ops go through the same resolution as everything else. */
/* Runtime LoRA, after the plugin and before the sampler: the sites read the plugin's finished
* graph, and the appended ops go through the same resolution as every other op. */
if (with_lora) {
b.set_lora_targets(nullptr);
s = lora_declare(b, *lora);
@@ -381,9 +407,9 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
/* The sampler declares into the same builder before finish(). An unresolved sampler op is not
* a declare failure (a deployment that never sends `typical_p` needs no typical kernel), so a
* negative return here is structural. Skipped for embedding programs and image generators,
* which sample no token. */
if (also && b.program().pooled_buf == RAD_NULL_HANDLE && !b.program().is_generator()) {
* negative return here is structural. Skipped for embedding programs and generators, which
* sample through no token sampler (an audio generator samples its frames itself). */
if (also && b.program().pooled_buf == RAD_NULL_HANDLE && !b.program().is_pass_driven()) {
/* This rank's vocabulary width, taken from the declared logits buffer rather than
* re-derived from n_vocab and world_size, which would break when a plugin does not split
* the vocabulary (arch/common/rad_arch.h does not). A wrong width does not crash; it
+11
View File
@@ -88,6 +88,17 @@ const RadChatFormat* rad_tools_chat_format(const LoadedPlugins& plugins, const R
* small to hold a field reads that field as null. */
const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& plugins, const RadModelMeta& meta);
/* A request's text rewritten by the architecture plugin for the audio generator's prompt
* (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);
/* 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);
/* Run declare.
*
* `also` declares into the same builder after the architecture plugin, which is how the sampler
+79 -15
View File
@@ -14,12 +14,14 @@
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <climits>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <set>
#include <sstream>
namespace rad {
@@ -104,9 +106,9 @@ static const Flag g_flags[] = {
" --lora). Each slot holds one adapter's A/B on the card"},
{ "--max-lora-rank", "R", "the rank each slot is sized for (default 16); a smaller\n"
" adapter is zero-padded, a larger one refused"},
{ "--lora-target-modules", "LIST", "comma-separated HF module names adapters may target\n"
" (q_proj,k_proj,...). Default: what the --lora adapters\n"
" target. Needed with --max-loras and no --lora"},
{ "--lora-target-modules", "LIST", "comma-separated HF module leaf names adapters may\n"
" target (q_proj,k_proj,...). Default: what the --lora\n"
" adapters target. Needed with --max-loras and no --lora"},
{ "--placement", "MODE", "all_vram | layer_offload | expert_tiered | auto" },
{ "--deterministic", nullptr, "pin placement to the plan the loader made, so the resident\n"
@@ -122,12 +124,12 @@ static const Flag g_flags[] = {
" intervals, and the checkpoints inside a span are not\n"
" written" },
/* A total, not per sequence: the snapshot store is one pool of N slots
* (KVManager::set_checkpoint_store). The default 8 gives one per sequence at 8 sequences,
* enough for append-only chat, where the next turn hits at the end of the last. */
{ "--checkpoint-slots", "N", "linear-state or sliding-window snapshots "
"retained IN TOTAL (not "
"per sequence), in pinned host memory; compare "
"against --max-num-seqs" },
* (KVManager::set_checkpoint_store). */
{ "--checkpoint-slots", "N", "linear-state or sliding-window snapshots the server holds in\n"
" total, in pinned host memory. Default `auto`: what\n"
" --checkpoint-policy keeps for a --max-model-len session, plus\n"
" 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" },
{ "--checkpoint-policy", "NAME", "which snapshots a session retains: geometric-backoff "
"(default), tip-only, keep-all" },
@@ -515,20 +517,29 @@ int config_parse(int argc, char** argv, Config* c) {
else if (S("--max-loras")) { if (!num(0, 64, &c->lora.max_loras)) return RAD_E_INVAL; }
else if (S("--max-lora-rank")) { if (!num(1, 512, &c->lora.max_rank)) return RAD_E_INVAL; }
else if (S("--lora-target-modules")) {
/* Module leaf names, as PEFT's target_modules lists them: a dotted path or a pattern
* would match no leaf and target nothing without a word. */
if (!(v = need(i))) return RAD_E_INVAL;
c->lora.targets.clear();
std::set<std::string> leaves;
std::string cur;
for (const char* q = v;; ++q) {
if (*q == ',' || !*q) {
if (!cur.empty()) c->lora.targets.insert(cur);
if (!cur.empty()) leaves.insert(cur);
cur.clear();
if (!*q) break;
} else if (*q != ' ') cur += *q;
} else if (std::isalnum((unsigned char)*q) || *q == '_') {
cur += *q;
} else if (*q != ' ') {
RAD_ERR("--lora-target-modules takes module leaf names (q_proj,k_proj,...); "
"'%s' holds '%c'", v, *q);
return RAD_E_INVAL;
}
}
if (c->lora.targets.empty()) {
if (leaves.empty()) {
RAD_ERR("--lora-target-modules names no module");
return RAD_E_INVAL;
}
c->lora.targets.assign(leaves.begin(), leaves.end());
}
/* The prefix cache has no disk tier; the removed flags name their replacements. */
else if (S("--prefix-cache-host-mib")) {
@@ -555,7 +566,17 @@ int config_parse(int argc, char** argv, Config* c) {
else if (S("--deterministic")) c->deterministic = true;
else if (S("--checkpoint-interval")) { if (!num(0, INT64_MAX, &c->checkpoint_interval)) return RAD_E_INVAL; }
else if (S("--prefill-span")) { if (!num(1, INT32_MAX, &c->prefill_span)) return RAD_E_INVAL; }
else if (S("--checkpoint-slots")) { if (!num(0, INT64_MAX, &c->checkpoint_slots)) return RAD_E_INVAL; }
else if (S("--checkpoint-slots")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "auto")) {
c->checkpoint_slots = -1;
} else if (!*v || std::strspn(v, "0123456789") != std::strlen(v)) {
RAD_ERR("--checkpoint-slots takes auto or a whole number, not '%s'", v);
return RAD_E_INVAL;
} else if (!parse_int(a.c_str(), v, 0, INT64_MAX, &c->checkpoint_slots)) {
return RAD_E_INVAL;
}
}
else if (S("--no-prefix-cache")) c->prefix_cache = false;
else if (S("--checkpoint-policy")) {
if (!(v = need(i))) return RAD_E_INVAL;
@@ -844,6 +865,48 @@ int config_parse(int argc, char** argv, Config* c) {
return RAD_E_INVAL;
}
/* Runtime LoRA: the slot flags need slots, the named adapters must fit them, and KL mode's
* adapter is one of them. */
{
const LoraConfig& L = c->lora;
std::set<std::string> names;
for (const auto& [name, path] : L.adapters)
if (!names.insert(name).second) {
RAD_ERR("--lora names the adapter '%s' twice", name.c_str());
return RAD_E_INVAL;
}
if (L.max_loras > 0 && L.max_loras < (int)L.adapters.size()) {
RAD_ERR("--max-loras %d holds fewer adapters than the %zu that --lora names",
L.max_loras, L.adapters.size());
return RAD_E_INVAL;
}
const bool rank_given = c->given.count("--max-lora-rank") != 0;
if (!L.enabled() && (rank_given || !L.targets.empty())) {
RAD_ERR("%s sizes runtime LoRA slots, and there are none: give --lora or --max-loras",
rank_given ? "--max-lora-rank" : "--lora-target-modules");
return RAD_E_INVAL;
}
if (L.adapters.empty() && L.max_loras > 0 && L.targets.empty()) {
RAD_ERR("--max-loras with no --lora names no module an adapter may target; give "
"--lora-target-modules (q_proj,k_proj,v_proj,o_proj,...)");
return RAD_E_INVAL;
}
if (!c->kld_lora.empty() && !c->kld()) {
RAD_ERR("--kld-lora scores through an adapter in KL mode; give --kld-record or "
"--kld-ref");
return RAD_E_INVAL;
}
if (!c->kld_lora.empty() && !names.count(c->kld_lora)) {
RAD_ERR("--kld-lora '%s' is not one of the adapters --lora names", c->kld_lora.c_str());
return RAD_E_INVAL;
}
if (!c->kld_lora_sources.empty() && c->kld_lora.empty()) {
RAD_ERR("--kld-lora-sources picks the documents that run through --kld-lora's adapter; "
"give --kld-lora");
return RAD_E_INVAL;
}
}
/* --reasoning-effort is a template variable ("none" also sets enable_thinking false), so
* either key in --chat-template-kwargs as well would give two defaults for one setting. */
if (!c->reasoning_effort.empty() &&
@@ -960,7 +1023,8 @@ const ShowRow kShow[] = {
{ "--deterministic", [](const Config& c) { return onoff(c.deterministic); } },
{ "--checkpoint-interval", [](const Config& c) { return num(c.checkpoint_interval); } },
{ "--prefill-span", [](const Config& c) { return num(c.prefill_span); } },
{ "--checkpoint-slots", [](const Config& c) { return num(c.checkpoint_slots); } },
{ "--checkpoint-slots", [](const Config& c) {
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"); } },
{ "--checkpoint-policy", [](const Config& c) { return c.checkpoint_policy; } },
+27 -25
View File
@@ -618,6 +618,9 @@ 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. */
constexpr uint32_t kStallMs = 5000;
uint64_t read_progress() {
std::lock_guard<std::mutex> lk(G().streams_mu);
uint64_t n = 0;
@@ -630,7 +633,7 @@ void (*g_dump_lanes)() = nullptr;
void dump_queues(const char* where) {
std::lock_guard<std::mutex> lk(G().streams_mu);
RAD_ERR("device: %s has waited 5 s; the queues:", where);
RAD_ERR("device: %s has seen no queue advance for %u s; the queues:", where, kStallMs / 1000);
for (Stream* s : G().streams) {
const uint64_t rd = hsa_queue_load_read_index_scacquire(s->q);
const uint64_t wr = hsa_queue_load_write_index_scacquire(s->q);
@@ -829,45 +832,44 @@ hsa_status_t on_system_event(const hsa_amd_event_t* e, void*) {
"exiting so a restart can bring the server back", card);
}
/* How long a host wait goes before it reports the queues; see dump_queues. */
constexpr uint32_t kStallMs = 5000;
/* Stall detector for a spin loop. tick() reads the clock every 64k iterations, a few thousand
* times a second at most.
*
* The dump alone cannot tell slow from stuck: a long prefill at deep context can hold one wait
* past 5 s while the queue drains, and a hung kernel holds it with the read index frozen. So the
* read indices are sampled with the dump and again one stall period later: advanced means a long
* wait, unchanged means the GPU is not running the queue. */
* A long wait is not a fault: a long prefill at deep context holds one wait for seconds, and a
* 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. */
struct Stall {
const char* where;
uint32_t n = 0;
int told = 0; /* 0 nothing said, 1 the dump, 2 the verdict */
bool told = false;
bool sampled = false;
uint64_t progress = 0;
std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point next =
std::chrono::steady_clock::now() + std::chrono::milliseconds(kStallMs);
explicit Stall(const char* w) : where(w) {}
void tick() {
if (told == 2 || (++n & 0xffff)) return;
if (told || (++n & 0xffff)) return;
check();
}
/* Checks on every call, for a loop that sleeps between calls. */
void check() {
if (told == 2) return;
const auto waited = std::chrono::steady_clock::now() - t0;
if (told == 0 && waited > std::chrono::milliseconds(kStallMs)) {
told = 1;
progress = read_progress();
if (told) return;
const auto now = std::chrono::steady_clock::now();
if (now < next) return;
next = now + std::chrono::milliseconds(kStallMs);
const uint64_t p = read_progress();
if (sampled && p == progress) {
told = true;
dump_queues(where);
} else if (told == 1 && waited > std::chrono::milliseconds(2 * kStallMs)) {
told = 2;
if (read_progress() != progress)
RAD_WARN("device: the queues advanced in the %u s since; %s is long, not stuck",
kStallMs / 1000, where);
else
RAD_ERR("device: no queue 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);
RAD_ERR("device: no queue 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;
}
sampled = true;
progress = p;
}
};
+177 -18
View File
@@ -4,6 +4,8 @@
*/
#include "engine_priv.h"
#include "gen/driver.h"
#include "gen/audio_driver.h"
#include "gen/video_driver.h"
#include "kld.h"
#include "mm/processor.h"
@@ -1343,28 +1345,39 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
return RAD_E_STATE;
}
embedding_ = ranks_[0]->program.pooled_buf != RAD_NULL_HANDLE;
const bool generator = ranks_[0]->program.is_generator();
const bool audio_gen = ranks_[0]->program.is_audio_generator();
const bool video_gen = ranks_[0]->program.is_video_generator();
const bool generator = ranks_[0]->program.is_pass_driven();
if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE && !embedding_ && !generator) {
RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits), no pooled output "
"(rad_declare_pooled) and no image generator (rad_declare_generator), so a step "
"produces nothing anyone can read. An encoder-only plugin cannot serve.",
"(rad_declare_pooled) and no generator (rad_declare_generator, "
"rad_declare_audio_generator, rad_declare_video_generator), so a step produces "
"nothing anyone can read. An encoder-only plugin cannot serve.",
plugins_.arch_plugin.c_str());
return RAD_E_UNSUPPORTED;
}
if (generator) {
const char* const what = audio_gen ? "audio" : video_gen ? "video" : "images";
if (cfg_.kld() || cfg_.n_spec > 0) {
RAD_ERR("the '%s' plugin makes images: --kld and speculative decoding have no tokens to "
"work on", plugins_.arch_plugin.c_str());
RAD_ERR("the '%s' plugin makes %s: --kld and speculative decoding have no tokens to "
"work on", plugins_.arch_plugin.c_str(), what);
return RAD_E_UNSUPPORTED;
}
for (size_t i = 1; i < ranks_.size(); ++i)
if (!ranks_[i]->program.is_generator()) {
RAD_ERR("rank %zu declared no image generator and rank 0 did", i);
if (ranks_[i]->program.is_audio_generator() != audio_gen ||
ranks_[i]->program.is_video_generator() != video_gen ||
!ranks_[i]->program.is_pass_driven()) {
RAD_ERR("rank %zu declared a different generator from rank 0's", i);
return RAD_E_STATE;
}
cfg_.prefix_cache = false;
prefix_off_why_ = "an image generator: a conditioning is read by its own request's images "
"and by nothing after them";
prefix_off_why_ = audio_gen
? "an audio generator: a prompt is read by its own request's frames and by nothing "
"after them"
: video_gen
? "a video generator: a prompt is read by its own request's steps and keeps no KV"
: "an image generator: a conditioning is read by its own request's images and by "
"nothing after them";
decide("--no-prefix-cache", "prefix caching off", prefix_off_why_);
}
if (embedding_) {
@@ -1498,13 +1511,33 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
rio.reserve(ranks_.size());
for (auto& rk : ranks_)
rio.push_back({ rk->device, rk->ctx.stream(), &rk->program });
if (generator) {
if (video_gen) {
/* As for the image generator below; the plugin lays out each request's rows. */
std::vector<gen::VideoDriver::RankIO> gio;
for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
auto d = std::make_unique<gen::VideoDriver>();
RAD_TRY(d->init(ranks_[0]->program, rad_tools_video_positions(plugins_), gio));
vid_gen_ = d.get();
gen_ = std::move(d);
RAD_TRY(rad_dev_set(ranks_[0]->device));
} else if (audio_gen) {
/* As for the image generator below. */
std::vector<gen::AudioDriver::RankIO> gio;
for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
auto d = std::make_unique<gen::AudioDriver>();
RAD_TRY(d->init(ranks_[0]->program, kv_iface_.get(), gio));
aud_gen_ = d.get();
gen_ = std::move(d);
RAD_TRY(rad_dev_set(ranks_[0]->device));
} else if (generator) {
/* The generator's driver replaces the scheduler, which is never initialised, so its
* token-step staging is never allocated. */
std::vector<gen::Driver::RankIO> gio;
for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
gen_ = std::make_unique<gen::Driver>();
RAD_TRY(gen_->init(ranks_[0]->program, kv_iface_.get(), gio));
auto d = std::make_unique<gen::Driver>();
RAD_TRY(d->init(ranks_[0]->program, kv_iface_.get(), gio));
img_gen_ = d.get();
gen_ = std::move(d);
RAD_TRY(rad_dev_set(ranks_[0]->device));
} else
RAD_TRY(sched_.init(ranks_[0]->program, cfg_, kv_iface_.get(), pc_iface_.get(), rio, &geo_));
@@ -2006,7 +2039,9 @@ int Engine::run_server() {
server::ServerOptions o{};
o.embedding_model = embedding_;
o.image_model = gen_ != nullptr;
o.image_model = img_gen_ != nullptr;
o.audio_model = aud_gen_ != nullptr;
o.video_model = vid_gen_ != nullptr;
o.decision_type = rad_meta_gets(&meta_, "decision.type", "");
o.model_id = !cfg_.served_model_name.empty() ? cfg_.served_model_name
: meta_.name && *meta_.name ? meta_.name : "radiance";
@@ -2024,9 +2059,9 @@ int Engine::run_server() {
o.default_reasoning_effort = cfg_.reasoning_effort;
o.reasoning_effort_map = cfg_.reasoning_effort_map;
o.default_thinking_budget = cfg_.thinking_token_budget;
{
if (!gen_) {
/* The four sampler defaults a file can state: the served value and, per field, its
* source. */
* source. A generator samples by its own rules and serves no text requests. */
GenSampling stated;
std::string src;
o.default_sampling =
@@ -2078,6 +2113,14 @@ int Engine::run_server() {
/* Per request, from a reading at most a second old (Engine::diagnostics_json). */
o.diagnostics_json = [this] { return diagnostics_json(); };
if (cfg_.lora.enabled()) {
/* `model` picks the adapter, and the served model's own name picks the base. */
for (const auto& [name, dir] : cfg_.lora.adapters)
if (name == o.model_id) {
RAD_ERR("lora: the adapter '%s' has the served model's own name, so a request "
"naming it would run the base; rename it or give --served-model-name",
name.c_str());
return RAD_E_INVAL;
}
o.lora_acquire = [this](const std::string& m, int32_t* slot, uint64_t* uid,
std::shared_ptr<void>* hold) {
return lora_acquire(m, slot, uid, hold);
@@ -2317,7 +2360,7 @@ int Engine::run_server() {
int64_t queued() const override { return drv->queued(); }
int64_t running() const override { return drv->running(); }
} image_bridge;
if (gen_) {
if (img_gen_) {
const Program& pg = ranks_[0]->program;
const RadGeneratorDecl& gd = pg.generator;
server::ImageGenInfo& in = image_bridge.inf;
@@ -2339,11 +2382,11 @@ int Engine::run_server() {
in.default_height = gd.default_height;
in.default_steps = gd.default_steps;
in.max_lanes = gd.max_lanes;
in.max_cond_tokens = gen_->max_cond_tokens();
in.max_cond_tokens = img_gen_->max_cond_tokens();
in.fixed_schedule = !pg.gen_str.sigmas.empty();
in.fixed_steps = (int64_t)pg.gen_str.sigmas.size();
in.default_cfg = gd.default_cfg;
image_bridge.drv = gen_.get();
image_bridge.drv = img_gen_;
image_bridge.proc = mm_proc.get();
d.images = &image_bridge;
/* The served model id is the generator's own name (qwen-image-2.1), not the container's
@@ -2359,6 +2402,116 @@ int Engine::run_server() {
: (std::to_string(in.default_steps) + " steps by default").c_str());
}
/* An audio generator's endpoint: the driver's queue, the declared prompt and limits, and the
* plugin's rewrite of a request's texts. */
struct AudioBridge final : server::IAudioGen {
gen::AudioDriver* drv = nullptr;
const LoadedPlugins* plugins = nullptr;
server::AudioGenInfo inf;
const server::AudioGenInfo& info() const override { return inf; }
int prepare(int field, const std::string& in, std::string* out,
std::string* why) const override {
const int s = rad_tools_text_prepare(*plugins, field, in, out);
if (s < 0 && why)
*why = s == RAD_E_INVAL ? "the model cannot take this text"
: std::string(rad_strerror(s));
return s;
}
int submit(std::unique_ptr<gen::AudioRequest> r, std::string* why) override {
return drv->submit(std::move(r), why);
}
int64_t queued() const override { return drv->queued(); }
int64_t running() const override { return drv->running(); }
} audio_bridge;
if (aud_gen_) {
const Program& pg = ranks_[0]->program;
const RadAudioGenDecl& ad = pg.audio_gen;
server::AudioGenInfo& in = audio_bridge.inf;
in.name = pg.agen_str.name;
in.tmpl = pg.agen_str.tmpl;
in.tmpl_plain = pg.agen_str.tmpl_plain;
in.neg_tmpl = pg.agen_str.neg_tmpl;
in.max_prompt = ad.max_prompt;
in.max_frames = ad.max_frames;
in.frame_rate_num = ad.frame_rate_num;
in.frame_rate_den = ad.frame_rate_den;
in.sample_rate = ad.sample_rate;
in.channels = ad.channels;
in.default_steps = ad.voc_chunk > 0 ? 0 : ad.default_steps;
in.default_cfg = ad.default_cfg;
in.max_lanes = ad.max_lanes;
audio_bridge.drv = aud_gen_;
audio_bridge.plugins = &plugins_;
d.audio = &audio_bridge;
if (cfg_.served_model_name.empty() && !in.name.empty()) {
o.model_id = in.name;
decide("--served-model-name", o.model_id, "an audio generator: its own name");
}
RAD_INFO("audio: '%s', %lld Hz x %lld, up to %lld frames (%lld s), %lld at once, %s",
in.name.c_str(), (long long)in.sample_rate, (long long)in.channels,
(long long)in.max_frames,
(long long)(in.max_frames * in.frame_rate_den / in.frame_rate_num),
(long long)in.max_lanes,
ad.voc_chunk > 0
? fmt("played %lld frames at a time as they are made",
(long long)ad.voc_chunk).c_str()
: fmt("%lld steps a window by default", (long long)in.default_steps).c_str());
}
/* A video generator's endpoints: the driver's queue and the declared prompt, sizes and
* lengths. */
struct VideoBridge final : server::IVideoGen {
gen::VideoDriver* drv = nullptr;
server::VideoGenInfo inf;
const server::VideoGenInfo& info() const override { return inf; }
int submit(std::unique_ptr<gen::VideoRequest> r, std::string* why) override {
return drv->submit(std::move(r), why);
}
int64_t queued() const override { return drv->queued(); }
int64_t running() const override { return drv->running(); }
} video_bridge;
if (vid_gen_) {
const Program& pg = ranks_[0]->program;
const RadVideoGenDecl& vd = pg.video_gen;
server::VideoGenInfo& in = video_bridge.inf;
in.name = pg.vgen_str.name;
in.tmpl = pg.vgen_str.tmpl;
in.max_text = vd.max_text;
in.fps_num = vd.fps_num;
in.fps_den = vd.fps_den;
in.frames_per_chunk = vd.frames_per_chunk;
in.frames_tail = vd.frames_tail;
in.min_chunks = vd.min_chunks;
in.max_chunks = vd.max_chunks;
in.size_multiple = vd.size_multiple;
in.min_side = vd.min_side;
in.max_area = vd.max_area;
in.max_aspect = vd.max_aspect;
in.default_width = vd.default_width;
in.default_height = vd.default_height;
in.default_chunks = vd.default_chunks;
in.sample_rate = vd.sample_rate;
in.channels = vd.audio_channels;
in.default_steps = vd.default_steps;
in.max_steps = vd.max_steps;
in.fixed_steps = vd.n_rungs > 0;
in.max_lanes = vd.max_lanes;
video_bridge.drv = vid_gen_;
d.videos = &video_bridge;
if (cfg_.served_model_name.empty() && !in.name.empty()) {
o.model_id = in.name;
decide("--served-model-name", o.model_id, "a video generator: its own name");
}
const double fps = (double)in.fps_num / (double)in.fps_den;
RAD_INFO("video: '%s', %lldx%lld by default (up to %lld pixels), %.2f to %.2f s at %g fps "
"with %lld Hz x %lld sound, %lld steps by default",
in.name.c_str(), (long long)in.default_width, (long long)in.default_height,
(long long)in.max_area,
(double)(in.frames_per_chunk * in.min_chunks + in.frames_tail) / fps,
(double)(in.frames_per_chunk * in.max_chunks + in.frames_tail) / fps, fps,
(long long)in.sample_rate, (long long)in.channels, (long long)in.default_steps);
}
if (encd.modalities == 0 && aend.modalities == 0 && cfg_.media_flags_set())
RAD_WARN("media: the media flags do nothing here -- this model %s",
cfg_.mm_max_patches == 0 ? "is served text only (--mm-max-patches 0)"
@@ -2417,6 +2570,12 @@ int Engine::run_server() {
if (embedding_)
RAD_INFO("serving on http://%s:%d (/v1/embeddings; completions and chat are 501%s)",
o.host.c_str(), o.port, keyed);
else if (aud_gen_)
RAD_INFO("serving on http://%s:%d (/v1/audio/speech; completions and chat are 501%s)",
o.host.c_str(), o.port, keyed);
else if (vid_gen_)
RAD_INFO("serving on http://%s:%d (/v1/videos; completions and chat are 501%s)",
o.host.c_str(), o.port, keyed);
else if (gen_)
RAD_INFO("serving on http://%s:%d (/v1/images/generations%s; completions and chat are "
"501%s)", o.host.c_str(), o.port,
+18 -13
View File
@@ -44,7 +44,7 @@ namespace rad {
class Kld;
class StallWatch;
namespace gen { class Driver; }
namespace gen { class Driver; class AudioDriver; class VideoDriver; struct IPassDriver; }
struct TierPump;
struct TierJob;
struct StepSlot;
@@ -136,21 +136,19 @@ private:
int apply_rope_scaling();
int declare();
int plan();
/* RUNTIME LoRA (core/engine_lora.cpp). Targets are fixed before declare; adapters are loaded
/* Runtime LoRA (core/engine_lora.cpp). Targets are fixed before declare; adapters are loaded
* into slots after every rank's Ctx is bound, and a request's `model` names one. */
int lora_targets();
int lora_start();
public:
int lora_load(const std::string& name, const std::string& dir, std::string* err);
/* Unpublish an adapter (lora::SlotTable::unload). Idle, its slot is freed at once; in use, it
* DRAINS: *in_flight says how many requests still hold it, no new request may name it, and
* the last of them frees the slot. A freed slot is reused only once the step loop has gone
* round three times since, so no step still on the card can read bytes a later load is
* writing (the next step is issued before the last is read back). */
* drains: *in_flight says how many requests still hold it, no new request may name it, and the
* last of them frees the slot, which cools before reuse (lora/slots.h). */
int lora_unload(const std::string& name, std::string* err, int* in_flight);
/* RAD_OK with the slot, the uid of its load and a HOLD -- the adapter is not freed while the
* hold lives (the server keeps it in the request's Generation, which outlives the request in
* the scheduler). RAD_E_NOTFOUND for a name no slot holds, or one that is draining. */
/* RAD_OK with the slot, the uid of its load and a hold: the adapter is not freed while the
* hold lives (the server keeps it in the request's Generation). RAD_E_NOTFOUND for a name no
* slot holds, or one that is draining. */
int lora_acquire(const std::string& name, int32_t* slot, uint64_t* uid,
std::shared_ptr<void>* hold);
std::vector<std::string> lora_names() const;
@@ -186,6 +184,8 @@ private:
std::vector<std::pair<const void*, void*>> table_copy_of_;
int load_weights();
int configure_kv();
/* Resolves --checkpoint-slots auto for snapshots of `slot` bytes (`what` names their kind). */
int size_checkpoint_store(int64_t slot, const char* what);
/* Maps the step's logits rows back to the sequences that wanted them. Not the identity: a
* mid-prompt prefill chunk produces no row, and a speculative verify produces 1 + n_spec. */
struct StepOut {
@@ -310,10 +310,15 @@ private:
float* pooled_host_ = nullptr;
int collect_pooled_issue(const RadBatch* b, StepOut& so);
int collect_pooled(const RadBatch* b, StepOut& so);
/* Image generator (rad_declare_generator): the driver that turns requests into passes and the
* loop that runs them, replacing the scheduler and step loop (engine_gen.cpp). Null for every
* other program. */
std::unique_ptr<gen::Driver> gen_;
/* A generator (rad_declare_generator, rad_declare_audio_generator,
* rad_declare_video_generator): the driver that turns requests into passes and the loop that
* runs them, replacing the scheduler and step loop (engine_gen.cpp). Null for every other
* program. `img_gen_`, `aud_gen_` and `vid_gen_` are the same driver by its kind, for the
* endpoints; one of them is set when `gen_` is. */
std::unique_ptr<gen::IPassDriver> gen_;
gen::Driver* img_gen_ = nullptr;
gen::AudioDriver* aud_gen_ = nullptr;
gen::VideoDriver* vid_gen_ = nullptr;
int gen_loop();
bool serial_drafting() const;
int advance_all(int mode, int round, bool from_proposal, int rows = -1);
+232 -64
View File
@@ -7,6 +7,8 @@
#include "engine_priv.h"
#include "engine_hostmem.h"
#include "gen/driver.h"
#include "gen/audio_driver.h"
#include "gen/video_driver.h"
#include "build/startup.h"
#include "build/rad_build.h"
@@ -205,12 +207,27 @@ static int64_t meminfo_bytes(const char* key) {
return -1;
}
/* The amdgpu driver's cap on the memory every process together pins: RAM less 1/64 and 1.5 GiB
* (half of RAM less 1/64 below 3 GiB), unless amdgpu.no_system_mem_limit lifts it;
* ttm.pages_limit does not apply. -1 when lifted (`*lifted` set) or MemTotal is unreadable. */
static int64_t amdgpu_pin_cap(bool* lifted) {
{
std::ifstream f("/sys/module/amdgpu/parameters/no_system_mem_limit");
std::string v;
*lifted = (f >> v) && (v == "Y" || v == "1");
}
const int64_t total = meminfo_bytes("MemTotal");
if (*lifted || total <= 0) return -1;
const int64_t reserve = (int64_t)3 << 29;
const int64_t cap = total - (total >> 6);
return cap < 2 * reserve ? cap >> 1 : cap - reserve;
}
/* Explain a refused pool allocation from the machine's current state.
*
* A card pool refused after the budget was measured (once, before any rank allocates) usually
* lost the memory to another process. A host pool is pinned, once per rank. Pinned memory counts
* against amdgpu's system-wide cap: RAM less 1/64 and 1.5 GiB (half of RAM less 1/64 below
* 3 GiB), unless amdgpu.no_system_mem_limit lifts it; ttm.pages_limit does not apply. */
* lost the memory to another process. A host pool is pinned, once per rank, and counts against
* amdgpu_pin_cap. */
static void report_pool_refusal(int rank, int device, const Pools& pools, const Config& cfg) {
bool card = false, host = false;
for (const Shortfall& f : pools.shortfalls()) (f.pool == "host_pool" ? host : card) = true;
@@ -226,19 +243,9 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const
int64_t pinned = 0, mapped = 0;
rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, nullptr);
rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, nullptr);
const int64_t total = meminfo_bytes("MemTotal"), avail = meminfo_bytes("MemAvailable");
const int64_t avail = meminfo_bytes("MemAvailable");
bool lifted = false;
{
std::ifstream f("/sys/module/amdgpu/parameters/no_system_mem_limit");
std::string v;
lifted = (f >> v) && (v == "Y" || v == "1");
}
const int64_t reserve = (int64_t)3 << 29;
int64_t cap = -1;
if (total > 0 && !lifted) {
cap = total - (total >> 6);
cap = cap < 2 * reserve ? cap >> 1 : cap - reserve;
}
const int64_t cap = amdgpu_pin_cap(&lifted);
/* With room under both limits the refusal is not about size; do not advise shrinking. */
const int64_t pool = cfg.host_pool_total_mib() * 1024 * 1024;
std::string tables, advice = "Lower --host-pool-mib";
@@ -273,6 +280,34 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const
* kernel reclaims the files the engine reads, then the OOM killer runs. */
static const int64_t kLockMargin = (int64_t)4 << 30;
/* Every level of every memory cgroup the process is in, leaf first: `visit(dir, room)` until it
* returns false (cgroup_levels). /proc/self/cgroup reads "0::/path" on v2 and "N:memory:/path"
* (or a comma list naming memory) on v1; each level up to the visible root is a limit of its
* own. */
static void memory_cgroups(const std::function<bool(const std::string&, int64_t)>& visit) {
std::ifstream f("/proc/self/cgroup");
std::string line;
bool go = true;
while (go && std::getline(f, line)) {
const size_t a = line.find(':'), b = a == std::string::npos ? a : line.find(':', a + 1);
if (b == std::string::npos) continue;
const std::string ctrl = line.substr(a + 1, b - a - 1);
std::string path = line.substr(b + 1);
const bool v2 = ctrl.empty();
bool memory = v2;
for (size_t i = 0; !memory && i < ctrl.size();) {
const size_t j = std::min(ctrl.find(',', i), ctrl.size());
memory = ctrl.compare(i, j - i, "memory") == 0;
i = j + 1;
}
if (!memory) continue;
const std::string root = v2 ? "/sys/fs/cgroup" : "/sys/fs/cgroup/memory";
cgroup_levels(root, path, v2, [&](const std::string& dir, int64_t room) {
return go = visit(dir, room);
});
}
}
/* Whether `need` more bytes fit in host memory after `still` more this process will allocate
* first, or why not. Checks MemAvailable; every memory cgroup from the process's own up to the
* visible root (Docker's --memory, enforced by the OOM killer); and, for an mlock()ed copy
@@ -307,37 +342,39 @@ static bool lockable_room(int64_t need, int64_t still, bool mlocks, std::string*
humanb(kLockMargin).c_str());
return false;
}
/* /proc/self/cgroup: "0::/path" on v2, "N:memory:/path" (or a comma list naming memory) on v1.
* Each level up to the visible root is a separate limit. */
std::ifstream f("/proc/self/cgroup");
std::string line;
while (std::getline(f, line)) {
const size_t a = line.find(':'), b = a == std::string::npos ? a : line.find(':', a + 1);
if (b == std::string::npos) continue;
const std::string ctrl = line.substr(a + 1, b - a - 1);
std::string path = line.substr(b + 1);
const bool v2 = ctrl.empty();
bool memory = v2;
for (size_t i = 0; !memory && i < ctrl.size();) {
const size_t j = std::min(ctrl.find(',', i), ctrl.size());
memory = ctrl.compare(i, j - i, "memory") == 0;
i = j + 1;
}
if (!memory) continue;
const std::string root = v2 ? "/sys/fs/cgroup" : "/sys/fs/cgroup/memory";
bool fits = true;
cgroup_levels(root, path, v2, [&](const std::string& dir, int64_t room) {
if (room - still - kLockMargin >= need) return true;
*why = fmt("the memory cgroup at %s leaves %s, %s more is still to be allocated, "
"and this wants %s with %s to spare", dir.c_str(),
humanb(room).c_str(), humanb(still).c_str(), humanb(need).c_str(),
humanb(kLockMargin).c_str());
fits = false;
return false;
});
if (!fits) return false;
bool fits = true;
memory_cgroups([&](const std::string& dir, int64_t room) {
if (room - still - kLockMargin >= need) return true;
*why = fmt("the memory cgroup at %s leaves %s, %s more is still to be allocated, "
"and this wants %s with %s to spare", dir.c_str(),
humanb(room).c_str(), humanb(still).c_str(), humanb(need).c_str(),
humanb(kLockMargin).c_str());
fits = false;
return false;
});
return fits;
}
/* The most lockable_room(need, still, false) admits, and in `limit` the bound that decides it.
* INT64_MAX when no limit can be read. */
static int64_t lockable_bytes(int64_t still, std::string* limit) {
int64_t most = INT64_MAX;
*limit = "no readable memory limit";
if (const int64_t avail = meminfo_bytes("MemAvailable"); avail >= 0) {
most = avail - still - kLockMargin;
*limit = fmt("%s of memory available, less %s still to be allocated and %s to spare",
humanb(avail).c_str(), humanb(still).c_str(), humanb(kLockMargin).c_str());
}
return true;
memory_cgroups([&](const std::string& dir, int64_t room) {
if (room - still - kLockMargin < most) {
most = room - still - kLockMargin;
*limit = fmt("the memory cgroup at %s, which leaves %s, less %s still to be allocated "
"and %s to spare", dir.c_str(), humanb(room).c_str(),
humanb(still).c_str(), humanb(kLockMargin).c_str());
}
return true;
});
return std::max<int64_t>(most, 0);
}
/* The copy is table_copy_make's (core/format/table_copy.h), or for a card, table_copy_fill into
@@ -878,7 +915,47 @@ int Engine::declare() {
{
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
if (pb.gen_rows > 0) {
if (pb.gen_rows > 0 && pb.gen_audio) {
if (!cfg_.given.count("--max-num-batched-tokens")) {
cfg_.max_tok = pb.gen_rows;
decide("--max-num-batched-tokens", std::to_string(cfg_.max_tok),
"an audio generator: a window's denoising step, both branches, and a "
"prompt chunk of half as many rows a branch");
}
if (!cfg_.given.count("--max-num-seqs")) {
cfg_.max_seqs = 8;
decide("--max-num-seqs", "8", "an audio generator: four requests at once, two "
"branches each");
}
if (!cfg_.given.count("--max-model-len") && cfg_.max_ctx == 0) {
cfg_.max_ctx = pb.gen_ctx > 0 ? pb.gen_ctx : pb.gen_rows;
decide("--max-model-len", std::to_string(cfg_.max_ctx),
"an audio generator: the longest prompt and every frame of the longest "
"piece");
}
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
if (cfg_.n_spec < 0) cfg_.n_spec = 0;
cfg_.prefix_cache = false;
} else if (pb.gen_rows > 0 && pb.gen_video) {
if (!cfg_.given.count("--max-num-batched-tokens")) {
cfg_.max_tok = pb.gen_rows;
decide("--max-num-batched-tokens", std::to_string(cfg_.max_tok),
"a video generator: a denoising step carries the prompt, the soundtrack "
"and every patch of the largest, longest video");
}
if (!cfg_.given.count("--max-num-seqs")) {
cfg_.max_seqs = 1;
decide("--max-num-seqs", "1", "a video generator: a pass is one request's");
}
if (!cfg_.given.count("--max-model-len") && cfg_.max_ctx == 0) {
cfg_.max_ctx = pb.gen_rows;
decide("--max-model-len", std::to_string(cfg_.max_ctx),
"a video generator: a step's rows");
}
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
if (cfg_.n_spec < 0) cfg_.n_spec = 0;
cfg_.prefix_cache = false;
} else if (pb.gen_rows > 0) {
if (!cfg_.given.count("--max-num-batched-tokens")) {
cfg_.max_tok = pb.gen_rows;
decide("--max-num-batched-tokens", std::to_string(cfg_.max_tok),
@@ -1308,8 +1385,10 @@ int Engine::plan() {
const int64_t w = probe.state_index_width((int32_t)i);
if (w > 0) kg.g[i].sidx_width = w;
}
f.staging = r->program.is_generator() ? gen::Driver::device_bytes(r->program)
: BatchBuilder::device_bytes(r->program, cfg_, kg);
f.staging = r->program.is_generator() ? gen::Driver::device_bytes(r->program)
: r->program.is_audio_generator() ? gen::AudioDriver::device_bytes(r->program)
: r->program.is_video_generator() ? gen::VideoDriver::device_bytes(r->program)
: BatchBuilder::device_bytes(r->program, cfg_, kg);
if (f.staging < 0) return RAD_E_INVAL;
late_step_bytes_ = std::max(late_step_bytes_, f.staging);
int64_t lazy = r->program.scratch_regions > 1 ? f.queue_bytes : 0;
@@ -1343,8 +1422,12 @@ int Engine::plan() {
facts[i].expert_floor = expert_vram_floor(wfs[i], std::max<int64_t>(room, 0));
}
/* Capped well below overflow, so the sums it joins stay defined: a store that large is
* refused by name in configure_kv. */
const int64_t ck_n = std::max<int64_t>(cfg_.checkpoint_slots, 0), ck_cap = INT64_MAX / 8;
* refused by name in configure_kv. Under --checkpoint-slots auto the store is sized in
* configure_kv from the memory the tables leave, and the tables leave room for the fewest
* slots auto resolves to. */
const int64_t ck_n =
cfg_.checkpoint_slots < 0 ? kCheckpointSlotsFloor : cfg_.checkpoint_slots;
const int64_t ck_cap = INT64_MAX / 8;
const int64_t ck_store = !cfg_.prefix_cache || ck_slot <= 0 ? 0
: ck_n > ck_cap / ck_slot ? ck_cap : ck_slot * ck_n;
RAD_TRY(resolve_table_placement(facts, emb_bytes, wfs, kv_floor, ngram_bytes,
@@ -2658,6 +2741,79 @@ int Engine::load_weights() {
*
* Runs after load, since it takes what the weight pool left, and before Ctx::init, which would
* otherwise resolve every RAD_OPK_KV operand to null. */
/* --checkpoint-slots auto, resolved into cfg_.checkpoint_slots once a slot's size is known
* (checkpoint_slots_auto in core/mem/prefix.h). The store is pinned for the life of the process,
* so it takes at most an eighth of host memory, leaving the rest to the page cache a model's
* mapped tables read through and to the host's other work. It is pinned before the host
* activation arenas and the prefix cache's host tier, so their bytes count as still to come;
* on a card the amdgpu pin cap bounds it too. */
int Engine::size_checkpoint_store(int64_t slot, const char* what) {
if (slot <= 0 || !cfg_.prefix_cache) {
cfg_.checkpoint_slots = 0;
decide("--checkpoint-slots", "0",
slot <= 0 ? "the model keeps no linear or sliding-window state to snapshot"
: "prefix caching is off (--no-prefix-cache)");
return RAD_OK;
}
const int64_t ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
const int64_t interval = geo_.checkpoint_interval;
const std::unique_ptr<CheckpointPolicy> pol =
make_checkpoint_policy(cfg_.checkpoint_policy, interval);
int64_t still = cfg_.prefix_cache_mib * ((int64_t)1 << 20);
for (const auto& r : ranks_) still += arena_host_bytes(r->program);
std::string limit;
int64_t room = lockable_bytes(still, &limit);
if (!device_is_host()) {
bool lifted = false;
if (const int64_t cap = amdgpu_pin_cap(&lifted); cap > 0) {
int64_t pinned = 0, mapped = 0;
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 "
"and still pins %s", humanb(cap).c_str(),
humanb(pinned + mapped).c_str(), humanb(still).c_str());
}
}
}
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,
share, room);
cfg_.checkpoint_slots = c.slots;
const std::string need =
fmt("%lld a sequence for --max-num-seqs %lld: %s keeps %lld for a %lld-token session at "
"a %lld-token interval, and one more for a running turn", (long long)c.per_seq,
(long long)cfg_.max_seqs, pol->name(), (long long)(c.per_seq - 1), (long long)ctx,
(long long)interval);
std::string bound;
if (c.bound == CheckpointSlots::Bound::Share)
bound = fmt("; %lld wanted, held to an eighth of host memory (%s); --checkpoint-slots N "
"sets more", (long long)c.want, humanb(share).c_str());
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);
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());
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());
else RAD_INFO("%s", line.c_str());
return RAD_OK;
}
int Engine::configure_kv() {
/* Resolved once, for the cache below and Scheduler::init later (see Engine::geo_). */
RAD_TRY(chunk_geometry_resolve(ranks_[0]->program, cfg_, &geo_));
@@ -2726,9 +2882,11 @@ int Engine::configure_kv() {
shard_off[i] = slot;
slot += ranks_[i]->kv.checkpoint_bytes();
}
const int64_t n = cfg_.checkpoint_slots > 0 ? cfg_.checkpoint_slots : 0;
/* 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";
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;
if (slot > 0 && n > 0 && cfg_.prefix_cache) {
/* Pinned all at once and outside every pool. A store larger than the memory left would
* push the process into reclaim, which stalls it without a word; one that cannot be had
@@ -2736,13 +2894,14 @@ int Engine::configure_kv() {
* makes visible. Either stops startup. */
const bool sized = n <= INT64_MAX / slot;
auto refuse = [&](const std::string& reason) {
RAD_ERR("checkpoint slots: %lld %s snapshot(s) of %s are %s of pinned host memory, "
"which %s. Lower --checkpoint-slots (a larger --checkpoint-interval needs "
"fewer for the same context), or pass --checkpoint-slots 0 to serve with "
"no %s snapshot, every prefix hit on this model then prefilling from the "
"start", (long long)n, what, humanb(slot).c_str(),
sized ? humanb(slot * n).c_str() : "more than 8 EiB", reason.c_str(),
what);
RAD_ERR("checkpoint slots: %lld %s snapshot(s)%s of %s are %s of pinned host "
"memory, which %s. Lower --checkpoint-slots (a larger "
"--checkpoint-interval needs fewer for the same context), or pass "
"--checkpoint-slots 0 to serve with no %s snapshot, every prefix hit on "
"this model then prefilling from the start", (long long)n, what,
sized_auto ? " (auto)" : "",
humanb(slot).c_str(), sized ? humanb(slot * n).c_str() : "more than 8 EiB",
reason.c_str(), what);
return RAD_E_NOMEM;
};
if (!sized) return refuse("no host has");
@@ -2750,10 +2909,11 @@ int Engine::configure_kv() {
if (!lockable_room(slot * n, 0, 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());
RAD_INFO("checkpoint slots: %lld %s snapshot(s) of %s in pinned host memory (%s), "
"none of it on the card", (long long)n, what, humanb(slot).c_str(),
humanb(ck_store_.cap_bytes()).c_str());
} else if (slot > 0 && cfg_.prefix_cache) {
if (!sized_auto)
RAD_INFO("checkpoint slots: %lld %s snapshot(s) of %s in pinned host memory (%s), "
"none of it on the card", (long long)n, what, humanb(slot).c_str(),
humanb(ck_store_.cap_bytes()).c_str());
} else if (slot > 0 && cfg_.prefix_cache && !sized_auto) {
RAD_INFO("checkpoint slots: --checkpoint-slots 0 keeps no %s snapshot, so every "
"prefix hit on this model prefills from the start", what);
}
@@ -2911,6 +3071,14 @@ int Engine::configure_kv() {
*
* For an image generator the sequence is a conditioning, which its driver refuses at
* admission; warn in those terms. */
if (ranks_[0]->program.is_audio_generator()) {
RAD_WARN("kv group '%s' holds %lld rows: a request needs its prompt and every "
"frame it may make, both branches, up to %lld rows a branch, so a long "
"piece is refused at once rather than cut short. Ask for shorter "
"pieces, use --kv-cache-dtype fp8, or add ranks.",
p->name.c_str(), (long long)cap, (long long)want);
continue;
}
if (ranks_[0]->program.is_generator()) {
RAD_WARN("kv group '%s' holds %lld rows: a conditioning longer than that -- a "
"prompt with its pictures, up to %lld rows -- is refused. A picture "
@@ -3139,8 +3307,8 @@ int Engine::start() {
}
}
/* RUNTIME LoRA: the startup adapters, copied into their slots now that every rank's pools have
* an address and before any step can read them. */
/* Runtime LoRA: the startup adapters, copied into their slots now that every rank's pools
* have an address and before any step can read them. */
RAD_TRY(lora_start());
/* ---- the loan: the cache's idle blocks, lent to the expert slab in place -----------------
+32 -12
View File
@@ -1,23 +1,41 @@
/* engine_gen.cpp -- the image generator's loop: the driver's passes (core/gen/driver.h) run on
* the ranks like token steps, one at a time, each drained before the next.
/* engine_gen.cpp -- a generator's loop: the driver's passes (core/gen/pass.h; driver.h for
* images, audio_driver.h for audio, video_driver.h for video) run on the ranks like token steps, one at a time, each drained
* before the next.
*
* Draining is cheap: a pass is tens to thousands of milliseconds of device work, and the next
* pass depends only on the driver's host bookkeeping, so the wait costs the microseconds of
* building it. Issuing ahead would need a second staging region and a commit protocol.
*/
#include "engine_priv.h"
#include "gen/driver.h"
#include "gen/pass.h"
#include <chrono>
#include <thread>
namespace rad {
/* A generator pass's kind, for the buffer probe's lines. */
static const char* pass_name(int gen) {
switch (gen) {
case RAD_GEN_PASS_COND: return "cond";
case RAD_GEN_PASS_DENOISE: return "denoise";
case RAD_GEN_PASS_DECODE: return "decode";
case RAD_GEN_PASS_PROMPT: return "prompt";
case RAD_GEN_PASS_FRAME: return "frame";
case RAD_GEN_PASS_WINDOW: return "window";
case RAD_GEN_PASS_VOCODE: return "vocode";
case RAD_GEN_PASS_VCOND: return "vcond";
case RAD_GEN_PASS_VSTEP: return "vstep";
case RAD_GEN_PASS_ADECODE: return "adecode";
case RAD_GEN_PASS_VDECODE: return "vdecode";
default: return "";
}
}
int Engine::gen_loop() {
if (rad_dev_set(ranks_[0]->device) < 0)
RAD_ERR("image generator loop: could not bind rank 0's device");
RAD_ERR("generator loop: could not bind rank 0's device");
int step = 0, idle = 0;
const rad_buf img = ranks_[0]->program.generator.image_out;
/* An error ends the driver's requests, then the loop. */
auto stop = [&](int st) {
gen_->shutdown("the engine stopped on an error and is not serving", st);
@@ -43,15 +61,17 @@ int Engine::gen_loop() {
rad_strerror(st));
return stop(st);
}
/* A decode pass's image, copied behind it on rank 0's stream; every rank holds the same
* pixels. */
if (const int64_t n = gen_->decode_bytes(); n > 0) {
const void* src = ranks_[0]->ctx.buf_ptr(img);
/* What the pass leaves for the host (an image, a window's samples, the frames' status),
* copied behind it on rank 0's stream; every rank holds the same values. */
for (const gen::IPassDriver::Readback& r : gen_->readbacks()) {
if (st < 0 || r.bytes <= 0) continue;
const void* src = ranks_[0]->ctx.buf_ptr(r.buf);
if (!src) {
RAD_ERR("the generator's image buffer was declared but never planned");
RAD_ERR("the generator's output buffer '%s' was declared but never planned",
ranks_[0]->program.buffers[r.buf].name.c_str());
return stop(RAD_E_STATE);
}
st = rad_memcpy_async(gen_->host_image(), src, n, ranks_[0]->ctx.stream());
st = rad_memcpy_async(r.host, src, r.bytes, ranks_[0]->ctx.stream());
}
for (auto& rk : ranks_)
if (st >= 0) st = rad_stream_sync(rk->ctx.stream());
@@ -59,7 +79,7 @@ int Engine::gen_loop() {
RAD_ERR("generator pass %d: the device failed: %s", step, rad_strerror(st));
return stop(st);
}
dump_buffers(ranks_[0]->ctx, step);
dump_buffers(ranks_[0]->ctx, step, pass_name(b->gen));
gen_->done();
++step;
}
+40 -25
View File
@@ -1,10 +1,10 @@
/* engine_lora.cpp -- runtime LoRA on the engine side: which modules adapters may target (fixed
* before declare), and loading an adapter into a slot of every rank's pools.
*
* A LOAD IS: pack the adapter for each rank (lora::load_adapter, host only), refuse a module no
* rank placed, copy each rank's bytes into the slot on a stream of its own, wait, and only then
* publish the name. A request can name the adapter only after the publish, so no step ever reads
* a slot while it is being written; a slot no published adapter holds is never referenced. */
* A load packs the adapter for each rank (lora::load_adapter, host only), refuses a module no rank
* placed, copies each rank's bytes into the slot on a stream of its own, waits, and only then
* publishes the name. A request can name the adapter only after the publish, so no step reads a
* slot while it is written. */
#include "engine_priv.h"
#include "lora/lora.h"
@@ -54,13 +54,8 @@ int read_targets(const std::string& dir, std::set<std::string>* out, std::string
int Engine::lora_targets() {
if (!cfg_.lora.enabled()) return RAD_OK;
lora_targets_ = cfg_.lora.targets;
lora_targets_ = std::set<std::string>(cfg_.lora.targets.begin(), cfg_.lora.targets.end());
if (lora_targets_.empty()) {
if (cfg_.lora.adapters.empty()) {
RAD_ERR("lora: --max-loras with no --lora names no module an adapter may target; give "
"them with --lora-target-modules (q_proj,k_proj,v_proj,o_proj,...)");
return RAD_E_INVAL;
}
for (const auto& [name, dir] : cfg_.lora.adapters) {
std::string err;
const int s = read_targets(dir, &lora_targets_, &err);
@@ -70,13 +65,6 @@ int Engine::lora_targets() {
}
}
}
std::set<std::string> seen;
for (const auto& [name, dir] : cfg_.lora.adapters) {
if (!seen.insert(name).second) {
RAD_ERR("lora: two adapters are named '%s'", name.c_str());
return RAD_E_INVAL;
}
}
lora_table_.reset(cfg_.lora.slots(), &lora_epoch_);
return RAD_OK;
}
@@ -92,6 +80,35 @@ int Engine::lora_start() {
t.c_str());
return RAD_E_UNSUPPORTED;
}
/* Every target is a module some rank carries adapters on. A leaf the model lacks, or holds
* only outside the trunk (embedding, lm_head, a tower, the drafter), would target nothing. */
{
std::set<std::string> carried;
for (const auto& r : ranks_)
for (const lora::Site& site : r->lora_sites)
for (const lora::SiteSource& src : site.sources)
if (src.targeted) carried.insert(src.module.substr(src.module.rfind('.') + 1));
for (const std::string& x : lora_targets_)
if (!carried.count(x)) {
RAD_ERR("lora: the target module '%s' is no trunk linear of this model, so no "
"adapter could land on it; leave it out of --lora-target-modules (or of "
"the adapters' target_modules)", x.c_str());
return RAD_E_UNSUPPORTED;
}
}
/* The adapter ops run in their GEMM's domain and read the pools on the card, so a targeted
* GEMM placed on the host could serve no adapter request. On the host backend every op and
* the pools are in host memory. */
if (!device_is_host())
for (const auto& r : ranks_)
for (const LoraIssueSite& site : r->program.lora_sites)
if (r->ctx.op_domain((rad_op)site.gemm) != RAD_DOMAIN_DEVICE) {
RAD_ERR("lora: rank %d: the GEMM over '%s' is placed on the host, and its "
"adapter ops read pools on the card; keep the targeted weights in "
"VRAM or leave the module out of --lora-target-modules", r->index,
r->program.lora_pools[(size_t)site.pool].weight.c_str());
return RAD_E_UNSUPPORTED;
}
{
const Program& P = ranks_[0]->program;
int64_t slot_bytes = 0;
@@ -118,12 +135,10 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri
std::lock_guard<std::mutex> lk(lora_mu_);
if (!cfg_.lora.enabled()) { *err = "the engine was started without adapters"; return RAD_E_STATE; }
if (name.empty()) { *err = "an adapter needs a name"; return RAD_E_INVAL; }
/* A SLOT FREED A MOMENT AGO IS WAITED FOR HERE, not handed back as a retry. It is reusable once
* the step loop has gone round three times (a pass issued ahead may still read it), and the
* loop goes round idle or busy, so that is milliseconds -- an unload followed at once by a load
* (a hot swap) would otherwise fail almost every time under traffic. Only other loads wait on
* lora_mu_ meanwhile; requests and unloads go to the table, and the step loop's counter is an
* atomic. */
/* A slot that is still cooling (lora/slots.h) is waited for here rather than answered with a
* retry: the step loop goes round idle or busy, so the wait is milliseconds, and a hot swap
* (unload, then load at once) would otherwise fail under traffic. Only other loads wait on
* lora_mu_ meanwhile; requests and unloads use the table alone. */
const auto give_up = std::chrono::steady_clock::now() + std::chrono::seconds(2);
int slot = -1;
for (;;) {
@@ -174,8 +189,8 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri
char* ds = (char*)P.buffers[lp.scale].ptr;
if (!da || !db || !ds) { rc = RAD_E_STATE; *err = "a pool has no address"; break; }
da += (int64_t)slot * ab; db += (int64_t)slot * bb; ds += (int64_t)slot * sb;
/* A pool this adapter does not touch is ZEROED, not left: the bytes are whatever the
* last adapter in the slot or the arena held, and a scale of 0 times a NaN is a NaN. */
/* A pool this adapter does not touch is zeroed, not left as it was: the bytes are what
* the slot's last adapter or the arena held, and a scale of 0 times a NaN is a NaN. */
if (ps.empty) {
if (rad_memset_async(da, 0, ab, st) < 0 || rad_memset_async(db, 0, bb, st) < 0 ||
rad_memset_async(ds, 0, sb, st) < 0)
+1 -1
View File
@@ -34,7 +34,7 @@ struct Engine::Rank {
int index = 0;
int device = 0;
Program program; /* declare runs once per rank: dimensions are already divided */
/* RUNTIME LoRA: this rank's sites (core/lora/lora.h), the loader's map from an adapter's
/* Runtime LoRA: this rank's sites (core/lora/lora.h), the loader's map from an adapter's
* modules to this rank's slot bytes. Empty with LoRA off. */
std::vector<lora::Site> lora_sites;
Plan plan;
+19 -3
View File
@@ -7,6 +7,7 @@
#include "device/device.h"
#include "rad_plugin.h"
#include <cstdio>
#include <cstring>
#include <cstdint>
#include <cstdlib>
@@ -21,7 +22,10 @@ namespace rad {
*
* RADIANCE_DUMP_BUF names declared buffers (comma separated); every step prints the first row of
* each: mean, largest magnitude and first four elements. RADIANCE_DUMP_HEAD=<n> adds the first n
* elements verbatim (integers included); RADIANCE_DUMP_TOPK=<k> adds the k largest.
* elements verbatim (integers included); RADIANCE_DUMP_TOPK=<k> adds the k largest. A name may
* carry a row count, `frame.mix:100`, to read that many rows as one (a code-major plane holds one
* code a row). RADIANCE_DUMP_DIR=<dir> also writes each read's raw bytes to
* <dir>/<step>-<phase>-<name>.bin, for a comparison against another implementation's tensors.
*
* It shows tensors inside a step, which neither rad-kbench (one op at a time) nor --debug-graph
* (what was declared) can. An environment variable at -vv only, because it adds a device-to-host
@@ -70,6 +74,13 @@ static void dump_row(int step, const char* phase, const char* name, uint32_t dty
uint64_t h = 1469598103934665603ull;
for (size_t i = 0; i < raw.size(); ++i) { h ^= raw[i]; h *= 1099511628211ull; }
const int64_t good = cnt - bad;
if (const char* dir = std::getenv("RADIANCE_DUMP_DIR"); dir && *dir) {
const std::string path = fmt("%s/%d-%s-%s.bin", dir, step, phase, name);
if (FILE* f = std::fopen(path.c_str(), "wb")) {
std::fwrite(raw.data(), 1, raw.size(), f);
std::fclose(f);
}
}
RAD_TRACE("step %d%-8s %-28s %-5s n=%lld hash %016llx mean %.6f amax %.5f "
"nonfinite %lld%s [%.6f %.6f %.6f %.6f]",
step, phase, name, rad_dtype_name(dtype), (long long)cnt, (unsigned long long)h,
@@ -159,8 +170,13 @@ void dump_buffers(Ctx& ctx, int step, const char* phase) {
for (const char* s = names; *s; ) {
const char* e = s;
while (*e && *e != ',') ++e;
const std::string want(s, (size_t)(e - s));
std::string want(s, (size_t)(e - s));
s = *e ? e + 1 : e;
int64_t rows = 1;
if (const size_t colon = want.find(':'); colon != std::string::npos) {
rows = std::max<long long>(1, std::strtoll(want.c_str() + colon + 1, nullptr, 10));
want.resize(colon);
}
if (want.empty()) continue;
/* Weights match the same names, to check that the loader put the right checkpoint tensor
@@ -188,7 +204,7 @@ void dump_buffers(Ctx& ctx, int step, const char* phase) {
const int64_t row = b.decl.rank >= 1 ? b.bytes / (b.decl.shape[0] ? b.decl.shape[0] : 1)
: b.bytes;
done = dump_at(ctx, step, phase, b.name, b.decl.dtype, ptr,
std::min<int64_t>(row, dump_cap()));
row <= dump_cap() ? std::min<int64_t>(row * rows, b.bytes) : dump_cap());
}
}
}
+791 -111
View File
File diff suppressed because it is too large. Load diff
+79 -17
View File
@@ -17,8 +17,8 @@
* convert time.
*
* An imported quantisation's descriptor (`auto-round`, `gptq`, `quark`, `compressed-tensors`,
* `paroquant`) names the tool, not a served form, so no plugin claims it; Checkpoint::imports()
* describes how the plugin is chosen.
* `paroquant`, `modelopt`) names the tool, not a served form, so no plugin claims it;
* Checkpoint::imports() describes how the plugin is chosen.
*/
#pragma once
#include "../rad_internal.h"
@@ -31,6 +31,7 @@
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
namespace rad {
@@ -54,12 +55,16 @@ struct SrcTensor {
* scale row covers. 0 for other tensors. */
int32_t gptq_bits = 0;
int64_t gptq_group = 0;
/* CT-INT4 (compressed-tensors' symmetric pack-quantized int4): `data` is X.weight_packed's
* int32 words [N, K / 8], eight codes per word along K from the low bits up, unsigned with zero
* point 8. The tensor described is the logical [N, K] code matrix, `rad_dtype` RAD_I4;
* `ct_group` is the K columns one scale of X.weight_scale [N, K / group] covers. 0 for other
* tensors. */
/* CT-INT4 (compressed-tensors' pack-quantized int4): `data` is X.weight_packed's int32 words
* [N, K / 8], eight codes per word along K from the low bits up, each the signed code plus 8.
* The tensor described is the logical [N, K] code matrix, `rad_dtype` RAD_I4 (symmetric) or
* RAD_U4 (asymmetric, the stored nibbles); `ct_group` is the K columns one scale of
* X.weight_scale [N, K / group] covers. 0 for other tensors. */
int64_t ct_group = 0;
/* An asymmetric CT-INT4 weight's X.weight_zero_point: int32 [ceil(N / 8), G], eight zero
* points per word along N from the low bits up, each the signed zero point plus 8
* (compressed-tensors packs it along dim 0). Null for a symmetric weight. */
const SrcTensor* ct_zero = nullptr;
/* ParoQuant's int5-bitplane (Import::ParoI5): `data` is the AWQ-packed low nibbles qweight
* [K, N/8] and the tensor described is the logical [N, K] u5 code matrix; `aux` are the fifth-bit
* plane qweight_hi [K, N/32], and the zero points qzeros [G, N/8] and qzeros_hi [G, N/32].
@@ -131,6 +136,9 @@ public:
/* Sub-tensor `index` along dim 0 of a stacked (rank >= 2) tensor, as a view owned here and
* valid for the checkpoint's life. Null, with the reason logged, if there is no such slice. */
const SrcTensor* slice(const SrcTensor& st, int index, const char* declared);
/* Rows [r0, r0 + n) along dim 0 of a plainly stored tensor, as a view owned here (a
* RAD_MAP_ROWS piece). Null, with the reason logged, when the rows are not there. */
const SrcTensor* rows(const SrcTensor& st, int64_t r0, int64_t n, const char* declared);
/* FP8's block, from quantization_config.weight_block_size; 128x128 when it says nothing. */
int64_t fp8_block_rows() const { return fp8_br_; }
@@ -141,21 +149,24 @@ public:
* (zero point stored less one). QuarkMx: Quark's MXFP4 (fp4 weights, per_group 32, e8m0
* scales, no per-layer overrides). ParoMx: ParoQuant's `paroquant_mxfp4` (Quark's codes and
* exponents in a rotated basis, rotations beside them). CtInt4, Nvfp4, CtFp8:
* compressed-tensors' pack-quantized int4, a release with an nvfp4-pack-quantized group, and
* one whose groups are all float-quantized FP8 (detect_import). In an Nvfp4 or CtFp8 release
* every weight without the NVFP4 tensors reads stock, so FP8 and bf16 linears beside the
* NVFP4 ones read by their own form. An unreadable form of these stays None, with the reason
* in import_refusal(). The quantization_config keys are then renamed
* `imported_quantization_config.*`, since they describe the tool, not a served format. */
enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoI5, ParoI4, Nvfp4, CtFp8 };
* compressed-tensors' pack-quantized int4 (symmetric, or asymmetric with a zero point), a
* release with an nvfp4-pack-quantized group, and one whose groups are all float-quantized FP8
* (detect_import). ModelOpt: NVIDIA ModelOpt's NVFP4, FP8, or both per layer
* (MIXED_PRECISION). In an Nvfp4, CtFp8 or ModelOpt release every weight without the NVFP4
* tensors reads stock, so FP8 and bf16 linears beside the NVFP4 ones read by their own form.
* An unreadable form of these stays None, with the reason in import_refusal(). The
* quantization_config keys are then renamed `imported_quantization_config.*`, since they
* describe the tool, not a served format. */
enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoI5, ParoI4, Nvfp4, CtFp8,
ModelOpt };
Import imports() const { return import_; }
const std::string& import_refusal() const { return import_why_; }
/* The pieces an imported `name` (a `.weight`) is read from, as views owned here: GPTQ-packed
* codes and their scales, Quark's codes and exponents as RAD dtypes, or NVFP4's codes as fp4
* beside an f32 scale plane derived from the e4m3 scales and the global scale. RAD_E_NOTFOUND
* when `name` is an ordinary tensor or absent; another error, with `why`, for an unreadable
* imported form. */
* beside an f32 scale plane derived from the e4m3 scales and the second level (a divisor in
* compressed-tensors, a multiplier in ModelOpt). RAD_E_NOTFOUND when `name` is an ordinary
* tensor or absent; another error, with `why`, for an unreadable imported form. */
int import_piece(const std::string& name, const SrcTensor** codes, const SrcTensor** scale,
std::string* why);
@@ -166,6 +177,7 @@ private:
const std::unordered_map<std::string, std::string>* owner = nullptr);
int open_safetensors(const std::string& path);
int open_diffusers();
int add_companions();
int open_gguf(const std::string& path);
void detect_import();
@@ -185,11 +197,27 @@ private:
Import import_ = Import::None;
std::string import_why_;
int64_t ct_group_ = 0; /* CtInt4: the group every weight's config states */
bool ct_asym_ = false; /* CtInt4: the config states asymmetric weights */
/* import_piece's answers by name, so a weight resolved twice reuses its views. */
std::unordered_map<std::string, std::pair<const SrcTensor*, const SrcTensor*>> imported_;
};
/* ================================================================== logical weights */
/* Another spelling of the numbers a weight ships, asked for by a recipe's `import` rule
* (ckpt_import_form). Each field left at its default keeps that part as the import writes it.
*
* codes an unsigned dtype of the shipped codes' width: a symmetric grid's signed codes c are
* written c + 2^(bits-1) under a zero point of 2^(bits-1), so (u - z) * s == c * s;
* zero the zero plane's dtype (a shipped or re-expressed zero point), which must hold it;
* scale the scale plane's dtype, each shipped scale rounded to nearest (counted when that
* changes it);
* block a scale shipped once per row or per tensor (FP8) repeated over this block grid,
* which every block's rows must share. */
struct ImportForm {
uint32_t codes = RAD_DT_INVALID, zero = RAD_DT_INVALID, scale = RAD_DT_INVALID;
int64_t block[2] = { 0, 0 };
};
/* A declared weight's source, as the name map resolves it: pieces joined along `concat_dim`, and
* for block-scaled FP8 each piece's scale plane beside it. */
struct CkptWeight {
@@ -216,6 +244,22 @@ struct CkptWeight {
* piece (a row part: gate and up, or q, k and v, each rotated separately). */
bool paro = false;
std::vector<const SrcTensor*> pq_pairs, pq_theta, pq_scale;
/* A weight-normalised tensor (RAD_MAP_WNORM): `pieces` is its direction v alone, and every
* element of v with first index i reads times wnorm_scale[i] = g_i / ||v_i||. Not trivial
* (the values change), so a recipe rule stores it. */
bool wnorm = false;
std::vector<float> wnorm_scale;
/* A weight computed from its sources at resolve (RAD_MAP_TRANSPOSE, RAD_MAP_EMA): its f32
* values in the logical shape, which ckpt_rows_f32 serves. Not trivial, so a recipe rule
* stores it. */
std::vector<float> derived;
/* An `import` rule's form, applied by ckpt_plane_rows (also `imported`). `rounded` counts the
* shipped scales `form.scale` does not hold exactly and `max_rel` is their largest relative
* change, both found by ckpt_import_form. */
bool reform = false;
ImportForm form{};
int64_t rounded = 0;
double max_rel = 0;
RadEncoding enc{};
std::string why;
};
@@ -226,6 +270,24 @@ struct CkptWeight {
int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, bool optional,
CkptWeight* out, std::string* why);
/* The quantiser name of a recipe rule rad-convert handles itself through ckpt_import_form. */
constexpr const char* kImportRule = "import";
/* An import rule's options (codes=DTYPE, zero=DTYPE, scale=DTYPE, block=RxC) as an ImportForm.
* RAD_E_INVAL, with the option named in `why`, for an option it does not take or a value it
* cannot read. */
int ckpt_import_form_parse(const std::vector<std::pair<std::string, std::string>>& options,
ImportForm* f, std::string* why);
/* Re-express a resolved `w` as `f` asks (a recipe's `import` rule): RAD_OK with `w->enc` the new
* encoding and the form recorded for ckpt_plane_rows. RAD_E_UNSUPPORTED, with `why`, when `w` is
* a plain float weight with nothing shipped to re-express (the rule declines it); any other error,
* with `why`, when its shipped form cannot take `f`: a form other than an integer grid (GPTQ,
* CT-INT4) or an FP8 weight with one scale per row or per tensor, a code or zero dtype that does
* not hold the shipped values, or a block whose rows carry different scales. Rounding a scale to
* `f.scale` is allowed and counted in `w->rounded`. */
int ckpt_import_form(CkptWeight* w, const ImportForm& f, std::string* why);
/* The checkpoint tensor a piece or scale reads: its name without the "[index]" a slice of a
* stacked tensor carries, so an expert reads the stack it was cut from. */
std::string ckpt_tensor_of(const SrcTensor& t);
+41 -2
View File
@@ -55,7 +55,42 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
"RAD_SHARD_NONE", w.decl.shard == RAD_SHARD_ROW ? "ROW" : "COL",
rank));
const bool cols = w.decl.shard == RAD_SHARD_COL || rank == 1;
if (cols) {
const int np1 = rank == 1 && w.decl.n_row_parts > 1 ? w.decl.n_row_parts : 1;
if (cols && np1 > 1) {
/* A rank-1 weight of stacked parts (a fused projection's bias, [value | gate]) is cut
* as the matrix it goes with: this rank's slice of each part, never a contiguous
* slice of the stack. Per-part spans and declared parts read as the row cut's do. */
if (w.n_part_spans > 0) {
if (w.n_part_spans != np1)
return refuse(fmt("%d per-part spans for %d stacked parts", w.n_part_spans, np1));
int64_t sum = 0, soff = 0;
for (int g = 0; g < np1; ++g) sum += w.part_total[g];
if (sum != VC)
return refuse(fmt("the %d stacked parts' stated elements sum to %lld and the "
"entry has %lld", np1, (long long)sum, (long long)VC));
for (int g = 0; g < np1; ++g) {
view.push_back({ 0, VR, soff + w.part_lo[g], soff + w.part_hi[g] });
soff += w.part_total[g];
}
} else {
if (span)
return refuse("a single span over a rank-1 weight of stacked parts is not "
"defined; state one span a part");
if (VC % world) return refuse(fmt("%lld elements do not divide by %d ranks",
(long long)VC, world));
int64_t sum = 0, soff = 0;
for (int g = 0; g < np1; ++g) sum += w.decl.row_parts[g];
if (sum != VC / world)
return refuse(fmt("%d declared parts sum to %lld, and the rank's share of %lld "
"elements at %d ranks is %lld", np1, (long long)sum,
(long long)VC, world, (long long)(VC / world)));
for (int g = 0; g < np1; ++g) {
const int64_t take = w.decl.row_parts[g];
view.push_back({ 0, VR, soff + index * take, soff + (index + 1) * take });
soff += take * world;
}
}
} else if (cols) {
int64_t c0 = w.shard_lo, c1 = w.shard_hi;
if (!span) {
if (VC % world) return refuse(fmt("%lld columns do not divide by %d ranks",
@@ -162,7 +197,11 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
s.rows += pq.rows;
s.cols = pq.cols;
}
if (s.rows != w.sel_rows[k] || s.cols != w.sel_cols[k])
/* A vector's stacked parts come out as one piece a part, each a row of the share; laid
* end to end they are the declared vector, so only the element count has to agree. */
const bool fits = rank == 1 ? s.rows * s.cols == w.sel_rows[k] * w.sel_cols[k]
: s.rows == w.sel_rows[k] && s.cols == w.sel_cols[k];
if (!fits)
return refuse(fmt("this rank's share of the '%s' plane is [%lld, %lld] and the "
"declaration says [%lld, %lld]", p.role, (long long)s.rows,
(long long)s.cols, (long long)w.sel_rows[k],
+76
View File
@@ -0,0 +1,76 @@
/* audio.h -- audio generation: the request and the channel its audio comes back on.
*
* An audio generator (abi/rad_builder.h, rad_declare_audio_generator) makes a piece in two stages,
* a language model writing it frame by frame and a denoiser turning runs of frames (windows) into
* audio, which a vocoder plays. core/gen/audio_driver.h turns a request into those passes; this is
* what a caller hands it and what it hands back: a window's samples as each is vocoded, then the
* end.
*/
#pragma once
#include "rad_core.h"
#include <atomic>
#include <condition_variable>
#include <deque>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace rad {
namespace gen {
/* One window's playable samples, interleaved, in [-1, 1]. */
struct AudioChunk {
int32_t window = 0;
std::vector<float> samples;
};
/* As Ticket (gen.h) is for an image: the driver thread writes, the caller reads. */
class AudioTicket {
public:
/* driver side */
void push(AudioChunk&& c);
void finish(int status, const std::string& why = std::string());
/* caller side: the next chunk, or false once the request has ended and every chunk was
* taken. Waits at most `ms` milliseconds; `*timed_out` marks a false that was a timeout. */
bool next(AudioChunk* out, int ms, bool* timed_out);
bool finished() const;
int status() const;
std::string why() const;
std::atomic<bool> cancel{false};
/* Usage for the response, written by the driver before finish(): prompt tokens, frames made,
* windows played and per-phase times. */
int64_t in_tokens = 0, frames = 0, windows = 0;
int64_t t_submit_ns = 0, t_prompt_ns = 0, t_frames_ns = 0, t_first_audio_ns = 0,
t_done_ns = 0;
/* Why the piece ended: the model ended it, or it reached the request's length. */
bool model_ended = false;
private:
mutable std::mutex mu_;
std::condition_variable cv_;
std::deque<AudioChunk> q_;
bool done_ = false;
int status_ = RAD_OK;
std::string why_;
};
struct AudioRequest {
/* The conditional prompt, and the unconditional one when the declaration renders it from a
* template of its own (RadAudioGenDecl::neg_tmpl); otherwise it is derived from the
* conditional prompt as the declaration says (neg_token), and `neg_tokens` is empty. */
std::vector<int32_t> tokens;
std::vector<int32_t> neg_tokens;
int64_t max_frames = 0; /* the most frames to make, >= 1 */
int32_t steps = 0; /* 0: the model's default */
float cfg = 0.0f; /* 0: the model's default */
uint64_t seed = 0;
std::shared_ptr<AudioTicket> ticket;
};
} /* namespace gen */
} /* namespace rad */
+910
View File
@@ -0,0 +1,910 @@
/* audio_driver.cpp -- the audio generator's pass driver (audio_driver.h), and the ticket a caller
* waits on (audio.h). */
#include "audio_driver.h"
#include "sched/mem_iface.h"
#include <algorithm>
#include <chrono>
#include <cstring>
namespace rad {
namespace gen {
/* ================================================================== the ticket */
void AudioTicket::push(AudioChunk&& c) {
{
std::lock_guard<std::mutex> lk(mu_);
q_.push_back(std::move(c));
}
cv_.notify_all();
}
void AudioTicket::finish(int status, const std::string& why) {
{
std::lock_guard<std::mutex> lk(mu_);
if (done_) return;
done_ = true;
status_ = status;
why_ = why;
}
cv_.notify_all();
}
bool AudioTicket::next(AudioChunk* out, int ms, bool* timed_out) {
std::unique_lock<std::mutex> lk(mu_);
if (timed_out) *timed_out = false;
if (q_.empty() && !done_)
cv_.wait_for(lk, std::chrono::milliseconds(ms), [this] { return !q_.empty() || done_; });
if (!q_.empty()) {
*out = std::move(q_.front());
q_.pop_front();
return true;
}
if (!done_ && timed_out) *timed_out = true;
return false;
}
bool AudioTicket::finished() const {
std::lock_guard<std::mutex> lk(mu_);
return done_ && q_.empty();
}
int AudioTicket::status() const {
std::lock_guard<std::mutex> lk(mu_);
return status_;
}
std::string AudioTicket::why() const {
std::lock_guard<std::mutex> lk(mu_);
return why_;
}
/* ================================================================== sizing */
namespace {
constexpr int64_t kAlign = 256;
int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
struct Sizes {
int64_t T = 0, S = 0, L = 0, NB = 0;
};
Sizes sizes_of(const Program& prog, int64_t block_size) {
const RadAudioGenDecl& d = prog.audio_gen;
Sizes z;
z.T = prog.ctx.max_tok;
z.S = prog.ctx.max_seqs;
z.L = d.max_lanes;
z.NB = block_size > 0 ? (AudioDriver::max_seq_rows(d) + block_size - 1) / block_size : 0;
return z;
}
/* Region offsets and sizes, in order, and the total; shared by the allocation and the VRAM budget.
* The order is the enum's in audio_driver.h. */
int64_t carve(const Sizes& z, int64_t (*bytes)[2], int n) {
const int64_t I = 4;
const int64_t SL = std::max(z.S, z.L);
const int64_t want[] = {
z.T * I, /* R_TOK */
z.T * I, /* R_POS */
(z.S + 1) * I, /* R_CU */
z.T * I, /* R_SLOT */
z.S * z.NB * I, /* R_BT */
z.S * I, /* R_USED */
z.L * I, /* R_LANE */
z.L * I, /* R_LAST */
z.L * I, /* R_FRAME */
2 * SL * I, /* R_SEED */
z.S * 4, /* R_T */
z.S * 4, /* R_TN */
z.S * 4, /* R_CFG */
z.S * I, /* R_PAIR */
z.S * I, /* R_WLANE */
z.S * I, /* R_FLAGS */
z.S * I, /* R_WIDX */
z.S * I, /* R_WF0 */
z.S * I, /* R_WNF */
(z.S + 1) * I, /* R_LCU */
z.T * I, /* R_LSRC */
z.S * I, /* R_ESLOT */
z.S * I, /* R_LROW */
z.S * I, /* R_PREFIX */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
bytes[r][0] = off;
bytes[r][1] = want[r];
off = align_up(off + want[r]);
}
return off;
}
} /* namespace */
int64_t AudioDriver::device_bytes(const Program& prog) {
if (!prog.is_audio_generator() || prog.kv_groups.size() < 2) return 0;
const Sizes z = sizes_of(prog, prog.kv_groups[1].block_size);
int64_t b[R_N][2];
return carve(z, b, R_N);
}
int AudioDriver::init(const Program& prog, IKVManager* kv, const std::vector<RankIO>& ranks) {
fini();
if (!prog.is_audio_generator()) return RAD_E_STATE;
decl_ = prog.audio_gen;
name_ = prog.agen_str.name;
kv_ = kv;
ranks_ = ranks;
/* The language model's KV, both branches of every lane: one paged full-attention group. */
if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL ||
prog.kv_groups[1].block_size <= 0) {
RAD_ERR("audio generator: the program declares %zu KV group(s); the driver stages exactly "
"one full-attention group, the language model's", prog.kv_groups.size() - 1);
return RAD_E_UNSUPPORTED;
}
kv_group_ = 1;
block_size_ = prog.kv_groups[1].block_size;
const Sizes z = sizes_of(prog, block_size_);
max_tok_ = z.T;
max_seqs_ = z.S;
max_blocks_ = z.NB;
neg_own_ = !prog.agen_str.neg_tmpl.empty();
/* A FRAME pass carries both branches of every lane; a window's step at least one window, a
* chunk's vocode its frames and their context, and a whole prompt both its branches. */
const int64_t step_rows = chunked() ? decl_.voc_context + decl_.voc_chunk
: 2 * (decl_.win_lead + win_latents(decl_.win_frames));
const int64_t prompt_rows = decl_.prompt_whole ? 2 * decl_.max_prompt : 2;
if (max_seqs_ < 2 * decl_.max_lanes || max_tok_ < 2 * decl_.max_lanes ||
max_tok_ < step_rows || max_tok_ < prompt_rows) {
RAD_ERR("audio generator: a pass carries %lld rows of %lld sequences; '%s' needs %lld "
"sequences for its %lld lanes, %lld rows for a %s and %lld for a whole prompt",
(long long)max_tok_, (long long)max_seqs_, name_.c_str(),
(long long)(2 * decl_.max_lanes), (long long)decl_.max_lanes,
(long long)step_rows, chunked() ? "chunk's vocode" : "window's step",
(long long)prompt_rows);
return RAD_E_UNSUPPORTED;
}
int64_t b[R_N][2];
bytes_ = carve(z, b, R_N);
for (int r = 0; r < R_N; ++r) { reg_[r].off = b[r][0]; reg_[r].bytes = b[r][1]; reg_[r].used = 0; }
host_ = static_cast<char*>(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED));
status_host_ = static_cast<int32_t*>(rad_dev_alloc(decl_.max_lanes * 4, RAD_MEM_HOST_PINNED));
audio_bytes_ = (chunked() ? decl_.voc_chunk : win_latents(decl_.win_frames)) *
decl_.samples_per_latent * decl_.channels * 4;
audio_host_ = static_cast<float*>(rad_dev_alloc(audio_bytes_, RAD_MEM_HOST_PINNED));
if (!host_ || !status_host_ || !audio_host_) {
RAD_ERR("audio generator: no pinned host memory for the pass staging (%lld + %lld bytes)",
(long long)bytes_, (long long)audio_bytes_);
return RAD_E_NOMEM;
}
std::memset(host_, 0, (size_t)bytes_);
dev_.assign(ranks_.size(), nullptr);
for (size_t r = 0; r < ranks_.size(); ++r) {
RAD_TRY(rad_dev_set(ranks_[r].device));
dev_[r] = rad_dev_alloc(bytes_, RAD_MEM_DEVICE);
if (!dev_[r]) {
RAD_ERR("audio generator: rank %zu has no room for the pass staging (%lld bytes)", r,
(long long)bytes_);
return RAD_E_NOMEM;
}
}
if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0].device));
out_.assign(ranks_.size(), RadBatch{});
aout_.assign(ranks_.size(), RadAudioGenBatch{});
kout_.assign(ranks_.size(), RadKVGroupBatch{});
free_lanes_.clear();
for (int64_t i = decl_.max_lanes - 1; i >= 0; --i) free_lanes_.push_back((int32_t)i);
return RAD_OK;
}
void AudioDriver::fini() {
for (size_t r = 0; r < dev_.size(); ++r)
if (dev_[r]) {
if (r < ranks_.size()) rad_dev_set(ranks_[r].device);
rad_dev_free(dev_[r], RAD_MEM_DEVICE);
}
dev_.clear();
if (!ranks_.empty()) rad_dev_set(ranks_[0].device);
if (host_) rad_dev_free(host_, RAD_MEM_HOST_PINNED);
if (status_host_) rad_dev_free(status_host_, RAD_MEM_HOST_PINNED);
if (audio_host_) rad_dev_free(audio_host_, RAD_MEM_HOST_PINNED);
host_ = nullptr;
status_host_ = nullptr;
audio_host_ = nullptr;
}
/* ================================================================== requests */
int AudioDriver::submit(std::unique_ptr<AudioRequest> r, std::string* why) {
if (!r || !r->ticket) return RAD_E_INVAL;
const RadAudioGenDecl& d = decl_;
auto no = [&](const std::string& w) {
if (why) *why = w;
return RAD_E_INVAL;
};
const int64_t T = (int64_t)r->tokens.size(), Tn = (int64_t)r->neg_tokens.size();
if (!neg_own_ && T <= d.neg_keep_head + d.neg_keep_tail)
return no("the prompt is " + std::to_string(T) + " tokens, too short to hold its own "
"markers");
if (T < 1 || std::max(T, Tn) > d.max_prompt)
return no("the prompt is " + std::to_string(std::max(T, Tn)) + " tokens; this model takes "
"1.." + std::to_string(d.max_prompt));
if (r->max_frames < 1 || r->max_frames > d.max_frames)
return no("the length must be 1.." + std::to_string(d.max_frames) + " frames (" +
std::to_string(d.max_frames * d.frame_rate_den / d.frame_rate_num) +
" seconds)");
if (r->steps < 0 || r->steps > 1000) return no("num_inference_steps must be 1..1000");
if (r->cfg != 0.0f && !(r->cfg >= 1.0f)) return no("guidance_scale must be >= 1");
if (!kv_->can_ever_fit(std::max(T, Tn) + r->max_frames + 1))
return no("a piece of " + std::to_string(r->max_frames) + " frames after a " +
std::to_string(T) + "-token prompt does not fit the KV cache even when it is "
"empty; ask for a shorter piece");
r->ticket->t_submit_ns = (int64_t)rad_mono_ns();
std::lock_guard<std::mutex> lk(mu_);
if (closed_) {
if (why) *why = closed_why_;
return closed_status_;
}
auto j = std::make_unique<Job>();
j->id = next_id_++;
j->T = T;
j->req = std::move(r);
jobs_.push_back(std::move(j));
return RAD_OK;
}
void AudioDriver::shutdown(const char* why, int status) {
std::lock_guard<std::mutex> lk(mu_);
closed_ = true;
closed_why_ = why ? why : "the engine stopped";
closed_status_ = status;
for (auto& j : jobs_) j->req->ticket->finish(status, closed_why_);
}
int64_t AudioDriver::queued() const {
std::lock_guard<std::mutex> lk(mu_);
int64_t n = 0;
for (const auto& j : jobs_) if (!j->admitted) ++n;
return n;
}
int64_t AudioDriver::running() const {
std::lock_guard<std::mutex> lk(mu_);
int64_t n = 0;
for (const auto& j : jobs_) if (j->admitted) ++n;
return n;
}
AudioDriver::Job* AudioDriver::job_locked(uint64_t id) {
for (auto& j : jobs_) if (j->id == id) return j.get();
return nullptr;
}
void AudioDriver::release_locked(Job& j) {
for (int b = 0; b < 2; ++b)
if (j.seq[b]) {
kv_->free_sequence(j.seq[b]);
j.seq[b] = 0;
}
j.have_kv = false;
if (j.lane >= 0) {
free_lanes_.push_back(j.lane);
j.lane = -1;
}
}
void AudioDriver::fail_locked(Job& j, int status, const std::string& why) {
j.failed = true;
j.req->ticket->finish(status, why);
}
/* In arrival order; a request that does not fit stops the ones behind it. */
int AudioDriver::admit_locked() {
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted || j.failed) continue;
if (free_lanes_.empty()) break;
const AudioRequest& r = *j.req;
const float cfg = r.cfg > 0.0f ? r.cfg : (float)decl_.default_cfg;
/* The unconditional prompt: the request's own (the conditional one at guidance 1, which
* makes the guided logits the conditional ones), or derived from the conditional one. */
std::vector<int32_t> neg = r.tokens;
if (neg_own_ && cfg != 1.0f && !r.neg_tokens.empty()) {
neg = r.neg_tokens;
} else if (!neg_own_) {
for (int64_t i = decl_.neg_keep_head; i < j.T - decl_.neg_keep_tail; ++i)
neg[(size_t)i] = decl_.neg_token;
}
/* Both branches for the whole piece, so nothing in flight ever waits for KV. */
bool ok = true;
for (int b = 0; b < 2 && ok; ++b) {
const int64_t rows = (b ? (int64_t)neg.size() : j.T) + r.max_frames + 1;
j.seq[b] = ((uint64_t)1 << 61) | next_seq_++;
if (kv_->add_sequence(j.seq[b]) < 0 || kv_->ensure(j.seq[b], rows) < 0) ok = false;
}
if (!ok) {
for (int b = 0; b < 2; ++b)
if (j.seq[b]) {
if (kv_->has_sequence(j.seq[b])) kv_->free_sequence(j.seq[b]);
j.seq[b] = 0;
}
break;
}
j.have_kv = true;
j.lane = free_lanes_.back();
free_lanes_.pop_back();
j.neg = std::move(neg);
j.Tn = (int64_t)j.neg.size();
j.steps = r.steps > 0 ? r.steps : (int32_t)decl_.default_steps;
j.cfg = cfg;
j.req->ticket->in_tokens = j.T;
j.admitted = true;
}
return RAD_OK;
}
/* ================================================================== windows */
/* Window k is frames [k hop, k hop + win_frames), cut short at the piece's end. Window 0 always
* exists; window k >= 1 exists while frames remain past its overlap with window k - 1. */
int64_t AudioDriver::window_frames(const Job& j, int32_t k) const {
const int64_t f0 = win_frame0(k);
return j.ar_done ? std::min<int64_t>(decl_.win_frames, j.kept - f0) : decl_.win_frames;
}
bool AudioDriver::window_ready(const Job& j) const {
if (j.voc_due >= 0) return false;
if (j.win_step > 0) return true;
const int64_t k = j.win;
if (j.ar_done)
return k == 0 ? j.kept >= 1
: j.kept > k * decl_.win_hop + (decl_.win_frames - decl_.win_hop);
return j.kept >= k * decl_.win_hop + decl_.win_frames;
}
bool AudioDriver::chunk_due(const Job& j) const {
const int64_t ready = j.kept - j.played;
return !j.finished && (ready >= decl_.voc_chunk || (j.ar_done && ready > 0));
}
int AudioDriver::window_last(const Job& j, int32_t k) const {
const bool next_exists =
j.kept > (int64_t)(k + 1) * decl_.win_hop + (decl_.win_frames - decl_.win_hop);
if (next_exists) return 0;
return j.ar_done ? 1 : -1;
}
/* ================================================================== staging */
int AudioDriver::upload() {
for (size_t r = 0; r < ranks_.size(); ++r)
for (int g = 0; g < R_N; ++g) {
if (reg_[g].used <= 0) continue;
RAD_TRY(rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off,
reg_[g].used, ranks_[r].stream));
}
return RAD_OK;
}
void AudioDriver::base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int32_t max_ctx,
int step, bool kv, int64_t bt_pitch) {
for (size_t r = 0; r < ranks_.size(); ++r) {
RadBatch& B = out_[r];
RadAudioGenBatch& A = aout_[r];
RadKVGroupBatch& K = kout_[r];
const int ri = (int)r;
B = RadBatch{};
B.step = step;
B.phase = RAD_PHASE_PREFILL;
B.n_tok = n_tok;
B.n_seq = n_seq;
B.max_q_len = max_q;
B.max_ctx_len = max_ctx;
B.max_q_len_prefill = max_q;
B.token_ids = dptr<int32_t>(ri, R_TOK);
B.positions = dptr<int32_t>(ri, R_POS);
B.cu_seqlens = dptr<int32_t>(ri, R_CU);
if (kv) {
K = RadKVGroupBatch{};
K.group = (rad_kvgroup)kv_group_;
K.slot_mapping = dptr<int32_t>(ri, R_SLOT);
K.block_table = dptr<int32_t>(ri, R_BT);
K.block_table_pitch = bt_pitch;
K.seqused = dptr<int32_t>(ri, R_USED);
K.block_size = block_size_;
K.max_blocks = max_blocks_;
B.n_kv_groups = 1;
B.kv = &K;
}
A = RadAudioGenBatch{};
A.lane = dptr<int32_t>(ri, R_LANE);
A.last = dptr<int32_t>(ri, R_LAST);
A.frame = dptr<int32_t>(ri, R_FRAME);
A.seed = dptr<uint32_t>(ri, R_SEED);
A.t = dptr<float>(ri, R_T);
A.t_next = dptr<float>(ri, R_TN);
A.cfg = dptr<float>(ri, R_CFG);
A.pair = dptr<int32_t>(ri, R_PAIR);
A.win_lane = dptr<int32_t>(ri, R_WLANE);
A.flags = dptr<int32_t>(ri, R_FLAGS);
A.win_index = dptr<int32_t>(ri, R_WIDX);
A.win_frame0 = dptr<int32_t>(ri, R_WF0);
A.win_frames = dptr<int32_t>(ri, R_WNF);
A.lat_cu = dptr<int32_t>(ri, R_LCU);
A.lat_src = dptr<int32_t>(ri, R_LSRC);
A.slot = dptr<int32_t>(ri, R_ESLOT);
A.last_row = dptr<int32_t>(ri, R_LROW);
A.prefix = dptr<int32_t>(ri, R_PREFIX);
B.agen_b = &A;
}
}
/* The KV slot of position `p` in a sequence with this block table. */
static int32_t slot_of(const std::vector<int32_t>& bt, int64_t p, int64_t bs) {
const int64_t bi = p / bs;
return bi < (int64_t)bt.size() ? (int32_t)(bt[(size_t)bi] * bs + p % bs) : -1;
}
/* ================================================================== the passes */
const RadBatch* AudioDriver::next(int step) {
std::lock_guard<std::mutex> lk(mu_);
pass_ = Pass{};
rb_.clear();
if (closed_) return nullptr;
/* Retire finished, failed and cancelled jobs, returning their KV and lanes before admitting.
* Safe because next() runs between passes, with nothing in flight. */
for (auto it = jobs_.begin(); it != jobs_.end();) {
Job& j = **it;
const bool cancelled = j.req->ticket->cancel.load(std::memory_order_acquire);
if (!(j.failed || cancelled || j.finished)) { ++it; continue; }
if (cancelled && !j.failed && !j.finished)
j.req->ticket->finish(RAD_E_CANCELLED, "the request was cancelled");
release_locked(j);
it = jobs_.erase(it);
}
admit_locked();
/* 1. A vocode: a chunk of frames that is ready, or a finished window, once it is known
* whether a window follows it. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed) continue;
if (chunked()) {
if (chunk_due(j)) return build_chunk(j, step);
continue;
}
if (j.voc_due >= 0 && window_last(j, j.voc_due) >= 0) return build_vocode(j, step);
}
/* 2. A prompt chunk. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted && !j.failed && j.prompt_done < j.T) return build_prompt(j, step);
}
/* 3. A frame of every lane in its autoregressive stage, or a step of the ready windows. */
std::vector<Job*> fr, win;
int64_t win_rows = 0, win_ent = 0;
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed || j.prompt_done < j.T) continue;
if (!j.ar_done) fr.push_back(&j);
if (!chunked() && window_ready(j)) {
const int64_t nb = j.cfg > 1.0f ? 2 : 1;
const int64_t rows =
nb * (decl_.win_lead + win_latents(window_frames(j, j.win)));
if (win_rows + rows <= max_tok_ && win_ent + nb <= max_seqs_) {
win_rows += rows;
win_ent += nb;
win.push_back(&j);
}
}
}
if (!fr.empty() && (win.empty() || frame_turn_)) {
frame_turn_ = false;
return build_frame(fr, step);
}
if (!win.empty()) {
frame_turn_ = true;
return build_window(win, step);
}
return nullptr;
}
const RadBatch* AudioDriver::batch_for(int rank) const {
if (rank < 0 || (size_t)rank >= out_.size() || pass_.kind == 0) return nullptr;
return &out_[(size_t)rank];
}
const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
/* Each branch's rows: both whole, or the same chunk of both (their lengths are then equal). */
const int64_t p0 = j.prompt_done;
int64_t cb[2];
if (decl_.prompt_whole) {
cb[0] = j.T;
cb[1] = j.Tn;
} else {
cb[0] = cb[1] = std::min<int64_t>(j.T - j.prompt_done, max_tok_ / 2);
}
const int64_t cmax = std::max(cb[0], cb[1]);
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* pos = hptr<int32_t>(R_POS);
int32_t* slot = hptr<int32_t>(R_SLOT);
int32_t* cu = hptr<int32_t>(R_CU);
int64_t pitch = 1;
for (int b = 0; b < 2; ++b)
pitch = std::max<int64_t>(pitch, (int64_t)kv_->block_table(j.seq[b], kv_group_).size());
int32_t* btab = hptr<int32_t>(R_BT);
int32_t* used = hptr<int32_t>(R_USED);
cu[0] = 0;
for (int b = 0; b < 2; ++b) {
const std::vector<int32_t>& src = b ? j.neg : j.req->tokens;
const std::vector<int32_t>& bt = kv_->block_table(j.seq[b], kv_group_);
for (int64_t i = 0; i < cb[b]; ++i) {
const int64_t e = cu[b] + i;
tok[e] = src[(size_t)(p0 + i)];
pos[e] = (int32_t)(p0 + i);
slot[e] = slot_of(bt, p0 + i, block_size_);
}
cu[b + 1] = (int32_t)(cu[b] + cb[b]);
for (int64_t k = 0; k < pitch; ++k)
btab[b * pitch + k] = k < (int64_t)bt.size() ? bt[(size_t)k] : -1;
used[b] = (int32_t)(p0 + cb[b]);
}
const int64_t rows = cu[2];
const bool last = p0 + cb[0] == j.T;
for (int b = 0; b < 2; ++b) {
hptr<int32_t>(R_ESLOT)[b] = 2 * j.lane + b;
hptr<int32_t>(R_LROW)[b] = cu[b + 1] - 1;
hptr<int32_t>(R_PREFIX)[b] = (int32_t)p0;
}
reg_[R_ESLOT].used = reg_[R_LROW].used = reg_[R_PREFIX].used = 2 * 4;
hptr<int32_t>(R_LANE)[0] = j.lane;
hptr<int32_t>(R_LAST)[0] = last ? 1 : 0;
hptr<uint32_t>(R_SEED)[0] = (uint32_t)(j.req->seed & 0xffffffffu);
hptr<uint32_t>(R_SEED)[1] = (uint32_t)(j.req->seed >> 32);
reg_[R_TOK].used = reg_[R_POS].used = reg_[R_SLOT].used = rows * 4;
reg_[R_CU].used = 3 * 4;
reg_[R_BT].used = 2 * pitch * 4;
reg_[R_USED].used = 2 * 4;
reg_[R_LANE].used = reg_[R_LAST].used = 4;
reg_[R_SEED].used = 8;
if (upload() < 0) return nullptr;
base_batches(rows, 2, (int32_t)cmax, (int32_t)(p0 + cmax), step, true, pitch);
h_lane_.assign(1, j.lane);
h_last_.assign(1, last ? 1 : 0);
for (size_t r = 0; r < ranks_.size(); ++r) {
out_[r].gen = RAD_GEN_PASS_PROMPT;
RadAudioGenBatch& A = aout_[r];
A.n_lane = 1;
A.lane_h = h_lane_.data();
A.last_h = h_last_.data();
}
pass_.kind = RAD_GEN_PASS_PROMPT;
pass_.jobs.assign(1, j.id);
pass_.rows.assign(1, cb[0]);
return &out_[0];
}
const RadBatch* AudioDriver::build_frame(const std::vector<Job*>& js, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const int64_t L = (int64_t)js.size(), S = 2 * L;
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* pos = hptr<int32_t>(R_POS);
int32_t* slot = hptr<int32_t>(R_SLOT);
int32_t* cu = hptr<int32_t>(R_CU);
int32_t* btab = hptr<int32_t>(R_BT);
int32_t* used = hptr<int32_t>(R_USED);
int32_t* lane = hptr<int32_t>(R_LANE);
int32_t* frame = hptr<int32_t>(R_FRAME);
uint32_t* seed = hptr<uint32_t>(R_SEED);
int64_t pitch = 1;
int32_t max_ctx = 0;
for (const Job* j : js)
for (int b = 0; b < 2; ++b)
pitch = std::max<int64_t>(pitch, (int64_t)kv_->block_table(j->seq[b], kv_group_).size());
h_lane_.assign((size_t)L, 0);
h_frame_.assign((size_t)L, 0);
pass_.jobs.clear();
for (int64_t i = 0; i < L; ++i) {
const Job& j = *js[(size_t)i];
for (int b = 0; b < 2; ++b) {
/* The frame's row follows the branch's prompt and its earlier frames. */
const int64_t p = (b ? j.Tn : j.T) + j.frame;
const int64_t e = 2 * i + b;
const std::vector<int32_t>& bt = kv_->block_table(j.seq[b], kv_group_);
tok[e] = 0;
pos[e] = (int32_t)p;
slot[e] = slot_of(bt, p, block_size_);
cu[e] = (int32_t)e;
for (int64_t k = 0; k < pitch; ++k)
btab[e * pitch + k] = k < (int64_t)bt.size() ? bt[(size_t)k] : -1;
used[e] = (int32_t)(p + 1);
hptr<int32_t>(R_ESLOT)[e] = 2 * j.lane + b;
hptr<int32_t>(R_LROW)[e] = (int32_t)e;
max_ctx = std::max<int32_t>(max_ctx, (int32_t)(p + 1));
}
hptr<float>(R_CFG)[i] = j.cfg;
lane[i] = h_lane_[(size_t)i] = j.lane;
frame[i] = h_frame_[(size_t)i] = j.frame;
seed[2 * i] = (uint32_t)(j.req->seed & 0xffffffffu);
seed[2 * i + 1] = (uint32_t)(j.req->seed >> 32);
pass_.jobs.push_back(j.id);
}
cu[S] = (int32_t)S;
reg_[R_TOK].used = reg_[R_POS].used = reg_[R_SLOT].used = S * 4;
reg_[R_CU].used = (S + 1) * 4;
reg_[R_BT].used = S * pitch * 4;
reg_[R_USED].used = S * 4;
reg_[R_LANE].used = reg_[R_FRAME].used = reg_[R_CFG].used = L * 4;
reg_[R_SEED].used = 2 * L * 4;
reg_[R_ESLOT].used = reg_[R_LROW].used = S * 4;
if (upload() < 0) return nullptr;
base_batches(S, S, 1, max_ctx, step, true, pitch);
for (size_t r = 0; r < ranks_.size(); ++r) {
RadBatch& B = out_[r];
B.gen = RAD_GEN_PASS_FRAME;
B.phase = RAD_PHASE_DECODE;
B.n_seq_decode = S;
B.n_tok_decode = S;
B.max_q_len_decode = 1;
B.max_q_len_prefill = 0;
RadAudioGenBatch& A = aout_[r];
A.n_lane = L;
A.lane_h = h_lane_.data();
A.frame_h = h_frame_.data();
}
rb_.assign(1, Readback{ decl_.status, decl_.max_lanes * 4, status_host_ });
pass_.kind = RAD_GEN_PASS_FRAME;
return &out_[0];
}
const RadBatch* AudioDriver::build_window(const std::vector<Job*>& js, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* pos = hptr<int32_t>(R_POS);
int32_t* cu = hptr<int32_t>(R_CU);
float* t = hptr<float>(R_T);
float* tn = hptr<float>(R_TN);
float* cfg = hptr<float>(R_CFG);
int32_t* pair = hptr<int32_t>(R_PAIR);
int32_t* wlane = hptr<int32_t>(R_WLANE);
int32_t* flags = hptr<int32_t>(R_FLAGS);
int32_t* widx = hptr<int32_t>(R_WIDX);
int32_t* wf0 = hptr<int32_t>(R_WF0);
int32_t* wnf = hptr<int32_t>(R_WNF);
int32_t* lcu = hptr<int32_t>(R_LCU);
int32_t* lsrc = hptr<int32_t>(R_LSRC);
uint32_t* seed = hptr<uint32_t>(R_SEED);
h_wlane_.clear();
h_flags_.clear();
h_widx_.clear();
h_wf0_.clear();
h_wnf_.clear();
h_lcu_.assign(1, 0);
pass_.jobs.clear();
int64_t S = 0, row = 0, lrow = 0;
int32_t max_q = 0;
cu[0] = 0;
lcu[0] = 0;
for (Job* jp : js) {
Job& j = *jp;
const int64_t nf = window_frames(j, j.win);
const int64_t nl = win_latents(nf);
const int64_t len = decl_.win_lead + nl;
const int nb = j.cfg > 1.0f ? 2 : 1;
int32_t f = 0;
if (j.win_step == 0) f |= RAD_AGEN_F_FIRST;
if (j.win_step + 1 == j.steps) f |= RAD_AGEN_F_LAST;
if (j.win > 0) f |= RAD_AGEN_F_JOIN;
for (int b = 0; b < nb; ++b) {
const int64_t e = S++;
for (int64_t k = 0; k < len; ++k) {
tok[row + k] = 0;
pos[row + k] = (int32_t)k;
}
for (int64_t k = 0; k < nl; ++k) lsrc[lrow + k] = (int32_t)(row + decl_.win_lead + k);
row += len;
lrow += nl;
cu[e + 1] = (int32_t)row;
lcu[e + 1] = (int32_t)lrow;
t[e] = (float)j.win_step / (float)j.steps;
tn[e] = (float)(j.win_step + 1) / (float)j.steps;
cfg[e] = b ? 0.0f : (nb > 1 ? j.cfg : 1.0f);
pair[e] = b ? -2 : (nb > 1 ? (int32_t)(e + 1) : -1);
wlane[e] = j.lane;
flags[e] = f;
widx[e] = j.win;
wf0[e] = (int32_t)win_frame0(j.win);
wnf[e] = (int32_t)nf;
seed[2 * e] = (uint32_t)(j.req->seed & 0xffffffffu);
seed[2 * e + 1] = (uint32_t)(j.req->seed >> 32);
h_wlane_.push_back(j.lane);
h_flags_.push_back(f);
h_widx_.push_back(j.win);
h_wf0_.push_back(wf0[e]);
h_wnf_.push_back((int32_t)nf);
h_lcu_.push_back((int32_t)lrow);
max_q = std::max<int32_t>(max_q, (int32_t)len);
}
pass_.jobs.push_back(j.id);
}
reg_[R_TOK].used = reg_[R_POS].used = row * 4;
reg_[R_CU].used = reg_[R_LCU].used = (S + 1) * 4;
reg_[R_T].used = reg_[R_TN].used = reg_[R_CFG].used = S * 4;
reg_[R_PAIR].used = reg_[R_WLANE].used = reg_[R_FLAGS].used = S * 4;
reg_[R_WIDX].used = reg_[R_WF0].used = reg_[R_WNF].used = S * 4;
reg_[R_SEED].used = 2 * S * 4;
reg_[R_LSRC].used = lrow * 4;
if (upload() < 0) return nullptr;
base_batches(row, S, max_q, 0, step, false, 0);
for (size_t r = 0; r < ranks_.size(); ++r) {
out_[r].gen = RAD_GEN_PASS_WINDOW;
RadAudioGenBatch& A = aout_[r];
A.win_lane_h = h_wlane_.data();
A.flags_h = h_flags_.data();
A.win_index_h = h_widx_.data();
A.win_frame0_h = h_wf0_.data();
A.win_frames_h = h_wnf_.data();
A.lat_rows = lrow;
A.lat_cu_h = h_lcu_.data();
}
pass_.kind = RAD_GEN_PASS_WINDOW;
return &out_[0];
}
const RadBatch* AudioDriver::build_vocode(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const int32_t k = j.voc_due;
const int64_t nl = win_latents(window_frames(j, k));
int64_t left = k > 0 ? decl_.win_crop_left : 0;
int64_t right = window_last(j, k) == 1 ? 0 : decl_.win_crop_right;
left = std::min<int64_t>(left, nl);
right = std::min<int64_t>(right, nl - left);
int32_t* cu = hptr<int32_t>(R_CU);
cu[0] = 0;
cu[1] = (int32_t)nl;
reg_[R_CU].used = 2 * 4;
if (upload() < 0) return nullptr;
base_batches(nl, 1, (int32_t)nl, 0, step, false, 0);
for (size_t r = 0; r < ranks_.size(); ++r) {
out_[r].gen = RAD_GEN_PASS_VOCODE;
RadAudioGenBatch& A = aout_[r];
A.voc_lane = j.lane;
A.voc_window = k;
A.voc_latents = (int32_t)nl;
A.voc_left = (int32_t)left;
A.voc_right = (int32_t)right;
}
const int64_t samples = (nl - left - right) * decl_.samples_per_latent;
rb_.assign(1, Readback{ decl_.audio_out, samples * decl_.channels * 4, audio_host_ });
pass_.kind = RAD_GEN_PASS_VOCODE;
pass_.voc_job = j.id;
pass_.voc_window = k;
pass_.voc_samples = samples;
return &out_[0];
}
/* A chunk of a lane's kept frames, after the frames it reads again for context. Its rows are
* the frames, at their positions in the piece. */
const RadBatch* AudioDriver::build_chunk(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const int64_t n = std::min<int64_t>(decl_.voc_chunk, j.kept - j.played);
const int64_t ctx = std::min<int64_t>(decl_.voc_context, j.played);
const int64_t f0 = j.played - ctx, nl = ctx + n;
int32_t* cu = hptr<int32_t>(R_CU);
int32_t* pos = hptr<int32_t>(R_POS);
cu[0] = 0;
cu[1] = (int32_t)nl;
for (int64_t i = 0; i < nl; ++i) pos[i] = (int32_t)(f0 + i);
reg_[R_CU].used = 2 * 4;
reg_[R_POS].used = nl * 4;
if (upload() < 0) return nullptr;
base_batches(nl, 1, (int32_t)nl, 0, step, false, 0);
for (size_t r = 0; r < ranks_.size(); ++r) {
out_[r].gen = RAD_GEN_PASS_VOCODE;
RadAudioGenBatch& A = aout_[r];
A.voc_lane = j.lane;
A.voc_window = j.windows_played;
A.voc_latents = (int32_t)nl;
A.voc_left = (int32_t)ctx;
A.voc_right = 0;
A.voc_frame0 = f0;
}
const int64_t samples = n * decl_.samples_per_latent;
rb_.assign(1, Readback{ decl_.audio_out, samples * decl_.channels * 4, audio_host_ });
pass_.kind = RAD_GEN_PASS_VOCODE;
pass_.voc_job = j.id;
pass_.voc_window = j.windows_played;
pass_.voc_samples = samples;
pass_.voc_frames = n;
return &out_[0];
}
int AudioDriver::done() {
std::lock_guard<std::mutex> lk(mu_);
const int64_t now = (int64_t)rad_mono_ns();
switch (pass_.kind) {
case RAD_GEN_PASS_PROMPT:
for (size_t i = 0; i < pass_.jobs.size(); ++i) {
Job* j = job_locked(pass_.jobs[i]);
if (!j) continue;
j->prompt_done += pass_.rows[i];
if (j->prompt_done >= j->T) j->req->ticket->t_prompt_ns = now;
}
break;
case RAD_GEN_PASS_FRAME:
for (uint64_t id : pass_.jobs) {
Job* j = job_locked(id);
if (!j || j->failed) continue;
const int32_t st = status_host_[j->lane];
if (st < 0) {
j->ar_done = true;
j->req->ticket->model_ended = true;
if (j->kept == 0) {
fail_locked(*j, RAD_E_INVAL, "the model ended the piece before its first "
"frame; try other text or another seed");
continue;
}
} else {
if (j->frame >= decl_.first_frame) j->kept = j->frame - decl_.first_frame + 1;
++j->frame;
if (j->kept >= j->req->max_frames) j->ar_done = true;
}
if (j->ar_done) {
j->req->ticket->frames = j->kept;
j->req->ticket->t_frames_ns = now;
/* Every frame already played: nothing more is owed. */
if (chunked() && j->played == j->kept) {
j->finished = true;
j->req->ticket->windows = j->windows_played;
j->req->ticket->t_done_ns = now;
j->req->ticket->finish(RAD_OK);
}
}
}
break;
case RAD_GEN_PASS_WINDOW:
for (uint64_t id : pass_.jobs) {
Job* j = job_locked(id);
if (!j) continue;
if (++j->win_step >= j->steps) {
j->voc_due = j->win;
j->win_step = 0;
}
}
break;
case RAD_GEN_PASS_VOCODE: {
Job* j = job_locked(pass_.voc_job);
if (!j) break;
AudioChunk c;
c.window = pass_.voc_window;
c.samples.assign(audio_host_, audio_host_ + pass_.voc_samples * decl_.channels);
j->req->ticket->push(std::move(c));
if (j->windows_played == 0) j->req->ticket->t_first_audio_ns = now;
++j->windows_played;
bool last;
if (chunked()) {
j->played += pass_.voc_frames;
last = j->ar_done && j->played == j->kept;
} else {
last = window_last(*j, j->voc_due) == 1;
j->voc_due = -1;
++j->win;
}
if (last) {
j->finished = true;
j->req->ticket->windows = j->windows_played;
j->req->ticket->t_done_ns = now;
j->req->ticket->finish(RAD_OK);
}
break;
}
default:
break;
}
pass_ = Pass{};
rb_.clear();
return RAD_OK;
}
} /* namespace gen */
} /* namespace rad */
+188
View File
@@ -0,0 +1,188 @@
/* audio_driver.h -- the audio generator's pass driver (audio.h, abi/rad_builder.h's
* RadAudioGenDecl describes the passes).
*
* Driven by the engine thread like the image driver (driver.h): `next()` picks and stages a pass,
* `done()` folds its result back once every rank has run it. Requests arrive from HTTP threads
* through `submit()` and leave through their AudioTicket.
*
* A request holds a lane and two KV sequences, its conditional and unconditional branches, from
* admission to its last window; both are reserved for the whole piece at admission (prompt plus
* every frame the request may make), so a request in flight never waits for KV.
*
* Pass priority, one pass at a time:
*
* 1. VOCODE a finished window is owed (it frees the lane's latent for the next window and gives
* the caller audio), or, for a vocoder that plays frames as they are made
* (RadAudioGenDecl::voc_chunk), a chunk of frames is ready: `voc_chunk` of them, or the
* piece's last.
* 2. PROMPT an admitted request's prompt is not all in the KV: the next chunk of it, both
* branches.
* 3. FRAME and WINDOW, taking turns when both have work: one frame of every request in its
* autoregressive stage, or one denoising step of the windows that are ready. A FRAME pass
* carries every lane at once, since its cost is reading the language model's weights, which
* the lanes share; a window's step is compute and carries what fits the pass's rows.
*
* A window is ready once the language model has made all its frames, or ended the piece. Its
* vocoding waits until it is known whether a window follows it (the crop at its end depends on
* that): once the frames of the next window have begun, or the piece has ended.
*/
#pragma once
#include "audio.h"
#include "pass.h"
#include "device/device.h"
#include <mutex>
namespace rad {
struct IKVManager;
namespace gen {
class AudioDriver final : public IPassDriver {
public:
struct RankIO {
int device = 0;
RadStream stream = nullptr;
};
/* `kv` is rank 0's KV manager: one block table serves every rank. */
int init(const Program& prog, IKVManager* kv, const std::vector<RankIO>& ranks);
void fini();
~AudioDriver() override { fini(); }
/* The bytes init() allocates on each rank's card, for the VRAM budget. */
static int64_t device_bytes(const Program& prog);
/* The longest sequence a branch holds: the whole prompt and every frame. The KV group is
* sized from it. */
static int64_t max_seq_rows(const RadAudioGenDecl& d) { return d.max_prompt + d.max_frames + 1; }
/* ---------------------------------------------------------- HTTP threads */
/* Queue a request, refused at once with `why` when it can never run. */
int submit(std::unique_ptr<AudioRequest> r, std::string* why);
const RadAudioGenDecl& decl() const { return decl_; }
void shutdown(const char* why, int status) override;
/* ---------------------------------------------------------- the engine thread */
const RadBatch* next(int step) override;
const RadBatch* batch_for(int rank) const override;
const std::vector<Readback>& readbacks() const override { return rb_; }
int done() override;
int64_t queued() const override;
int64_t running() const override;
private:
struct Job {
uint64_t id = 0;
std::unique_ptr<AudioRequest> req;
int32_t lane = -1;
uint64_t seq[2] = { 0, 0 };
bool have_kv = false;
bool admitted = false;
bool failed = false;
int64_t T = 0; /* prompt tokens */
std::vector<int32_t> neg; /* the unconditional prompt */
int64_t Tn = 0; /* its tokens */
int64_t prompt_done = 0; /* prompt rows in the KV */
/* The autoregressive stage: the next frame to make, the frames kept, and whether it is
* over (the model ended the piece, or it reached max_frames). */
int32_t frame = 0;
int64_t kept = 0;
bool ar_done = false;
/* The windows: the one being stepped (or next to start), its step, and the one owed a
* vocode pass (-1 none). */
int32_t win = 0;
int32_t win_step = 0;
int32_t steps = 0;
float cfg = 1.0f;
int32_t voc_due = -1;
int32_t windows_played = 0;
/* A vocoder playing frames as they are made: the kept frames played so far. */
int64_t played = 0;
bool finished = false;
};
/* The pass in flight, for done(). */
struct Pass {
int kind = 0;
std::vector<uint64_t> jobs; /* PROMPT, FRAME, WINDOW: one per lane or window */
std::vector<int64_t> rows; /* PROMPT: the chunk each job's branches advanced */
uint64_t voc_job = 0;
int32_t voc_window = -1;
int64_t voc_samples = 0;
int64_t voc_frames = 0; /* a chunk's frames played */
};
/* Staging regions: their offsets in the host span and every rank's slab. */
struct Region { int64_t off = 0, bytes = 0, used = 0; };
enum { R_TOK, R_POS, R_CU, R_SLOT, R_BT, R_USED, R_LANE, R_LAST, R_FRAME, R_SEED,
R_T, R_TN, R_CFG, R_PAIR, R_WLANE, R_FLAGS, R_WIDX, R_WF0, R_WNF, R_LCU, R_LSRC,
R_ESLOT, R_LROW, R_PREFIX, R_N };
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
template <class T> T* dptr(int rank, int r) const {
return reinterpret_cast<T*>((char*)dev_[(size_t)rank] + reg_[r].off);
}
int upload();
void base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int32_t max_ctx, int step,
bool kv, int64_t bt_pitch);
int admit_locked();
void release_locked(Job& j);
void fail_locked(Job& j, int status, const std::string& why);
Job* job_locked(uint64_t id);
/* Window geometry: window k's first frame and frames once the piece has `n` frames (or
* at least `n`, with `ended` false), whether it exists, and whether it is the last. */
int64_t win_frame0(int32_t k) const { return (int64_t)k * decl_.win_hop; }
int64_t win_latents(int64_t frames) const { return frames * decl_.lat_num / decl_.lat_den; }
bool window_ready(const Job& j) const;
/* A vocoder playing frames as they are made: whether a chunk of `j`'s frames is due. */
bool chunk_due(const Job& j) const;
bool chunked() const { return decl_.voc_chunk > 0; }
int window_last(const Job& j, int32_t k) const; /* 1 last, 0 not, -1 not yet known */
int64_t window_frames(const Job& j, int32_t k) const;
const RadBatch* build_prompt(Job& j, int step);
const RadBatch* build_frame(const std::vector<Job*>& js, int step);
const RadBatch* build_window(const std::vector<Job*>& js, int step);
const RadBatch* build_vocode(Job& j, int step);
const RadBatch* build_chunk(Job& j, int step);
RadAudioGenDecl decl_{};
std::string name_;
int64_t max_tok_ = 0, max_seqs_ = 0;
int64_t block_size_ = 0, max_blocks_ = 0;
int32_t kv_group_ = 0;
bool neg_own_ = false; /* the unconditional prompt is the request's own */
std::vector<RankIO> ranks_;
IKVManager* kv_ = nullptr;
char* host_ = nullptr; /* pinned, same layout as each slab */
int64_t bytes_ = 0;
std::vector<void*> dev_;
Region reg_[R_N];
int32_t* status_host_ = nullptr;
float* audio_host_ = nullptr;
int64_t audio_bytes_ = 0;
std::vector<Readback> rb_;
std::vector<RadBatch> out_; /* one per rank */
std::vector<RadAudioGenBatch> aout_;
std::vector<RadKVGroupBatch> kout_;
Pass pass_;
bool frame_turn_ = true; /* FRAME goes first when both are due */
/* Host arrays a pass's plugin reads on the host (the _h fields), for the life of the pass. */
std::vector<int32_t> h_lane_, h_last_, h_frame_, h_wlane_, h_flags_, h_widx_,
h_wf0_, h_wnf_, h_lcu_;
mutable std::mutex mu_;
std::deque<std::unique_ptr<Job>> jobs_; /* arrival order */
std::vector<int32_t> free_lanes_;
uint64_t next_id_ = 1;
uint64_t next_seq_ = 1;
bool closed_ = false;
std::string closed_why_;
int closed_status_ = RAD_E_STATE;
};
} /* namespace gen */
} /* namespace rad */
+3
View File
@@ -439,6 +439,7 @@ const RadBatch* Driver::next(int step) {
std::lock_guard<std::mutex> lk(mu_);
pass_ = Pass{};
dec_bytes_ = 0;
rb_.clear();
if (closed_) return nullptr;
/* Retire finished, failed and cancelled jobs, returning their KV and lanes before admitting.
* Safe because next() runs between passes, with nothing in flight. */
@@ -820,6 +821,7 @@ const RadBatch* Driver::build_decode(int32_t l, bool preview, int step) {
G.dec_preview = preview ? 1 : 0;
}
dec_bytes_ = (int64_t)j->req->width * j->req->height * decl_.pixel_channels;
rb_.assign(1, Readback{ decl_.image_out, dec_bytes_, img_host_ });
pass_.kind = RAD_GEN_PASS_DECODE;
pass_.job = j->id;
pass_.lane = l;
@@ -889,6 +891,7 @@ int Driver::done() {
}
pass_ = Pass{};
dec_bytes_ = 0;
rb_.clear();
return RAD_OK;
}
+11 -16
View File
@@ -23,6 +23,7 @@
*/
#pragma once
#include "gen.h"
#include "pass.h"
#include "device/device.h"
#include <mutex>
@@ -31,7 +32,7 @@
namespace rad {
namespace gen {
class Driver {
class Driver final : public IPassDriver {
public:
struct RankIO {
int device = 0;
@@ -54,25 +55,18 @@ public:
* request. */
const RadGeneratorDecl& decl() const { return decl_; }
int64_t max_cond_tokens() const { return max_tok_; }
/* Fail every request queued or in flight, and refuse new ones. */
void shutdown(const char* why, int status);
void shutdown(const char* why, int status) override;
/* ---------------------------------------------------------- the engine thread */
/* The next pass, staged on every rank's stream, or null when there is nothing to run.
* `step` is the engine's pass counter, carried into RadBatch::step. */
const RadBatch* next(int step);
const RadBatch* batch_for(int rank) const;
/* Bytes of image output the staged pass produces, 0 if none; the engine copies them to
* host_image() behind the pass. */
int64_t decode_bytes() const { return dec_bytes_; }
void* host_image() const { return img_host_; }
/* The pass has run on every rank and its streams are drained. */
int done();
const RadBatch* next(int step) override;
const RadBatch* batch_for(int rank) const override;
/* A decode pass's pixels: `image_out` into the pinned image buffer. */
const std::vector<Readback>& readbacks() const override { return rb_; }
int done() override;
bool busy() const;
/* For /health, /stats and the dashboard. */
int64_t queued() const;
int64_t running() const;
int64_t queued() const override;
int64_t running() const override;
private:
struct Cond {
@@ -160,6 +154,7 @@ private:
void* img_host_ = nullptr;
int64_t img_bytes_ = 0;
int64_t dec_bytes_ = 0;
std::vector<Readback> rb_;
std::vector<RadBatch> out_; /* one per rank */
std::vector<RadGenBatch> gout_;
+45
View File
@@ -0,0 +1,45 @@
/* pass.h -- what the engine's pass loop needs of a generator's driver.
*
* A generator program is driven by passes rather than token steps (abi/rad_builder.h,
* rad_declare_generator and rad_declare_audio_generator). Each kind has its own driver, which turns
* its requests into passes (core/gen/driver.h for images, core/gen/audio_driver.h for audio); the
* loop that runs them on the ranks is one (Engine::gen_loop). The loop asks for the next pass,
* runs it on every rank, copies back what the driver names and hands the pass back.
*/
#pragma once
#include "rad_core.h"
#include <vector>
namespace rad {
namespace gen {
struct IPassDriver {
/* A device buffer the staged pass leaves for the host: `bytes` from the start of `buf` on
* rank 0, copied to `host` behind the pass. Every rank holds the same values. */
struct Readback {
rad_buf buf = RAD_NULL_HANDLE;
int64_t bytes = 0;
void* host = nullptr;
};
virtual ~IPassDriver() = default;
/* The next pass, staged on every rank's stream, or null when there is nothing to run.
* `step` is the engine's pass counter, carried into RadBatch::step. */
virtual const RadBatch* next(int step) = 0;
virtual const RadBatch* batch_for(int rank) const = 0;
/* What the staged pass's results are, valid until done(). */
virtual const std::vector<Readback>& readbacks() const = 0;
/* The pass has run on every rank, its streams are drained and the readbacks have landed. */
virtual int done() = 0;
/* Fail every request queued or in flight, and refuse new ones. */
virtual void shutdown(const char* why, int status) = 0;
/* For /health, /stats and the dashboard. */
virtual int64_t queued() const = 0;
virtual int64_t running() const = 0;
};
} /* namespace gen */
} /* namespace rad */
+97
View File
@@ -0,0 +1,97 @@
/* video.h -- video generation: the request and the channel its video comes back on.
*
* A video generator (abi/rad_builder.h, rad_declare_video_generator) makes a video and its
* soundtrack in one denoising loop over a packed sequence, then decodes the soundtrack and the
* frames, a chunk of frames at a time. core/gen/video_driver.h turns a request into those passes;
* this is what a caller hands it and what it hands back: progress as the steps run, the
* soundtrack, the frames chunk by chunk in order, then the end.
*/
#pragma once
#include "rad_core.h"
#include <atomic>
#include <condition_variable>
#include <deque>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace rad {
namespace gen {
/* One thing a request has made. */
struct VideoEvent {
enum Kind { STEP = 1, AUDIO = 2, FRAMES = 3 };
int kind = 0;
int32_t steps_done = 0; /* STEP: denoising steps finished */
/* AUDIO: the whole soundtrack, interleaved, in [-1, 1]. */
std::vector<float> samples;
/* FRAMES: frames [first, first + n) of the video, each [height, width, 3] u8 RGB. */
int32_t first = 0, n = 0;
std::vector<uint8_t> rgb;
};
/* As Ticket (gen.h) is for an image: the driver thread writes, the caller reads. */
class VideoTicket {
public:
/* driver side */
void push(VideoEvent&& e);
void finish(int status, const std::string& why = std::string());
/* caller side: the next event, or false once the request has ended and every event was
* taken. Waits at most `ms` milliseconds; `*timed_out` marks a false that was a timeout. */
bool next(VideoEvent* out, int ms, bool* timed_out);
bool finished() const;
int status() const;
std::string why() const;
std::atomic<bool> cancel{false};
/* What the request makes, written by the driver at submit: the frames and their size, the
* steps, and the soundtrack's rate and channels. */
int32_t frames = 0, width = 0, height = 0, steps = 0;
int64_t sample_rate = 0, channels = 0;
double fps = 0.0;
/* Usage, written by the driver before finish(): prompt tokens, rows a step and per-phase
* times. */
int64_t in_tokens = 0, rows = 0;
int64_t t_submit_ns = 0, t_cond_ns = 0, t_denoised_ns = 0, t_done_ns = 0;
private:
mutable std::mutex mu_;
std::condition_variable cv_;
std::deque<VideoEvent> q_;
bool done_ = false;
int status_ = RAD_OK;
std::string why_;
};
struct VideoRequest {
std::vector<int32_t> tokens; /* the prompt, rendered and tokenised */
int32_t width = 0, height = 0; /* pixels, within the declaration's limits */
int32_t chunks = 0; /* the length in chunks (RadVideoGenDecl) */
int32_t steps = 0; /* sigma grid points; 0: the model's default */
uint64_t seed = 0;
std::shared_ptr<VideoTicket> ticket;
};
/* A request's shape under a declaration: frames, latent grid, soundtrack latents and the rows of
* a step. Shared by the driver and the server, which checks a request before preparing it. */
struct VideoShape {
int32_t frames = 0, lat_frames = 0, lat_h = 0, lat_w = 0, n_audio = 0;
int64_t video_rows = 0, audio_rows = 0;
};
VideoShape video_shape(const RadVideoGenDecl& d, int32_t width, int32_t height, int32_t chunks);
/* The two schedules a request of `steps` grid points runs (RadVideoGenDecl, "The sampler"): each
* the f32 sigmas, last 0, and the model evaluations it takes, the shorter of the two. With a
* trained schedule any other step count than n_rungs + 1 gives no steps. */
struct VideoSchedule {
std::vector<float> sig_v, sig_a;
int32_t steps = 0;
};
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps);
} /* namespace gen */
} /* namespace rad */
+665
View File
@@ -0,0 +1,665 @@
/* video_driver.cpp -- the video generator's pass driver (video_driver.h), the ticket a caller
* waits on, and a request's shape and schedule (video.h). */
#include "video_driver.h"
#include <algorithm>
#include <chrono>
#include <cstring>
namespace rad {
namespace gen {
/* ================================================================== the ticket */
void VideoTicket::push(VideoEvent&& e) {
{
std::lock_guard<std::mutex> lk(mu_);
q_.push_back(std::move(e));
}
cv_.notify_all();
}
void VideoTicket::finish(int status, const std::string& why) {
{
std::lock_guard<std::mutex> lk(mu_);
if (done_) return;
done_ = true;
status_ = status;
why_ = why;
}
cv_.notify_all();
}
bool VideoTicket::next(VideoEvent* out, int ms, bool* timed_out) {
std::unique_lock<std::mutex> lk(mu_);
if (timed_out) *timed_out = false;
if (q_.empty() && !done_)
cv_.wait_for(lk, std::chrono::milliseconds(ms), [this] { return !q_.empty() || done_; });
if (!q_.empty()) {
*out = std::move(q_.front());
q_.pop_front();
return true;
}
if (!done_ && timed_out) *timed_out = true;
return false;
}
bool VideoTicket::finished() const {
std::lock_guard<std::mutex> lk(mu_);
return done_ && q_.empty();
}
int VideoTicket::status() const {
std::lock_guard<std::mutex> lk(mu_);
return status_;
}
std::string VideoTicket::why() const {
std::lock_guard<std::mutex> lk(mu_);
return why_;
}
/* ================================================================== shape and schedule */
VideoShape video_shape(const RadVideoGenDecl& d, int32_t width, int32_t height, int32_t chunks) {
VideoShape s;
s.frames = (int32_t)(d.frames_per_chunk * chunks + d.frames_tail);
s.lat_frames = (int32_t)(d.latents_per_chunk * chunks + d.latents_tail);
s.lat_h = (int32_t)(height / d.latent_scale);
s.lat_w = (int32_t)(width / d.latent_scale);
/* round(frames / fps * audio_rate), ties to even as the reference's float round; with an
* integer numerator and denominator a tie is exact. */
const int64_t num = (int64_t)s.frames * d.fps_den * d.audio_rate, den = d.fps_num;
int64_t q = num / den;
const int64_t r2 = 2 * (num % den);
if (r2 > den || (r2 == den && (q & 1))) ++q;
s.n_audio = (int32_t)q;
s.video_rows = (int64_t)s.lat_frames * (s.lat_h / d.patch) * (s.lat_w / d.patch);
s.audio_rows = d.audio_channels * (int64_t)s.n_audio;
return s;
}
/* The shift of one base time, in f32 as the reference's tensor arithmetic. */
static float shift_sigma(double shift, float b) {
const float sh = (float)shift, sh1 = (float)(shift - 1.0);
return (sh * b) / (1.0f + sh1 * b);
}
/* torch.linspace(1, 0, n) in f32, which computes the first half up from the start and the
* second half down from the end, then the exponential shift, consecutive duplicates dropped. */
static std::vector<float> shifted_sigmas(double shift, int64_t n) {
std::vector<float> s;
if (n < 2) return s;
const float start = 1.0f, end = 0.0f;
const float step = (end - start) / (float)(n - 1);
const int64_t half = n / 2;
for (int64_t i = 0; i < n; ++i) {
const float b = i < half ? start + step * (float)i : end - step * (float)(n - i - 1);
const float v = shift_sigma(shift, b);
if (s.empty() || v != s.back()) s.push_back(v);
}
return s;
}
/* A trained schedule: each rung taken to f32 and shifted, then the terminal 0. */
static std::vector<float> rung_sigmas(double shift, const double* rungs, int32_t n) {
std::vector<float> s;
for (int32_t i = 0; i < n; ++i) s.push_back(shift_sigma(shift, (float)rungs[i]));
s.push_back(0.0f);
return s;
}
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps) {
VideoSchedule v;
if (d.n_rungs > 0) {
if (steps != d.n_rungs + 1) return v;
v.sig_v = rung_sigmas(d.shift_video, d.rungs, d.n_rungs);
v.sig_a = rung_sigmas(d.shift_audio, d.rungs, d.n_rungs);
v.steps = d.n_rungs;
return v;
}
v.sig_v = shifted_sigmas(d.shift_video, steps);
v.sig_a = shifted_sigmas(d.shift_audio, steps);
const size_t n = std::min(v.sig_v.size(), v.sig_a.size());
v.steps = n > 0 ? (int32_t)(n - 1) : 0;
return v;
}
/* ================================================================== sizing */
namespace {
constexpr int64_t kAlign = 256;
int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
/* Region offsets and sizes, in the enum's order (video_driver.h), and the total; shared by the
* allocation and the VRAM budget. */
int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t (*bytes)[2], int n) {
const int64_t want[] = {
d.max_text * 4, /* R_TOK */
d.max_text * 4, /* R_POS */
2 * 4, /* R_CU */
3 * max_tok * 4, /* R_ROPE: a step's rotary positions */
RAD_VGEOM_N * 4, /* R_GEOM */
6 * 4, /* R_SCHED */
d.max_steps * 4, /* R_TV */
d.max_steps * 4, /* R_TA */
4 * 4, /* R_SEED */
4, /* R_LANE */
4, /* R_FIRST */
4 * 4, /* R_SEG */
4 * 4, /* R_LAT */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
bytes[r][0] = off;
bytes[r][1] = want[r];
off = align_up(off + want[r]);
}
return off;
}
int64_t frames_bytes_of(const RadVideoGenDecl& d) {
return (d.frames_per_chunk + d.frames_tail) * d.max_area * 3;
}
/* The samples a channel of a soundtrack under `frames` frames: its latents rounded up, which
* bounds the rounding video_shape does. */
int64_t samples_of(const RadVideoGenDecl& d, int32_t frames) {
const int64_t num = (int64_t)frames * d.fps_den * d.audio_rate;
return (num / d.fps_num + 1) * (d.sample_rate / d.audio_rate);
}
} /* namespace */
int64_t VideoDriver::device_bytes(const Program& prog) {
if (!prog.is_video_generator()) return 0;
int64_t b[R_N][2];
return carve(prog.video_gen, prog.ctx.max_tok, b, R_N);
}
int VideoDriver::init(const Program& prog, PositionsFn positions,
const std::vector<RankIO>& ranks) {
fini();
if (!prog.is_video_generator()) return RAD_E_STATE;
decl_ = prog.video_gen;
rungs_ = prog.vgen_str.rungs;
decl_.rungs = rungs_.empty() ? nullptr : rungs_.data();
name_ = prog.vgen_str.name;
ranks_ = ranks;
positions_ = positions;
max_tok_ = prog.ctx.max_tok;
if (!positions_) {
RAD_ERR("video generator '%s': the plugin exports no rad_arch_video_positions, which a "
"video generator must", name_.c_str());
return RAD_E_UNSUPPORTED;
}
if (max_tok_ < decl_.max_text) {
RAD_ERR("video generator '%s': a pass carries %lld rows and a prompt may be %lld tokens",
name_.c_str(), (long long)max_tok_, (long long)decl_.max_text);
return RAD_E_UNSUPPORTED;
}
int64_t b[R_N][2];
bytes_ = carve(decl_, max_tok_, b, R_N);
for (int r = 0; r < R_N; ++r) { reg_[r].off = b[r][0]; reg_[r].bytes = b[r][1]; reg_[r].used = 0; }
frames_bytes_ = frames_bytes_of(decl_);
audio_bytes_ = samples_of(decl_, (int32_t)(decl_.frames_per_chunk * decl_.max_chunks +
decl_.frames_tail)) *
decl_.audio_channels * 4;
host_ = static_cast<char*>(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED));
frames_host_ = static_cast<uint8_t*>(rad_dev_alloc(frames_bytes_, RAD_MEM_HOST_PINNED));
audio_host_ = static_cast<float*>(rad_dev_alloc(audio_bytes_, RAD_MEM_HOST_PINNED));
if (!host_ || !frames_host_ || !audio_host_) {
RAD_ERR("video generator: no pinned host memory for the pass staging and outputs (%lld + "
"%lld + %lld bytes)", (long long)bytes_, (long long)frames_bytes_,
(long long)audio_bytes_);
return RAD_E_NOMEM;
}
std::memset(host_, 0, (size_t)bytes_);
dev_.assign(ranks_.size(), nullptr);
for (size_t r = 0; r < ranks_.size(); ++r) {
RAD_TRY(rad_dev_set(ranks_[r].device));
dev_[r] = rad_dev_alloc(bytes_, RAD_MEM_DEVICE);
if (!dev_[r]) {
RAD_ERR("video generator: rank %zu has no room for the pass staging (%lld bytes)", r,
(long long)bytes_);
return RAD_E_NOMEM;
}
}
if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0].device));
out_.assign(ranks_.size(), RadBatch{});
vout_.assign(ranks_.size(), RadVideoGenBatch{});
free_lanes_.clear();
for (int64_t i = decl_.max_lanes - 1; i >= 0; --i) free_lanes_.push_back((int32_t)i);
return RAD_OK;
}
void VideoDriver::fini() {
for (size_t r = 0; r < dev_.size(); ++r)
if (dev_[r]) {
if (r < ranks_.size()) rad_dev_set(ranks_[r].device);
rad_dev_free(dev_[r], RAD_MEM_DEVICE);
}
dev_.clear();
if (!ranks_.empty()) rad_dev_set(ranks_[0].device);
if (host_) rad_dev_free(host_, RAD_MEM_HOST_PINNED);
if (frames_host_) rad_dev_free(frames_host_, RAD_MEM_HOST_PINNED);
if (audio_host_) rad_dev_free(audio_host_, RAD_MEM_HOST_PINNED);
host_ = nullptr;
frames_host_ = nullptr;
audio_host_ = nullptr;
}
/* ================================================================== requests */
int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
if (!r || !r->ticket) return RAD_E_INVAL;
const RadVideoGenDecl& d = decl_;
auto no = [&](const std::string& w) {
if (why) *why = w;
return RAD_E_INVAL;
};
const int64_t T = (int64_t)r->tokens.size();
if (T < 1 || T > d.max_text)
return no("the prompt is " + std::to_string(T) + " tokens; this model takes 1.." +
std::to_string(d.max_text));
if (r->chunks < d.min_chunks || r->chunks > d.max_chunks)
return no("the length must be " + std::to_string(d.min_chunks) + ".." +
std::to_string(d.max_chunks) + " chunks");
const int64_t W = r->width, H = r->height;
if (W % d.size_multiple || H % d.size_multiple || W < d.min_side || H < d.min_side ||
W * H > d.max_area || std::max(W, H) > d.max_aspect * std::min(W, H))
return no("the size " + std::to_string(W) + "x" + std::to_string(H) + " is not one this "
"model makes: sides multiples of " + std::to_string(d.size_multiple) + " from " +
std::to_string(d.min_side) + ", at most " + std::to_string(d.max_area) +
" pixels, the long side at most " + std::to_string(d.max_aspect) +
" times the short");
const int32_t steps = r->steps > 0 ? r->steps : (int32_t)d.default_steps;
if (d.n_rungs > 0 && steps != d.n_rungs + 1)
return no("num_inference_steps must be " + std::to_string(d.n_rungs + 1) + ": this model "
"runs the schedule it was trained on, " + std::to_string(d.n_rungs) +
" evaluations");
if (steps < 2 || steps > d.max_steps)
return no("num_inference_steps must be 2.." + std::to_string(d.max_steps) + " (sigma grid "
"points, the last one 0)");
auto j = std::make_unique<Job>();
const VideoShape s = video_shape(d, r->width, r->height, r->chunks);
j->geom.n_text = (int32_t)T;
j->geom.frames = s.frames;
j->geom.lat_frames = s.lat_frames;
j->geom.lat_h = s.lat_h;
j->geom.lat_w = s.lat_w;
j->geom.n_audio = s.n_audio;
j->rows = T + s.audio_rows + s.video_rows;
if (j->rows > max_tok_)
return no("a step of this video is " + std::to_string(j->rows) + " rows and a pass "
"carries " + std::to_string(max_tok_) + "; ask for a shorter or smaller video");
const int64_t nr = positions_(RAD_VPOS_STEP, &j->geom, nullptr, 0);
const int64_t nd = positions_(RAD_VPOS_DECODE, &j->geom, nullptr, 0);
if (nr != j->rows || nd <= 0 || nd > max_tok_)
return no("the model lays this video out in " + std::to_string(nr) + " step rows and " +
std::to_string(nd) + " decoder rows, which this server cannot run");
j->dec_rows = nd;
j->pos.assign((size_t)(3 * nr), 0.0f);
if (positions_(RAD_VPOS_STEP, &j->geom, j->pos.data(), nr) != nr)
return no("the model could not lay this video out");
j->sched = video_schedule(d, steps);
if (j->sched.steps < 1) return no("the schedule has no steps");
j->n_chunks = r->chunks;
j->n_samples = (int64_t)s.n_audio * (d.sample_rate / d.audio_rate);
VideoTicket& t = *r->ticket;
t.frames = s.frames;
t.width = r->width;
t.height = r->height;
t.steps = j->sched.steps;
t.sample_rate = d.sample_rate;
t.channels = d.audio_channels;
t.fps = (double)d.fps_num / (double)d.fps_den;
t.in_tokens = T;
t.rows = j->rows;
t.t_submit_ns = (int64_t)rad_mono_ns();
std::lock_guard<std::mutex> lk(mu_);
if (closed_) {
if (why) *why = closed_why_;
return closed_status_;
}
j->id = next_id_++;
j->req = std::move(r);
jobs_.push_back(std::move(j));
return RAD_OK;
}
void VideoDriver::shutdown(const char* why, int status) {
std::lock_guard<std::mutex> lk(mu_);
closed_ = true;
closed_why_ = why ? why : "the engine stopped";
closed_status_ = status;
for (auto& j : jobs_) j->req->ticket->finish(status, closed_why_);
}
int64_t VideoDriver::queued() const {
std::lock_guard<std::mutex> lk(mu_);
int64_t n = 0;
for (const auto& j : jobs_) if (!j->admitted) ++n;
return n;
}
int64_t VideoDriver::running() const {
std::lock_guard<std::mutex> lk(mu_);
int64_t n = 0;
for (const auto& j : jobs_) if (j->admitted) ++n;
return n;
}
VideoDriver::Job* VideoDriver::job_locked(uint64_t id) {
for (auto& j : jobs_) if (j->id == id) return j.get();
return nullptr;
}
void VideoDriver::release_locked(Job& j) {
if (j.lane >= 0) {
free_lanes_.push_back(j.lane);
j.lane = -1;
}
}
void VideoDriver::fail_locked(Job& j, int status, const std::string& why) {
j.failed = true;
j.req->ticket->finish(status, why);
}
/* In arrival order: a request needs only a lane. */
void VideoDriver::admit_locked() {
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted || j.failed) continue;
if (free_lanes_.empty()) break;
j.lane = free_lanes_.back();
free_lanes_.pop_back();
j.admitted = true;
}
}
/* ================================================================== staging */
int VideoDriver::upload() {
for (size_t r = 0; r < ranks_.size(); ++r)
for (int g = 0; g < R_N; ++g) {
if (reg_[g].used <= 0) continue;
RAD_TRY(rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off,
reg_[g].used, ranks_[r].stream));
}
return RAD_OK;
}
/* The geometry a pass's ops read off the device (RAD_VGEOM_*), with chunk `chunk`'s span when it
* is a decode's. */
void VideoDriver::stage_geom(const Job& j, int32_t chunk) {
int32_t* g = hptr<int32_t>(R_GEOM);
std::memset(g, 0, RAD_VGEOM_N * 4);
g[RAD_VGEOM_LAT_FRAMES] = j.geom.lat_frames;
g[RAD_VGEOM_LAT_H] = j.geom.lat_h;
g[RAD_VGEOM_LAT_W] = j.geom.lat_w;
g[RAD_VGEOM_N_TEXT] = j.geom.n_text;
g[RAD_VGEOM_N_AUDIO] = j.geom.n_audio;
g[RAD_VGEOM_CHUNK_LAT0] = (int32_t)(decl_.latents_per_chunk * chunk);
g[RAD_VGEOM_CHUNK_FRAMES] = (int32_t)decl_.dec_latents;
g[RAD_VGEOM_CHUNK_H] = j.geom.lat_h;
g[RAD_VGEOM_CHUNK_W] = j.geom.lat_w;
g[RAD_VGEOM_CHUNK_FIRST] = chunk == 0;
g[RAD_VGEOM_CHUNK_LAST] = chunk == j.n_chunks - 1;
g[RAD_VGEOM_PATCH_FRAMES] = (int32_t)decl_.dec_latents;
g[RAD_VGEOM_PATCH_H] = (int32_t)(j.geom.lat_h / decl_.patch);
g[RAD_VGEOM_PATCH_W] = (int32_t)(j.geom.lat_w / decl_.patch);
reg_[R_GEOM].used = RAD_VGEOM_N * 4;
const int64_t audio_rows = decl_.audio_channels * (int64_t)j.geom.n_audio;
const int64_t video_rows = j.rows - j.geom.n_text - audio_rows;
*hptr<int32_t>(R_LANE) = j.lane;
*hptr<int32_t>(R_FIRST) = j.step == 0;
int32_t* seg = hptr<int32_t>(R_SEG);
seg[0] = 0;
seg[1] = j.geom.n_text;
seg[2] = (int32_t)(j.geom.n_text + audio_rows);
seg[3] = (int32_t)j.rows;
int32_t* lat = hptr<int32_t>(R_LAT);
lat[0] = 0;
lat[1] = (int32_t)video_rows;
lat[2] = 0;
lat[3] = (int32_t)audio_rows;
reg_[R_LANE].used = 4;
reg_[R_FIRST].used = 4;
reg_[R_SEG].used = 4 * 4;
reg_[R_LAT].used = 4 * 4;
}
void VideoDriver::base_batches(const Job& j, int64_t n_tok, int step) {
for (size_t r = 0; r < ranks_.size(); ++r) {
RadBatch& B = out_[r];
RadVideoGenBatch& V = vout_[r];
const int ri = (int)r;
B = RadBatch{};
B.step = step;
B.phase = RAD_PHASE_PREFILL;
B.n_tok = n_tok;
B.n_seq = 1;
B.max_q_len = (int32_t)n_tok;
B.max_q_len_prefill = (int32_t)n_tok;
B.token_ids = dptr<int32_t>(ri, R_TOK);
B.positions = dptr<int32_t>(ri, R_POS);
B.cu_seqlens = dptr<int32_t>(ri, R_CU);
V = RadVideoGenBatch{};
V.lane = j.lane;
V.geom = j.geom;
V.geom_d = dptr<int32_t>(ri, R_GEOM);
V.lane_d = dptr<int32_t>(ri, R_LANE);
V.first_d = dptr<int32_t>(ri, R_FIRST);
V.seg_cu = dptr<int32_t>(ri, R_SEG);
V.lat_cu = dptr<int32_t>(ri, R_LAT);
V.n_steps = j.sched.steps;
V.t_video = dptr<float>(ri, R_TV);
V.t_audio = dptr<float>(ri, R_TA);
V.step = j.step;
V.sched = dptr<float>(ri, R_SCHED);
V.pos = dptr<float>(ri, R_ROPE);
V.seed = dptr<uint32_t>(ri, R_SEED);
V.chunk = j.chunk;
V.n_chunks = j.n_chunks;
V.dec_rows = j.dec_rows;
V.n_samples = j.n_samples;
B.vgen_b = &V;
}
}
/* ================================================================== the passes */
const RadBatch* VideoDriver::next(int step) {
std::lock_guard<std::mutex> lk(mu_);
pass_ = Pass{};
rb_.clear();
if (closed_) return nullptr;
/* Retire finished, failed and cancelled jobs, returning their lanes before admitting. Safe
* because next() runs between passes, with nothing in flight. */
for (auto it = jobs_.begin(); it != jobs_.end();) {
Job& j = **it;
const bool cancelled = j.req->ticket->cancel.load(std::memory_order_acquire);
if (!(j.failed || cancelled || j.finished)) { ++it; continue; }
if (cancelled && !j.failed && !j.finished)
j.req->ticket->finish(RAD_E_CANCELLED, "the request was cancelled");
release_locked(j);
it = jobs_.erase(it);
}
admit_locked();
/* 1. The decodes of a denoised lane: the soundtrack, then the chunks in order. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed || j.step < j.sched.steps) continue;
if (!j.audio_done) return build_audio(j, step);
if (j.chunk < j.n_chunks) return build_chunk(j, step);
}
/* 2. A prompt. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted && !j.failed && !j.cond_done) return build_cond(j, step);
}
/* 3. The oldest lane's next step. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted && !j.failed && j.cond_done && j.step < j.sched.steps)
return build_step(j, step);
}
return nullptr;
}
const RadBatch* VideoDriver::batch_for(int rank) const {
if (rank < 0 || (size_t)rank >= out_.size() || pass_.kind == 0) return nullptr;
return &out_[(size_t)rank];
}
const RadBatch* VideoDriver::build_cond(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const int64_t T = j.geom.n_text;
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* pos = hptr<int32_t>(R_POS);
std::memcpy(tok, j.req->tokens.data(), (size_t)T * 4);
for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)i;
int32_t* cu = hptr<int32_t>(R_CU);
cu[0] = 0;
cu[1] = (int32_t)T;
float* tv = hptr<float>(R_TV);
float* ta = hptr<float>(R_TA);
for (int32_t i = 0; i < j.sched.steps; ++i) {
tv[i] = 1.0f - j.sched.sig_v[(size_t)i];
ta[i] = 1.0f - j.sched.sig_a[(size_t)i];
}
reg_[R_TOK].used = T * 4;
reg_[R_POS].used = T * 4;
reg_[R_CU].used = 2 * 4;
reg_[R_TV].used = j.sched.steps * 4;
reg_[R_TA].used = j.sched.steps * 4;
stage_geom(j, 0);
if (upload() < 0) return nullptr;
base_batches(j, T, step);
for (auto& B : out_) B.gen = RAD_GEN_PASS_VCOND;
pass_.kind = RAD_GEN_PASS_VCOND;
pass_.job = j.id;
return &out_[0];
}
const RadBatch* VideoDriver::build_step(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const int32_t i = j.step;
float* s = hptr<float>(R_SCHED);
s[0] = 1.0f - j.sched.sig_v[(size_t)i];
s[1] = j.sched.sig_v[(size_t)i];
s[2] = j.sched.sig_v[(size_t)i + 1];
s[3] = 1.0f - j.sched.sig_a[(size_t)i];
s[4] = j.sched.sig_a[(size_t)i];
s[5] = j.sched.sig_a[(size_t)i + 1];
reg_[R_SCHED].used = 6 * 4;
std::memcpy(hptr<float>(R_ROPE), j.pos.data(), j.pos.size() * 4);
reg_[R_ROPE].used = (int64_t)j.pos.size() * 4;
/* The video's noise seed is the request's; the soundtrack's the same with its top bit flipped,
* so the two streams never coincide. */
uint32_t* sd = hptr<uint32_t>(R_SEED);
const uint64_t seed = j.req->seed;
sd[0] = (uint32_t)seed;
sd[1] = (uint32_t)(seed >> 32);
sd[2] = (uint32_t)seed;
sd[3] = (uint32_t)(seed >> 32) ^ 0x80000000u;
reg_[R_SEED].used = 4 * 4;
/* The packed sequence is one attention document. */
int32_t* cu = hptr<int32_t>(R_CU);
cu[0] = 0;
cu[1] = (int32_t)j.rows;
reg_[R_CU].used = 2 * 4;
stage_geom(j, 0);
if (upload() < 0) return nullptr;
base_batches(j, j.rows, step);
for (auto& B : out_) B.gen = RAD_GEN_PASS_VSTEP;
pass_.kind = RAD_GEN_PASS_VSTEP;
pass_.job = j.id;
return &out_[0];
}
const RadBatch* VideoDriver::build_audio(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
stage_geom(j, 0);
if (upload() < 0) return nullptr;
base_batches(j, 0, step);
for (auto& B : out_) B.gen = RAD_GEN_PASS_ADECODE;
rb_.assign(1, Readback{ decl_.audio_out, j.n_samples * decl_.audio_channels * 4, audio_host_ });
pass_.kind = RAD_GEN_PASS_ADECODE;
pass_.job = j.id;
return &out_[0];
}
const RadBatch* VideoDriver::build_chunk(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
stage_geom(j, j.chunk);
if (upload() < 0) return nullptr;
base_batches(j, j.dec_rows, step);
const bool last = j.chunk == j.n_chunks - 1;
const int32_t n = (int32_t)(decl_.frames_per_chunk + (last ? decl_.frames_tail : 0));
for (size_t r = 0; r < out_.size(); ++r) {
out_[r].gen = RAD_GEN_PASS_VDECODE;
vout_[r].n_frames_out = n;
}
const int64_t bytes = (int64_t)n * j.req->height * j.req->width * 3;
rb_.assign(1, Readback{ decl_.frames_out, bytes, frames_host_ });
pass_.kind = RAD_GEN_PASS_VDECODE;
pass_.job = j.id;
pass_.n_frames = n;
return &out_[0];
}
int VideoDriver::done() {
std::lock_guard<std::mutex> lk(mu_);
const int64_t now = (int64_t)rad_mono_ns();
Job* j = job_locked(pass_.job);
switch (j ? pass_.kind : 0) {
case RAD_GEN_PASS_VCOND:
j->cond_done = true;
j->req->ticket->t_cond_ns = now;
break;
case RAD_GEN_PASS_VSTEP: {
++j->step;
VideoEvent e;
e.kind = VideoEvent::STEP;
e.steps_done = j->step;
j->req->ticket->push(std::move(e));
if (j->step >= j->sched.steps) j->req->ticket->t_denoised_ns = now;
break;
}
case RAD_GEN_PASS_ADECODE: {
VideoEvent e;
e.kind = VideoEvent::AUDIO;
e.samples.assign(audio_host_, audio_host_ + j->n_samples * decl_.audio_channels);
j->req->ticket->push(std::move(e));
j->audio_done = true;
break;
}
case RAD_GEN_PASS_VDECODE: {
VideoEvent e;
e.kind = VideoEvent::FRAMES;
e.first = j->frames_out;
e.n = pass_.n_frames;
const size_t bytes = (size_t)pass_.n_frames * j->req->height * j->req->width * 3;
e.rgb.assign(frames_host_, frames_host_ + bytes);
j->req->ticket->push(std::move(e));
j->frames_out += pass_.n_frames;
if (++j->chunk == j->n_chunks) {
j->finished = true;
j->req->ticket->t_done_ns = now;
j->req->ticket->finish(RAD_OK);
}
break;
}
default:
break;
}
pass_ = Pass{};
rb_.clear();
return RAD_OK;
}
} /* namespace gen */
} /* namespace rad */
+141
View File
@@ -0,0 +1,141 @@
/* video_driver.h -- the video generator's pass driver (video.h; abi/rad_builder.h's
* RadVideoGenDecl describes the passes).
*
* Driven by the engine thread like the other drivers (driver.h): `next()` picks and stages a
* pass, `done()` folds its result back once every rank has run it. Requests arrive from HTTP
* threads through `submit()` and leave through their VideoTicket.
*
* A request holds a lane from admission to its last chunk. Its geometry, schedule and rotary
* positions are fixed at submit, so nothing is computed between passes but the staging.
*
* Pass priority, one pass at a time:
*
* 1. ADECODE, then each VDECODE chunk in order, of a lane whose denoising is done: they finish
* a request and free its lane.
* 2. VCOND of an admitted request, so its steps can follow the current request's without a gap.
* 3. VSTEP of the oldest lane with steps left. Requests are denoised one after another, not in
* turns: a pass is one request's whole sequence, so taking turns would only delay the first.
*/
#pragma once
#include "video.h"
#include "pass.h"
#include "device/device.h"
#include <mutex>
namespace rad {
namespace gen {
class VideoDriver final : public IPassDriver {
public:
struct RankIO {
int device = 0;
RadStream stream = nullptr;
};
using PositionsFn = int64_t (*)(int, const RadVideoGeom*, float*, int64_t);
/* `positions` is the plugin's rad_arch_video_positions. */
int init(const Program& prog, PositionsFn positions, const std::vector<RankIO>& ranks);
void fini();
~VideoDriver() override { fini(); }
/* The bytes init() allocates on each rank's card, for the VRAM budget. */
static int64_t device_bytes(const Program& prog);
/* ---------------------------------------------------------- HTTP threads */
/* Queue a request, refused at once with `why` when it can never run. */
int submit(std::unique_ptr<VideoRequest> r, std::string* why);
const RadVideoGenDecl& decl() const { return decl_; }
void shutdown(const char* why, int status) override;
/* ---------------------------------------------------------- the engine thread */
const RadBatch* next(int step) override;
const RadBatch* batch_for(int rank) const override;
const std::vector<Readback>& readbacks() const override { return rb_; }
int done() override;
int64_t queued() const override;
int64_t running() const override;
private:
struct Job {
uint64_t id = 0;
std::unique_ptr<VideoRequest> req;
RadVideoGeom geom{};
int64_t rows = 0, dec_rows = 0;
int32_t n_chunks = 0;
int64_t n_samples = 0; /* the soundtrack's samples a channel */
VideoSchedule sched;
std::vector<float> pos; /* [3, rows] */
int32_t lane = -1;
bool admitted = false;
bool cond_done = false;
int32_t step = 0; /* steps done */
bool audio_done = false;
int32_t chunk = 0; /* chunks decoded */
int32_t frames_out = 0; /* frames handed to the caller */
bool failed = false;
bool finished = false;
};
/* The pass in flight, for done(). */
struct Pass {
int kind = 0;
uint64_t job = 0;
int32_t n_frames = 0;
};
/* Staging regions: their offsets in the host span and every rank's slab. */
struct Region { int64_t off = 0, bytes = 0, used = 0; };
enum { R_TOK, R_POS, R_CU, R_ROPE, R_GEOM, R_SCHED, R_TV, R_TA, R_SEED, R_LANE, R_FIRST,
R_SEG, R_LAT, R_N };
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
template <class T> T* dptr(int rank, int r) const {
return reinterpret_cast<T*>((char*)dev_[(size_t)rank] + reg_[r].off);
}
int upload();
void base_batches(const Job& j, int64_t n_tok, int step);
void stage_geom(const Job& j, int32_t chunk);
void admit_locked();
void release_locked(Job& j);
void fail_locked(Job& j, int status, const std::string& why);
Job* job_locked(uint64_t id);
const RadBatch* build_cond(Job& j, int step);
const RadBatch* build_step(Job& j, int step);
const RadBatch* build_audio(Job& j, int step);
const RadBatch* build_chunk(Job& j, int step);
RadVideoGenDecl decl_{};
std::vector<double> rungs_; /* decl_.rungs points here */
std::string name_;
PositionsFn positions_ = nullptr;
int64_t max_tok_ = 0;
std::vector<RankIO> ranks_;
char* host_ = nullptr; /* pinned, same layout as each slab */
int64_t bytes_ = 0;
std::vector<void*> dev_;
Region reg_[R_N];
uint8_t* frames_host_ = nullptr;
int64_t frames_bytes_ = 0;
float* audio_host_ = nullptr;
int64_t audio_bytes_ = 0;
std::vector<Readback> rb_;
std::vector<RadBatch> out_; /* one per rank */
std::vector<RadVideoGenBatch> vout_;
Pass pass_;
mutable std::mutex mu_;
std::deque<std::unique_ptr<Job>> jobs_; /* arrival order */
std::vector<int32_t> free_lanes_;
uint64_t next_id_ = 1;
bool closed_ = false;
std::string closed_why_;
int closed_status_ = RAD_E_STATE;
};
} /* namespace gen */
} /* namespace rad */
+5 -9
View File
@@ -2,11 +2,9 @@
* --lora-target-modules). Read by declare (which sites and pools exist), by the adapter manager
* (what may be loaded into them) and by nothing else.
*
* OFF UNLESS ASKED FOR: with no adapter named and no --max-loras, `enabled()` is false, declare
* appends nothing, the program has no pool and no extra op, and the engine computes exactly what it
* computed before this file existed. */
* Off unless asked for: with no adapter named and no --max-loras, `enabled()` is false, declare
* appends nothing, the program has no pool and no extra op, and no step carries an adapter slot. */
#pragma once
#include <set>
#include <string>
#include <utility>
#include <vector>
@@ -20,11 +18,9 @@ struct LoraConfig {
int max_loras = 0;
/* The rank every slot is sized for; an adapter of lower rank is zero-padded into it. */
int max_rank = 16;
/* HF module leaf names (q_proj, gate_proj, in_proj_qkv, ...) the sites are built for. Empty:
* the union of the startup adapters' target_modules, or -- with no startup adapter -- every
* LoRA-capable trunk linear (`all_linear`). */
std::set<std::string> targets;
bool all_linear = false;
/* HF module leaf names (q_proj, gate_proj, in_proj_qkv, ...) the sites are built for, sorted
* and unique. Empty: the union of the startup adapters' target_modules. */
std::vector<std::string> targets;
bool enabled() const { return max_loras > 0 || !adapters.empty(); }
int slots() const {
+57 -16
View File
@@ -28,6 +28,38 @@ bool is_coded(uint32_t dt) {
return dt == RAD_F8E4M3 || dt == RAD_F8E5M2 || dt == RAD_I8;
}
/* The block of a scale stream of `blocks` groups over `ext` elements, as the kernel libraries
* read one (libref/ref_gemm.h's grid_block): the power of two whose ceiling division gives
* `blocks`, else the plain ceiling; one group is the whole extent. */
int64_t grid_block(int64_t ext, int64_t blocks) {
if (ext <= 0) return 1;
if (blocks <= 1) return ext;
const int64_t lo = (ext + blocks - 1) / blocks;
int64_t b = 1;
while (b < lo) b <<= 1;
return (ext + b - 1) / b == blocks ? b : lo;
}
/* The scale grid of a coded activation the GEMM `reads`: the read set's one f32 buffer beside
* the codes (reads[0]), [rows, groups] or one scale a row, over the codes' full width. The
* GEMM's own `group` is the weight's (an MXFP4 weight's 32-wide exponent block reads an
* activation scaled per 128), and a GEMM may read a column span of the activation, so neither
* its `group` nor its K gives the activation's grid. 0 when the stream is not one f32 buffer. */
int64_t activation_grid(const Program& P, const std::vector<rad_buf>& reads) {
const RadBufDecl& a = P.buffers[reads[0]].decl;
const RadBufDecl* s = nullptr;
for (size_t i = 1; i < reads.size(); ++i) {
const RadBufDecl& d = P.buffers[reads[i]].decl;
if (d.dtype != RAD_F32) continue;
if (s) return 0;
s = &d;
}
if (!s || a.rank < 1 || s->rank < 1) return 0;
const int64_t width = a.shape[a.rank - 1];
const int64_t groups = s->rank >= 2 ? s->shape[s->rank - 1] : 1;
return groups > 0 ? grid_block(width, groups) : 0;
}
rad_buf decl_persist(Builder& b, const std::string& name, uint32_t dtype, uint32_t rank,
const int64_t* shape) {
RadBufDecl d{};
@@ -44,6 +76,16 @@ rad_buf decl_persist(Builder& b, const std::string& name, uint32_t dtype, uint32
int lora_declare(Builder& b, const LoraDeclare& d) {
if (!d.cfg || !d.cfg->enabled()) return RAD_OK;
Program& P = b.program();
/* Adapters are chosen per request and applied on the token steps of a model that writes
* logits; a generator's passes and an embedding model's requests carry no adapter. */
if (P.is_pass_driven() || P.pooled_buf != RAD_NULL_HANDLE ||
P.logits_buf == RAD_NULL_HANDLE) {
RAD_ERR("lora: runtime LoRA adapters serve a model that generates text, and this one %s",
P.is_pass_driven() ? "is an image, audio or video generator"
: P.pooled_buf != RAD_NULL_HANDLE ? "makes embeddings"
: "declares no logits");
return RAD_E_UNSUPPORTED;
}
const int S = d.cfg->slots();
const int max_rank = d.cfg->max_rank;
const int64_t max_tok = P.ctx.max_tok;
@@ -53,10 +95,8 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
return RAD_E_INVAL;
}
/* EVERY READER OF A TARGETED WEIGHT CARRIES THE DELTA, OR STARTUP REFUSES. A targeted weight
* that some op multiplies without the adapter is a model that is the base in one place and the
* adapter in another, and the text it writes is wrong in a way no test of the targeted GEMM
* would show. */
/* Every reader of a targeted weight carries the delta, or startup refuses: a weight some op
* multiplies without the adapter would be the base in one place and the adapter in another. */
std::vector<lora::UnsupportedUse> bad;
int s = lora::find_unsupported_uses(P, d.targets, &bad);
if (s < 0) return s;
@@ -110,10 +150,10 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
}
}
/* ---- t = A.x, one f32 plane per capacity R and lane. PERSIST and not TRANSIENT: the ops that
* use it are issued inside the GEMM's issue, at the GEMM's position, while the buffer plan would
* place a transient by the appended ops' own position at the end of the program -- and share
* its bytes with whatever is live there. */
/* ---- t = A.x, one f32 plane per capacity R and lane. Persistent, not transient: the ops that
* use it run at the GEMM's position, but the buffer plan would place a transient at the
* appended ops' own position, the end of the program, and share its bytes with buffers live
* mid-program. */
std::map<int64_t, int32_t> t_by_r;
P.lora_t.clear();
for (const lora::Site& x : sites) {
@@ -136,14 +176,13 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
const uint32_t gh = x.gemm;
if (gh == 0 || gh >= P.ops.size()) return RAD_E_STATE;
if (!b.op_resolved(gh)) continue; /* never handed to the plugin, so never issued */
/* Copied out first: decl_op below appends to P.ops and moves every OpInfo. */
/* Copied out first: decl_op below appends to P.ops, which may move every OpInfo. */
const OpInfo& g = P.ops[gh];
const std::string gop = g.op;
const std::string rkey = g.ranged_key;
const int64_t lo = g.range_lo, hi = g.range_hi;
long long gk = 0, gn = 0, gg = 0;
long long gk = 0, gn = 0;
const bool has_k = g.base.get_i("K", &gk), has_n = g.base.get_i("N", &gn);
const bool has_group = g.base.get_i("group", &gg) && gg > 0;
const int oa = opd_index(g, "a"), oas = opd_index(g, "a_scale"), oy = opd_index(g, "y");
const std::vector<rad_buf> reads = b.op_read_set(gh), writes = b.op_write_set(gh);
@@ -167,6 +206,12 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
const uint32_t y_dt = P.buffers[writes[0]].decl.dtype;
const bool coded = is_coded(a_dt);
if (coded && oas < 0) { refuse("a coded activation and no `a_scale` operand"); continue; }
const int64_t a_grid = coded ? activation_grid(P, reads) : 0;
if (coded && a_grid <= 0) {
refuse("a coded activation whose read set holds no single f32 scale stream beside the "
"codes, so the grid lora_shrink reads it at is not known at declare");
continue;
}
RadParam sp[6];
int n_sp = 0;
@@ -174,7 +219,7 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
sp[n_sp++] = RAD_INT("K", x.K_r);
sp[n_sp++] = RAD_INT("R", x.R);
sp[n_sp++] = RAD_INT("S", S);
if (coded && has_group) sp[n_sp++] = RAD_INT("group", gg);
if (coded) sp[n_sp++] = RAD_INT("group", a_grid);
sp[n_sp++] = RAD_STR("dtype", rad_dtype_name(a_dt));
const rad_op hs = b.decl_op("lora_shrink", sp, n_sp, nullptr, 0);
@@ -200,10 +245,6 @@ int lora_declare(Builder& b, const LoraDeclare& d) {
P.ops[he].anchor = (int32_t)gh;
P.ops[gh].lora_site = (int32_t)P.lora_sites.size();
P.lora_sites.push_back(is);
x.lora_shrink = hs; x.lora_expand = he;
const LoraPool& lp = P.lora_pools[(size_t)x.pool];
x.pool_a = lp.a; x.pool_b = lp.b; x.pool_scale = lp.scale;
}
if (n_refused) return RAD_E_UNSUPPORTED;
+3 -3
View File
@@ -2,9 +2,9 @@
* its program, build the sites (lora.h), declare the adapter pools and the two ops each targeted
* GEMM is followed by, and record what the issue path needs (Program::lora_sites).
*
* Runs inside rad_tools_declare, after rad_arch_declare and before the sampler, on the real
* declare AND on every sizing declare -- identically, because a sizing declare must produce the
* same op list (rad_builder.cpp checks it op by op). */
* Runs inside rad_tools_declare, after rad_arch_declare and before the sampler, identically on the
* real declare and on every sizing declare, which must produce the same op list (rad_builder.cpp
* checks it op by op). */
#pragma once
#include "lora/config.h"
#include "lora/lora.h"
+39 -52
View File
@@ -130,7 +130,7 @@ struct MapIndex {
}
};
/* THE predicate, over the maps already found. */
/* weight_targeted(), over the maps already found. */
bool targeted_core(const Program& prog, const WeightInfo& w,
const std::vector<const RadNameMap*>& maps, const TargetSet& targets) {
if (targets.empty() || maps.empty()) return false;
@@ -190,11 +190,6 @@ rad_weight b_weight(const OpInfo& op) {
return op.weights.empty() ? 0 : op.weights[0];
}
void fnv(uint64_t* h, const void* p, size_t n) {
const uint8_t* b = static_cast<const uint8_t*>(p);
for (size_t i = 0; i < n; ++i) { *h ^= b[i]; *h *= 1099511628211ull; }
}
bool read_file(const std::string& path, std::string* out) {
std::ifstream f(path, std::ios::binary);
if (!f) return false;
@@ -339,11 +334,9 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets,
Site s;
s.gemm = op_index;
s.op = op.op;
s.w = wh;
s.weight = W.name;
s.shard = W.decl.shard;
s.max_rank = max_rank;
s.res_unchecked = op.op == "gemm_nt_bias";
if (W.decl.rank != 2)
return fail(err, RAD_E_SHAPE, fmt("weight '%s' is rank %u; a LoRA site needs a matrix",
@@ -425,8 +418,8 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets,
int64_t N_full = 0;
for (int64_t t : s.part_total) N_full = (t > 0 && N_full >= 0) ? N_full + t : -1;
/* ---- THE LOADER'S OWN FUNCTION AGREES, or this is not a site. weight_share is what puts the
* base weight's bytes on this rank; asked for a plain [N_full, K_full] entry it must name the
/* ---- the loader's own cut must agree, or this is not a site: weight_share, which puts the
* base weight's bytes on this rank, must name for a plain [N_full, K_full] entry the
* rectangles this geometry names. */
if (N_full > 0 && s.K_full > 0) {
WeightInfo v = W;
@@ -483,7 +476,7 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets,
srcs.push_back(m->src[k] ? m->src[k] : "");
}
if (alternatives) {
/* COPY with alternatives: the first one the container holds IS the weight, and which one
/* COPY with alternatives: the first one the container holds is the weight, and which one
* that is is not recorded. Usable only when exactly one alternative is targeted. */
std::vector<std::string> hit;
for (const std::string& x : srcs) {
@@ -580,6 +573,15 @@ bool op_is_site(const Program& prog, const OpInfo& op, rad_weight* b_out, std::s
return no(fmt("gemm_nt_q over rotated parts (pb1=%lld pb2=%lld): its input is the "
"rotated activation", p1, p2));
}
if (gq || gqb) {
/* At w4a8, w8a8 and w2a8 `a` is quant_act_i8's codes in the int8 WMMA's step order (the
* middle dwords of every 16-byte step exchanged, docs/OPS.md), which lora_shrink would
* read as the activation's columns. */
const char* dt = op.base.get_s("dtype");
if (dt && (!std::strcmp(dt, "w4a8") || !std::strcmp(dt, "w8a8") || !std::strcmp(dt, "w2a8")))
return no(fmt("%s at %s reads quant_act_i8's codes in the int8 WMMA's step order, not "
"in the activation's column order", op.op.c_str(), dt));
}
const WeightInfo& w = prog.weights[b];
if (gq || gqb) {
long long k = 0;
@@ -607,7 +609,7 @@ int find_unsupported_uses(const Program& prog, const TargetSet& targets,
const bool site = op_is_site(prog, op, &b, &why);
for (rad_weight h : op.weights) {
if (!targeted_idx(prog, mi, h, targets)) continue;
/* Every view of a targeted weight read by a site over the SAME logical weight is the
/* Every view of a targeted weight read by a site over the same logical weight is the
* site's own (codes, scale, ref). Anything else reading it is not a site. */
if (site && b && prog.weights[b].source == prog.weights[h].source) continue;
UnsupportedUse u;
@@ -669,32 +671,6 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank,
return RAD_OK;
}
TargetSet all_capable_targets(const Program& prog) {
std::set<std::string> leaves;
for (size_t h = 1; h < prog.weights.size(); ++h) {
const WeightInfo& w = prog.weights[h];
if (excluded_weight(prog, w)) continue;
std::vector<const RadNameMap*> maps;
scan_maps(prog, w.source, &maps);
for (const RadNameMap* m : maps)
for (int k = 0; k < m->n_src && k < 8; ++k) {
std::string leaf;
const std::string src = m->src[k] ? m->src[k] : "";
if (!module_of(src, &leaf).empty() && !excluded_source(src)) leaves.insert(leaf);
}
}
TargetSet ok;
for (const std::string& l : leaves) {
const TargetSet one{ l };
std::vector<Site> s;
std::string e;
if (find_unsupported_uses(prog, one, nullptr) == 0 && build_sites(prog, one, 1, &s, &e) == RAD_OK &&
!s.empty())
ok.insert(l);
}
return ok;
}
std::string explain_module(const Program& prog, const TargetSet& targets, const std::string& module) {
const std::string want[3] = {
module,
@@ -817,6 +793,17 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
if (truthy("trainable_token_indices"))
return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": trainable_token_indices -- embedding "
"updates are not served");
/* PEFT options that change the forward pass itself, not only the weights. */
if (truthy("layer_replication"))
return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": layer_replication -- an adapter over "
"repeated base layers is not served");
if (truthy("use_qalora"))
return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": use_qalora -- QA-LoRA's pooled input is "
"not served");
if (truthy("alora_invocation_tokens"))
return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": alora_invocation_tokens -- an activated "
"LoRA, which applies only after its "
"invocation, is not served");
if (!cfg.contains("r") || !cfg["r"].is_number_integer() || cfg["r"].get<int64_t>() <= 0)
return fail(err, RAD_E_FORMAT, cfg_path + ": no positive integer `r`");
if (!cfg.contains("lora_alpha") || !cfg["lora_alpha"].is_number())
@@ -833,6 +820,9 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
else if (t.is_array())
for (const ojson& x : t) if (x.is_string()) info->target_modules.push_back(x.get<std::string>());
}
/* PEFT's get_pattern_key: a key matches a module whose name ends in it on a dot boundary,
* `(.*\.)?(key)$` from the start of the name, and the first matching key in the file's order
* wins. */
struct Pat { std::string key; std::regex re; double v; };
std::vector<Pat> rpat, apat;
for (const char* which : { "rank_pattern", "alpha_pattern" }) {
@@ -846,14 +836,17 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
Pat p;
p.key = it.key();
try {
p.re = std::regex(p.key, std::regex::ECMAScript);
p.re = std::regex("(.*\\.)?(" + p.key + ")$", std::regex::ECMAScript);
} catch (const std::regex_error& e) {
return fail(err, RAD_E_FORMAT, cfg_path + ": " + which + " key '" + p.key +
"' is not a regex this engine reads (" + e.what() + ")");
}
p.v = it.value().get<double>();
if (!std::isfinite(p.v))
return fail(err, RAD_E_FORMAT, cfg_path + ": " + which + "[" + p.key +
"] is not a finite number");
if (!std::strcmp(which, "rank_pattern")) {
if (!it.value().is_number_integer() || p.v <= 0)
if (!it.value().is_number_integer() || p.v <= 0 || p.v > (double)INT32_MAX)
return fail(err, RAD_E_FORMAT, cfg_path + ": rank_pattern[" + p.key +
"] is not a positive integer");
info->rank_pattern.push_back({ p.key, (int64_t)p.v });
@@ -873,19 +866,10 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
"adapter as safetensors");
if (st.open(st_path) != RAD_OK) return fail(err, RAD_E_IO, st_path + ": cannot open as safetensors");
uint64_t hash = 1469598103934665603ull;
fnv(&hash, text.data(), text.size());
std::vector<const StTensor*> order;
for (const StTensor& t : st.tensors()) order.push_back(&t);
std::sort(order.begin(), order.end(),
[](const StTensor* a, const StTensor* b) { return a->name < b->name; });
for (const StTensor* t : order) {
fnv(&hash, t->name.data(), t->name.size() + 1);
fnv(&hash, t->dtype_str.data(), t->dtype_str.size() + 1);
for (int64_t d : t->shape) fnv(&hash, &d, sizeof d);
if (t->data) fnv(&hash, t->data, (size_t)t->bytes);
}
info->content_hash = hash;
static const std::regex key_re(R"(^(.*)\.lora_([AB])\.(weight|default\.weight)$)");
std::map<std::string, AdModule> mods;
@@ -902,7 +886,7 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
"; only linear LoRA A/B pairs are served");
}
std::string mod = m[1].str();
const size_t at = mod.find("base_model.model."); /* rad-export: first occurrence */
const size_t at = mod.find("base_model.model."); /* the first one, as rad-export strips it */
if (at != std::string::npos) mod.erase(at, 17);
AdModule& am = mods[mod];
am.name = mod;
@@ -932,8 +916,8 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
}
int64_t rr = info->r;
double aa = info->alpha;
for (const Pat& p : rpat) if (std::regex_search(am.name, p.re)) { rr = (int64_t)p.v; break; }
for (const Pat& p : apat) if (std::regex_search(am.name, p.re)) { aa = p.v; break; }
for (const Pat& p : rpat) if (std::regex_match(am.name, p.re)) { rr = (int64_t)p.v; break; }
for (const Pat& p : apat) if (std::regex_match(am.name, p.re)) { aa = p.v; break; }
if (am.A->shape[0] != rr || am.B->shape[1] != rr)
return fail(err, RAD_E_SHAPE,
fmt("module %s: expected rank %lld (r / rank_pattern), found lora_A %s and "
@@ -945,6 +929,9 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
am.rank = rr;
am.alpha = aa;
am.scale = (float)(info->rslora ? aa / std::sqrt((double)rr) : aa / (double)rr);
if (!std::isfinite(am.scale))
return fail(err, RAD_E_FORMAT, fmt("module %s: alpha %g over rank %lld is no finite "
"f32 scale", am.name.c_str(), aa, (long long)rr));
info->max_module_rank = std::max(info->max_module_rank, rr);
const size_t d = am.name.rfind('.');
info->leaves.insert(d == std::string::npos ? am.name : am.name.substr(d + 1));
+22 -41
View File
@@ -1,22 +1,19 @@
/* lora.h -- runtime LoRA: which declared GEMMs an adapter lands in, and the bytes of one adapter for
* one rank (research/radiance/lora/DESIGN.md §2, §5).
* one rank. Two host-only steps that read nothing but the declared Program:
*
* TWO PURE STEPS, both host-only and both read nothing but the declared Program:
* build_sites() after declare, every LoRA-capable trunk GEMM whose weight a target names becomes
* a Site: the weight's per-rank geometry (K slice, output width, where each PEFT
* module's rows land in y), read from what the plugin recorded on the weight
* (shard mode, row parts, shard and part spans, name-map sources), never from a
* plugin's own split rule. One Site per GEMM op; the Sites of one declared weight
* share one pool.
* load_adapter() a PEFT directory -> one PackedSite per pool, the bytes of one slot.
*
* build_sites() after declare: every LoRA-capable trunk GEMM whose weight a target names becomes
* a Site -- the weight's per-rank geometry (K slice, output width, which rows of
* which PEFT module land where in the GEMM's y) read off the facts the plugin
* recorded on the weight: its shard mode, row parts, shard / part spans and its
* name-map sources. Never a plugin's own split rule. One Site per GEMM op; the
* Sites of one declared weight share one POOL (one slot layout per weight).
* load_adapter() a PEFT directory -> one PackedSite per pool: exactly the bytes of one slot.
* Nothing here touches a device; the caller declares the pools and copies.
*
* Nothing here allocates device memory or touches a device; the caller declares the pools and copies.
*
* TARGETS ARE HF MODULE LEAF NAMES ("q_proj", "gate_proj", "in_proj_qkv", ...). A declared weight is
* targeted when one of its name-map sources is `<prefix>.<leaf>.weight`, `leaf` in the set, and the
* weight is not in a non-trunk scope (weight_targeted() states the rule; build_sites and
* find_unsupported_uses use exactly that predicate, and the builder may call it mid-declare).
* Targets are HF module leaf names ("q_proj", "gate_proj", "in_proj_qkv", ...). A declared weight is
* targeted when one of its name-map sources is `<prefix>.<leaf>.weight` with `leaf` in the set and
* the weight is in the trunk; weight_targeted() is the one predicate everything here uses.
*/
#pragma once
#include "../rad_core.h"
@@ -30,25 +27,23 @@
namespace rad {
namespace lora {
/* HF module LEAF names. A std::set so two callers that build it in different orders get the same
* answer. Empty targets nothing. */
/* HF module leaf names, ordered so every caller builds the same set. Empty targets nothing. */
using TargetSet = std::set<std::string>;
/* ONE CONTIGUOUS RUN OF ONE PEFT MODULE'S ROWS INSIDE THIS SITE'S y, ON THIS RANK.
* A module may need SEVERAL parts: in_proj_qkv covers three row parts of the delta net's fused
* ssm_inz, and a rank holds a slice of EACH, so its B rows on that rank are three disjoint runs
* landing at three y columns. Every part of one module carries the same t_off. */
/* One contiguous run of one PEFT module's rows inside this site's y, on this rank. A module may
* need several: in_proj_qkv covers three row parts of the delta net's fused ssm_inz and a rank
* holds a slice of each, so its B rows there are three runs at three y columns. Every part of one
* module has the same t_off. */
struct SitePart {
std::string module; /* HF module path without ".weight", as the name map spells it */
int64_t src_lo = 0, src_hi = 0;/* rows [lo,hi) of the module's full output (= rows of lora_B) */
int64_t y_col = 0; /* column of this site's per-rank y where row src_lo lands */
int64_t t_off = 0; /* first t column of the module's block = module slot * max_rank */
/* ADDED: the weight's row part this run lies in (0 for a weight of one part). */
int32_t row_part = 0;
int32_t row_part = 0; /* the weight's row part this run lies in (0: a single part) */
};
/* ADDED: one name-map source of the site's weight, in concatenation order -- targeted or not,
* because an untargeted source still occupies rows of the fused weight. */
/* One name-map source of the site's weight, in concatenation order, targeted or not: an untargeted
* source still occupies rows of the fused weight. */
struct SiteSource {
std::string module; /* source without ".weight" */
bool targeted = false;
@@ -59,28 +54,20 @@ struct SiteSource {
};
struct Site {
uint32_t gemm = 0; /* the gemm op handle (anchor) */
uint32_t lora_shrink = 0, lora_expand = 0; /* appended op handles (stream G) */
uint32_t gemm = 0; /* the gemm op handle */
std::string weight; /* declared weight name */
int shard = 0; /* RAD_SHARD_ROW / COL / NONE of the base weight */
int64_t K_r = 0, k_lo = 0, K_full = 0; /* x columns on this rank; COL: A columns
* [k_lo, k_lo + K_r). K_full 0 = not recorded on
* the weight (a COL span): taken from lora_A. */
int64_t N_r = 0; /* per-rank y width the gemm writes */
int64_t R = 0; /* capacity: n_modules * max_rank (see report:
* DESIGN said parts.size() * max_rank) */
int64_t R = 0; /* capacity: n_modules * max_rank */
std::vector<SitePart> parts; /* empty while !parts_resolved */
uint32_t pool_a = 0, pool_b = 0, pool_scale = 0; /* PERSIST buffers; 0 here, the caller's */
/* ---- ADDED */
int32_t pool = -1; /* index of the weight in build_sites' per-weight pool list */
uint32_t w = 0; /* the declared weight's handle */
std::string op; /* the gemm's op name */
int32_t n_modules = 0; /* targeted sources */
int32_t max_rank = 0;
bool parts_resolved = true; /* false: the fused layout is decided by B rows at load */
bool res_unchecked = false; /* gemm_nt_bias: its optional `res` operand is bound at
* issue, not at declare -- stream G checks it there */
std::vector<SiteSource> sources;
/* Per row part g of the weight (P = max(1, n_row_parts) entries): the part's rows in the
* container (0 = not recorded: an equal-part single span), this rank's rows [lo, hi) of it in
@@ -93,7 +80,6 @@ struct PackedSite {
std::vector<uint16_t> a; /* [R, K_r] bf16, zero rows past the module's rank in each block */
std::vector<uint16_t> b; /* [N_r, R] bf16, zero outside the module's rows / rank block */
std::vector<float> scale; /* [N_r]: the module's alpha/r (alpha/sqrt(r) rsLoRA) on its rows */
/* ADDED */
int32_t pool = -1;
bool empty = true; /* no module of this adapter lands in this pool */
};
@@ -121,7 +107,6 @@ struct AdapterInfo {
std::set<std::string> leaves; /* leaf names present in the tensors (targets present) */
std::vector<std::string> absent; /* modules no site on THIS rank took (see check_placed) */
int64_t max_module_rank = 0;
uint64_t content_hash = 0; /* FNV-1a 64 over the config bytes and the tensors */
};
/* A targeted weight read by an op that is not a LoRA site. The caller refuses at startup. */
@@ -165,10 +150,6 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank,
std::vector<Site>* out, std::string* err,
std::vector<std::string>* pool_weights = nullptr);
/* Every leaf whose every targeted weight in `prog` would be a site: what "all LoRA-capable trunk
* linears" means when no adapter names the targets. */
TargetSet all_capable_targets(const Program& prog);
/* One adapter for one rank: `packed` gets one PackedSite per pool (index = Site::pool), in the
* slot layout of the pool's sites. Refusals return a negative code and name module, expected and
* found. A module with no site on THIS rank is not refused here -- an attention-zero rank holds no
+2 -3
View File
@@ -29,9 +29,8 @@ int SlotTable::reserve(const std::string& name, int* slot, bool* cooling, std::s
*err = "an adapter named '" + name + "' is already loaded";
return RAD_E_INVAL;
}
/* The old adapter's requests are still running on its slot, and a request naming
* the new one would be told apart from them only by the uid: load it once the old one
* is gone (POST /v1/unload_lora_adapter says how many remain). */
/* The old adapter's requests still run on its slot; the name loads again once they
* are gone (POST /v1/unload_lora_adapter says how many remain). */
const auto it = refs_.find(x.uid);
const int n = it == refs_.end() ? 0 : it->second;
*err = fmt("an adapter named '%s' is being unloaded: %d request%s still use%s it", name.c_str(),
+11 -11
View File
@@ -2,22 +2,22 @@
* be written again. Host bookkeeping only: the engine copies the adapter's bytes (engine_lora.cpp)
* and this table decides which slot, publishes the name, hands out holds and frees slots.
*
* A SLOT'S LIFE:
* A slot's life:
*
* free --load--> loaded --unload, no request uses it--> free (cooling)
* | ^
* +--unload, requests use it--> draining ---+ the last of them finishes
*
* A request holds the adapter it names from admission until its reply is done (the server keeps
* the hold in the request's Generation), so an adapter is never unloaded under a request. An
* unload of an adapter in use DRAINS it: from that moment no new request can name it (it is gone
* from the names, and acquire answers as for a name never loaded), the requests already holding
* it finish normally, and the last hold to go frees the slot. A load of the same name waits for
* that rather than racing it.
* A request holds the adapter it names from admission until its reply is done or it is cancelled
* (the server keeps the hold in the request's Generation), so an adapter is never unloaded under a
* request. An unload of an adapter in use drains it: no new request can name it (acquire answers
* as for a name never loaded), the requests already holding it finish, and the last hold to go
* frees the slot. A load of the same name is refused until then.
*
* COOLING: a freed slot is written again only once the step loop has gone round three times
* since (`epoch` below counts its rounds): the step after a request's last one may already be on
* the card, issued ahead, and reads the slot through the step batch until it runs.
* Cooling: a freed slot is written again only after the step loop has gone round
* kSlotCoolRounds times (`epoch` counts its rounds). A step that read the slot may still be on
* the card when the last hold goes, issued ahead of the readback; an idle round has no step in
* flight and a busy round collects one, so with one step issued ahead two rounds suffice.
*
* Thread-safe: every call takes the table's lock. Loads are serialised by the caller (one at a
* time between reserve and publish), which is what keeps a reserved slot from being handed out
@@ -85,7 +85,7 @@ private:
const std::atomic<uint64_t>* epoch_ = nullptr;
};
/* Step-loop rounds a freed slot waits before it is written again (see COOLING above). */
/* Step-loop rounds a freed slot waits before it is written again (see Cooling above). */
inline constexpr uint64_t kSlotCoolRounds = 3;
} /* namespace lora */
+64 -12
View File
@@ -82,6 +82,58 @@ void KeepAll::select(const std::vector<int64_t>& pos, std::vector<int64_t>* keep
*keep = pos;
}
/* A session's tip is usually a prompt's tail between two interval checkpoints, so each step also
* counts the ladder with a tail half an interval on as its tip. */
int64_t CheckpointPolicy::held(int64_t ctx, int64_t interval) const {
if (interval <= 0 || ctx < interval) return 1;
std::vector<int64_t> kept, keep;
size_t most = 0;
for (int64_t p = interval; p <= ctx; p += interval) {
kept.push_back(p);
select(kept, &keep);
std::sort(keep.begin(), keep.end());
kept.swap(keep);
most = std::max(most, kept.size());
if (p + interval / 2 <= ctx) {
std::vector<int64_t> tipped = kept;
tipped.push_back(p + interval / 2);
select(tipped, &keep);
most = std::max(most, keep.size());
}
}
return (int64_t)most;
}
int64_t KeepAll::held(int64_t ctx, int64_t interval) const {
return interval > 0 && ctx >= interval ? ctx / interval : 1;
}
std::unique_ptr<CheckpointPolicy> make_checkpoint_policy(const std::string& name,
int64_t interval) {
if (name == "tip-only") return std::make_unique<KeepTipOnly>();
if (name == "keep-all") return std::make_unique<KeepAll>();
return std::make_unique<GeometricBackoff>(interval);
}
CheckpointSlots checkpoint_slots_auto(const CheckpointPolicy& policy, int64_t max_seqs,
int64_t ctx, int64_t interval, int64_t slot_bytes,
int64_t share_bytes, int64_t room_bytes) {
CheckpointSlots c;
c.per_seq = policy.held(ctx, interval) + 1;
const int64_t seqs = std::max<int64_t>(max_seqs, 1);
c.want = seqs > INT64_MAX / c.per_seq ? INT64_MAX : seqs * c.per_seq;
if (slot_bytes <= 0) return c;
const int64_t share = std::max<int64_t>(share_bytes, 0) / slot_bytes;
const int64_t room = std::max<int64_t>(room_bytes, 0) / slot_bytes;
c.slots = std::min(c.want, std::max(share, std::min(c.want, kCheckpointSlotsFloor)));
if (c.slots < c.want) c.bound = CheckpointSlots::Bound::Share;
if (room < c.slots) {
c.slots = room;
c.bound = CheckpointSlots::Bound::Room;
}
return c;
}
/* ------------------------------------------------------------------ configure */
int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_interval) {
@@ -93,11 +145,8 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
groups_.clear();
map_.clear(); lru_.clear();
ck_by_prefix_.clear(); ck_by_session_.clear();
/* config_parse rejects unknown names, so the else branch is "geometric-backoff".
* set_policy() may override this afterwards. */
if (cfg.checkpoint_policy == "tip-only") policy_ = std::make_unique<KeepTipOnly>();
else if (cfg.checkpoint_policy == "keep-all") policy_ = std::make_unique<KeepAll>();
else policy_ = std::make_unique<GeometricBackoff>(checkpoint_interval);
/* set_policy() may override this afterwards. */
policy_ = make_checkpoint_policy(cfg.checkpoint_policy, checkpoint_interval);
report_.clear();
if (!kv) return RAD_E_INVAL;
@@ -202,7 +251,7 @@ void PrefixCache::touch(const BlockHash& h, uint64_t now_ns) const {
CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
std::vector<std::vector<int32_t>>* blocks_out,
const HitCap* cap) const {
const HitCap* cap, uint64_t session) const {
CacheHit hit;
if (blocks_out) { blocks_out->assign(groups_.size(), {}); }
if (!enabled_ || tokens.empty()) return hit;
@@ -296,6 +345,7 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
best->second.used_ns = now;
handed_.push_back(best->first);
++stats_.ckpt_hits;
if (session != 0) take_over(session, hs, hit.n_attn_tokens);
return hit;
}
@@ -384,13 +434,16 @@ int PrefixCache::insert(uint64_t session,
tiers_->note_session(session, hs, n_tokens, now, label);
}
/* A conversation's snapshots belong to its latest turn. Sessions are keyed by request id, so
* without this each earlier turn's deepest snapshot would stay a protected tip. Every snapshot
* on the chain just published moves under this id, so the policy sees one session, one tip. */
take_over(session, hs, n_full * block_size_);
return RAD_OK;
}
void PrefixCache::take_over(uint64_t session, const std::vector<BlockHash>& hs,
int64_t upto) const {
for (auto& kvp : ck_by_prefix_) {
Ckpt& c = kvp.second;
if (c.session == session || c.pos <= 0 || c.pos > n_full * block_size_ ||
c.pos % block_size_ != 0 || hs[(size_t)(c.pos / block_size_ - 1)] != kvp.first)
if (c.session == session || c.pos <= 0 || c.pos > upto || c.pos % block_size_ != 0 ||
hs[(size_t)(c.pos / block_size_ - 1)] != kvp.first)
continue;
auto old = ck_by_session_.find(c.session);
if (old != ck_by_session_.end()) {
@@ -401,7 +454,6 @@ int PrefixCache::insert(uint64_t session,
c.session = session;
ck_by_session_[session].push_back(kvp.first);
}
return RAD_OK;
}
+43 -3
View File
@@ -110,6 +110,11 @@ public:
* retain. The tip, positions.back(), must always be kept: an appending transcript resumes
* from it. */
virtual void select(const std::vector<int64_t>& positions, std::vector<int64_t>* keep) const = 0;
/* The most snapshots the policy keeps for one session that grows to `ctx` tokens with a
* checkpoint on every `interval`, retention applied after each: the session's standing share
* of the store. The base applies select() to its own output one checkpoint at a time, which
* is cheap only for a policy that keeps few. */
virtual int64_t held(int64_t ctx, int64_t interval) const;
};
/* Keep the tip and, at every scale S = interval x 2^k, the shallowest checkpoint in the tip's
@@ -134,13 +139,40 @@ class KeepTipOnly final : public CheckpointPolicy {
public:
const char* name() const override { return "tip-only"; }
void select(const std::vector<int64_t>& positions, std::vector<int64_t>* keep) const override;
int64_t held(int64_t, int64_t) const override { return 1; }
};
class KeepAll final : public CheckpointPolicy {
public:
const char* name() const override { return "keep-all"; }
void select(const std::vector<int64_t>& positions, std::vector<int64_t>* keep) const override;
int64_t held(int64_t ctx, int64_t interval) const override;
};
/* The policy --checkpoint-policy names, at the resolved checkpoint interval. config_parse admits
* only the three names, so any other is geometric backoff. */
std::unique_ptr<CheckpointPolicy> make_checkpoint_policy(const std::string& name, int64_t interval);
/* ------------------------------------------------------------------ the store's size */
/* --checkpoint-slots auto. Every sequence --max-num-seqs admits gets its session's standing share
* at --max-model-len (CheckpointPolicy::held) plus one slot for the checkpoint its running turn
* writes while the previous turn's snapshots are still held. The store is pinned for the life of
* the process, so the count is bounded by two byte budgets the engine measures: `share`, the part
* of host memory the store may take, and `room`, what the host can pin after everything still to
* be allocated. Under the share it never drops below kCheckpointSlotsFloor (or `want`, if fewer);
* the room is a hard bound. */
constexpr int64_t kCheckpointSlotsFloor = 8;
struct CheckpointSlots {
int64_t per_seq = 0; /* snapshots a sequence is given */
int64_t want = 0; /* --max-num-seqs x per_seq */
int64_t slots = 0; /* the store's size */
enum class Bound { Want, Share, Room } bound = Bound::Want;
};
CheckpointSlots checkpoint_slots_auto(const CheckpointPolicy& policy, int64_t max_seqs,
int64_t ctx, int64_t interval, int64_t slot_bytes,
int64_t share_bytes, int64_t room_bytes);
/* ------------------------------------------------------------------ the cache */
class PrefixCache {
public:
@@ -168,11 +200,13 @@ public:
* cached_groups() order, ready for KVManager::adopt().
*
* Never returns the whole prompt: one token must remain to compute a logit from, so a full
* hit is backed off by one block. `cap`, when given, ends the hit early (HitCap). */
* hit is backed off by one block. `cap`, when given, ends the hit early (HitCap). `session`,
* when not 0, is the request being admitted: it takes over the snapshots on the chain it hit
* (take_over). */
CacheHit lookup(const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
std::vector<std::vector<int32_t>>* blocks_out = nullptr,
const HitCap* cap = nullptr) const;
const HitCap* cap = nullptr, uint64_t session = 0) const;
/* Publish the whole blocks a sequence just filled. `blocks[i]` is the block table of
* cached_groups()[i]. Takes a KV reference on every newly indexed block. */
@@ -347,6 +381,12 @@ private:
/* Retire one snapshot: free its slot and tell the tiers. The session index is left to the
* caller. */
void retire_ckpt(std::unordered_map<BlockHash, Ckpt, BlockHashHash>::iterator it);
/* Move every snapshot on the chain `hs` at or below `upto` tokens under `session`. A
* conversation's snapshots belong to its latest turn: sessions are request ids, so otherwise
* each earlier turn's deepest snapshot would stay a protected tip, and a running turn would be
* a second session beside its conversation, two ladders where retention should keep one.
* The admission's lookup and the publish both call it. */
void take_over(uint64_t session, const std::vector<BlockHash>& hs, int64_t upto) const;
/* Take one key out of a session's index entry, and the entry when it empties. */
void unindex_ckpt(uint64_t session, const BlockHash& key);
/* For the debug lines: whether `c` is its session's deepest snapshot, and seconds since a
@@ -375,7 +415,7 @@ private:
std::unordered_map<BlockHash, int32_t, BlockHashHash> held_;
bool released_ = false;
mutable std::unordered_map<BlockHash, Ckpt, BlockHashHash> ck_by_prefix_;
std::unordered_map<uint64_t, std::vector<BlockHash>> ck_by_session_;
mutable std::unordered_map<uint64_t, std::vector<BlockHash>> ck_by_session_;
/* Snapshots lookup handed out since begin_step; kept in their slots until the next one. */
mutable std::vector<BlockHash> handed_;
bool handed(const BlockHash& h) const {
+405
View File
@@ -0,0 +1,405 @@
/* mp4.cpp -- Mp4Writer (mp4.h) over libavformat, libavcodec and libswscale. */
#include "mm/mp4.h"
#include <algorithm>
#include <cstring>
#include <mutex>
#ifdef RAD_HAVE_FFMPEG
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/channel_layout.h>
#include <libavutil/opt.h>
#include <libswscale/swscale.h>
}
#endif
namespace rad {
namespace mm {
#ifndef RAD_HAVE_FFMPEG
struct Mp4Writer::Impl {};
Mp4Writer::Mp4Writer() = default;
Mp4Writer::~Mp4Writer() = default;
static int no_ffmpeg(std::string* why) {
if (why) *why = "this build has no libavcodec, so it writes no video";
return RAD_E_UNSUPPORTED;
}
int Mp4Writer::open(int32_t, int32_t, int64_t, int64_t, int64_t, int64_t, std::string* why) {
return no_ffmpeg(why);
}
int Mp4Writer::add_frames(const uint8_t*, int32_t, std::string* why) { return no_ffmpeg(why); }
int Mp4Writer::add_audio(const float*, int64_t, std::string* why) { return no_ffmpeg(why); }
int Mp4Writer::finish(std::string*, std::string* why) { return no_ffmpeg(why); }
#else
namespace {
/* The file in memory. The MP4 muxer seeks back to patch sizes and, to put the moov atom first,
* reopens its output for reading and moves the media data up (FFmpeg's shift_data): the reader is
* a second handle on the same bytes with a position of its own. */
struct MemFile {
std::string data;
int64_t pos = 0;
};
struct MemReader {
MemFile* f = nullptr;
int64_t pos = 0;
};
int mem_write(void* op, const uint8_t* buf, int n) {
MemFile* f = static_cast<MemFile*>(op);
const int64_t end = f->pos + n;
if (end > (int64_t)f->data.size()) f->data.resize((size_t)end);
std::memcpy(&f->data[(size_t)f->pos], buf, (size_t)n);
f->pos = end;
return n;
}
int64_t mem_seek(void* op, int64_t off, int whence) {
MemFile* f = static_cast<MemFile*>(op);
const int64_t size = (int64_t)f->data.size();
switch (whence & ~AVSEEK_FORCE) {
case AVSEEK_SIZE: return size;
case SEEK_SET: f->pos = off; break;
case SEEK_CUR: f->pos += off; break;
case SEEK_END: f->pos = size + off; break;
default: return AVERROR(EINVAL);
}
return f->pos < 0 ? AVERROR(EINVAL) : f->pos;
}
int mem_read(void* op, uint8_t* buf, int n) {
MemReader* r = static_cast<MemReader*>(op);
const int64_t size = (int64_t)r->f->data.size();
if (r->pos >= size) return AVERROR_EOF;
const int k = (int)std::min<int64_t>(n, size - r->pos);
std::memcpy(buf, r->f->data.data() + r->pos, (size_t)k);
r->pos += k;
return k;
}
int64_t mem_read_seek(void* op, int64_t off, int whence) {
MemReader* r = static_cast<MemReader*>(op);
const int64_t size = (int64_t)r->f->data.size();
switch (whence & ~AVSEEK_FORCE) {
case AVSEEK_SIZE: return size;
case SEEK_SET: r->pos = off; break;
case SEEK_CUR: r->pos += off; break;
case SEEK_END: r->pos = size + off; break;
default: return AVERROR(EINVAL);
}
return r->pos < 0 ? AVERROR(EINVAL) : r->pos;
}
constexpr int kIoBuf = 1 << 16;
std::string av_why(const char* what, int e) {
char b[AV_ERROR_MAX_STRING_SIZE] = {};
av_strerror(e, b, sizeof b);
return std::string(what) + ": " + b;
}
} /* namespace */
struct Mp4Writer::Impl {
MemFile file;
AVFormatContext* oc = nullptr;
AVCodecContext* vc = nullptr;
AVCodecContext* ac = nullptr;
AVStream* vs = nullptr;
AVStream* as = nullptr;
SwsContext* sws = nullptr;
AVFrame* vf = nullptr;
AVFrame* af = nullptr;
AVPacket* pkt = nullptr;
int32_t w = 0, h = 0;
int64_t channels = 0;
int64_t next_frame = 0;
std::vector<float> audio; /* interleaved, encoded at finish */
bool header = false;
~Impl() {
if (oc) {
if (oc->pb) {
av_freep(&oc->pb->buffer);
avio_context_free(&oc->pb);
}
avformat_free_context(oc);
}
avcodec_free_context(&vc);
avcodec_free_context(&ac);
sws_freeContext(sws);
av_frame_free(&vf);
av_frame_free(&af);
av_packet_free(&pkt);
}
/* Every packet `c` has ready, onto stream `st`. */
int drain(AVCodecContext* c, AVStream* st, std::string* why) {
for (;;) {
const int e = avcodec_receive_packet(c, pkt);
if (e == AVERROR(EAGAIN) || e == AVERROR_EOF) return RAD_OK;
if (e < 0) {
if (why) *why = av_why("encoding", e);
return RAD_E_INVAL;
}
av_packet_rescale_ts(pkt, c->time_base, st->time_base);
pkt->stream_index = st->index;
const int w2 = av_interleaved_write_frame(oc, pkt);
if (w2 < 0) {
if (why) *why = av_why("writing the file", w2);
return RAD_E_INVAL;
}
}
}
};
/* The reader shift_data opens on the output's own URL; any other URL is refused. */
static int open_reader(AVFormatContext* s, AVIOContext** pb, const char*, int flags, AVDictionary**) {
if (!(flags & AVIO_FLAG_READ) || (flags & AVIO_FLAG_WRITE)) return AVERROR(EINVAL);
MemFile* f = static_cast<MemFile*>(s->opaque);
MemReader* r = new MemReader{ f, 0 };
uint8_t* buf = static_cast<uint8_t*>(av_malloc(kIoBuf));
*pb = buf ? avio_alloc_context(buf, kIoBuf, 0, r, mem_read, nullptr, mem_read_seek) : nullptr;
if (!*pb) {
av_free(buf);
delete r;
return AVERROR(ENOMEM);
}
return 0;
}
static int close_reader(AVFormatContext*, AVIOContext* pb) {
if (!pb) return 0;
delete static_cast<MemReader*>(pb->opaque);
av_freep(&pb->buffer);
avio_context_free(&pb);
return 0;
}
Mp4Writer::Mp4Writer() : p_(std::make_unique<Impl>()) {}
Mp4Writer::~Mp4Writer() = default;
int Mp4Writer::open(int32_t width, int32_t height, int64_t fps_num, int64_t fps_den,
int64_t sample_rate, int64_t channels, std::string* why) {
Impl& p = *p_;
/* The encoders print their settings and a file's statistics at FFmpeg's info level, on stderr,
* for every video; a failure comes back through the calls here, so only errors are let
* through. */
static std::once_flag quiet;
std::call_once(quiet, [] { if (av_log_get_level() > AV_LOG_ERROR) av_log_set_level(AV_LOG_ERROR); });
if (width <= 0 || height <= 0 || (width & 1) || (height & 1) || fps_num <= 0 || fps_den <= 0) {
if (why) *why = "the frames must be a positive even size at a positive rate";
return RAD_E_INVAL;
}
p.w = width;
p.h = height;
p.channels = channels;
if (avformat_alloc_output_context2(&p.oc, nullptr, "mp4", nullptr) < 0 || !p.oc) {
if (why) *why = "this libavformat has no MP4 muxer";
return RAD_E_UNSUPPORTED;
}
p.oc->url = av_strdup("radiance.mp4");
p.oc->opaque = &p.file;
p.oc->io_open = open_reader;
p.oc->io_close2 = close_reader;
uint8_t* buf = static_cast<uint8_t*>(av_malloc(kIoBuf));
p.oc->pb = buf ? avio_alloc_context(buf, kIoBuf, 1, &p.file, nullptr, mem_write, mem_seek)
: nullptr;
p.pkt = av_packet_alloc();
if (!p.oc->url || !p.oc->pb || !p.pkt) {
if (!p.oc->pb) av_free(buf);
if (why) *why = "out of memory";
return RAD_E_NOMEM;
}
/* ---- video */
const AVCodec* vcodec = nullptr;
for (const char* name : { "libx264", "libopenh264" })
if ((vcodec = avcodec_find_encoder_by_name(name))) break;
if (!vcodec) vcodec = avcodec_find_encoder(AV_CODEC_ID_H264);
if (!vcodec) {
if (why) *why = "this libavcodec has no H.264 encoder";
return RAD_E_UNSUPPORTED;
}
venc_name_ = vcodec->name;
p.vs = avformat_new_stream(p.oc, nullptr);
p.vc = avcodec_alloc_context3(vcodec);
if (!p.vs || !p.vc) {
if (why) *why = "out of memory";
return RAD_E_NOMEM;
}
p.vc->width = width;
p.vc->height = height;
p.vc->pix_fmt = AV_PIX_FMT_YUV420P;
p.vc->time_base = AVRational{ (int)fps_den, (int)fps_num };
p.vc->framerate = AVRational{ (int)fps_num, (int)fps_den };
p.vc->gop_size = (int)std::max<int64_t>(1, 2 * fps_num / fps_den);
p.vc->colorspace = AVCOL_SPC_BT709;
p.vc->color_primaries = AVCOL_PRI_BT709;
p.vc->color_trc = AVCOL_TRC_BT709;
p.vc->color_range = AVCOL_RANGE_MPEG;
if (venc_name_ == "libx264") {
/* Constant quality, visually lossless for generated footage. */
av_opt_set(p.vc->priv_data, "preset", "medium", 0);
av_opt_set(p.vc->priv_data, "crf", "18", 0);
} else {
/* An encoder without a quality mode: 0.2 bits a pixel, about 5 Mbit/s at 1344x768 x 24. */
p.vc->bit_rate = (int64_t)((double)width * height * fps_num / fps_den * 0.2);
}
if (p.oc->oformat->flags & AVFMT_GLOBALHEADER) p.vc->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
int e = avcodec_open2(p.vc, vcodec, nullptr);
if (e < 0) {
if (why) *why = av_why(("opening the " + venc_name_ + " encoder").c_str(), e);
return RAD_E_INVAL;
}
avcodec_parameters_from_context(p.vs->codecpar, p.vc);
p.vs->time_base = p.vc->time_base;
p.vs->avg_frame_rate = p.vc->framerate;
p.vf = av_frame_alloc();
if (!p.vf) return RAD_E_NOMEM;
p.vf->format = AV_PIX_FMT_YUV420P;
p.vf->width = width;
p.vf->height = height;
if (av_frame_get_buffer(p.vf, 0) < 0) return RAD_E_NOMEM;
p.sws = sws_getContext(width, height, AV_PIX_FMT_RGB24, width, height, AV_PIX_FMT_YUV420P,
SWS_BICUBIC | SWS_ACCURATE_RND, nullptr, nullptr, nullptr);
if (!p.sws) {
if (why) *why = "libswscale cannot convert RGB to yuv420p";
return RAD_E_UNSUPPORTED;
}
/* Full-range RGB to limited-range BT.709, what the stream's colour tags say. */
sws_setColorspaceDetails(p.sws, sws_getCoefficients(SWS_CS_DEFAULT), 1,
sws_getCoefficients(SWS_CS_ITU709), 0, 0, 1 << 16, 1 << 16);
/* ---- audio */
if (channels > 0) {
const AVCodec* acodec = avcodec_find_encoder(AV_CODEC_ID_AAC);
if (!acodec) {
if (why) *why = "this libavcodec has no AAC encoder";
return RAD_E_UNSUPPORTED;
}
p.as = avformat_new_stream(p.oc, nullptr);
p.ac = avcodec_alloc_context3(acodec);
if (!p.as || !p.ac) return RAD_E_NOMEM;
p.ac->sample_fmt = AV_SAMPLE_FMT_FLTP;
p.ac->sample_rate = (int)sample_rate;
av_channel_layout_default(&p.ac->ch_layout, (int)channels);
p.ac->bit_rate = 96000 * channels;
p.ac->time_base = AVRational{ 1, (int)sample_rate };
if (p.oc->oformat->flags & AVFMT_GLOBALHEADER) p.ac->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
e = avcodec_open2(p.ac, acodec, nullptr);
if (e < 0) {
if (why) *why = av_why("opening the AAC encoder", e);
return RAD_E_INVAL;
}
avcodec_parameters_from_context(p.as->codecpar, p.ac);
p.as->time_base = p.ac->time_base;
p.af = av_frame_alloc();
if (!p.af) return RAD_E_NOMEM;
p.af->format = AV_SAMPLE_FMT_FLTP;
p.af->sample_rate = p.ac->sample_rate;
av_channel_layout_copy(&p.af->ch_layout, &p.ac->ch_layout);
p.af->nb_samples = p.ac->frame_size > 0 ? p.ac->frame_size : 1024;
if (av_frame_get_buffer(p.af, 0) < 0) return RAD_E_NOMEM;
}
AVDictionary* opts = nullptr;
av_dict_set(&opts, "movflags", "+faststart", 0);
e = avformat_write_header(p.oc, &opts);
av_dict_free(&opts);
if (e < 0) {
if (why) *why = av_why("writing the MP4 header", e);
return RAD_E_INVAL;
}
p.header = true;
return RAD_OK;
}
int Mp4Writer::add_frames(const uint8_t* rgb, int32_t n, std::string* why) {
Impl& p = *p_;
if (!p.header) {
if (why) *why = "the writer is not open";
return RAD_E_STATE;
}
const int64_t frame_bytes = (int64_t)p.w * p.h * 3;
for (int32_t i = 0; i < n; ++i) {
if (av_frame_make_writable(p.vf) < 0) return RAD_E_NOMEM;
const uint8_t* src[1] = { rgb + i * frame_bytes };
const int stride[1] = { p.w * 3 };
sws_scale(p.sws, src, stride, 0, p.h, p.vf->data, p.vf->linesize);
p.vf->pts = p.next_frame++;
const int e = avcodec_send_frame(p.vc, p.vf);
if (e < 0) {
if (why) *why = av_why("encoding a frame", e);
return RAD_E_INVAL;
}
RAD_TRY(p.drain(p.vc, p.vs, why));
}
return RAD_OK;
}
int Mp4Writer::add_audio(const float* samples, int64_t n_frames, std::string* why) {
Impl& p = *p_;
if (!p.header || !p.ac) {
if (why) *why = "the writer has no soundtrack";
return RAD_E_STATE;
}
p.audio.insert(p.audio.end(), samples, samples + n_frames * p.channels);
return RAD_OK;
}
int Mp4Writer::finish(std::string* out, std::string* why) {
Impl& p = *p_;
if (!p.header) {
if (why) *why = "the writer is not open";
return RAD_E_STATE;
}
if (p.ac) {
/* The soundtrack in the encoder's frames, deinterleaved; the last frame padded with
* silence, which the encoder's own length bookkeeping trims. */
const int64_t total = (int64_t)p.audio.size() / p.channels;
const int fs = p.af->nb_samples;
for (int64_t at = 0; at < total; at += fs) {
if (av_frame_make_writable(p.af) < 0) return RAD_E_NOMEM;
const int64_t k = std::min<int64_t>(fs, total - at);
p.af->nb_samples = (int)k;
for (int64_t c = 0; c < p.channels; ++c) {
float* d = reinterpret_cast<float*>(p.af->data[c]);
for (int64_t i = 0; i < k; ++i)
d[i] = p.audio[(size_t)((at + i) * p.channels + c)];
}
p.af->pts = at;
const int e = avcodec_send_frame(p.ac, p.af);
if (e < 0) {
if (why) *why = av_why("encoding the soundtrack", e);
return RAD_E_INVAL;
}
RAD_TRY(p.drain(p.ac, p.as, why));
p.af->nb_samples = fs;
}
avcodec_send_frame(p.ac, nullptr);
RAD_TRY(p.drain(p.ac, p.as, why));
}
avcodec_send_frame(p.vc, nullptr);
RAD_TRY(p.drain(p.vc, p.vs, why));
const int e = av_write_trailer(p.oc);
if (e < 0) {
if (why) *why = av_why("finishing the MP4 file", e);
return RAD_E_INVAL;
}
avio_flush(p.oc->pb);
*out = std::move(p.file.data);
p.file.data.clear();
p.header = false;
return RAD_OK;
}
#endif /* RAD_HAVE_FFMPEG */
} /* namespace mm */
} /* namespace rad */
+52
View File
@@ -0,0 +1,52 @@
/* mp4.h -- a video and its soundtrack written as an MP4 file in memory: H.264 video in yuv420p
* (BT.709, limited range) and AAC audio, the moov atom at the front so a player can start before
* the whole file has arrived.
*
* The frames arrive in order, in any number of calls; the soundtrack may come before, between or
* after them, whole or in pieces. Nothing is written until finish(), which encodes the soundtrack
* and interleaves it with the video: a video is at most tens of seconds, and its frames are
* encoded as they come so the RGB is never all held at once.
*
* The H.264 encoder is the best the linked libavcodec has: libx264 (constant quality), else
* libopenh264, else whatever encoder it registers for H.264. Without libavcodec every call
* returns RAD_E_UNSUPPORTED.
*/
#pragma once
#include "rad_core.h"
#include <memory>
#include <string>
#include <vector>
namespace rad {
namespace mm {
class Mp4Writer {
public:
Mp4Writer();
~Mp4Writer();
Mp4Writer(const Mp4Writer&) = delete;
Mp4Writer& operator=(const Mp4Writer&) = delete;
/* A video of `width` x `height` (even) at fps_num / fps_den frames a second, with a soundtrack
* of `channels` channels at `sample_rate` (0 channels: none). */
int open(int32_t width, int32_t height, int64_t fps_num, int64_t fps_den, int64_t sample_rate,
int64_t channels, std::string* why);
/* `n` frames, each [height, width, 3] u8 RGB, after those already added. */
int add_frames(const uint8_t* rgb, int32_t n, std::string* why);
/* Samples interleaved over the channels, in [-1, 1], after those already added. */
int add_audio(const float* samples, int64_t n_frames, std::string* why);
/* Flushes both encoders and writes the file into `out`. */
int finish(std::string* out, std::string* why);
/* The H.264 encoder in use, for the log. */
const std::string& video_encoder() const { return venc_name_; }
private:
struct Impl;
std::unique_ptr<Impl> p_;
std::string venc_name_;
};
} /* namespace mm */
} /* namespace rad */
+6
View File
@@ -219,6 +219,12 @@ int Registry::commit_(Staged& s, int order) {
/* Optional: absent means the model serves no speech route. */
p.arch_audio_format = dl_fn<const RadAudioFormat* (*)(const RadModelMeta*)>(
s.handle, "rad_arch_audio_format");
/* Optional: absent means an audio generator's prompt takes a request's texts as given. */
p.arch_text_prepare = dl_fn<int64_t (*)(int, const char*, char*, int64_t)>(
s.handle, "rad_arch_text_prepare");
/* A video generator's rotary positions; the driver refuses to start without it. */
p.arch_video_positions = dl_fn<int64_t (*)(int, const RadVideoGeom*, float*, int64_t)>(
s.handle, "rad_arch_video_positions");
/* The (architecture id, quantisation) pair selects the plugin, so no two plugins may claim
* the same pair (§2.4). Sharing an id at different quantisations is normal (qwen35_bf16
+5
View File
@@ -89,6 +89,11 @@ struct Plugin {
const RadChatFormat* (*arch_chat_format)(const RadModelMeta*) = nullptr;
/* Optional (rad_builder.h); null means the model serves no speech route. */
const RadAudioFormat* (*arch_audio_format)(const RadModelMeta*) = nullptr;
/* Optional (rad_builder.h); null means a request's texts go into the audio generator's
* prompt as given. */
int64_t (*arch_text_prepare)(int, const char*, char*, int64_t) = nullptr;
/* Required of a video generator (rad_builder.h); null for every other plugin. */
int64_t (*arch_video_positions)(int, const RadVideoGeom*, float*, int64_t) = nullptr;
RadPluginCloseFn close = nullptr;
};
+36 -17
View File
@@ -265,15 +265,15 @@ struct OpInfo {
const RadOpSchema* schema = nullptr;
int32_t index = 0; /* position in the declared order */
bool issued = false; /* did the run phase ever issue it */
/* RUNTIME LoRA (core/lora/). `anchor`: an op the CORE appended after the plugin's declare and
* issues inside another op's issue -- its buffers are that op's, so buffer liveness is judged
* at the anchor's position, not at this op's own (which is past every plugin op). -1 for every
* plugin op. `lora_site`: on a targeted gemm, its row in Program::lora_sites; -1 otherwise. */
/* Runtime LoRA (core/lora/). `anchor`: the op a core-appended op is issued inside of; its
* buffers are that op's, so their liveness is judged at the anchor's position rather than this
* op's own (past every plugin op). -1 for a plugin op. `lora_site`: a targeted gemm's row in
* Program::lora_sites, -1 otherwise. */
int32_t anchor = -1;
int32_t lora_site = -1;
/* Declined at declare because runtime LoRA targets its weight (a fused GEMM no delta can follow):
* recorded unresolved on purpose, its handle never handed to the plugin, so it is never issued
* and the reference-kernel gate does not count it. */
/* Declined at declare because runtime LoRA targets its weight (a fused GEMM no delta can
* follow): recorded unresolved and never handed to the plugin, so it is never issued and the
* reference-kernel gate does not count it. */
bool lora_declined = false;
};
@@ -300,9 +300,9 @@ inline int64_t conv_window_entries(const RadKVGroupDecl& d, int64_t n_spec) {
return (d.conv_width > 0 ? d.conv_width - 1 : 0) + (n_spec > 0 ? n_spec : 0);
}
/* ONE TARGETED GEMM OF A RUNTIME-LoRA PROGRAM (core/lora/), as the issue path needs it: the two ops
* the core appended for it, where in the gemm's own operand list its activation and output are,
* and the buffers the appended ops read. Built once at declare; issue reads it and nothing else. */
/* One targeted GEMM of a runtime-LoRA program (core/lora/), as the issue path needs it: the two ops
* the core appended for it, where the gemm's activation and output are in its operand list, and
* the buffers the appended ops read. Built once at declare. */
struct LoraIssueSite {
uint32_t gemm = 0, shrink = 0, expand = 0; /* op handles */
int8_t opd_a = -1, opd_a_scale = -1, opd_y = -1; /* positions in the GEMM's schema */
@@ -312,7 +312,7 @@ struct LoraIssueSite {
int64_t R = 0, K = 0, N = 0;
};
/* One targeted weight's adapter slots: A [S, R, K], B [S, N, R] bf16 and the per-column scale
* [S, N] f32 -- PERSIST buffers, so the arena plan (and with it the KV budget) holds them. */
* [S, N] f32, persistent buffers, so the arena plan (and with it the KV budget) holds them. */
struct LoraPool {
std::string weight;
rad_buf a = 0, b = 0, scale = 0;
@@ -345,7 +345,7 @@ public:
* no logits buffer. */
rad_buf pooled_buf = 0;
/* RUNTIME LoRA (core/lora/), empty unless the engine was started with adapters enabled. */
/* Runtime LoRA (core/lora/), empty unless the engine was started with adapters enabled. */
std::vector<LoraIssueSite> lora_sites;
std::vector<LoraPool> lora_pools;
std::vector<LoraScratch> lora_t;
@@ -380,6 +380,24 @@ public:
std::vector<double> sigmas;
} gen_str;
bool is_generator() const { return generator.layout != 0; }
/* The declared audio generator (rad_declare_audio_generator); `max_lanes` 0 when none. Its
* strings point at `agen_str`, as the image generator's do at `gen_str`. */
RadAudioGenDecl audio_gen{};
struct AudioGenStrings {
std::string name, tmpl, tmpl_plain, neg_tmpl; /* "" for an absent template */
} agen_str;
bool is_audio_generator() const { return audio_gen.max_lanes != 0; }
/* The declared video generator (rad_declare_video_generator); `max_lanes` 0 when none. */
RadVideoGenDecl video_gen{};
struct VideoGenStrings {
std::string name, tmpl;
std::vector<double> rungs; /* RadVideoGenDecl::rungs; the declaration's pointer is null */
} vgen_str;
bool is_video_generator() const { return video_gen.max_lanes != 0; }
/* Driven by passes, not token steps: any generator. */
bool is_pass_driven() const {
return is_generator() || is_audio_generator() || is_video_generator();
}
/* Two arenas, because a host-site activation cannot index device memory. The buffer plan
* colours each domain separately (transients share storage only within a domain), so each is
@@ -578,9 +596,9 @@ struct TokenScores {
struct Request {
uint64_t id = 0;
/* THE RUNTIME LoRA ADAPTER this request is served with (core/lora/): its slot in the adapter
* pools, -1 for the base model, and the uid of the load that slot held when the request was
* admitted -- the prefix cache keys on the uid, so a reload under the same name starts cold. */
/* The runtime LoRA adapter this request runs with (core/lora/): its slot in the adapter pools,
* -1 for the base model, and the uid of the load that slot held at admission. The prefix cache
* keys on the uid, so a reload under the same name starts cold. */
int32_t lora_slot = -1;
uint64_t lora_uid = 0;
std::vector<int32_t> prompt;
@@ -769,8 +787,9 @@ struct Config {
/* Cap on linear-state (or sliding-window) snapshots held at once, for the whole server. The
* slots are pinned host memory, all allocated at startup and never on the card (spec §7.3).
* A slot is a sizeable fraction of a gigabyte on a linear-attention model, so raising the cap
* trades host RAM for retained checkpoints. */
int64_t checkpoint_slots = 8;
* trades host RAM for retained checkpoints. -1 is `auto`, resolved by the engine when the
* store is opened (checkpoint_slots_auto in core/mem/prefix.h). */
int64_t checkpoint_slots = -1;
bool prefix_cache = true;
/* geometric-backoff | tip-only | keep-all. §19.1 records the default as unmeasured;
* core/mem/prefix.h ships the two extremes so they can be compared. */
+7 -6
View File
@@ -899,8 +899,9 @@ int Ctx::lane_join(int from, int to) {
/* The key below reads every RadBatch field a pass's shape or arguments can depend on, by hand. A
* field added to RadBatch changes its size: decide whether the key must read it, then update the
* size here. */
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 320,
* size here. `agen_b` and `vgen_b` are set only on generator passes, which are never recorded
* (below). */
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 336,
"RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on");
static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 72,
"RadKVGroupBatch changed: check that Ctx::pass_key reads every new field");
@@ -909,7 +910,8 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
/* Not recordable: encoder passes are shaped by their media, and passes carrying encoder rows
* issue the scatter only when they have some. */
if (b->enc || b->n_mm_rows > 0) return 0;
/* A generator pass is shaped by what RadBatch::gen_b carries, which no key below reads. */
/* A generator pass is shaped by what RadBatch::gen_b, agen_b or vgen_b carries, which no key
* below reads. */
if (b->gen) return 0;
uint64_t h = 0x9e3779b97f4a7c15ull;
auto mix = [&](uint64_t v) {
@@ -927,9 +929,8 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
ptr(b->token_ids); ptr(b->positions); ptr(b->cu_seqlens); ptr(b->seq_ids);
ptr(b->out_ids); ptr(b->q_lens); ptr(b->ctx_lens); ptr(b->num_accepted);
ptr(b->spec_parent); ptr(b->checkpoint_tok); ptr(b->checkpoint_slot); ptr(b->draft_out_ids);
/* The adapter ops' slot pointer. One address per rank for the engine's life, null without
* adapters; the slots themselves are read on the card, and the ops are issued whether or not a
* row has an adapter, so what a recorded pass launches never depends on their values. */
/* Null on a step with no adapter row, which then issues no adapter op (Ctx::issue_lora): the
* two are different passes. The slots themselves are read on the card. */
ptr(b->lora_slot);
for (int g = 0; g < b->n_kv_groups; ++g) {
const RadKVGroupBatch& k = b->kv[g];
+1 -1
View File
@@ -86,7 +86,7 @@ struct OpPlan {
/* The conventional all_reduce, whose `n` is the message's element count, so its link bytes
* can be counted (ar_bytes) apart from the expert mover's. */
bool billed = false;
/* RUNTIME LoRA: this gemm's row in Program::lora_sites, -1 for every op that is not one. */
/* Runtime LoRA: this gemm's row in Program::lora_sites, -1 for every op that is not one. */
int32_t lora_site = -1;
};
+32 -27
View File
@@ -415,27 +415,37 @@ int Ctx::issue(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
return rc;
}
/* RUNTIME LoRA: the two ops the core appended for a targeted gemm, issued right behind it on the
/* Runtime LoRA: the two ops the core appended for a targeted gemm, issued right behind it on the
* same stream, over the same rows, through the ordinary issue path (bands, tape, hazards).
*
* t = A[slot] . x lora_shrink, x = the gemm's own activation operand(s)
* y += scale . B[slot] . t lora_expand, y = the gemm's own output operand
*
* Here and only here: a row-parallel gemm's y is this rank's PARTIAL sum and the plugin reduces it
* after this returns, so the delta rides the same reduction (B.A.x is linear in x's shards). Only
* the trunk pass: a draft pass runs the drafter's weights, an encoder pass the tower's. A base row
* (slot -1) is not touched by either kernel, so a step with no adapter rows computes exactly what
* the same step without LoRA does. */
* A row-parallel gemm's y is this rank's partial sum and the plugin reduces it after this returns,
* so the delta rides the same reduction (B.A.x is linear in x's shards). Nothing is issued on a
* step with no adapter row (RadBatch::lora_slot null), which is then the pass an engine without
* adapters runs, nor on a draft pass, whose proposals the trunk verifies. An encoder or generator
* pass never reaches a site: such a weight is outside the targets' scope rule (core/lora/lora.h),
* so reaching one here is refused rather than run without its delta. */
int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
if (!batch_ || batch_->draft_pass != 0 || batch_->enc != 0 || batch_->gen != 0) return RAD_OK;
if (!batch_) return RAD_OK;
if (batch_->enc != 0 || batch_->gen != 0)
return abort_step_msg(h, RAD_E_UNSUPPORTED,
"a LoRA-targeted gemm was issued by an encoder or generator pass, "
"which runtime LoRA does not reach; leave its module out of "
"--lora-target-modules");
if (!batch_->lora_slot || batch_->draft_pass != 0) return RAD_OK;
const OpPlan& p = plans_[h];
const LoraIssueSite& s = program_->lora_sites[(size_t)p.lora_site];
if (n == RAD_N_BATCH) n = batch_->n_tok;
if (n <= 0) return RAD_OK;
if (op_domain_[h].load(std::memory_order_relaxed) != RAD_DOMAIN_DEVICE)
/* The adapter ops run in the gemm's domain and read the pools, which are device buffers: on a
* card that is the device domain, and on the host backend every domain is host memory. */
const int dom = (int)op_domain_[h].load(std::memory_order_relaxed);
if (dom != RAD_DOMAIN_DEVICE && !device_is_host())
return abort_step_msg(h, RAD_E_UNSUPPORTED,
"a LoRA-targeted gemm was placed on the host; its adapter delta has "
"no host path, so the step would compute the base model's output");
"a LoRA-targeted gemm was placed on the host, and the adapter pools "
"are on the card");
if (s.opd_a < 0 || s.opd_a >= n_opd || s.opd_y < 0 || s.opd_y >= n_opd)
return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm was issued with fewer operands "
"than its schema names");
@@ -445,9 +455,9 @@ int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
(size_t)ya.handle >= program_->buffers.size() || (size_t)xa.handle >= program_->buffers.size())
return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: the gemm's activation or output is "
"not a declared buffer");
/* THE ROWS THE GEMM WROTE ARE ROWS OF THE STEP'S TOKENS starting at r0, so the slot array is
* read from r0 too. A row slice offsets by whole rows of the buffer's declared width; a column
* slice offsets by less than one row. Anything else is a view this code cannot place. */
/* The rows the gemm wrote are the step's token rows from r0 on, so the slot array is read from
* r0 too. A row slice offsets by whole rows of the buffer's declared width and a column slice
* by less than one row; any other view cannot be placed. */
const RadBufDecl& yd = program_->buffers[ya.handle].decl;
const RadBufDecl& xd = program_->buffers[xa.handle].decl;
if (yd.dtype != s.y_dtype || xd.dtype != s.a_dtype)
@@ -461,30 +471,25 @@ int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's output view starts inside a "
"row, so its token rows cannot be told");
const int64_t r0 = ya.offset / yw;
/* ...and the activation must be the SAME rows: shrink reads x's row m and expand writes y's
* row m with one slot, so a GEMM whose two views start at different tokens cannot be followed. */
/* The activation must start at the same row: shrink reads x's row m and expand writes y's row
* m with one slot. */
{
const int64_t xw = xd.rank >= 2 ? xd.shape[xd.rank - 1] : 0;
if (xw <= 0 || (xa.cols == 0 && xa.offset % xw != 0) || xa.offset / xw != r0)
return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's activation and output "
"views do not start at the same token row");
}
if (op_domain_[s.shrink].load(std::memory_order_relaxed) != RAD_DOMAIN_DEVICE ||
op_domain_[s.expand].load(std::memory_order_relaxed) != RAD_DOMAIN_DEVICE)
return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: the adapter ops were placed off "
"the device the gemm runs on");
if ((int)op_domain_[s.shrink].load(std::memory_order_relaxed) != dom ||
(int)op_domain_[s.expand].load(std::memory_order_relaxed) != dom)
return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: the adapter ops were placed in "
"another domain than the gemm they follow");
if (r0 < 0 || r0 + n > batch_->n_tok)
return abort_step_msg(h, RAD_E_STATE,
fmt("LoRA site: the gemm wrote rows [%lld, %lld) of a %lld-token step",
(long long)r0, (long long)(r0 + n), (long long)batch_->n_tok));
/* Each row's adapter is the step batch's (RadBatch::lora_slot), which the builder fills from
* every request's slot. It sits at one address per rank for the engine's life and is
* rewritten in stream order before each step's kernels, so the pointer this launch records is
* the one a replay of it reads. */
if (!batch_->lora_slot)
return abort_step_msg(h, RAD_E_STATE, "LoRA site: the step batch carries no per-row adapter "
"slot (RadBatch::lora_slot), so the engine was started "
"without adapters and should have declared no site");
/* Each row's adapter is the step batch's (RadBatch::lora_slot), rewritten in stream order
* before each step's kernels, so the pointer this launch records is the one a replay of it
* reads. */
const LoraPool& pool = program_->lora_pools[(size_t)s.pool];
const rad_buf t = program_->lora_t[(size_t)s.t].lane[lane_ ? 1 : 0];
RadOperand slot = RAD_P_T(batch_->lora_slot + r0, RAD_I32);
+7 -3
View File
@@ -124,8 +124,8 @@ void BatchBuilder::carve(Set& s, char* h) {
* moves a rotary position off the token index. */
pair(&s.h_rope, &s.d_rope, mm_on_ ? 3 * T : 0);
pair(&s.h_mmrow, &s.d_mmrow, mm_on_ ? T : 0);
/* Each row's adapter slot, only when the engine serves adapters: with none the slab and every
* offset in it are what they were before adapters existed. */
/* Each row's adapter slot, carved only when the engine serves adapters, so an engine without
* them lays the slab out as if the array did not exist. */
pair(&s.h_lora, &s.d_lora, lora_on_ ? T : 0);
/* Host-only (derived metadata is copied into the planned arena), but carved on both sides to
* keep device offsets equal to host offsets. */
@@ -871,6 +871,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
int64_t n_out = 0, n_dout = 0;
int32_t rope_mixed = 0;
int64_t n_mm = 0;
bool lora_rows = false;
s.h_cu[0] = 0;
for (int64_t i = 0; i < n_seq; ++i) {
const StepEntry& e = plan.e[(size_t)i];
@@ -902,6 +903,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
if (lora_on_) {
const int32_t ls = e.req ? e.req->lora_slot : -1;
for (int32_t j = 0; j < e.n_tokens; ++j) s.h_lora[k + j] = ls;
if (ls >= 0 && e.n_tokens > 0) lora_rows = true;
}
/* Rotary position of each row at its own position (draft-head rows rotate at the index
* they write, not the token they embed). Three planes of n_tok. */
@@ -1108,7 +1110,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
B.n_mm_rows = n_mm;
B.mm_rows = n_mm ? on_rank(base, b0, s.d_mmrow) : nullptr;
B.mm_embd = n_mm ? mm_dev_[r] : nullptr;
B.lora_slot = lora_on_ ? on_rank(base, b0, s.d_lora) : nullptr;
/* Null on a step with no adapter row: the core then issues no adapter op, and the step
* runs the same pass as an engine serving no adapters. */
B.lora_slot = lora_rows ? on_rank(base, b0, s.d_lora) : nullptr;
B.enc = 0;
B.enc_n_patch = 0;
B.enc_pixels = nullptr;
+6 -6
View File
@@ -284,11 +284,10 @@ struct KVBinding final : IKVManager {
* and segment: the same picture at the same place hits, two pictures never alias. */
inline void media_keys(const Request& r, std::vector<MMContentKey>* out) {
out->clear();
/* THE RUNTIME LoRA ADAPTER IS PART OF EVERY BLOCK'S KEY. KV written under an adapter is not
* the base's, so it rides into the chain as one span over the whole sequence, keyed by the
* adapter's load uid -- every block overlaps it, and with uid 0 (the base) there is no span and
* every hash is what it was before adapters existed. The uid, never the name: a reload under
* the same name is new weights and must start cold. */
/* The runtime LoRA adapter is part of every block's key: KV written under an adapter is not
* the base's. It enters the chain as one span over the whole sequence, keyed by the adapter's
* load uid, so every block overlaps it; the base (uid 0) adds no span and its hashes are
* unchanged. The uid and not the name, because a reload under the same name is new weights. */
if (r.lora_uid != 0) {
MMContentKey k;
k.tok_begin = 0;
@@ -319,7 +318,8 @@ struct PCBinding final : IPrefixCache {
CacheHit lookup(const Request& r, std::vector<std::vector<int32_t>>* out,
const HitCap* cap) const override {
media_keys(r, &mm_);
return m->lookup(r.prompt, mm_, out, cap);
/* r.id: the admission takes its conversation's snapshots over. */
return m->lookup(r.prompt, mm_, out, cap, r.id);
}
/* Installed by the engine when the idle tiers are on; empty otherwise. */
+8 -3
View File
@@ -8,8 +8,9 @@
*
* Deliberately absent, answering 404: vLLM's /pooling, /classify, /score and /rerank (no
* classifier or cross-encoder head), /sleep, /wake_up and /is_sleeping (no sleep mode; weights
* are placed once, spec §5), the LoRA endpoints (no LoRA), /invocations (a SageMaker envelope),
* stored Responses-API responses (would need a conversation store), and llama-server's /slots.
* are placed once, spec §5), /invocations (a SageMaker envelope), stored Responses-API responses
* (would need a conversation store), and llama-server's /slots and /lora-adapters (a runtime LoRA
* adapter is chosen per request by `model`; vLLM's load and unload routes are in server.cpp).
*/
#include "server.h"
@@ -311,6 +312,8 @@ HttpResponse Server::handle_props(const HttpRequest&) {
params["backend_sampling"] = false;
params["timings_per_token"] = false;
params["post_sampling_probs"] = false;
/* The adapters a request runs with when it names none: never any, since an adapter is chosen
* by `model` (they are listed on /v1/models). */
params["lora"] = json::array();
json gen;
@@ -385,7 +388,7 @@ json Server::capabilities() const {
caps["reasoning"] = deps_.chat && deps_.chat->supports_reasoning();
/* An image model reads pictures only for edits and writes no text a grammar could constrain,
* whatever its conditioning network's processor would take. */
const bool img = opt_.image_model;
const bool img = opt_.image_model || opt_.video_model;
caps["grammar"] = !img && deps_.grammar != nullptr;
caps["embedding"] = deps_.embed != nullptr;
caps["image"] = deps_.mm && deps_.mm->accepts(MediaKind::Image);
@@ -394,6 +397,8 @@ json Server::capabilities() const {
caps["logprobs"] = opt_.supports_logprobs;
caps["image_generation"] = deps_.images != nullptr;
caps["image_edit"] = deps_.images != nullptr && deps_.images->info().max_refs > 0;
caps["audio_generation"] = deps_.audio != nullptr;
caps["video_generation"] = deps_.videos != nullptr;
/* The efforts a chat request may send, probed from the template at startup; null when it
* takes any word. "none" and "minimal" are this server's and turn thinking off. */
if (lim_.reasoning_efforts.empty()) {
+442
View File
@@ -0,0 +1,442 @@
/* audio_gen.cpp -- POST /v1/audio/speech over an audio generator (core/gen/audio_driver.h): music
* from a description and lyrics, or speech from text and a description of the voice.
*
* The request is OpenAI's speech request: `input` is the text the audio carries (a song's lyrics,
* as SGLang-Omni reads it for a music model, or the words to speak) and `instructions` describes
* it (the piece, or the voice). A model with a template for requests without instructions takes
* them as optional. `voice` is accepted and ignored (the instructions say who sings or speaks),
* `speed` must be 1. The length is `max_new_tokens`, in the model's frames as SGLang-Omni counts
* it, or `duration` in seconds; without either the audio may run to the model's longest, and the
* model usually ends it before that. Also read: `seed` (-1 or absent picks one),
* `guidance_scale` (the model's guidance: the denoiser's for a music model, the frame model's for
* a speech one) and, for a model with a denoiser, `num_inference_steps`.
*
* Prompt: the plugin's template with its slots filled, each text first rewritten by the plugin
* into the form the model was trained on (rad_arch_text_prepare). The template is tokenised with
* its special tokens and the texts without, so a caller cannot write the model's control tokens
* into a lyric. A model that declares the unconditional branch's own template gets that one
* rendered from the same texts.
*
* Response: the whole piece, once it is finished, as `response_format` wav (16-bit PCM, the
* model's rate and channels) or pcm (the same samples raw, little-endian). Streamed as the
* vocoder plays each window, in two forms (vLLM-Omni's reading of OpenAI's `stream_format`):
* `stream_format` "audio" sends the bytes themselves as they are made (a wav's header then states
* no length, as a stream's cannot), and `stream` true or `stream_format` "sse" sends Server-Sent
* Events, `speech.audio.delta` with a chunk of base64 PCM and `speech.audio.done` with the usage,
* or `speech.audio.error`.
*/
#include "server.h"
#include "oai.h"
#include "gen/audio.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <map>
#include <random>
namespace rad {
namespace server {
namespace {
void put_le(std::string* s, uint32_t v, int bytes) {
for (int i = 0; i < bytes; ++i) s->push_back((char)((v >> (8 * i)) & 0xff));
}
} /* namespace */
/* Samples in [-1, 1] as 16-bit PCM, as libsndfile writes float data to PCM_16 (scaled by 32767,
* rounded, clipped). */
void append_pcm16(const std::vector<float>& x, std::string* out) {
const size_t at = out->size();
out->resize(at + 2 * x.size());
char* p = &(*out)[at];
for (size_t i = 0; i < x.size(); ++i) {
const float v = std::min(1.0f, std::max(-1.0f, x[i]));
const int16_t q = (int16_t)std::lrint(v * 32767.0f);
std::memcpy(p + 2 * i, &q, 2);
}
}
/* A RIFF/WAVE header for `bytes` of 16-bit PCM; -1 states no length, as a stream's header must,
* with both sizes at their largest (how ffmpeg and libsndfile read a WAV of unknown length). */
std::string wav_header(int64_t bytes, int64_t rate, int64_t channels) {
std::string h;
h += "RIFF";
put_le(&h, bytes < 0 ? 0xffffffffu : (uint32_t)(36 + bytes), 4);
h += "WAVEfmt ";
put_le(&h, 16, 4);
put_le(&h, 1, 2); /* PCM */
put_le(&h, (uint32_t)channels, 2);
put_le(&h, (uint32_t)rate, 4);
put_le(&h, (uint32_t)(rate * channels * 2), 4); /* byte rate */
put_le(&h, (uint32_t)(channels * 2), 2); /* block align */
put_le(&h, 16, 2); /* bits a sample */
h += "data";
put_le(&h, bytes < 0 ? 0xffffffffu : (uint32_t)bytes, 4);
return h;
}
/* The request's description of the audio, `text` its input: the instructions, the tempo, the
* length, the denoiser's steps, the guidance and the seed, and the prompt rendered from the
* model's templates. */
int Server::speech_request(const json& body, const std::string& text,
std::unique_ptr<gen::AudioRequest>* out, ApiError* err) {
const AudioGenInfo& info = deps_.audio->info();
auto fail = [&](ApiError e) {
*err = std::move(e);
return -1;
};
auto str = [&](const char* k, std::string* v) -> int {
if (!body.contains(k) || body[k].is_null()) return 0;
if (!body[k].is_string()) return -1;
*v = body[k].get<std::string>();
return 1;
};
auto blank = [](const std::string& t) {
return t.find_first_not_of(" \t\r\n") == std::string::npos;
};
std::string inst;
const int has_inst = str("instructions", &inst);
if (has_inst < 0) return fail(err_bad("instructions", "expected a string"));
if (has_inst > 0 && blank(inst)) inst.clear();
if (inst.empty() && info.tmpl_plain.empty())
return fail(err_bad("instructions", "this model needs instructions, as a non-empty "
"string: for a song its genre, mood, vocals and "
"instruments"));
if (body.contains("speed") && !body["speed"].is_null() &&
!(body["speed"].is_number() && body["speed"].get<double>() == 1.0))
return fail(err_unsupported("speed", "this model keeps its own tempo; the instructions "
"set it"));
auto r = std::make_unique<gen::AudioRequest>();
/* The length: frames, or seconds, or the model's longest. */
const bool has_frames = body.contains("max_new_tokens") && !body["max_new_tokens"].is_null();
const bool has_dur = body.contains("duration") && !body["duration"].is_null();
if (has_frames && has_dur)
return fail(err_bad("duration", "give max_new_tokens or duration, not both"));
r->max_frames = info.max_frames;
if (has_frames) {
if (!body["max_new_tokens"].is_number_integer() ||
body["max_new_tokens"].get<int64_t>() < 1 ||
body["max_new_tokens"].get<int64_t>() > info.max_frames)
return fail(err_bad("max_new_tokens", "expected an integer in 1.." +
std::to_string(info.max_frames) + " (frames, " +
rad::fmt("%g", (double)info.frame_rate_num /
(double)info.frame_rate_den) +
" a second)"));
r->max_frames = body["max_new_tokens"].get<int64_t>();
}
if (has_dur) {
const double max_s = (double)info.max_frames * info.frame_rate_den / info.frame_rate_num;
if (!body["duration"].is_number() || !(body["duration"].get<double>() > 0) ||
body["duration"].get<double>() > max_s)
return fail(err_bad("duration", "expected seconds in (0, " +
std::to_string((int64_t)max_s) + "]"));
r->max_frames = std::max<int64_t>(
1, std::min<int64_t>(info.max_frames,
(int64_t)std::ceil(body["duration"].get<double>() *
info.frame_rate_num / info.frame_rate_den)));
}
if (body.contains("num_inference_steps") && !body["num_inference_steps"].is_null()) {
if (info.default_steps <= 0)
return fail(err_unsupported("num_inference_steps", "this model has no denoiser"));
if (!body["num_inference_steps"].is_number_integer() ||
body["num_inference_steps"].get<int64_t>() < 1 ||
body["num_inference_steps"].get<int64_t>() > 1000)
return fail(err_bad("num_inference_steps", "expected an integer in 1..1000"));
r->steps = (int32_t)body["num_inference_steps"].get<int64_t>();
}
if (body.contains("guidance_scale") && !body["guidance_scale"].is_null()) {
if (!body["guidance_scale"].is_number() || !(body["guidance_scale"].get<double>() >= 1.0) ||
body["guidance_scale"].get<double>() > 30.0)
return fail(err_bad("guidance_scale", "expected a number in [1, 30]"));
r->cfg = (float)body["guidance_scale"].get<double>();
}
bool seed_given = false;
if (body.contains("seed") && !body["seed"].is_null()) {
if (!body["seed"].is_number_integer()) return fail(err_bad("seed", "expected an integer"));
r->seed = (uint64_t)body["seed"].get<int64_t>();
seed_given = body["seed"].is_number_unsigned() || body["seed"].get<int64_t>() != -1;
}
if (!seed_given) {
/* 53 bits, as the images endpoints choose one: JavaScript reads a number as a double. */
std::random_device rd;
r->seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1);
}
/* ---- the prompt */
std::string i2, t2, why;
if (!inst.empty() && deps_.audio->prepare(RAD_TEXT_INSTRUCTIONS, inst, &i2, &why) < 0)
return fail(err_bad("instructions", why));
if (deps_.audio->prepare(RAD_TEXT_INPUT, text, &t2, &why) < 0)
return fail(err_bad("input", why));
/* A template a segment at a time: its own text with special tokens, each slot without. */
auto render = [&](const std::string& t, std::vector<int32_t>* ids_out) {
static const std::string kInst = "{instructions}", kInput = "{input}";
size_t at = 0;
while (at <= t.size()) {
const size_t a = t.find(kInst, at), b = t.find(kInput, at);
const size_t p = std::min(a, b);
const std::string lit =
t.substr(at, p == std::string::npos ? std::string::npos : p - at);
if (!lit.empty()) {
const auto ids = deps_.tok->encode(lit, false, /*parse_special=*/true);
ids_out->insert(ids_out->end(), ids.begin(), ids.end());
}
if (p == std::string::npos) break;
const bool is_inst = p == a;
const auto ids = deps_.tok->encode(is_inst ? i2 : t2, false, /*parse_special=*/false);
ids_out->insert(ids_out->end(), ids.begin(), ids.end());
at = p + (is_inst ? kInst : kInput).size();
}
};
render(inst.empty() ? info.tmpl_plain : info.tmpl, &r->tokens);
if (!info.neg_tmpl.empty()) render(info.neg_tmpl, &r->neg_tokens);
const size_t n_prompt = std::max(r->tokens.size(), r->neg_tokens.size());
if ((int64_t)n_prompt > info.max_prompt)
return fail(err_bad("input", "the prompt is " + std::to_string(n_prompt) +
" tokens; this model takes at most " +
std::to_string(info.max_prompt)));
*out = std::move(r);
return 0;
}
HttpResponse Server::handle_speech(const HttpRequest& req) {
if (!deps_.audio || !deps_.tok)
return error_response(err_not_implemented(
opt_.image_model ? "/v1/audio/speech requires an audio generation model; this one "
"makes images"
: "/v1/audio/speech requires an audio generation model; this one "
"generates text"), req.peer);
const AudioGenInfo& info = deps_.audio->info();
json body = json::object();
{
ApiError err;
if (parse_request_object(req.body, lim_, &body, &err) < 0)
return error_response(err, req.peer);
}
static const char* kKnown[] = {
"model", "input", "instructions", "voice", "response_format", "speed", "stream",
"stream_format", "seed", "max_new_tokens", "duration", "num_inference_steps",
"guidance_scale", "user",
};
for (auto it = body.begin(); it != body.end(); ++it) {
bool known = false;
for (const char* k : kKnown) known = known || it.key() == k;
if (!known)
return error_response(err_bad(it.key(), "'" + it.key() + "' is not a field of "
"/v1/audio/speech"), req.peer);
}
auto str = [&](const char* k, std::string* out) -> int {
if (!body.contains(k) || body[k].is_null()) return 0;
if (!body[k].is_string()) return -1;
*out = body[k].get<std::string>();
return 1;
};
std::string text, fmt;
if (str("input", &text) <= 0 || text.find_first_not_of(" \t\r\n") == std::string::npos)
return error_response(err_bad("input", "the text is required, as a non-empty string"),
req.peer);
/* How the audio comes back: whole, as raw bytes while it is made, or as events. */
bool stream = false;
if (body.contains("stream") && !body["stream"].is_null()) {
if (!body["stream"].is_boolean())
return error_response(err_bad("stream", "expected a boolean"), req.peer);
stream = body["stream"].get<bool>();
}
std::string sfmt;
if (str("stream_format", &sfmt) < 0 || (!sfmt.empty() && sfmt != "sse" && sfmt != "audio")) {
ApiError e = err_unsupported("stream_format", "a stream is sent as sse or audio");
e.supported = { "sse", "audio" };
return error_response(e, req.peer);
}
if (stream && sfmt == "audio")
return error_response(err_bad("stream", "stream sends Server-Sent Events and "
"stream_format audio sends the bytes themselves; "
"give one"), req.peer);
const bool sse = stream || sfmt == "sse", raw = sfmt == "audio";
if (str("response_format", &fmt) < 0) fmt = "?";
if (fmt.empty()) fmt = sse ? "pcm" : "wav";
if (fmt != "wav" && fmt != "pcm") {
ApiError e = err_unsupported("response_format", "this server writes wav or pcm");
e.supported = { "wav", "pcm" };
return error_response(e, req.peer);
}
if (sse && fmt != "pcm")
return error_response(err_unsupported("response_format", "an event carries raw PCM; set "
"response_format pcm"), req.peer);
std::unique_ptr<gen::AudioRequest> r;
{
ApiError err;
if (speech_request(body, text, &r, &err) < 0) return error_response(err, req.peer);
}
/* ---- admitted and queued */
if (auto no = admit(1, req.peer)) return *no;
r->ticket = std::make_shared<gen::AudioTicket>();
std::shared_ptr<gen::AudioTicket> ticket = r->ticket;
const int64_t frames_max = r->max_frames;
const uint64_t seed = r->seed;
const int64_t n_tok = (int64_t)r->tokens.size();
{
std::string w;
const int s = deps_.audio->submit(std::move(r), &w);
if (s < 0) {
release(1);
ApiError e = err_bad("", w.empty() ? std::string(rad_strerror(s)) : w);
if (s != RAD_E_INVAL) { e.status = 503; e.type = "server_error"; }
return error_response(e, req.peer);
}
}
RAD_INFO("audio: %lld prompt tokens, up to %lld frames, seed=%llu", (long long)n_tok,
(long long)frames_max, (unsigned long long)seed);
if (sse || raw) return stream_speech(ticket, info, n_tok, seed, sse, fmt == "wav");
/* ---- the windows as they are played, in order */
std::vector<gen::AudioChunk> chunks;
for (;;) {
gen::AudioChunk c;
bool to = false;
if (ticket->next(&c, 200, &to)) {
chunks.push_back(std::move(c));
continue;
}
if (!to) break;
if (req.peer_gone()) {
ticket->cancel.store(true);
release(1);
metrics_.observe_http(499);
return HttpResponse::text(499, "client closed request\n");
}
if (stopping_.load()) {
ticket->cancel.store(true);
release(1);
return error_response(err_overloaded("the server is shutting down"), req.peer);
}
}
release(1);
if (ticket->status() < 0 || chunks.empty()) {
/* RAD_E_INVAL is the driver's refusal of this request (or the model ending the piece
* before it began), so a 400; anything else failed while running. */
ApiError e;
const bool client = ticket->status() == RAD_E_INVAL;
e.status = client ? 400 : 500;
e.type = client ? "invalid_request_error" : "server_error";
e.message = ticket->why().empty() ? "the audio generator failed" : ticket->why();
return error_response(e, req.peer);
}
std::sort(chunks.begin(), chunks.end(), [](const gen::AudioChunk& a, const gen::AudioChunk& b) {
return a.window < b.window;
});
std::string pcm;
for (const gen::AudioChunk& c : chunks) append_pcm16(c.samples, &pcm);
const double secs = (double)pcm.size() / 2.0 / (double)(info.channels * info.sample_rate);
RAD_INFO("audio: %.1f s from %lld frames in %lld windows, %.1f s%s", secs,
(long long)ticket->frames, (long long)ticket->windows,
(double)(ticket->t_done_ns - ticket->t_submit_ns) * 1e-9,
ticket->model_ended ? "" : " (the request's length)");
HttpResponse res;
res.status = 200;
if (fmt == "wav") {
res.content_type = "audio/wav";
res.body = wav_header((int64_t)pcm.size(), info.sample_rate, info.channels) + pcm;
} else {
res.content_type = "audio/pcm";
res.body = std::move(pcm);
}
res.set_header("X-Audio-Sample-Rate", std::to_string(info.sample_rate));
res.set_header("X-Audio-Channels", std::to_string(info.channels));
res.set_header("X-Seed", std::to_string(seed));
metrics_.observe_http(200);
return res;
}
/* The piece as it is played: each window's samples once every earlier window has gone (the driver
* may finish them out of order), as bytes or as `speech.audio.delta` events. */
HttpResponse Server::stream_speech(std::shared_ptr<gen::AudioTicket> ticket,
const AudioGenInfo& info, int64_t n_tok, uint64_t seed,
bool sse, bool wav) {
HttpResponse res;
res.status = 200;
res.content_type = sse ? "text/event-stream" : wav ? "audio/wav" : "audio/pcm";
if (sse) res.set_header("Cache-Control", "no-cache");
res.set_header("X-Audio-Sample-Rate", std::to_string(info.sample_rate));
res.set_header("X-Audio-Channels", std::to_string(info.channels));
res.set_header("X-Seed", std::to_string(seed));
struct State {
std::map<int32_t, std::vector<float>> held; /* windows ahead of the next one */
int32_t next = 0;
bool header = false, finished = false, released = false;
};
auto st = std::make_shared<State>();
st->header = !wav || sse;
const int64_t rate = info.sample_rate, channels = info.channels;
res.next = [this, ticket, st, sse, rate, channels, n_tok](std::string& chunk) -> bool {
if (st->finished) return false;
chunk.clear();
if (!st->header) {
chunk = wav_header(-1, rate, channels);
st->header = true;
}
gen::AudioChunk c;
bool to = false;
if (ticket->next(&c, 100, &to)) {
st->held[c.window] = std::move(c.samples);
std::string pcm;
for (auto it = st->held.find(st->next); it != st->held.end();
it = st->held.find(st->next)) {
append_pcm16(it->second, &pcm);
st->held.erase(it);
++st->next;
}
if (pcm.empty()) return true;
if (!sse) {
chunk += pcm;
return true;
}
json ev;
ev["type"] = "speech.audio.delta";
ev["audio"] = base64_encode(pcm.data(), pcm.size());
ev["response_format"] = "pcm";
ev["sample_rate"] = rate;
ev["channels"] = channels;
chunk += "event: speech.audio.delta\ndata: " + json_dump(ev) + "\n\n";
return true;
}
if (to) return !stopping_.load();
st->finished = true;
if (!st->released) { st->released = true; release(1); }
if (!sse) return !chunk.empty();
json ev;
if (ticket->status() < 0 || st->next == 0) {
ev["type"] = "speech.audio.error";
ev["error"] = json{
{ "message", ticket->why().empty() ? "the audio generator failed" : ticket->why() },
{ "type", ticket->status() == RAD_E_INVAL ? "invalid_request_error"
: "server_error" } };
} else {
ev["type"] = "speech.audio.done";
ev["usage"] = json{ { "input_tokens", n_tok }, { "output_tokens", ticket->frames },
{ "total_tokens", n_tok + ticket->frames } };
}
chunk += "event: " + ev["type"].get<std::string>() + "\ndata: " + json_dump(ev) + "\n\n";
return true;
};
res.on_close = [this, ticket, st](bool ok) {
if (!ok) ticket->cancel.store(true);
if (!st->released) { st->released = true; release(1); }
};
metrics_.observe_http(200);
return res;
}
} /* namespace server */
} /* namespace rad */
+3
View File
@@ -417,6 +417,9 @@ public:
return true;
}
bool send(const std::string& text) override { return ws_.send(text); }
bool send_binary(const std::string& bytes) override {
return ws_.send(bytes.data(), bytes.size());
}
void close(int code, const std::string& reason) override {
ws_.close((httplib::ws::CloseStatus)code, reason);
}
+6
View File
@@ -90,6 +90,12 @@ public:
virtual bool read(std::string* msg, bool* binary) = 0;
/* A text message. Safe from any thread; false once the connection is gone. */
virtual bool send(const std::string& text) = 0;
/* A binary message (raw audio). Safe from any thread; false once the connection is gone, or
* for a connection that carries text only. */
virtual bool send_binary(const std::string& bytes) {
(void)bytes;
return false;
}
/* Ends the connection with a close code and reason (RFC 6455 §7.4); a read() blocked on it
* returns false once the peer has answered or gone. Safe from any thread. */
virtual void close(int code, const std::string& reason) = 0;
+55 -1
View File
@@ -20,7 +20,7 @@
#include <vector>
namespace rad {
namespace gen { struct Request; }
namespace gen { struct Request; struct AudioRequest; class AudioTicket; struct VideoRequest; class VideoTicket; }
namespace mm { struct Frame; struct Item; }
namespace server {
@@ -599,5 +599,59 @@ public:
virtual int64_t running() const = 0;
};
/* The audio generator (core/gen/audio_driver.h), for a model that makes music or other audio from
* text: its declared prompt template and limits, the plugin's rewrite of a request's texts into
* the form it was trained on, and its request queue. The server renders and tokenises the prompt
* and reads the audio back off the ticket, a window at a time. */
struct AudioGenInfo {
/* The prompt templates (RadAudioGenDecl): with instructions, without them ("" makes them
* required), and the unconditional branch's own ("" derives it from the conditional prompt). */
std::string name, tmpl, tmpl_plain, neg_tmpl;
int64_t max_prompt = 0, max_frames = 0, frame_rate_num = 1, frame_rate_den = 1;
int64_t sample_rate = 0, channels = 0;
int64_t default_steps = 0, max_lanes = 1; /* default_steps 0: no denoiser */
double default_cfg = 1.0;
};
class IAudioGen {
public:
virtual ~IAudioGen() = default;
virtual const AudioGenInfo& info() const = 0;
/* `in` rewritten as the model wants text for `field` (RAD_TEXT_*); the text unchanged when the
* plugin states no rewrite. RAD_E_INVAL with `why` for text the model cannot take. */
virtual int prepare(int field, const std::string& in, std::string* out,
std::string* why) const = 0;
/* Queue a request; refused at once, with `why`, when it can never run. */
virtual int submit(std::unique_ptr<gen::AudioRequest> r, std::string* why) = 0;
virtual int64_t queued() const = 0;
virtual int64_t running() const = 0;
};
/* The video generator (core/gen/video_driver.h), for a model that makes a video and its
* soundtrack from text: its declared prompt template, sizes and lengths, and its request queue.
* The server renders and tokenises the prompt, queues the request as a job, and turns what the
* ticket hands back into an MP4 file. */
struct VideoGenInfo {
std::string name, tmpl;
int64_t max_text = 0;
int64_t fps_num = 1, fps_den = 1;
int64_t frames_per_chunk = 1, frames_tail = 0, min_chunks = 1, max_chunks = 1;
int64_t size_multiple = 32, min_side = 0, max_area = 0, max_aspect = 1;
int64_t default_width = 0, default_height = 0, default_chunks = 1;
int64_t sample_rate = 0, channels = 0;
int64_t default_steps = 0, max_steps = 0, max_lanes = 1;
bool fixed_steps = false; /* a trained schedule: max_steps grid points and no other */
};
class IVideoGen {
public:
virtual ~IVideoGen() = default;
virtual const VideoGenInfo& info() const = 0;
/* Queue a request; refused at once, with `why`, when it can never run. */
virtual int submit(std::unique_ptr<gen::VideoRequest> r, std::string* why) = 0;
virtual int64_t queued() const = 0;
virtual int64_t running() const = 0;
};
} /* namespace server */
} /* namespace rad */
+3 -1
View File
@@ -313,7 +313,9 @@ const Guarded kGuarded[] = {
"implemented" },
{ "suffix", empty_value, "an empty string", "infilling through /v1/completions is not "
"implemented" },
{ "lora", empty_value, "an empty list", "LoRA is explicitly out of scope (spec, Scope)" },
{ "lora", empty_value, "an empty list",
"a per-request adapter list is not served; a runtime LoRA adapter is chosen by `model` "
"(--lora)" },
{ "modalities", text_only, "[\"text\"]", "output modalities other than text are not "
"implemented" },
{ "audio", empty_value, "null", "audio output is not implemented" },
+42 -13
View File
@@ -96,6 +96,14 @@ void Server::register_routes() {
router_.post("/v1/images/edits", [this](const HttpRequest& q) { return handle_images(q, true); });
router_.post("/v1/systemone", [this](const HttpRequest& q) { return handle_systemone(q); });
/* Speech to text, for a model whose plugin says how it transcribes (RadAudioFormat). */
router_.post("/v1/audio/speech", [this](const HttpRequest& q) { return handle_speech(q); });
router_.post("/v1/videos", [this](const HttpRequest& q) { return handle_video_create(q); });
router_.get ("/v1/videos", [this](const HttpRequest& q) { return handle_video_list(q); });
router_.get ("/v1/videos/:id", [this](const HttpRequest& q) { return handle_video_get(q); });
router_.add ("DELETE", "/v1/videos/:id",
[this](const HttpRequest& q) { return handle_video_delete(q); });
router_.get ("/v1/videos/:id/content",
[this](const HttpRequest& q) { return handle_video_content(q); });
router_.post("/v1/audio/transcriptions",
[this](const HttpRequest& q) { return handle_transcription(q); });
/* The same, live over a WebSocket (OpenAI's realtime transcription session). A plain GET
@@ -110,6 +118,19 @@ void Server::register_routes() {
r.set_header("Upgrade", "websocket");
return r;
});
/* Speech made while its text is still being written (vLLM-Omni's realtime speech session). */
router_.socket("/v1/audio/speech/stream",
[this](const HttpRequest& q, WsConn& c) { handle_speech_stream(q, c); });
router_.get ("/v1/audio/speech/stream", [this](const HttpRequest& q) {
ApiError e;
e.status = 426;
e.type = "invalid_request_error";
e.message = "/v1/audio/speech/stream is a WebSocket: connect with an Upgrade: websocket "
"request";
HttpResponse r = error_response(e, q.peer);
r.set_header("Upgrade", "websocket");
return r;
});
router_.get ("/v1/models", [this](const HttpRequest& q) { return handle_models(q); });
router_.get ("/v1/models/*id", [this](const HttpRequest& q) { return handle_models(q); });
router_.post("/v1/load_lora_adapter", [this](const HttpRequest& q) { return handle_lora_admin(q, true); });
@@ -126,6 +147,7 @@ void Server::register_routes() {
router_.post("/images/generations", [this](const HttpRequest& q) { return handle_images(q, false); });
router_.post("/images/edits", [this](const HttpRequest& q) { return handle_images(q, true); });
router_.post("/audio/transcriptions", [this](const HttpRequest& q) { return handle_transcription(q); });
router_.post("/audio/speech", [this](const HttpRequest& q) { return handle_speech(q); });
router_.get ("/models", [this](const HttpRequest& q) { return handle_models(q); });
/* llama-server's: the prompt a chat request renders to, and how many tokens it is. */
router_.post("/apply-template", [this](const HttpRequest& q) { return handle_apply_template(q); });
@@ -281,6 +303,7 @@ std::string Server::check_thinking_budget() const {
void Server::stop() {
stopping_.store(true);
transport_.stop();
stop_videos();
drain_graveyard(2000);
}
@@ -390,9 +413,9 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
}
}
/* RUNTIME LoRA: `model` picks the adapter. The served model's own name, or no name, is the
* base; with adapters enabled anything else must be a loaded adapter -- a typo served by the
* base would answer as the wrong model and say nothing. */
/* Runtime LoRA: `model` picks the adapter. The served model's own name, or no name, is the
* base; with adapters enabled anything else must be a loaded adapter, since a typo served by
* the base would answer as the wrong model without a word. */
int32_t lora_slot = -1;
uint64_t lora_uid = 0;
std::shared_ptr<void> lora_hold;
@@ -1269,6 +1292,10 @@ std::optional<HttpResponse> Server::refuse_text(const std::string& peer, ApiShap
"generates no text"
: opt_.image_model ? "this is an image model: it serves /v1/images/generations "
"and /v1/images/edits and generates no text"
: opt_.audio_model ? "this is an audio model: it serves /v1/audio/speech and "
"generates no text"
: opt_.video_model ? "this is a video model: it serves /v1/videos and generates "
"no text"
: nullptr;
if (!why) return std::nullopt;
return error_response(err_not_implemented(why), peer, shape);
@@ -1536,8 +1563,10 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) {
if (!deps_.embed)
return error_response(err_not_implemented(
opt_.image_model ? "/v1/embeddings requires an embedding model; this one makes images"
: "/v1/embeddings requires an embedding model; this one generates "
"text"), req.peer);
: opt_.audio_model ? "/v1/embeddings requires an embedding model; this one makes audio"
: opt_.video_model ? "/v1/embeddings requires an embedding model; this one makes video"
: "/v1/embeddings requires an embedding model; this one generates "
"text"), req.peer);
OaiRequest r;
ApiError err;
@@ -1775,7 +1804,7 @@ HttpResponse Server::handle_systemone(const HttpRequest& req) {
HttpResponse Server::handle_models(const HttpRequest& req) {
const std::string id = req.param("id");
/* RUNTIME LoRA: each loaded adapter is a model of its own, whose parent is the served one. */
/* Runtime LoRA: each loaded adapter is a model of its own, whose parent is the served one. */
std::vector<std::string> adapters;
if (opt_.lora_names) adapters = opt_.lora_names();
const bool is_adapter = !id.empty() && std::find(adapters.begin(), adapters.end(), id) != adapters.end();
@@ -1805,9 +1834,9 @@ HttpResponse Server::handle_models(const HttpRequest& req) {
return HttpResponse::json_body(200, id.empty() ? models_body(cards) : model_body(c));
}
/* RUNTIME LoRA ADMIN, vLLM's routes and bodies: {"lora_name", "lora_path"} to load, {"lora_name"}
* to unload. The path is read on THIS machine, so without --api-key only a loopback client may ask
* -- the rule /diagnostics follows. */
/* Runtime LoRA admin, vLLM's routes and bodies: {"lora_name", "lora_path"} to load, {"lora_name"}
* to unload. The path is read on this machine, so without --api-key only a loopback client may
* ask, the rule /diagnostics follows. */
HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) {
using json = nlohmann::json;
auto fail = [&](int status, const char* type, const std::string& msg) {
@@ -1845,10 +1874,10 @@ HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) {
if (s == RAD_E_STATE) return fail(409, "conflict_error", err);
if (s == RAD_E_FULL) return fail(503, "service_unavailable", err);
if (s < 0) return fail(400, "invalid_request_error", err.empty() ? std::string(rad_strerror(s)) : err);
/* AN UNLOAD OF AN ADAPTER IN USE DRAINS IT (lora/slots.h): accepted, not done. New requests
* naming it are already refused as an unknown model and it is off /v1/models; the requests
* counted here finish normally, and the last of them frees the slot. Asking again answers
* the same with the count as it is then, and a 404 once it is gone. */
/* An unload of an adapter in use drains it (lora/slots.h): accepted, not done. New requests
* naming it are refused as an unknown model and it is off /v1/models; the requests counted
* here finish, and the last of them frees the slot. Asking again answers with the count as it
* is then, and 404 once it is gone. */
if (!load && in_flight > 0) {
metrics_.observe_http(202);
return HttpResponse::json_body(202, json{ { "action", "draining" }, { "lora_name", name },
+53 -1
View File
@@ -39,6 +39,8 @@ struct Deps {
IEmbedder* embed = nullptr; /* absent -> /v1/embeddings is 501 */
IMultimodal* mm = nullptr; /* absent -> image and audio parts are 501 */
IImageGen* images = nullptr; /* absent -> the images endpoints are 501 */
IAudioGen* audio = nullptr; /* absent -> /v1/audio/speech is 501 */
IVideoGen* videos = nullptr; /* absent -> /v1/videos is 501 */
const SpeechFormat* speech = nullptr; /* absent -> /v1/audio/transcriptions is 501 */
/* Engine-side state the server cannot see (per-card VRAM, the expert plane), as a snapshot
@@ -56,6 +58,16 @@ struct ServerOptions {
/* An image generator (rad_declare_generator) generates no text: the text endpoints answer
* 501 naming /v1/images/generations and /v1/images/edits. */
bool image_model = false;
/* An audio generator (rad_declare_audio_generator) generates no text either: the text
* endpoints answer 501 naming /v1/audio/speech. */
bool audio_model = false;
/* A video generator (rad_declare_video_generator) generates no text either: the text
* endpoints answer 501 naming /v1/videos. */
bool video_model = false;
/* How long a finished video's file is kept for /v1/videos/{id}/content, in seconds, and how
* many finished videos are kept at most (the oldest go first). */
int64_t video_ttl_s = 3600;
int64_t max_videos = 32;
/* The decision protocol from the container's `decision.type`: "d1" serves /v1/systemone
* (systemone.h); empty answers it 501. Never inferred from a name. */
std::string decision_type;
@@ -119,7 +131,7 @@ struct ServerOptions {
* clock only mean something under load: queried during a long prefill, it tells a link parked
* below its maximum from one at rest. */
std::function<std::string()> diagnostics_json;
/* RUNTIME LoRA (Engine::lora_acquire): a request's `model` naming a loaded adapter gets that
/* Runtime LoRA (Engine::lora_acquire): a request's `model` naming a loaded adapter gets that
* adapter's slot, load uid and a hold on it. Unset with LoRA off, and then any `model` is
* served by the base. `lora_names` lists the adapters a request may name (not the draining
* ones). */
@@ -183,6 +195,8 @@ private:
struct Generation;
struct TranscriptionJob; /* speech.cpp */
struct RealtimeSession; /* realtime.cpp */
struct SpeechSession; /* speech_stream.cpp */
struct VideoJob; /* videos.cpp */
struct StreamState;
static UsageOut usage_of(const OaiRequest& r, const std::vector<Generation>& gens);
@@ -226,6 +240,37 @@ private:
/* ------------------------------------------------------------------ images.cpp */
HttpResponse handle_images(const HttpRequest& req, bool edit);
/* ------------------------------------------------------------------ audio_gen.cpp */
HttpResponse handle_speech(const HttpRequest& req);
/* The audio a speech request describes, `text` its input, as the generator's request; -1 with
* `err` naming the field. Shared by the route and the realtime session. */
int speech_request(const json& body, const std::string& text,
std::unique_ptr<gen::AudioRequest>* out, ApiError* err);
HttpResponse stream_speech(std::shared_ptr<gen::AudioTicket> ticket, const AudioGenInfo& info,
int64_t n_tok, uint64_t seed, bool sse, bool wav);
/* ------------------------------------------------------------------ videos.cpp
* OpenAI's video jobs: created by POST, made in the background, polled and downloaded. */
HttpResponse handle_video_create(const HttpRequest& req);
HttpResponse handle_video_list(const HttpRequest& req);
HttpResponse handle_video_get(const HttpRequest& req);
HttpResponse handle_video_delete(const HttpRequest& req);
HttpResponse handle_video_content(const HttpRequest& req);
/* A job's thread: the ticket's events into progress and an MP4 file. */
void video_work(std::shared_ptr<VideoJob> j);
/* Drops expired and surplus finished jobs; under videos_m_. */
void sweep_videos_locked(int64_t now);
/* Cancels every job and joins its thread; at stop(). */
void stop_videos();
static json video_json(const VideoJob& j);
/* ------------------------------------------------------------------ speech_stream.cpp */
/* vLLM-Omni's realtime speech session over a WebSocket at /v1/audio/speech/stream: text
* streamed in, each sentence's audio streamed out as soon as the sentence is complete. */
void handle_speech_stream(const HttpRequest& req, WsConn& ws);
void speech_stream_run(SpeechSession& s, WsConn& ws);
bool speech_stream_loop(SpeechSession& s, WsConn& ws);
/* ------------------------------------------------------------------ admin.cpp
* vLLM's non-generation surface, answered on the HTTP thread without the step path, the
* admission queue or a Sink. */
@@ -303,6 +348,7 @@ private:
std::atomic<int64_t> in_flight_{0};
int64_t queue_depth_ = 0;
std::atomic<int64_t> realtime_sessions_{0};
std::atomic<int64_t> speech_sessions_{0};
std::atomic<bool> stopping_{false};
int64_t started_at_ = 0;
@@ -311,6 +357,12 @@ private:
* it under a running step is a use-after-free. */
std::mutex grave_m_;
std::vector<std::shared_ptr<Sink>> grave_;
/* The video jobs, oldest first, and the threads that make them (videos.cpp); deleted jobs
* wait in `videos_gone_` until their threads are done. */
std::mutex videos_m_;
std::vector<std::shared_ptr<VideoJob>> videos_;
std::vector<std::shared_ptr<VideoJob>> videos_gone_;
};
} /* namespace server */
+6
View File
@@ -86,5 +86,11 @@ size_t speech_transcript_start(const SpeechFormat& f, const std::string& text, b
* between words when there is a pause to cut in. */
int64_t speech_quiet_point(const std::vector<float>& x, int64_t lo, int64_t hi, int32_t rate);
/* ---- audio_gen.cpp: what the audio generator's routes write */
/* Samples in [-1, 1] as 16-bit little-endian PCM, appended. */
void append_pcm16(const std::vector<float>& x, std::string* out);
/* A RIFF/WAVE header for `bytes` of 16-bit PCM; -1 states no length, as a stream's must. */
std::string wav_header(int64_t bytes, int64_t rate, int64_t channels);
} /* namespace server */
} /* namespace rad */
+452
View File
@@ -0,0 +1,452 @@
/* speech_stream.cpp -- vLLM-Omni's realtime speech session, over a WebSocket at
* /v1/audio/speech/stream.
*
* The POST route (audio_gen.cpp) speaks a text it is given whole. This one is sent the text as it
* is produced, a language model's reply token by token or a typist's keystrokes, and speaks each
* sentence as soon as it is complete: the first audio waits for the first sentence, not the text.
*
* Protocol: vLLM-Omni's, in its buffered text mode. The client sends `session.config` first (the
* POST route's fields but `input`, and `response_format` pcm or wav, `stream_audio`,
* `split_granularity` none / sentence / clause, `text_input_mode` buffered), then `input.text`
* {text} pieces, `input.done` to end an utterance, and `session.close`. The server answers each
* sentence with `audio.start` {utterance_index, sentence_index, sentence_text, format,
* sample_rate, channels}, its audio as binary messages of 16-bit little-endian PCM (one with
* `stream_audio` false; several, as the vocoder plays it, with it true; a wav begins with a header
* that states its length, or none while it streams), and `audio.done` {utterance_index,
* sentence_index, total_bytes, error}; once an utterance's last sentence is spoken,
* `session.done` {utterance_index, total_sentences}. The session stays open for the next
* utterance until `session.close` or the socket's close. A refusal or failure is `error`
* {message, param}; the session goes on.
*
* A sentence is one request, built from the session's fields as the POST route builds one
* (Server::speech_request), and the sentences of a session are spoken one at a time in order.
*
* Threads: the connection's thread reads messages and queues them. The session's thread does
* everything else, so the session's state has one owner and its messages go out in the order they
* happen.
*/
#include "server.h"
#include "server_priv.h"
#include "text_split.h"
#include "gen/audio.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <deque>
#include <map>
#include <mutex>
#include <thread>
namespace rad {
namespace server {
namespace {
using ojson = nlohmann::ordered_json;
/* The client messages a session may have queued and not yet taken in. */
constexpr size_t kMaxQueuedBytes = 16u << 20;
/* An utterance's text not yet spoken: a client that never ends a sentence is refused past it. */
constexpr size_t kMaxPendingBytes = 128u << 10;
ojson event(const char* type) {
ojson o;
o["type"] = type;
return o;
}
/* The fields that shape the session rather than each sentence's request. */
bool session_field(const std::string& k) {
return k == "type" || k == "stream_audio" || k == "split_granularity" ||
k == "text_input_mode" || k == "response_format";
}
} /* namespace */
struct Server::SpeechSession {
std::string id;
std::string peer;
/* The connection's thread to the session's: messages, and whether the peer is gone. */
std::mutex m;
std::condition_variable cv;
std::deque<std::pair<std::string, bool>> inbox; /* (message, binary) */
size_t inbox_bytes = 0;
bool peer_gone = false;
bool overflow = false;
/* Everything below is the session thread's alone. */
bool configured = false;
json fields = json::object(); /* every sentence's request, but its input */
bool stream_audio = false;
bool wav = false;
TextSplit split = TextSplit::Sentence;
std::string pending; /* the utterance's text not yet a sentence */
std::deque<std::string> sentences; /* complete, not yet spoken */
bool done_asked = false; /* input.done: the utterance ends once spoken */
int64_t utterance = 0;
int64_t sentence = 0; /* the utterance's next sentence index */
int64_t spoken = 0; /* sentences over the session's life */
/* The sentence being spoken. */
struct Current {
bool active = false;
std::shared_ptr<gen::AudioTicket> ticket;
int64_t index = 0;
std::map<int32_t, std::vector<float>> held; /* chunks ahead of the next one */
int32_t next = 0;
std::string pcm; /* the whole sentence, when it is sent at once */
int64_t bytes = 0; /* binary bytes sent for it */
} cur;
};
/* ------------------------------------------------------------------ the connection's thread */
void Server::handle_speech_stream(const HttpRequest& req, WsConn& ws) {
auto refuse = [&](const std::string& why, int close_code, const char* reason) {
ojson o = event("error");
o["message"] = why;
ws.send(json_dump(o));
RAD_INFO("speech stream refused from %s: %s", req.peer.c_str(), why.c_str());
ws.close(close_code, reason);
};
if (stopping_.load()) return refuse("the server is shutting down", 1001, "shutting down");
if (!deps_.audio || !deps_.tok)
return refuse("/v1/audio/speech/stream requires an audio generation model; this one "
"makes none", 1008, "model not supported");
/* A session speaks one sentence at a time: more sessions than the generator has lanes would
* only queue. */
const int64_t cap = std::max<int64_t>(1, deps_.audio->info().max_lanes);
if (speech_sessions_.fetch_add(1) >= cap) {
speech_sessions_.fetch_sub(1);
return refuse(fmt("this server holds %lld speech sessions at once; try again later",
(long long)cap), 1013, "session limit");
}
struct Count {
std::atomic<int64_t>& n;
~Count() { n.fetch_sub(1); }
} count{ speech_sessions_ };
/* One admission place for the session's whole life, as the realtime transcription session
* holds one. */
if (admit(1, req.peer))
return refuse("the admission queue is full; try again later", 1013, "rate limited");
struct Place {
Server& srv;
~Place() { srv.release(1); }
} place{ *this };
SpeechSession s;
s.id = random_id("speech_");
s.peer = req.peer;
std::thread worker([this, &s, &ws] { speech_stream_run(s, ws); });
/* The session's thread ends once the peer is gone, however this one leaves. */
struct Join {
SpeechSession& s;
std::thread& t;
~Join() {
{
std::lock_guard<std::mutex> lk(s.m);
s.peer_gone = true;
}
s.cv.notify_one();
if (t.joinable()) t.join();
}
} join{ s, worker };
std::string msg;
bool binary = false;
while (ws.read(&msg, &binary)) {
std::lock_guard<std::mutex> lk(s.m);
if (s.inbox_bytes + msg.size() > kMaxQueuedBytes) {
s.overflow = true;
s.cv.notify_one();
break;
}
s.inbox_bytes += msg.size();
s.inbox.emplace_back(std::move(msg), binary);
s.cv.notify_one();
}
}
/* ------------------------------------------------------------------ the session's thread */
void Server::speech_stream_run(SpeechSession& s, WsConn& ws) {
try {
speech_stream_loop(s, ws);
} catch (const std::exception& e) {
RAD_ERR("speech stream %s failed: %s", s.id.c_str(), e.what());
ojson o = event("error");
o["message"] = std::string("the session failed: ") + e.what();
ws.send(json_dump(o));
ws.close(1011, "internal error");
}
if (s.cur.active) s.cur.ticket->cancel.store(true);
RAD_INFO("speech stream %s closed: %lld utterances, %lld sentences", s.id.c_str(),
(long long)s.utterance, (long long)s.spoken);
}
bool Server::speech_stream_loop(SpeechSession& s, WsConn& ws) {
const AudioGenInfo& info = deps_.audio->info();
auto send = [&](const ojson& o) { ws.send(json_dump(o)); };
auto error = [&](const std::string& why, const std::string& param = std::string()) {
ojson o = event("error");
o["message"] = why;
o["param"] = param.empty() ? ojson(nullptr) : ojson(param);
send(o);
};
auto binary = [&](const std::string& bytes) {
if (bytes.empty()) return;
ws.send_binary(bytes);
s.cur.bytes += (int64_t)bytes.size();
};
/* ---- session.config: checked whole, then applied whole, between utterances only */
auto configure = [&](const json& j) {
if (s.cur.active || !s.sentences.empty() || !s.pending.empty() || s.done_asked)
return error("session.config applies between utterances; this one is still being "
"spoken");
static const char* kFields[] = {
"type", "model", "instructions", "voice", "response_format", "speed", "seed",
"max_new_tokens", "duration", "num_inference_steps", "guidance_scale", "user",
"stream_audio", "split_granularity", "text_input_mode",
};
json fields = json::object();
for (auto it = j.begin(); it != j.end(); ++it) {
bool known = false;
for (const char* k : kFields) known = known || it.key() == k;
if (it.key() == "input")
return error("the text arrives in input.text messages, not in the configuration",
"input");
if (!known)
return error("'" + it.key() + "' is not a field of session.config", it.key());
if (!session_field(it.key())) fields[it.key()] = it.value();
}
if (j.contains("text_input_mode") && !j["text_input_mode"].is_null()) {
const json& m = j["text_input_mode"];
if (!m.is_string() || (m != "buffered" && m != "commitment"))
return error("text_input_mode is buffered", "text_input_mode");
if (m == "commitment")
return error("text_input_mode commitment is not served here; buffered is",
"text_input_mode");
}
TextSplit split = TextSplit::Sentence;
if (j.contains("split_granularity") && !j["split_granularity"].is_null()) {
const json& g = j["split_granularity"];
if (g == "none") split = TextSplit::None;
else if (g == "clause") split = TextSplit::Clause;
else if (g != "sentence")
return error("split_granularity is none, sentence or clause", "split_granularity");
}
bool stream_audio = false;
if (j.contains("stream_audio") && !j["stream_audio"].is_null()) {
if (!j["stream_audio"].is_boolean())
return error("stream_audio is a boolean", "stream_audio");
stream_audio = j["stream_audio"].get<bool>();
}
bool wav = false;
if (j.contains("response_format") && !j["response_format"].is_null()) {
const json& f = j["response_format"];
if (f != "pcm" && f != "wav")
return error("response_format is pcm or wav", "response_format");
wav = f == "wav";
}
/* The request fields as every sentence will be made with them, tried on a stand-in. */
std::unique_ptr<gen::AudioRequest> probe;
ApiError err;
if (speech_request(fields, "a", &probe, &err) < 0) return error(err.message, err.param);
s.fields = std::move(fields);
s.split = split;
s.stream_audio = stream_audio;
s.wav = wav;
s.configured = true;
};
auto take = [&](bool final) {
for (std::string& u : take_text_units(&s.pending, s.split, final))
s.sentences.push_back(std::move(u));
};
/* Returns true when the session is over. */
auto handle = [&](const std::string& msg, bool bin) -> bool {
if (bin) {
error("this session takes JSON messages: session.config, input.text, input.done and "
"session.close");
return false;
}
const json j = json::parse(msg, nullptr, /*allow_exceptions=*/false);
if (j.is_discarded() || !j.is_object() || !j.contains("type") || !j["type"].is_string()) {
error("a client message is a JSON object with a string `type`");
return false;
}
const std::string type = j["type"].get<std::string>();
if (type == "session.config") {
configure(j);
return false;
}
if (type == "session.close") {
ws.close(1000, "session closed");
return true;
}
if (type != "input.text" && type != "input.done") {
error("this session takes session.config, input.text, input.done and session.close; "
"not '" + type + "'", "type");
return false;
}
if (!s.configured) {
error("send session.config before any text");
return false;
}
if (type == "input.done") {
take(true);
s.done_asked = true;
return false;
}
if (!j.contains("text") || !j["text"].is_string()) {
error("input.text carries `text`, a string", "text");
return false;
}
const std::string& t = j["text"].get_ref<const std::string&>();
if (s.pending.size() + t.size() > kMaxPendingBytes) {
error(fmt("the utterance holds more than %zu KiB of text without a sentence's end; "
"this piece was dropped", kMaxPendingBytes >> 10), "text");
return false;
}
s.pending += t;
take(false);
return false;
};
/* ---- a sentence: begun, its chunks sent as they come in order, and ended */
auto done = [&](bool failed) {
ojson o = event("audio.done");
o["utterance_index"] = s.utterance;
o["sentence_index"] = s.cur.index;
o["total_bytes"] = s.cur.bytes;
o["error"] = failed;
send(o);
s.cur = SpeechSession::Current{};
++s.spoken;
};
auto begin = [&]() {
const std::string text = std::move(s.sentences.front());
s.sentences.pop_front();
s.cur = SpeechSession::Current{};
s.cur.index = s.sentence++;
ojson o = event("audio.start");
o["utterance_index"] = s.utterance;
o["sentence_index"] = s.cur.index;
o["sentence_text"] = text;
o["format"] = s.wav ? "wav" : "pcm";
o["sample_rate"] = info.sample_rate;
o["channels"] = info.channels;
send(o);
std::unique_ptr<gen::AudioRequest> r;
ApiError err;
if (speech_request(s.fields, text, &r, &err) < 0) {
error(err.message, err.param);
return done(true);
}
r->ticket = std::make_shared<gen::AudioTicket>();
std::shared_ptr<gen::AudioTicket> ticket = r->ticket;
std::string why;
const int st = deps_.audio->submit(std::move(r), &why);
if (st < 0) {
error(why.empty() ? std::string(rad_strerror(st)) : why);
return done(true);
}
s.cur.active = true;
s.cur.ticket = std::move(ticket);
if (s.stream_audio && s.wav) binary(wav_header(-1, info.sample_rate, info.channels));
};
auto poll = [&](int wait_ms) {
gen::AudioChunk c;
bool to = false;
for (int ms = wait_ms;; ms = 0) {
if (s.cur.ticket->next(&c, ms, &to)) {
s.cur.held[c.window] = std::move(c.samples);
std::string pcm;
for (auto it = s.cur.held.find(s.cur.next); it != s.cur.held.end();
it = s.cur.held.find(s.cur.next)) {
append_pcm16(it->second, &pcm);
s.cur.held.erase(it);
++s.cur.next;
}
if (s.stream_audio) binary(pcm);
else s.cur.pcm += pcm;
continue;
}
if (to) return;
/* The sentence has ended. */
gen::AudioTicket& t = *s.cur.ticket;
if (t.status() < 0 || s.cur.next == 0) {
error(t.why().empty() ? "the audio generator failed" : t.why());
return done(true);
}
if (!s.stream_audio) {
const std::string& pcm = s.cur.pcm;
binary(s.wav ? wav_header((int64_t)pcm.size(), info.sample_rate, info.channels) +
pcm
: pcm);
}
return done(false);
}
};
/* ---- the loop */
RAD_INFO("speech stream %s open from %s", s.id.c_str(), s.peer.c_str());
for (;;) {
std::deque<std::pair<std::string, bool>> got;
bool gone = false, overflow = false;
{
std::unique_lock<std::mutex> lk(s.m);
const bool work = s.cur.active || !s.sentences.empty() || s.done_asked;
if (s.inbox.empty() && !s.peer_gone && !s.overflow && !work)
s.cv.wait_for(lk, std::chrono::milliseconds(100));
got.swap(s.inbox);
s.inbox_bytes = 0;
gone = s.peer_gone;
overflow = s.overflow;
}
if (overflow) {
error(fmt("the session fell more than %zu MiB of messages behind",
kMaxQueuedBytes >> 20));
ws.close(1008, "buffer overflow");
return true;
}
for (const auto& m : got)
if (handle(m.first, m.second)) return true;
if (gone) return false;
if (stopping_.load()) {
error("the server is shutting down");
ws.close(1001, "closing");
return true;
}
if (!s.cur.active && !s.sentences.empty()) begin();
if (s.cur.active) {
bool idle;
{
std::lock_guard<std::mutex> lk(s.m);
idle = s.inbox.empty() && !s.peer_gone;
}
poll(idle ? 10 : 0);
}
if (!s.cur.active && s.sentences.empty() && s.done_asked) {
ojson o = event("session.done");
o["utterance_index"] = s.utterance;
o["total_sentences"] = s.sentence;
send(o);
++s.utterance;
s.sentence = 0;
s.done_asked = false;
}
}
}
} /* namespace server */
} /* namespace rad */
+195
View File
@@ -0,0 +1,195 @@
/* text_split.cpp -- sentence and clause units of text that arrives in pieces (text_split.h). */
#include "text_split.h"
#include <cctype>
#include <cstdint>
namespace rad {
namespace server {
namespace {
/* The code point at `i` and its length in bytes; a byte that starts no valid sequence is read as
* itself, one byte long, so malformed text still advances. */
uint32_t cp_at(const std::string& s, size_t i, size_t* len) {
const unsigned char c = (unsigned char)s[i];
auto cont = [&](size_t k) {
return i + k < s.size() && ((unsigned char)s[i + k] & 0xC0) == 0x80;
};
if (c < 0x80) { *len = 1; return c; }
if ((c & 0xE0) == 0xC0 && cont(1)) {
*len = 2;
return ((uint32_t)(c & 0x1F) << 6) | ((unsigned char)s[i + 1] & 0x3F);
}
if ((c & 0xF0) == 0xE0 && cont(1) && cont(2)) {
*len = 3;
return ((uint32_t)(c & 0x0F) << 12) | ((uint32_t)((unsigned char)s[i + 1] & 0x3F) << 6) |
((unsigned char)s[i + 2] & 0x3F);
}
if ((c & 0xF8) == 0xF0 && cont(1) && cont(2) && cont(3)) {
*len = 4;
return ((uint32_t)(c & 0x07) << 18) | ((uint32_t)((unsigned char)s[i + 1] & 0x3F) << 12) |
((uint32_t)((unsigned char)s[i + 2] & 0x3F) << 6) | ((unsigned char)s[i + 3] & 0x3F);
}
*len = 1;
return c;
}
bool ends_sentence(uint32_t c) {
switch (c) {
case '.': case '!': case '?':
case 0x3002: /* 。 */
case 0xFF01: /* ! */
case 0xFF1F: /* ? */
case 0xFF0E: /* . */
case 0x2026: /* … */
case 0x0964: /* । */
case 0x0965: /* ॥ */
case 0x061F: /* ؟ */
return true;
default:
return false;
}
}
bool ends_clause(uint32_t c) {
switch (c) {
case ',': case ';':
case 0xFF0C: /* , */
case 0xFF1B: /* ; */
case 0x060C: /* ، */
case 0x061B: /* ؛ */
return true;
default:
return false;
}
}
/* What may follow a unit's closing punctuation and still belong to it. */
bool closes(uint32_t c) {
switch (c) {
case ')': case ']': case '}': case '"': case '\'':
case 0x201D: case 0x2019: case 0x00BB: /* ” ’ » */
case 0x300D: case 0x300F: case 0xFF09: case 0x3011: /* 」 』 ) 】 */
case 0x300B: case 0x3009: case 0x3015: case 0xFF3D: /* 》 〉 〕 ] */
case 0xFF5D: /* } */
return true;
default:
return false;
}
}
bool space_cp(uint32_t c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v' ||
c == 0x00A0 || c == 0x3000;
}
/* A full stop that ends no sentence: one closing a common abbreviation or an initial. `word` is
* the text from the last whitespace to the stop, the stop included. */
bool no_stop(std::string word) {
while (!word.empty() && (word[0] == '(' || word[0] == '"' || word[0] == '\'' ||
word[0] == '['))
word.erase(0, 1);
std::string low;
for (char ch : word) low += (char)std::tolower((unsigned char)ch);
static const char* const kAbbrev[] = {
"mr.", "mrs.", "ms.", "dr.", "prof.", "sr.", "jr.", "st.", "mt.", "vs.", "etc.", "e.g.",
"i.e.", "inc.", "ltd.", "co.", "no.", "fig.", "approx.", "dept.", "est.",
};
for (const char* a : kAbbrev)
if (low == a) return true;
/* An initial or a run of them: "J." or "J.R.", each an upper-case letter and a stop. */
if (word.size() >= 2 && word.size() % 2 == 0 && std::isupper((unsigned char)word[0])) {
bool initials = true;
for (size_t k = 0; k < word.size(); k += 2)
initials = initials && std::isalpha((unsigned char)word[k]) && word[k + 1] == '.';
if (initials) return true;
}
return false;
}
std::string trim(const std::string& s, size_t a, size_t b) {
while (a < b) {
size_t n = 1;
if (!space_cp(cp_at(s, a, &n))) break;
a += n;
}
while (b > a && std::isspace((unsigned char)s[b - 1])) --b;
return s.substr(a, b - a);
}
/* Whether a unit carries anything to say: some character that is no punctuation or space. */
bool says_something(const std::string& u) {
for (size_t i = 0; i < u.size();) {
size_t n = 1;
const uint32_t c = cp_at(u, i, &n);
i += n;
if (space_cp(c) || ends_sentence(c) || ends_clause(c) || closes(c)) continue;
if (c < 0x80 && std::ispunct((int)c)) continue;
return true;
}
return false;
}
} /* namespace */
std::vector<std::string> take_text_units(std::string* pending, TextSplit mode, bool final) {
std::vector<std::string> out;
std::string& s = *pending;
auto push = [&](std::string u) {
if (says_something(u)) out.push_back(std::move(u));
};
size_t start = 0;
if (mode != TextSplit::None) {
size_t i = 0;
while (i < s.size()) {
size_t n = 1;
const uint32_t c = cp_at(s, i, &n);
const bool term = ends_sentence(c) || (mode == TextSplit::Clause && ends_clause(c));
if (!term) { i += n; continue; }
/* The punctuation run: further stops and closing quotes or brackets. */
size_t j = i + n;
while (j < s.size()) {
size_t m = 1;
const uint32_t d = cp_at(s, j, &m);
if (!(ends_sentence(d) || ends_clause(d) || closes(d))) break;
j += m;
}
if (j == s.size()) {
/* Whether the unit ended shows only in what comes next. */
if (!final) break;
i = j;
continue;
}
size_t m = 1;
const uint32_t next = cp_at(s, j, &m);
const bool ascii = c < 0x80;
bool boundary = ascii ? space_cp(next) : true;
if (boundary && c == '.') {
size_t w = i;
while (w > start && !std::isspace((unsigned char)s[w - 1])) --w;
boundary = !no_stop(s.substr(w, i + 1 - w));
}
if (!boundary) { i = j; continue; }
push(trim(s, start, j));
/* The next unit starts at its first character. */
while (j < s.size()) {
size_t k = 1;
if (!space_cp(cp_at(s, j, &k))) break;
j += k;
}
start = j;
i = j;
}
}
if (final) {
push(trim(s, start, s.size()));
s.clear();
} else {
s.erase(0, start);
}
return out;
}
} /* namespace server */
} /* namespace rad */
+35
View File
@@ -0,0 +1,35 @@
/* text_split.h -- text that arrives in pieces, cut into the units a speech model reads one at a
* time: sentences, or clauses (text_split.cpp).
*
* The realtime speech session (speech_stream.cpp) is sent text as a client produces it, a language
* model's tokens or a typist's keystrokes, and speaks each unit as soon as it is complete, so the
* first audio does not wait for the whole text. A unit is complete once the text after its closing
* punctuation shows that it ended; the end of the input ends the last one.
*/
#pragma once
#include <string>
#include <vector>
namespace rad {
namespace server {
enum class TextSplit {
None, /* no cutting: the whole input is one unit */
Sentence, /* after . ! ? and their CJK, Indic and Arabic forms */
Clause, /* also after , ; and their full-width and Arabic forms */
};
/* The complete units at the front of `*pending`, trimmed, in order; `*pending` keeps the rest.
* With `final` (the input has ended) the rest is a unit too and `*pending` is left empty.
*
* A unit ends at its closing punctuation together with any run of punctuation and closing quotes
* or brackets after it ("Really?!", "he said.”"). After ASCII punctuation the end needs
* whitespace to follow, so "3.14" and "a.b" do not end one; after full-width, CJK, Indic or Arabic
* punctuation any next character does, since those scripts put no space there. A full stop after a
* common abbreviation (Dr., Mr., e.g., etc.) or an initial (J., J.R.) ends nothing. A unit with
* nothing to say (only punctuation) is dropped. */
std::vector<std::string> take_text_units(std::string* pending, TextSplit mode, bool final);
} /* namespace server */
} /* namespace rad */
+621
View File
@@ -0,0 +1,621 @@
/* videos.cpp -- OpenAI's video endpoints over a video generator (core/gen/video_driver.h): a video
* and its soundtrack from a prompt.
*
* A video takes minutes, so it is a job, as OpenAI's API has it: POST /v1/videos queues one and
* answers with the video object at once, GET /v1/videos/{id} reports its status and progress, and
* GET /v1/videos/{id}/content downloads the MP4 once it is completed (`variant` thumbnail gives
* the first frame as WebP). GET /v1/videos lists the jobs, newest first, and DELETE removes one,
* cancelling it when it is still running. A finished video is kept for `video_ttl_s` seconds
* (`expires_at`), at most `max_videos` of them.
*
* The request takes OpenAI's fields (`prompt`, `model`, `seconds`, `size`) as JSON or as a
* multipart form, and SGLang's for the same model: `task` (t2va), `target` {`short_edge`,
* `aspect_ratio`, `duration_seconds`}, `conditions` (empty), `seed`, and `num_inference_steps`.
* `size` is the frame's width x height, multiples of the model's size multiple; `aspect_ratio`
* (`w:h`) instead lays the model's own canvas over that ratio: the short edge (the model's, or
* `short_edge`), the area capped at the model's largest, both sides rounded to the multiple.
* A video's length is a whole number of the model's chunks: `seconds` is rounded up to the next.
* Nothing that conditions on media is served: `input_reference` and non-empty `conditions` are
* refused.
*
* The prompt is the model's template with `{prompt}` filled; the template is tokenised with its
* special tokens and the prompt without, so a caller cannot write control tokens into it.
*/
#include "server.h"
#include "oai.h"
#include "gen/video.h"
#include "mm/media.h"
#include "mm/mp4.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <ctime>
#include <random>
#include <thread>
namespace rad {
namespace server {
struct Server::VideoJob {
std::string id, model, prompt, seconds, size;
int64_t created_at = 0;
uint64_t seed = 0;
std::shared_ptr<gen::VideoTicket> ticket;
std::thread worker;
/* Under Server::videos_m_ from here on. */
std::string status = "queued";
int progress = 0;
int64_t completed_at = 0, expires_at = 0;
bool failed = false;
std::string err_code, err_message;
std::string mp4;
std::vector<uint8_t> first; /* the first frame, RGB, for the thumbnail */
int32_t w = 0, h = 0;
bool worker_done = false; /* its thread has nothing left to do but return */
};
namespace {
std::string new_video_id() {
static const char* hex = "0123456789abcdef";
std::random_device rd;
std::string id = "video_";
for (int i = 0; i < 32; ++i) id.push_back(hex[rd() & 15]);
return id;
}
/* "1344x768" -> (1344, 768); false for anything else. */
bool parse_size(const std::string& s, int64_t* w, int64_t* h) {
const size_t x = s.find_first_of("xX");
if (x == std::string::npos || x == 0 || x + 1 >= s.size()) return false;
char* e = nullptr;
*w = std::strtoll(s.c_str(), &e, 10);
if (e != s.c_str() + x) return false;
*h = std::strtoll(s.c_str() + x + 1, &e, 10);
return *e == '\0' && *w > 0 && *h > 0;
}
/* "16:9" -> 16/9 as two positives; false for anything else. */
bool parse_ratio(const std::string& s, double* a, double* b) {
const size_t c = s.find(':');
if (c == std::string::npos) return false;
char* e = nullptr;
*a = std::strtod(s.c_str(), &e);
if (e != s.c_str() + c) return false;
*b = std::strtod(s.c_str() + c + 1, &e);
return *e == '\0' && *a > 0 && *b > 0;
}
/* The model's canvas for a ratio: the short edge, the area capped, both sides rounded to the
* multiple (ties to even, as the reference's float round). */
void canvas_for(double rw, double rh, int64_t short_edge, int64_t max_area, int64_t mult,
int64_t* w, int64_t* h) {
const double ratio = rw / rh;
double W = ratio >= 1.0 ? short_edge * ratio : (double)short_edge;
double H = ratio >= 1.0 ? (double)short_edge : short_edge / ratio;
if (W * H > (double)max_area) {
const double sc = std::sqrt((double)max_area / (W * H));
W *= sc;
H *= sc;
}
*w = std::max<int64_t>(mult, (int64_t)std::nearbyint(W / mult) * mult);
*h = std::max<int64_t>(mult, (int64_t)std::nearbyint(H / mult) * mult);
}
} /* namespace */
HttpResponse Server::handle_video_create(const HttpRequest& req) {
if (!deps_.videos || !deps_.tok)
return error_response(err_not_implemented(
"/v1/videos requires a video generation model; this one does not make video"),
req.peer);
const VideoGenInfo& info = deps_.videos->info();
/* JSON, or a form whose fields are strings (OpenAI's clients send the create call as a form,
* since it may carry a file). */
json body = json::object();
if (!req.form.empty()) {
for (const FormPart& p : req.form) {
if (p.name == "input_reference")
return error_response(err_unsupported("input_reference", "this server makes video "
"from text only"), req.peer);
if (!p.filename.empty())
return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a file"),
req.peer);
json v = p.data;
if (p.name == "target" || p.name == "conditions") {
v = json::parse(p.data, nullptr, false);
if (v.is_discarded())
return error_response(err_bad(p.name, "expected JSON"), req.peer);
}
body[p.name] = v;
}
} else {
ApiError err;
if (parse_request_object(req.body, lim_, &body, &err) < 0)
return error_response(err, req.peer);
}
static const char* kKnown[] = {
"model", "prompt", "seconds", "size", "input_reference", "seed", "num_inference_steps",
"task", "target", "conditions", "user",
};
for (auto it = body.begin(); it != body.end(); ++it) {
bool known = false;
for (const char* k : kKnown) known = known || it.key() == k;
if (!known)
return error_response(err_bad(it.key(), "'" + it.key() + "' is not a field of "
"/v1/videos"), req.peer);
}
auto bad = [&](const char* k, const std::string& why) { return error_response(err_bad(k, why), req.peer); };
auto has = [&](const json& o, const char* k) { return o.contains(k) && !o[k].is_null(); };
/* A number, or a string holding one (a form's fields are strings). */
auto number = [&](const json& v, double* out) {
if (v.is_number()) { *out = v.get<double>(); return true; }
if (!v.is_string()) return false;
const std::string s = v.get<std::string>();
char* e = nullptr;
*out = std::strtod(s.c_str(), &e);
return !s.empty() && *e == '\0';
};
if (!has(body, "prompt") || !body["prompt"].is_string() ||
body["prompt"].get<std::string>().find_first_not_of(" \t\r\n") == std::string::npos)
return bad("prompt", "the prompt is required, as a non-empty string");
const std::string prompt = body["prompt"].get<std::string>();
if (has(body, "input_reference"))
return error_response(err_unsupported("input_reference", "this server makes video from "
"text only"), req.peer);
if (has(body, "task") && (!body["task"].is_string() || body["task"].get<std::string>() != "t2va")) {
ApiError e = err_unsupported("task", "this server makes video from text: t2va");
e.supported = { "t2va" };
return error_response(e, req.peer);
}
if (has(body, "conditions") && (!body["conditions"].is_array() || !body["conditions"].empty()))
return error_response(err_unsupported("conditions", "this server makes video from text "
"only; conditions must be empty"), req.peer);
json target = json::object();
if (has(body, "target")) {
if (!body["target"].is_object()) return bad("target", "expected an object");
target = body["target"];
for (auto it = target.begin(); it != target.end(); ++it)
if (it.key() != "short_edge" && it.key() != "aspect_ratio" &&
it.key() != "duration_seconds")
return bad("target", "'" + it.key() + "' is not a field of target");
}
/* ---- the size */
int64_t W = info.default_width, H = info.default_height;
const int64_t short_def = std::min(info.default_width, info.default_height);
if (has(body, "size")) {
if (!body["size"].is_string() || !parse_size(body["size"].get<std::string>(), &W, &H))
return bad("size", "expected WIDTHxHEIGHT, e.g. " + std::to_string(info.default_width) +
"x" + std::to_string(info.default_height));
if (has(target, "aspect_ratio") || has(target, "short_edge"))
return bad("size", "give size or target's aspect_ratio and short_edge, not both");
} else if (has(target, "aspect_ratio") || has(target, "short_edge")) {
double rw = (double)info.default_width, rh = (double)info.default_height;
if (has(target, "aspect_ratio")) {
if (!target["aspect_ratio"].is_string())
return bad("target", "aspect_ratio is a string, w:h or auto");
const std::string ar = target["aspect_ratio"].get<std::string>();
if (ar != "auto" && !parse_ratio(ar, &rw, &rh))
return bad("target", "aspect_ratio must be w:h (16:9) or auto");
}
int64_t se = short_def;
if (has(target, "short_edge")) {
double v = 0;
if (!number(target["short_edge"], &v) || v < 1 || v != std::floor(v))
return bad("target", "short_edge must be a positive whole number of pixels");
se = (int64_t)v;
}
if (std::max(rw, rh) > (double)info.max_aspect * std::min(rw, rh))
return bad("target", "the aspect ratio may be at most " +
std::to_string(info.max_aspect) + ":1 either way");
canvas_for(rw, rh, se, info.max_area, info.size_multiple, &W, &H);
}
if (W % info.size_multiple || H % info.size_multiple || W < info.min_side ||
H < info.min_side || W * H > info.max_area ||
std::max(W, H) > info.max_aspect * std::min(W, H)) {
int64_t sw = 0, sh = 0;
canvas_for((double)W, (double)H, short_def, info.max_area, info.size_multiple, &sw, &sh);
return bad("size", std::to_string(W) + "x" + std::to_string(H) + " is not a size this "
"model makes: sides are multiples of " + std::to_string(info.size_multiple) +
" from " + std::to_string(info.min_side) + ", at most " +
std::to_string(info.max_area) + " pixels and " +
std::to_string(info.max_aspect) + ":1; its canvas at that ratio is " +
std::to_string(sw) + "x" + std::to_string(sh));
}
/* ---- the length, in whole chunks */
const double fps = (double)info.fps_num / (double)info.fps_den;
const double min_s = (double)(info.frames_per_chunk * info.min_chunks + info.frames_tail) / fps;
const double max_s = (double)(info.frames_per_chunk * info.max_chunks + info.frames_tail) / fps;
int64_t chunks = info.default_chunks;
const bool has_sec = has(body, "seconds"), has_dur = has(target, "duration_seconds");
if (has_sec && has_dur)
return bad("seconds", "give seconds or target's duration_seconds, not both");
if (has_sec || has_dur) {
double sec = 0;
if (!number(has_sec ? body["seconds"] : target["duration_seconds"], &sec) || !(sec > 0))
return bad(has_sec ? "seconds" : "target", "the length is a positive number of seconds");
const int64_t want = (int64_t)std::ceil(sec * fps - 1e-9);
chunks = std::max<int64_t>(info.min_chunks,
(want - info.frames_tail + info.frames_per_chunk - 1) /
info.frames_per_chunk);
if (chunks > info.max_chunks)
return bad(has_sec ? "seconds" : "target",
"this model makes " + rad::fmt("%.2f", min_s) + " to " +
rad::fmt("%.2f", max_s) + " seconds");
}
const int64_t frames = info.frames_per_chunk * chunks + info.frames_tail;
std::unique_ptr<gen::VideoRequest> r = std::make_unique<gen::VideoRequest>();
r->width = (int32_t)W;
r->height = (int32_t)H;
r->chunks = (int32_t)chunks;
if (has(body, "num_inference_steps")) {
double v = 0;
if (info.fixed_steps && (!number(body["num_inference_steps"], &v) ||
v != (double)info.max_steps))
return bad("num_inference_steps",
"this model runs the schedule it was trained on: " +
std::to_string(info.max_steps) + " sigma grid points, the last one 0");
if (!number(body["num_inference_steps"], &v) || v != std::floor(v) || v < 2 ||
v > (double)info.max_steps)
return bad("num_inference_steps", "expected an integer in 2.." +
std::to_string(info.max_steps) +
" (sigma grid points, the last one 0)");
r->steps = (int32_t)v;
}
bool seed_given = false;
if (has(body, "seed")) {
double v = 0;
if (!number(body["seed"], &v) || v != std::floor(v)) return bad("seed", "expected an integer");
r->seed = (uint64_t)(int64_t)v;
seed_given = v != -1;
}
if (!seed_given) {
/* 53 bits, as the other generators choose one: JavaScript reads a number as a double. */
std::random_device rd;
r->seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1);
}
/* ---- the prompt: the template's text with special tokens, the prompt without */
{
static const std::string kSlot = "{prompt}";
const std::string& t = info.tmpl;
const size_t p = t.find(kSlot);
auto put = [&](const std::string& s, bool special) {
if (s.empty()) return;
const auto ids = deps_.tok->encode(s, false, special);
r->tokens.insert(r->tokens.end(), ids.begin(), ids.end());
};
put(t.substr(0, p), true);
put(prompt, false);
put(t.substr(p + kSlot.size()), true);
if ((int64_t)r->tokens.size() > info.max_text)
return bad("prompt", "the prompt is " + std::to_string(r->tokens.size()) +
" tokens; this model takes at most " +
std::to_string(info.max_text));
}
/* ---- admitted and queued: the job holds its place until its file is written */
if (auto no = admit(1, req.peer)) return *no;
auto j = std::make_shared<VideoJob>();
j->id = new_video_id();
j->model = opt_.model_id;
j->prompt = prompt;
j->seconds = rad::fmt("%.2f", (double)frames / fps);
j->size = std::to_string(W) + "x" + std::to_string(H);
j->created_at = unix_now();
j->seed = r->seed;
j->ticket = std::make_shared<gen::VideoTicket>();
r->ticket = j->ticket;
const int64_t n_tok = (int64_t)r->tokens.size();
const int32_t steps = r->steps;
{
std::string w;
const int s = deps_.videos->submit(std::move(r), &w);
if (s < 0) {
release(1);
ApiError e = err_bad("", w.empty() ? std::string(rad_strerror(s)) : w);
if (s != RAD_E_INVAL) { e.status = 503; e.type = "server_error"; }
return error_response(e, req.peer);
}
}
RAD_INFO("video %s: %s, %lld frames (%s s), %lld prompt tokens, %d steps, seed=%llu",
j->id.c_str(), j->size.c_str(), (long long)frames, j->seconds.c_str(),
(long long)n_tok, steps > 0 ? steps : (int)j->ticket->steps,
(unsigned long long)j->seed);
std::lock_guard<std::mutex> lk(videos_m_);
sweep_videos_locked(unix_now());
videos_.push_back(j);
j->worker = std::thread([this, j] { video_work(j); });
return HttpResponse::json_body(200, json_dump(video_json(*j)));
}
/* The job's thread. Progress is the steps' share of 90, then the frames' of the last 10. */
void Server::video_work(std::shared_ptr<VideoJob> j) {
gen::VideoTicket& t = *j->ticket;
const VideoGenInfo& info = deps_.videos->info();
mm::Mp4Writer mp4;
std::string why;
int st = mp4.open(t.width, t.height, info.fps_num, info.fps_den, t.sample_rate, t.channels,
&why);
int32_t frames = 0;
bool aborted = false;
while (st >= 0) {
gen::VideoEvent e;
bool to = false;
if (!t.next(&e, 500, &to)) {
if (!to) break;
if (stopping_.load()) {
t.cancel.store(true);
aborted = true;
break;
}
continue;
}
if (e.kind == gen::VideoEvent::STEP) {
std::lock_guard<std::mutex> lk(videos_m_);
j->status = "in_progress";
j->progress = t.steps > 0 ? (int)(90LL * e.steps_done / t.steps) : 0;
} else if (e.kind == gen::VideoEvent::AUDIO) {
if (t.channels > 0)
st = mp4.add_audio(e.samples.data(), (int64_t)e.samples.size() / t.channels, &why);
} else if (e.kind == gen::VideoEvent::FRAMES) {
if (e.first == 0 && e.n > 0) {
std::lock_guard<std::mutex> lk(videos_m_);
j->first.assign(e.rgb.begin(), e.rgb.begin() + (size_t)t.width * t.height * 3);
j->w = t.width;
j->h = t.height;
}
st = mp4.add_frames(e.rgb.data(), e.n, &why);
frames += e.n;
std::lock_guard<std::mutex> lk(videos_m_);
j->progress = 90 + (t.frames > 0 ? (int)(10LL * frames / t.frames) : 0);
}
}
if (st < 0) t.cancel.store(true);
std::string file;
if (st >= 0 && !aborted && t.status() >= 0 && frames == t.frames)
st = mp4.finish(&file, &why);
release(1);
std::lock_guard<std::mutex> lk(videos_m_);
const int64_t now = unix_now();
if (st >= 0 && !aborted && t.status() >= 0 && frames == t.frames) {
j->status = "completed";
j->progress = 100;
j->completed_at = now;
j->expires_at = now + opt_.video_ttl_s;
j->mp4 = std::move(file);
RAD_INFO("video %s: completed, %.1f MB (%s), %.1f s", j->id.c_str(),
(double)j->mp4.size() / 1e6, mp4.video_encoder().c_str(),
(double)(t.t_done_ns - t.t_submit_ns) / 1e9);
} else {
j->status = "failed";
j->failed = true;
j->completed_at = now;
if (st < 0) {
j->err_code = "encoding_failed";
j->err_message = "the video could not be written: " + why;
} else if (aborted || t.status() == RAD_E_CANCELLED) {
j->err_code = "cancelled";
j->err_message = aborted ? "the server is shutting down" : "the video was cancelled";
} else {
j->err_code = t.status() == RAD_E_INVAL ? "invalid_request" : "generation_failed";
j->err_message = t.why().empty() ? std::string(rad_strerror(t.status())) : t.why();
}
RAD_WARN("video %s: failed: %s", j->id.c_str(), j->err_message.c_str());
}
j->worker_done = true;
}
void Server::sweep_videos_locked(int64_t now) {
/* Deleted jobs whose threads are done are joined. */
for (size_t i = 0; i < videos_gone_.size();) {
if (!videos_gone_[i]->worker_done) { ++i; continue; }
if (videos_gone_[i]->worker.joinable()) videos_gone_[i]->worker.join();
videos_gone_.erase(videos_gone_.begin() + (std::ptrdiff_t)i);
}
/* Expired files go first, then the oldest finished jobs past the count. A running job is
* never dropped here: it holds an admission place and its thread. */
auto drop = [&](size_t i) {
if (videos_[i]->worker.joinable()) videos_[i]->worker.join();
videos_.erase(videos_.begin() + (std::ptrdiff_t)i);
};
for (size_t i = 0; i < videos_.size();) {
const VideoJob& j = *videos_[i];
const bool done = j.status == "completed" || j.status == "failed";
if (done && j.expires_at > 0 && j.expires_at <= now) drop(i);
else if (done && j.failed && j.completed_at + opt_.video_ttl_s <= now) drop(i);
else ++i;
}
int64_t finished = 0;
for (const auto& j : videos_) finished += j->status == "completed" || j->status == "failed";
for (size_t i = 0; i < videos_.size() && finished > opt_.max_videos;) {
const VideoJob& j = *videos_[i];
if (j.status == "completed" || j.status == "failed") {
drop(i);
--finished;
} else {
++i;
}
}
}
void Server::stop_videos() {
std::vector<std::shared_ptr<VideoJob>> all;
{
std::lock_guard<std::mutex> lk(videos_m_);
all = videos_;
all.insert(all.end(), videos_gone_.begin(), videos_gone_.end());
}
for (auto& j : all) j->ticket->cancel.store(true);
for (auto& j : all)
if (j->worker.joinable()) j->worker.join();
}
/* The video object, OpenAI's shape. */
json Server::video_json(const VideoJob& j) {
json o;
o["id"] = j.id;
o["object"] = "video";
o["model"] = j.model;
o["status"] = j.status;
o["progress"] = j.progress;
o["created_at"] = j.created_at;
o["completed_at"] = j.completed_at ? json(j.completed_at) : json(nullptr);
o["expires_at"] = j.expires_at ? json(j.expires_at) : json(nullptr);
o["prompt"] = j.prompt;
o["seconds"] = j.seconds;
o["size"] = j.size;
o["seed"] = j.seed;
o["remixed_from_video_id"] = nullptr;
if (j.failed) {
json e;
e["code"] = j.err_code;
e["message"] = j.err_message;
o["error"] = e;
} else {
o["error"] = nullptr;
}
return o;
}
HttpResponse Server::handle_video_get(const HttpRequest& req) {
if (!deps_.videos)
return error_response(err_not_implemented("/v1/videos requires a video generation model"),
req.peer);
const std::string id = req.param("id");
std::lock_guard<std::mutex> lk(videos_m_);
for (const auto& j : videos_)
if (j->id == id) return HttpResponse::json_body(200, json_dump(video_json(*j)));
ApiError e = err_bad("id", "no video '" + id + "'; it may have expired");
e.status = 404;
e.type = "not_found_error";
return error_response(e, req.peer);
}
HttpResponse Server::handle_video_list(const HttpRequest& req) {
if (!deps_.videos)
return error_response(err_not_implemented("/v1/videos requires a video generation model"),
req.peer);
int64_t limit = 20;
if (auto it = req.query.find("limit"); it != req.query.end()) {
char* e = nullptr;
limit = std::strtoll(it->second.c_str(), &e, 10);
if (*e || limit < 1 || limit > 100)
return error_response(err_bad("limit", "expected an integer in 1..100"), req.peer);
}
const auto ord = req.query.find("order");
const bool asc = ord != req.query.end() && ord->second == "asc";
if (ord != req.query.end() && ord->second != "asc" && ord->second != "desc")
return error_response(err_bad("order", "expected asc or desc"), req.peer);
const auto after = req.query.find("after");
std::lock_guard<std::mutex> lk(videos_m_);
sweep_videos_locked(unix_now());
std::vector<std::shared_ptr<VideoJob>> v = videos_;
if (!asc) std::reverse(v.begin(), v.end());
size_t at = 0;
if (after != req.query.end()) {
while (at < v.size() && v[at]->id != after->second) ++at;
if (at == v.size())
return error_response(err_bad("after", "no video '" + after->second + "'"), req.peer);
++at;
}
json data = json::array();
for (size_t i = at; i < v.size() && (int64_t)data.size() < limit; ++i)
data.push_back(video_json(*v[i]));
json o;
o["object"] = "list";
o["data"] = data;
o["first_id"] = data.empty() ? json(nullptr) : data.front()["id"];
o["last_id"] = data.empty() ? json(nullptr) : data.back()["id"];
o["has_more"] = at + data.size() < v.size();
return HttpResponse::json_body(200, json_dump(o));
}
HttpResponse Server::handle_video_delete(const HttpRequest& req) {
if (!deps_.videos)
return error_response(err_not_implemented("/v1/videos requires a video generation model"),
req.peer);
const std::string id = req.param("id");
std::lock_guard<std::mutex> lk(videos_m_);
std::shared_ptr<VideoJob> j;
for (size_t i = 0; i < videos_.size(); ++i)
if (videos_[i]->id == id) {
j = videos_[i];
videos_.erase(videos_.begin() + (std::ptrdiff_t)i);
break;
}
if (!j) {
ApiError e = err_bad("id", "no video '" + id + "'");
e.status = 404;
e.type = "not_found_error";
return error_response(e, req.peer);
}
/* A running job is cancelled, and its thread ends once the driver has seen that (at its next
* pass, which may be seconds away); it is joined then. */
j->ticket->cancel.store(true);
videos_gone_.push_back(j);
sweep_videos_locked(unix_now());
json o;
o["id"] = id;
o["object"] = "video.deleted";
o["deleted"] = true;
return HttpResponse::json_body(200, json_dump(o));
}
HttpResponse Server::handle_video_content(const HttpRequest& req) {
if (!deps_.videos)
return error_response(err_not_implemented("/v1/videos requires a video generation model"),
req.peer);
const std::string id = req.param("id");
std::string variant = "video";
if (auto it = req.query.find("variant"); it != req.query.end()) variant = it->second;
if (variant != "video" && variant != "thumbnail") {
ApiError e = err_unsupported("variant", "this server gives the video or its thumbnail");
e.supported = { "video", "thumbnail" };
return error_response(e, req.peer);
}
std::lock_guard<std::mutex> lk(videos_m_);
for (const auto& j : videos_) {
if (j->id != id) continue;
if (variant == "thumbnail") {
if (j->first.empty())
return error_response(err_bad("id", "video '" + id + "' has no frames yet"),
req.peer);
std::vector<uint8_t> file;
std::string why;
if (mm::encode_image(j->first.data(), j->w, j->h, 3, "webp", 90, &file, &why) < 0)
return error_response(err_internal("the thumbnail could not be encoded: " + why),
req.peer);
HttpResponse res;
res.content_type = "image/webp";
res.body.assign((const char*)file.data(), file.size());
return res;
}
if (j->status != "completed")
return error_response(err_bad("id", "video '" + id + "' is " + j->status +
(j->failed ? ": " + j->err_message : "")),
req.peer);
HttpResponse res;
res.content_type = "video/mp4";
res.body = j->mp4;
return res;
}
ApiError e = err_bad("id", "no video '" + id + "'; it may have expired");
e.status = 404;
e.type = "not_found_error";
return error_response(e, req.peer);
}
} /* namespace server */
} /* namespace rad */
+23
View File
@@ -0,0 +1,23 @@
# breeze-tts2-bf16.recipe -- Breeze-TTS-2 served at bf16, the precision its reference runs the
# text encoder, the backbone and the depth decoder at.
#
# rad-convert <Breeze-TTS-2 directory> \
# --recipe data/recipes/breeze-tts2-bf16.recipe -o breeze-tts2-bf16.rad
#
# The directory holds the model and, in audio_tokenizer/, the codec it plays frames through; both
# are read as one checkpoint. The model ships bf16 and is kept. The depth decoder's heads are
# stored (in, out) and are transposed here. The codec ships f32: its linears and convolutions are
# cast to bf16 here, its codebooks divided by their usage first (an EMA codebook), while its norms,
# layer scales and snake parameters stay f32 -- read once a pass or less.
dep.heads.weight cast dtype=bf16
codec.*.n1.weight cast dtype=f32
codec.*.n2.weight cast dtype=f32
codec.*.ls1.weight cast dtype=f32
codec.*.ls2.weight cast dtype=f32
codec.norm.weight cast dtype=f32
codec.up*.ln.* cast dtype=f32
codec.up*.gamma cast dtype=f32
codec.*.alpha cast dtype=f32
codec.*.beta cast dtype=f32
codec.* cast dtype=bf16
+46
View File
@@ -0,0 +1,46 @@
# minimax-h3-fp8.recipe -- MiniMax-H3 (text to video and audio) with block-scaled fp8 linears.
#
# rad-convert <MiniMax-H3 pipeline directory> --recipe data/recipes/minimax-h3-fp8.recipe \
# -o minimax-h3-fp8.rad
#
# The directory needs the text-to-video-and-audio components only: text_encoder/, transformer/,
# vae/, audio_vae/, the processor or tokenizer and both scheduler folders (transformer_ref/ and
# the original-layout FL2VA/ and Ref2VA/ are not read).
#
# FastVideo's FastH3 releases (the denoiser distilled to eight steps with video sparse attention)
# take the same recipe: their text encoder and decoders are MiniMax-H3's files, so a container of
# the base model can supply them, with every transformer tensor listed as changed:
#
# rad-convert <FastH3 directory> --recipe data/recipes/minimax-h3-fp8.recipe \
# --reuse minimax-h3-fp8.rad --changed <the transformer's tensor names, "transformer." first> \
# -o fasth3-8step-fp8.rad
#
# Every linear of the text encoder's first 50 layers, of the token refiner and of the DiT's 50
# blocks, and the per-modality modulation projections, become E4M3 codes with a bf16 scale a
# 128 x 128 block, read by the fp8a8 GEMMs. What keeps the checkpoint's precision is read once a
# step or less: the embedding table, context_embedder and norm_out (bf16), the timestep MLP and the
# four patch projections (f32), every norm and bias. The video decoder's linears are cast to bf16
# from the checkpoint's f32, its norms, layer scales, biases and register tokens stay f32; the
# audio decoder stays f32 (its weight norms folded at convert).
te.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
te.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
te.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
te.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
te.blk.*.attn_norm.weight cast dtype=f32
te.blk.*.ffn_norm.weight cast dtype=f32
ref.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
ref.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
ref.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
ref.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dit.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dit.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dit.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dit.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
dit.blk.*.ada*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
vae.blk.*.attn_qkv.weight cast dtype=bf16
vae.blk.*.attn_out.weight cast dtype=bf16
vae.blk.*.ffn_up.weight cast dtype=bf16
vae.blk.*.ffn_down.weight cast dtype=bf16
vae.proj_out.* cast dtype=bf16
aud.*.weight cast dtype=f32
+18
View File
@@ -0,0 +1,18 @@
# minimax-music3-bf16.recipe -- MiniMax-Music3 served at bf16, the precision diffusers runs it at.
#
# rad-convert <MiniMax-Music3 pipeline directory> \
# --recipe data/recipes/minimax-music3-bf16.recipe -o minimax-music3-bf16.rad
#
# The language model and the depth decoder ship bf16 and are kept. The DiT, the condition encoder
# and the vocoder ship f32: their linears and convolutions are cast to bf16 here, once (the
# vocoder's weight norm folded in f32 first, rad_builder.h's RAD_MAP_WNORM), while their norms, the
# snake alphas, the Fourier projection and the layer mix stay f32 -- read once a pass or less.
dit.*.ln1.* cast dtype=f32
dit.*.ln2.* cast dtype=f32
dit.t.fourier cast dtype=f32
dit.* cast dtype=bf16
cond.mix.* cast dtype=f32
cond.* cast dtype=bf16
voc.*.alpha cast dtype=f32
voc.* cast dtype=bf16
@@ -0,0 +1,39 @@
# q38-27b-modelopt-nvfp4.recipe -- an NVIDIA ModelOpt NVFP4 release of Qwen3.8-27B (or a finetune of
# it, such as ukisai's Swift 1.5 NVFP4): FP8 attention and delta-net projections, NVFP4 MLPs and head.
#
# rad-convert <ModelOpt NVFP4 release> --recipe data/recipes/q38-27b-modelopt-nvfp4.recipe -o model.rad
#
# The release is ModelOpt's MIXED_PRECISION: the attention q, k, v and output and the delta net's
# qkv, z and output projections are FP8 with one f32 scale per tensor; the MLPs and the lm_head are
# NVFP4 (e2m1 codes, an e4m3 scale per 16 of K, times an f32 weight_scale_2 per tensor); the delta
# net's a/b projections, the norms, the embedding, the vision tower and the MTP head are bf16. Its
# static input scales are not read: activations are quantised from their own values.
#
# - The FP8 projections keep their codes. The import rule writes each tensor's scale as the
# block plane the block-fp8 GEMM reads, rounded to bf16: one factor for the whole tensor, off
# by at most 2^-8 (3.3e-3 on Swift 1.5's 208 tensors); qkv and z keep their own scales, each
# a whole number of 128-row blocks.
# - No kernel reads NVFP4, so the MLPs are made OCP-MXFP4 (`fp4_e2m1`, an e8m0 scale per 32 of
# K, the encoding and kernel of q38-27b-quark-mxfp4-df2.recipe) from their exact values. That
# rounds twice (e4m3 scales per 16 to a power of two per 32): 0.116 relative error against
# the release's NVFP4 values on Swift 1.5, and unsloth's NVFP4 release made MXFP4 this way
# scores mean KL 0.287 against the block-fp8 base, AMD's Quark MXFP4 0.206.
# `codes=fp8_e4m3 block=128x128 scale=bf16` on the two MLP rules instead keeps them within
# 0.027 of the release at 28.2 GiB of weights against 20.8.
# - The head is block fp8 from its exact NVFP4 values, as in the other 27B recipes.
# - The MTP head stays bf16 as shipped (blk.64 is its layer); it drafts through a 2-bit copy of
# the head (u2 with a u8 zero, least-squares clip search) rescored against the fp8 head.
blk.*.attn_qg.weight import block=128x128 scale=bf16
blk.*.attn_k.weight import block=128x128 scale=bf16
blk.*.attn_v.weight import block=128x128 scale=bf16
blk.*.attn_output.weight import block=128x128 scale=bf16
blk.*.ssm_inz.weight import block=128x128 scale=bf16
blk.*.ssm_out.weight import block=128x128 scale=bf16
blk.64.ffn_*.weight cast dtype=bf16
blk.*.ffn_gate_up.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
blk.*.ffn_down.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 rule=search
+27
View File
@@ -0,0 +1,27 @@
# q38-27b-w4a16.recipe -- an int4 W4A16 release of Qwen3.8-27B (or a finetune of it, such as
# ukisai's Swift 1.5 W4A16-AWQ, INT4 and W4A16-AutoRound), served at the 4-bit weights it ships.
#
# rad-convert <int4 release> --recipe data/recipes/q38-27b-w4a16.recipe -o model.rad
#
# The releases read are compressed-tensors' pack-quantized int4 in groups of 128, symmetric or
# asymmetric with a zero point per group (llm-compressor's AWQ, W4A16_ASYM), act-order none or
# `static`, and AutoRound's `auto_round:auto_gptq` export (symmetric, group 128). rad-convert
# imports each linear as it ships and the import rule writes it in the form the 4-bit GEMMs read:
# u4 codes, an f16 scale and a u4 zero point per 128 of K, a symmetric grid's codes made unsigned
# under a zero of 8. The numbers are the release's: every code and zero point as shipped, every
# f16 scale as shipped, and a bf16 scale converted to f16, which holds it exactly unless it lies
# below f16's normal range (2^-14); rad-convert reports how many it rounded.
#
# Served by the family's quantised plugin (qwen35_fp8): w4a16_asym over the input cast to f16 at
# up to 64 rows a step, w4a8i8_asym over an int8 activation with a scale per (row, 128) above.
#
# What the release keeps in bf16 stays bf16: the delta net's a/b projections, the norms, the
# embedding, the vision tower and the MTP head. Its head is made block fp8 as in the other 27B
# recipes (the widest GEMM, read every step, at half the bytes), and the MTP head drafts through a
# 2-bit copy of it (u2 with a u8 zero, least-squares clip search) whose top candidates the engine
# rescores against the fp8 head.
blk.*.weight import codes=u4 zero=u4 scale=f16
output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 rule=search
+15
View File
@@ -0,0 +1,15 @@
# Breeze-TTS-2 (BreezeBlue/Breeze-TTS-2) in bf16: speech on /v1/audio/speech, whole or streamed,
# and text spoken as it is written over the /v1/audio/speech/stream WebSocket. It runs on one card,
# RADIANCE_GPU in .env (default 0). Breeze-TTS-2 is licensed for research and non-commercial use
# only, and BreezeBlue counts hosting it as an API as commercial.
name: radiance-breeze-tts2
services:
radiance:
extends: { file: common.yaml, service: radiance }
container_name: radiance-breeze-tts2
environment:
ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}"
command: >
--model /models/breeze-tts2-bf16.rad
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
--tp 1
+13
View File
@@ -0,0 +1,13 @@
# FastVideo's FastH3 8-Step V2 (FastVideo/FastVideo-FastH3-8-Step-V2) as block fp8: MiniMax-H3
# distilled to eight steps with video sparse attention, the same /v1/videos API and host memory
# as minimax-h3.yaml, about 70 s a 1344x768 clip. It runs only its trained schedule, so a
# request's num_inference_steps may only be 9 (grid points). MiniMax-H3's license applies to it.
name: radiance-fasth3
services:
radiance:
extends: { file: common.yaml, service: radiance }
container_name: radiance-fasth3
command: >
--model /models/fasth3-8-step-v2-fp8.rad
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
--tp 2 --vision-tower-placement ram
+14
View File
@@ -0,0 +1,14 @@
# MiniMax-H3 (MiniMaxAI/MiniMax-H3) as block fp8: video with its stereo soundtrack from text, on
# OpenAI's /v1/videos, 1344x768 and 5.17 s by default, about 9 minutes a clip at its 50 steps.
# The text encoder and the modulation projections are read from pinned host memory
# (--vision-tower-placement ram), about 39 GiB of it. MiniMax-H3's license excludes use in the EU,
# the UK, the Republic of Korea and the USA.
name: radiance-minimax-h3
services:
radiance:
extends: { file: common.yaml, service: radiance }
container_name: radiance-minimax-h3
command: >
--model /models/minimax-h3-fp8.rad
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
--tp 2 --vision-tower-placement ram
+12
View File
@@ -0,0 +1,12 @@
# MiniMax-Music3 (MiniMaxAI/MiniMax-Music3) in bf16: songs from lyrics (`input`) and a description
# (`instructions`) on /v1/audio/speech, 44.1 kHz stereo, whole or streamed as they are made, at about
# the speed they play on two cards.
name: radiance-minimax-music3
services:
radiance:
extends: { file: common.yaml, service: radiance }
container_name: radiance-minimax-music3
command: >
--model /models/minimax-music3-bf16.rad
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
--tp 2
+258
View File
@@ -19,6 +19,9 @@ plugin claims.
| `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint (the 26B-A4B MoE and the dense sizes without per-layer embeddings) with z-lab's DFlash drafter; routed experts bf16 or block fp8 |
| `arch/qwenimage21` | `qwenimage21` | *(empty)* | Qwen-Image 2.1 and 2.1-Turbo, an image generator, from the diffusers pipeline directory; DiT and text encoder bf16 or block fp8 |
| `arch/qwen3asr_bf16` | `qwen3asr` | *(empty)* | Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder, speech to text |
| `arch/minimaxmusic3` | `minimaxmusic3` | *(empty)* | MiniMax-Music3, songs from a description and lyrics: a Qwen3-8B frame model, a depth decoder, a flow-matching DiT and a DAC vocoder, from the diffusers pipeline directory, bf16 |
| `arch/breeze` | `breeze` | *(empty)* | Breeze-TTS-2, speech from text and a description of the voice: a T5Gemma 2 text encoder, a Qwen3 backbone with a 16-codebook depth decoder and the Qwen3-TTS 12 Hz codec, from the release directory, bf16, one card |
| `arch/minimaxh3` | `minimaxh3` | *(empty)* | MiniMax-H3, a video with its stereo soundtrack from text: Qwen3-VL-32B's language model as the text encoder, a 33B single-stream diffusion transformer, a tiled ViT video decoder and a BigVGAN audio decoder, from the diffusers pipeline directory; linears block fp8 (`data/recipes/minimax-h3-fp8.recipe`) |
The traps below are readings that are wrong without any error: the model produces fluent output.
@@ -640,3 +643,258 @@ clips at their pauses (docs/GUIDE.md §5.14). Against transformers on LibriSpeec
test-other clips, the encoder's rows are within 1.1-1.3% relative L2 of the bf16 reference's; on
the one clip where they differed by 5%, the reference itself was 5.3% from a float32 run of the
same model and this engine 0.8%. The transcripts match word for word.
---
# `minimaxmusic3`: MiniMax-Music3, songs
`arch/minimaxmusic3` declares an audio generator (`rad_declare_audio_generator`), which makes the
program a four-pass one the engine drives through `core/gen/audio_driver.h`: PROMPT runs the
language model over prompt chunks, FRAME samples one frame of every song in flight and runs the
language model over its embedding, WINDOW steps the denoiser over a window of frames, VOCODE plays
a finished window. A song is a lane; up to four are made at once. It is served on
`/v1/audio/speech` ([GUIDE §5.15](GUIDE.md)), bf16 on one card or two. The checkpoint is the
diffusers pipeline directory, read as one.
```
LM Qwen3-8B with its embedding and head adapted to music codes: 36 layers of 4096 (32 x 128,
8 kv heads), theta 1e6. Two branches a song, conditional and unconditional. Each frame's
first code: one of 16384 semantic codes (ids 151675..) or the end of the song (151670),
from u + 1.5 (c - u); the candidates are the top 50 of c, of which the top 50 of the
guided logits are drawn
depth 4 layers of 4096, 16 heads of 256, SwiGLU 6144, learned positions: the frame's other
seven codes (1024 each) one at a time, each with the same guidance, the sequence
recomputed whole at every step. The next LM input is the eight codes' embeddings summed,
times 8^-0.5
cond the frame's hidden planes mixed by softmax(learned logits), scaled; a window's rows
through a 3-tap conv to 2048 channels, resampled nearest to 441/128 latents a frame
DiT 36 layers of 2048 (32 x 64), LayerNorm with affine, SwiGLU 16384 with biases, RoPE over
the first 32 of 64 dims; input [latent 128 | zeros 128 | cond 2048] plus a 1x1-conv
residual, the timestep token prepended, non-causal. 30 Euler steps at t = i / 30,
guidance 1.7 against an all-zero conditioning
windows 200 frames, a new one every 100; each binds its first 172 latents to its predecessor's
vocoder DAC's decoder: the latent's two 64-channel halves as two streams (left, right), four
transposed convolutions (8, 8, 4, 2), dilated residual units with snake; 512 samples a
latent, 44.1 kHz stereo
```
Traps:
- **The randomness is radiance's.** Each pick draws `rad_philox_uniform_s(seed, 2^32 + frame,
sub-step)` by inverse CDF in descending guided logit (ties to the lower index), and window k's
noise is `rad_philox_normal_s(seed, 1 + k, row * 128 + c)` (`abi/rad_philox.h`). Parity against
diffusers means handing diffusers the same picks and noise, which a NumPy port of the streams
does.
- **The unconditional prompt is the conditional one with its middle blanked**: its first token and
last two kept, every token between them the filler 151654, so both branches have one length.
An empty or shortened prompt is a different guidance and still sings.
- **The first frame after the prompt is consumed, not played**: it only moves the language model
past the prompt, and no conditioning row is stored for it.
- **The DiT's positions start at the timestep token**: position 0 is that token and the latents
follow from 1. Starting the latents at 0 shifts every rotation by one and the song still plays.
- **A window's join runs in one order**: its head is set from the previous window's kept tail
first, and only then is the next window's tail taken from the joined latent. The other order
binds a window to its own tail, and the song drops in level for a moment at every join.
- **The model card says 32 kHz; the vocoder plays 44.1 kHz** (512 samples a latent), as diffusers'
port and its config do.
- **Under tensor parallelism, a fused projection's stacked bias is cut per part**: a rank-1
`[value | gate]` vector holds its share of each half, as the matrix it goes with does. A
contiguous slice of the stack runs and is 5-6% off in every DiT velocity.
Against diffusers' own pipeline in bf16, from the same picks and noise: with radiance's codes
teacher-forced into the reference, the language model's last hidden row is 1.55% from the
reference's (relative L2; the reference is 1.27% from itself across bf16 and f32), the window
conditioning 1.33% (1.10%), a DiT step's velocity 1.3% (1.8%). At one card a 4 s song is 29.0 dB
SNR from the reference's audio, against 28.7 dB between the reference's own attention kernels; at
two cards a 12 s song of two windows is 26.3 dB (32.0), and the 4 s song 20.8 dB, one passage of it
having taken another turn, which a rounding-level change makes in the reference too. A pick is chaotic: with the same history,
the reference and radiance choose differently at 318 of 808 sub-steps, and the reference chooses
differently from itself across precisions at 314.
---
# `breeze`: Breeze-TTS-2, speech
`arch/breeze` declares an audio generator in its chunked form (`rad_declare_audio_generator` with
`voc_chunk`): PROMPT runs the text encoder and the backbone over both branches' whole prompts,
FRAME samples one frame of every speech in flight and runs the backbone over its embedding, VOCODE
plays a lane's newest frames, four at most, as soon as they are made. It is served on
`/v1/audio/speech` and `/v1/audio/speech/stream` ([GUIDE §5.15](GUIDE.md)), bf16 on one card. The
checkpoint is the release directory; its codec, in `audio_tokenizer/`, is read with it.
```
text T5Gemma 2's text encoder in Gemma 3 1B's shape: 26 layers of 1152, 4 query heads over one
KV head of 256 (q/k RMS-normed, scale 1/16), sandwich RMS norms with a (1 + w) gain,
gelu-tanh GLU 6912, the embedding times 34.0 (bf16 of sqrt 1152). BIDIRECTIONAL over the
whole prompt: sliding layers see 255 keys behind and 256 ahead (theta 1e4); layers 5,
11, 17 and 23 see everything (theta 1e6, positions divided by 8). Final norm, then
1152 -> 2048
backbone Qwen3: 28 layers of 2048, 16 heads over 8 KV heads of 128, q/k norms, theta 1e6, eps
1e-6. Its prompt rows ARE the encoder's projection; a frame's input is the bf16 of the
f32 sum of its 16 codes' rows of one table [16 x 2051, 2048]. Head 2052: 2048 codes,
three never drawn, the end of the speech
depth 12 layers of 1024, 8 heads over 2 KV heads of 128, Llama 3's rotary (theta 5e5, factor
32, original length 16, low 1/512, high 1/128), no q/k norms: position 0 is the
backbone's hidden state, position p code p - 1's row of the table, both through one
2048 -> 1024 projection; 15 heads, one a codebook
sampling u + g (c - u) against an unconditional prompt without the voice description (g 1, the
default: none); top 50 at temperature 0.9; the first code also takes a repetition penalty
of 1.1 over the speech's earlier first codes
codec the Qwen3-TTS 12 Hz tokenizer's decoder: EMA codebooks (the first code's, the other
fifteen's) projected 256 -> 512 and summed; a causal conv k3 to 1024; 8 layers of 512
(16 heads of 64, rotary at the frame's index, causal over 72 frames, layer scales);
twice a transposed conv k2 s2 and a ConvNeXt block (causal depthwise k7, LayerNorm,
exact GELU over 4096); a causal conv k7 to 1536; four blocks of SnakeBeta, a causal
transposed conv (8, 5, 4, 3) and three residual units (dilations 1, 3, 9); SnakeBeta and
a conv k7 to one channel: 1920 samples a frame, 24 kHz mono
```
Traps (each still speaks, wrongly):
- **The backbone's configuration is `backbone_config`.** The top level's Llama 3 rotary at theta
5e5 and eps 1e-5 belong to a native backbone the release does not build; the Qwen3 backbone runs
at theta 1e6 and eps 1e-6.
- **The backbone never embeds text.** Every prompt row is the encoder's output projected; the
checkpoint's `embed_text_tokens` (0.5B parameters) is unused, and so is the Mimi codec in the
main file.
- **The encoder reads the whole prompt at once**, so a prompt is never split across passes
(`prompt_whole`), and its sliding window is lopsided: transformers' mask at 512 sees 255 keys
behind and 256 ahead. A symmetric window differs on prompts over 256 tokens.
- **The depth heads are stored (in, out)**, `[15, 1024, 2051]`, and are transposed at convert
(`RAD_MAP_TRANSPOSE`); the codec's codebooks are EMA sums, divided by their usage at convert
(`RAD_MAP_EMA`).
- **A frame's sixteen embeddings are summed in f32 and rounded once**, as torch sums a bf16 tensor;
rounding after each would move every backbone input.
- **The codec's first two transposed convolutions have a kernel of one stride**, the four after
them of two, all causal: the full output's last rows dropped, no padding in front.
- **The reference's streaming codec is not a reference.** Its 72-slot KV ring shifts with an
overlapping in-place copy that races on the GPU: three identical decodes agree at 20-26 dB.
Compare against the offline decode, which radiance's chunks reproduce: every codec layer is
causal, so a chunk decoded again over the 85 frames its outputs reach back to is exact. The
reference's own codec decoded on radiance's schedule is 117 dB from its whole decode (f32
rounding); with 60 frames of context it is 30 dB.
Against BreezeBlue's eager reference in bf16, teacher-forced with radiance's codes (a CPU run):
the backbone's hidden rows are 1.04% from the reference's (relative L2, median over the prompt and
72 frames; the reference is 0.94% from itself across bf16 and f32). The reference would have drawn
another code at 323 of 1168 picks, all near-ties: the code radiance drew had a median 0.998 of
the reference's own pick's probability, and the first code differed once in 73 frames. Through
the codec alone, radiance's bf16 audio is 38.4 dB SNR from the reference's f32 decode of the same
codes. Whisper large-v3 transcribes radiance's speech word for word.
---
# `minimaxh3`: MiniMax-H3, video with sound
`arch/minimaxh3` declares a video generator (`rad_declare_video_generator`), which makes the
program a four-pass one the engine drives through `core/gen/video_driver.h`: VCOND runs the text
encoder and the refiner over the prompt and computes every step's modulation, VSTEP is one
denoising step of one request's packed sequence, ADECODE plays the soundtrack, VDECODE decodes
one temporal chunk of frames. A request is a lane; two hold state at once (one denoising, one
conditioned and waiting). It is served on `/v1/videos` ([GUIDE §5.16](GUIDE.md)), block fp8 on two
cards with `--vision-tower-placement ram`. The checkpoint is the diffusers pipeline directory,
read as one; only workflow t2va is served.
```
text Qwen3-VL-32B's language model: 64 layers of 5120 (64 q / 8 kv heads of 128, ff 25600,
eps 1e-6, theta 5e6, interleaved M-RoPE, which is NeoX for text). The conditioning is
the hidden state AFTER LAYER 50, before any norm; layers 50..63 are never read and the
container leaves them out. The prompt is tokenised as written, no template, no special
tokens
refiner context_embedder 5120 -> 5376 (bias), two plain pre-norm blocks over the prompt (full
attention, no rotary, q/k RMS norms), a final RMSNorm
DiT 50 blocks of 5376 (56 heads of 128), SwiGLU 14336, RMSNorm eps 1e-5, no biases, one
packed sequence [text | soundtrack ch0 | soundtrack ch1 | video] under full attention.
Each row is modulated by its modality (0 video, 1 text, 2 audio) at its timestep (text
rows take the video's): six vectors a block from Linear(silu(temb), 3 x 6 x 5376).
norm_out's shift and scale are per timestep. Video latents 24 channels in 1x2x2 patches
(96 values a row, proj_in f32), the soundtrack's 32 channels a row (f32). Guidance-
distilled: one forward a step
rotary 3 axes (time, row, column), 16 frequencies each (theta 1e4) over the first 96 of 128
dims, rotate-half pairs (i, i + 48); f32 positions
schedule per modality: sigma = s x / (1 + (s - 1) x) over linspace(1, 0, N) (N grid points, N - 1
evaluations), shift 12 for the video and 3 for the soundtrack; t = 1 - sigma; x0 =
x + (1 - t) v, then x' = r x + (1 - r) x0 with r = sigma_next / sigma
video ViT decoder, 36 layers of 2048 (32 heads of 64), f32 residual, RMSNorm, q/k RMS norms
VAE without weights, rotary 8/8/8 over 48 of 64 dims (theta 100, angles 2 pi (2 (i + .5) /
n - 1)), layer scales, SwiGLU 8192 with biases, 4 registers and a zero token a tile.
A token is a latent: 4 frames x 16 x 16 pixels. Tiles of 16 x 16 latents, overlap 4 at
least; chunks of 7 latent frames every 5. Pixels come out ImageNet-normalised
audio dec_in_proj 32 -> 2048, BigVGAN: conv_pre k7 to 1024, 7 transposed convolutions (5 5 2 2
VAE 2 2 2), each followed by the mean of three AMP blocks (k 3/7/11, dilations 1/3/5) with
anti-aliased SnakeBeta (x2 up, x2 down, 12-tap Kaiser filters); conv_post k7 to one
channel, clamped. 800 samples a latent, 32 kHz, each stereo channel its own sequence
length 24 fps; a video of n chunks is 17 n + 5 frames over 5 n + 2 latent frames, n 7..20
(5.17 to 14.4 s); the soundtrack is round-half-even(frames x 40 / 24) latents a channel
```
Traps:
- **The feed-forward's value half comes first** in the checkpoint (`[value | gate]`, out =
`value * silu(gate)`), in the DiT, the refiner and the video decoder alike. The halves are
swapped at convert into the `[gate | value]` that `silu_mul` reads.
- **The modulation gate has no tanh**, and the residual is `h += gate * branch`. The timestep
embedding reads t in [0, 1] as it is, not scaled to 1000.
- **The grid's second half is linspace's from the end**: torch computes `linspace(1, 0, N)` half
from each end in f32, which `gen::video_schedule` reproduces.
- **The packed rows' positions are f64 rounded to f32**: a latent frame spans 5/3 x (1, 4, 4, 4,
4)[i mod 5] time units from `n_text`, the spatial axes are each side's latents over the square
root of the frame's area, centred on the unit interval, times 32, and the soundtrack's two
channels sit at the two ends of the width axis.
- **A tile is blended with its neighbours as they were decoded**: the vertical blend reads the
original tile above, and the horizontal blend the original tile to the left, not the blended
ones. Chunks keep frames [3, 20) of their 28 and blend their last 5 linearly into the next
chunk's first 5.
Tensor parallel: the text encoder, refiner and DiT blocks split by heads and feed-forward width.
A block's three modulation projections split by rows, three of the six vectors a rank, and
VCOND writes every step's modulation into the lane once a request, so the 13B modulation
parameters and the text encoder (RAD_ACCESS_PER_REQUEST) live in pinned host memory under
`--vision-tower-placement ram`. Each step gathers its row of the table across the ranks. The video
decoder is replicated and splits its tiles between the ranks, gathering the decoded pixels; the
audio decoder runs whole on each.
Against diffusers' pipeline in bf16 from the same noise, a 256 x 256 clip of 4 grid points: the
fp8 text encoder's conditioning is 4.15% from the reference's (relative L2). With radiance's
conditioning given to both, the first evaluation's velocity is 5.4% (video) and 4.3% (soundtrack)
from the reference's, at slope 0.99 and cosine 0.9985; the reference itself, with radiance's
block-fp8 rounding emulated on the same linears, is 6.8% and 4.6% from its own bf16 and shows the
same per-channel bias. Fed the same latents, the video decoder is 36.9 dB PSNR from the
reference's frames (H.264 included) and the audio decoder 51.0 dB SNR from its samples. The same
seed gives the same latents, run to run.
Attention precision: the DiT's attention takes its scores in int8 (the keys quantised per row and
head by `quant_act_i8g`, the query inside the op) and its P.V in fp8 (the values quantised per
column by `quant_cols_fp8`, the weights `e4m3(448 p)` against an exactly tracked row max), so both
halves run on the 8-bit matrix instruction. Along an exact trajectory in diffusers (256 x 256), the
int8 scores move the velocity 1.9-5.9% and the fp8 P.V another 1-3 points, where exact f32
softmax and SDPA's bf16 flash kernel already differ by 1.7-4.4%; finished clips keep their shot,
motion and detail.
## FastH3: eight trained steps with video sparse attention
FastVideo's FastH3 releases (FastVideo/FastVideo-FastH3-8-Step-V2) are the same denoiser distilled
(DMD2) to eight evaluations with video sparse attention, and name both in their
`fastvideo_inference.json`, which the converter reads under `fastvideo_inference.` keys. The
plugin takes from it:
```
schedule the trained timesteps 999 874 749 624 500 375 250 125 over a 1000-step clock, each
shifted per modality (10 for the video, checked against scheduler_config.json, 3 for the
soundtrack), then 0: nine grid points, eight evaluations, no other count
(RadVideoGenDecl::rungs)
attention VIDEO_SPARSE_ATTN_H3 at sparsity 0.8 and 64-row tiles: the prompt's and the
soundtrack's rows in 64-row chunks of their own (dense: their queries see every key, and
every query sees them), the video's patches in 4 x 4 x 4 boxes of (time, row, column);
a video query tile keeps the ceil(0.2 V) video tiles of best mean-q . mean-k score, per
head. A fourth projection beside q, k and v (attn.to_gate_compress, appended to the
fused qkv) gates in an attention over the tiles' means: vsa_select, then attn_vsa
(docs/OPS.md)
name served as `fastvideo-fasth3-8-step-v2`
```
Its text encoder and both decoders are MiniMax-H3's files byte for byte, so a container of the base
model supplies them (`--reuse`, the transformer's tensors listed as `--changed`; see the recipe's
header). The distilled model's first evaluation moves 21-23% under any perturbation (the reference
itself between bf16 and emulated fp8, or with the fp8 text encoder's conditioning), so its per-step
numbers against the reference say little; radiance's frames and the reference's agree by eye.
+4
View File
@@ -138,6 +138,10 @@ the cards the engine runs on.
| `qwen-image-2.1.yaml` | `qwen-image-2.1-fp8.rad` | Qwen-Image 2.1 as block fp8 on two cards: OpenAI's images API, generation and edits |
| `qwen-image-2.1-turbo.yaml` | `qwen-image-2.1-turbo-fp8.rad` | Qwen-Image 2.1 Turbo, the same in 8 steps |
| `qwen3-asr-1.7b.yaml` | `Qwen3-ASR-1.7B-hf/` (the checkpoint) | Qwen3-ASR 1.7B: `/v1/audio/transcriptions` and live `/v1/realtime`, on one card (`RADIANCE_GPU`) |
| `minimax-h3.yaml` | `minimax-h3-fp8.rad` | MiniMax-H3 as block fp8: video with its stereo soundtrack on `/v1/videos`, two cards and about 39 GiB of pinned host memory |
| `fasth3.yaml` | `fasth3-8-step-v2-fp8.rad` | FastVideo's FastH3 8-Step V2, the same in eight steps |
| `minimax-music3.yaml` | `minimax-music3-bf16.rad` | MiniMax-Music3 in bf16: songs from lyrics and a description on `/v1/audio/speech` |
| `breeze-tts2.yaml` | `breeze-tts2-bf16.rad` | Breeze-TTS-2 in bf16: speech on `/v1/audio/speech` and live over `/v1/audio/speech/stream`, on one card (`RADIANCE_GPU`) |
The container names are the files the README's model table downloads or converts.
+273 -25
View File
@@ -276,6 +276,8 @@ and runs.
| `embgemma2` | EmbeddingGemma 2, an embedding model (§5.6) |
| `qwenimage21` | Qwen-Image 2.1 and 2.1-Turbo, an image model (§5.6) |
| `qwen3asr_bf16` | Qwen3-ASR, speech to text from the checkpoint as it ships (§5.14) |
| `minimaxmusic3` | MiniMax-Music3, songs from a description and lyrics (§5.15) |
| `breeze` | Breeze-TTS-2, speech from text and an optional description of the voice (§5.15) |
**4. Falling back to the reference library is fatal.** If any op resolves to `libref`, the engine
refuses to start and names the ops, because serving from it is orders of magnitude slower with nothing
@@ -389,6 +391,16 @@ rad-convert /srv/models/Qwen/Qwen-Image-2.1 -o qwen-image-2.1-fp8.rad \
--recipe data/recipes/qwen-image-2.1-fp8.recipe
rad-convert /srv/models/Qwen/Qwen-Image-2.1-Turbo -o qwen-image-2.1-turbo-fp8.rad \
--recipe data/recipes/qwen-image-2.1-fp8.recipe
# MiniMax-Music3, songs (§5.15): the diffusers pipeline directory is the checkpoint (language model,
# depth decoder, condition encoder, DiT, vocoder, tokenizer); bf16 throughout (21 GB, one card or two)
rad-convert /srv/models/MiniMaxAI/MiniMax-Music3 -o minimax-music3-bf16.rad \
--recipe data/recipes/minimax-music3-bf16.recipe
# Breeze-TTS-2, speech (§5.15): the release directory, its codec in audio_tokenizer/ read with it;
# bf16 (6 GB, one card)
rad-convert /srv/models/BreezeBlue/Breeze-TTS-2 -o breeze-tts2-bf16.rad \
--recipe data/recipes/breeze-tts2-bf16.recipe
```
A checkpoint directory's `model.safetensors.index.json` decides which shard each tensor is read
@@ -409,18 +421,21 @@ dequantisation where the architecture's kernels read another form, and NVFP4 alw
| `quark`, MXFP4 weights (fp4, per_group 32, e8m0) | `fp4_e2m1*e8m0[1x32]` | byte for byte: the same codes and exponents. A checkpoint of this form is also served as it stands (§3.4) |
| `paroquant_mxfp4` (z-lab's ParoQuant on the MXFP4 grid: `format mxfp4`, `mxfp4_block 32`, `group_size 128`) | `fp4_e2m1*e8m0[1x32]/givens` | the codes and exponents byte for byte, plus the learned rotation as the encoding's `givens` tables: per checkpoint tensor the Givens pairs (made whole-row columns), angles and `1 / channel_scales`, a fused gate\|up or qkv\|z carrying one set a part. Convert-time only (the tables are built, not mapped); served by the rotating activation quantiser `givens_dense_quant` and the MXFP4 GEMM (docs/OPS.md). Its fp8 heads and embedding (one f32 scale a row) are read exactly, for a recipe's `cast`/`rtn` rule |
| `paroquant`, `format int5-bitplane` (bits 5, group 128) and z-lab's plain `paroquant` (bits 4, group 128) | `u5*f16[1x128]-u8[1x128]/givens` and `u4*f16[1x128]-u8[1x128]/givens` | the AWQ-packed low nibbles (plus the fifth-bit plane) re-laid as a code bit stream along K, the f16 scales and integer zero points transposed to `[N, K/128]`, and the rotation as the `givens` tables above. Convert-time only; served by `givens_rotate` and `gemm_nt_q` at `w5a16` / `w4a16_asym` over an f16 activation (docs/OPS.md) |
| `compressed-tensors`, `format: pack-quantized` with every config group 4-bit `int` weights, `symmetric`, `strategy: group`, not `dynamic`, no `actorder` and no `input_activations` (e.g. Google's Gemma 4 QAT w4a16-ct) | `i4*<scale>[1xG]`, G the groups' one group size | `X.weight_packed` (int32 `[N, K/8]`, eight codes a word from the low bits, offset 8) made signed, beside `X.weight_scale` (`[N, K/G]`, f16, bf16 or f32) as shipped. A zero point is refused by name, and an `X.weight_shape` must state the codes' `[N, K]`. Convert-time only; `data/recipes/gemma4-31b-dense-w4a8.recipe` re-quantises the group-32 release to the group-128 grid the w4a8 kernels read |
| `auto-round` with `packing_format: auto_round:auto_gptq`, and `gptq` (v1) | `i4*bf16[1x128]` or `i8*bf16[1x128]` | the GPTQ-packed codes transposed and made signed, the f16 scales rounded to bf16. Symmetric, group 128 or a multiple of it (per channel included), no act-order. Convert-time only, because the scales are not served as shipped |
| `compressed-tensors`, `format: pack-quantized` with every config group 4-bit `int` weights, `strategy: group`, not `dynamic`, no `input_activations`, `actorder` none, `static` or `weight` (e.g. Google's Gemma 4 QAT w4a16-ct, ukisai's Swift 1.5 27B INT4) | `i4*<scale>[1xG]`, G the groups' one group size | `X.weight_packed` (int32 `[N, K/8]`, eight codes a word from the low bits, offset 8) made signed, beside `X.weight_scale` (`[N, K/G]`, f16, bf16 or f32) as shipped. Act-order `static`/`weight` keeps each group's columns together and reads as none; `group`/`dynamic` reorders the groups and is refused by name, as is an `X.weight_g_idx` that moves a column. An `X.weight_shape` must state the codes' `[N, K]`. Convert-time only; `data/recipes/gemma4-31b-dense-w4a8.recipe` re-quantises the group-32 release to the group-128 grid the w4a8 kernels read, `data/recipes/q38-27b-w4a16.recipe` serves a group-128 one at its own numbers |
| the same with `symmetric: false` (W4A16_ASYM, as llm-compressor's AWQ writes it; e.g. ukisai's Swift 1.5 27B W4A16-AWQ) | `u4*<scale>[1xG]-u4[1xG]` | the stored nibbles as the codes and `X.weight_zero_point` (int32 `[N/8, G]`, eight zero points a word along N, offset 8) as the zero plane, so `(u - z) * s` is compressed-tensors' `(q - zero_point) * scale` bit for bit |
| `auto-round` with `packing_format: auto_round:auto_gptq`, and `gptq` (v1) | `i4*bf16[1x128]` or `i8*bf16[1x128]` | the GPTQ-packed codes transposed and made signed, the f16 scales rounded to bf16 (the routed-expert GEMMs' scale). Symmetric, group 128 or a multiple of it (per channel included), no act-order. Convert-time only, because the scales are not served as shipped; an `import` rule keeps them in their shipped f16 (`data/recipes/q38-27b-w4a16.recipe`) |
| `compressed-tensors` with an `nvfp4-pack-quantized` config group (`weights`: 4-bit float, group 16) | `fp4_e2m1*f32[1x16]` | the packed e2m1 codes beside an f32 scale per 16 of K, `weight_scale / weight_global_scale`: the global scale is a divisor, as compressed-tensors' dequantise and vLLM read it. Each piece keeps its own global, so a fused gate\|up reads both exactly. No kernel serves NVFP4, so every NVFP4 weight takes a recipe rule (`data/recipes/q38-27b-nvfp4-df2.recipe` makes it MXFP4) |
| `compressed-tensors` whose config groups are all `float-quantized` with 8-bit `float` weights | `fp8_e4m3*<scale>[1x*]` or `[RxC]` | nothing is imported: each `X.weight` reads stock as FP8 with `X.weight_scale` beside it, one scale a row (`[N, 1]` or `[N]`, the channel strategy) or a block plane; a per-tensor scale is refused at the weight. The quantisation is still the tool's, so the family's quantised plugin serves it |
| `compressed-tensors` whose config groups are all `float-quantized` with 8-bit `float` weights | `fp8_e4m3*<scale>[1x*]` or `[RxC]` | nothing is imported: each `X.weight` reads stock as FP8 with `X.weight_scale` beside it, one scale a row (`[N, 1]` or `[N]`, the channel strategy) or a block plane; a per-tensor scale (`[1]`) is written once a row, so it is imported rather than byte for byte. The quantisation is still the tool's, so the family's quantised plugin serves it |
| `modelopt` (NVIDIA ModelOpt) with `quant_algo` `NVFP4`, `FP8`, or `MIXED_PRECISION` whose `quantized_layers` are each NVFP4 (group 16) or FP8 (e.g. ukisai's Swift 1.5 27B NVFP4) | NVFP4: `fp4_e2m1*f32[1x16]`; FP8: `fp8_e4m3*f32[1x*]` | NVFP4: `X.weight` (U8 `[N, K/2]`, the even k in the low nibble) beside an f32 scale per 16 of K, `float(X.weight_scale) * X.weight_scale_2`: ModelOpt's second level multiplies, where compressed-tensors' global scale divides. FP8: `X.weight` E4M3 with its one f32 `X.weight_scale`, written once a row. `X.input_scale` (a static activation scale) is not read: activations are quantised from their own values. Any other algorithm is refused by name. No kernel serves NVFP4, and none an FP8 scale per tensor, so both take recipe rules (`data/recipes/q38-27b-modelopt-nvfp4.recipe`) |
The width is read per tensor, so a release mixing int4 experts with int8 projections imports both.
A mixed-precision release (NVFP4 MLPs beside FP8 or bf16 linears, the usual NVFP4 layout) reads
every weight by its own form: a weight without `X.weight_packed` is not NVFP4 and reads stock, its
`float-quantized` FP8 with the per-row (`[N, 1]`) or block scale beside it. A compressed-tensors
release whose groups are all `float-quantized` FP8 reads the same way, with nothing to import.
What an import cannot read (an asymmetric zero point, an act-order index, a group under 128, a
missing or zero global scale, a compressed-tensors format not listed here) is refused by name. The release's `quantization_config` names the tool, not a served
What an import cannot read (a GPTQ zero point other than the symmetric one, an act-order index
that reorders groups, a GPTQ group under 128, a missing or zero global scale, a format or
algorithm not listed here) is refused by name. The release's `quantization_config` names the tool, not a served
form, so it is kept as `imported_quantization_config.*`, and the model is served by its family's
quantised plugin (`qwen35_fp8` for Qwen3.8-27B, `qwen4exp_fp8` for Flash-Next).
@@ -430,8 +445,17 @@ the source, so one recipe covers a mixed release in one pass. NVFP4 to MXFP4 rou
scales per 16 to a power of two per 32), so it loses more than MXFP4 made from the bf16 original:
against the block-fp8 Qwen3.8-27B on the same four documents, unsloth's NVFP4 release made MXFP4
scores mean KL 0.287 and top-1 agreement 87.5%, AMD's calibrated Quark MXFP4 container 0.206 and
89.3%. Prefer the Quark container unless you need that particular checkpoint. The recipes of
record:
89.3%. Prefer the Quark container unless you need that particular checkpoint.
Where the kernels read the release's own numbers in another spelling, a recipe's `import` rule
(rad-convert's own, docs/TOOLS.md) writes them so instead of quantising again. An int4 W4A16
release reaches the 4-bit GEMMs that way, `blk.*.weight import codes=u4 zero=u4 scale=f16`: u4
codes, an f16 scale and a u4 zero point per 128 of K, a symmetric grid's codes made unsigned under a
zero of 8. Every code and zero point is the release's and every scale is exact in f16 except a bf16
scale below f16's normal range (2^-14), which rounds; rad-convert reports how many did. Qwen3.8-27B
serves them on `gemm_nt_q` at `w4a16_asym` over the input cast to f16 up to 64 rows a step and at
`w4a8i8_asym` over an int8 activation with a scale per (row, 128) above (docs/OPS.md). The recipes
of record:
```sh
# AMD's Quark AWQ-MXFP4 Qwen3.8-27B with the DFlash2 drafter
@@ -451,6 +475,17 @@ rad-convert /srv/models/Launch80/Qwen3.8-27B-PARO-int5 --draft-model /srv/models
rad-convert /srv/models/unsloth/Qwen3.8-27B-NVFP4 --draft-model /srv/models/z-lab/Qwen3.8-27B-DFlash2 \
--recipe data/recipes/q38-27b-nvfp4-df2.recipe -o q38-27b-nvfp4-df2.rad
# An int4 W4A16 Qwen3.8-27B (compressed-tensors AWQ or GPTQ, AutoRound's auto_gptq; here ukisai's
# Swift 1.5 W4A16-AWQ, and its INT4 and W4A16-AutoRound the same way): the shipped grids on the
# 4-bit GEMMs, the head block fp8
rad-convert /srv/models/ukisai/Swift-1.5-Qwen3.8-27b-W4A16-AWQ \
--recipe data/recipes/q38-27b-w4a16.recipe -o swift15-27b-w4a16-awq.rad
# An NVIDIA ModelOpt NVFP4 Qwen3.8-27B (ukisai's Swift 1.5 NVFP4): the FP8 projections' codes kept
# as block fp8, the NVFP4 MLPs made MXFP4, the NVFP4 head block fp8
rad-convert /srv/models/ukisai/Swift-1.5-Qwen3.8-27b-NVFP4 \
--recipe data/recipes/q38-27b-modelopt-nvfp4.recipe -o swift15-27b-nvfp4.rad
# An AutoRound int4 Qwen3.8-Flash-Next: its experts imported, its int4 projections made int8
rad-convert /srv/models/ukisai/Swift-1.5-Qwen3.8-Flash-Next-W4A16-AutoRound \
--recipe data/recipes/qwen4exp-autoround-i8-hc8m.recipe -o swift-autoround.rad
@@ -1030,6 +1065,32 @@ hit. Snapshots never take VRAM: each is copied to host memory after the step tha
back before the step that resumes from it. `/sessions` shows what is stored, where, and whether the
linear half is served.
**How many snapshots.** The snapshot store (`--checkpoint-slots`) is shared by every conversation,
running or not, and a conversation without a snapshot under its next prompt reuses nothing. With
`auto`, the default, each of `--max-num-seqs` gets what `--checkpoint-policy` keeps for one
`--max-model-len` conversation plus one for the checkpoint its running turn writes: geometric
backoff keeps 9 for a 200K-token conversation at the default 2048-token interval, so 10 a sequence,
80 at `--max-num-seqs 8`. The store is pinned for the life of the server, so `auto` takes at most an
eighth of host memory (and never less than 8 slots where the host can pin them), and never more than
the host can pin after the host pools, the host tier and the activation arenas. The startup log says
what it chose; Flash-Next at `--tp 2 --max-num-seqs 8` on a host with 128 GB of RAM:
```
checkpoint slots: auto: 80 linear-state snapshot(s) of 113.50 MiB in pinned host memory (8.87 GiB),
none of it on the card; 10 a sequence for --max-num-seqs 8: geometric-backoff keeps 9 for a
200000-token session at a 2048-token interval, and one more for a running turn
```
A line that says `held to an eighth of host memory`, or (a warning) `held to what the host can
pin`, means the store is smaller than the policy wants; `--checkpoint-slots N` sets the count
outright. An agent client with subagents keeps more
conversations alive than it runs at once: a parent waits while its subagent runs, and in a store
much smaller than `auto`'s the subagent's snapshots displace the parent's, whose next turn then
prefills its whole history again. `radiance:prefix_hit_cut_tokens_total` counts the prompt tokens
the attention cache held and admission computed again for want of a snapshot, and
`radiance:prefix_cache_ckpt_evictions_by_reason_total{reason="store_full"}` the snapshots a full
store gave up; `scripts/agentreplay.py` drives that workload against a server.
### 4.9 Request defaults
Each default applies only to a request that does not name the field.
@@ -1136,10 +1197,13 @@ radiance --model base.rad --lora mytune=/adapters/mytune --lora other=/adapters/
```
Each request picks one by `model`: `"model": "mytune"` runs with that adapter, the served model's
own name (or no name) runs the base. Requests for different adapters and for the base share one
batch. The base weights are never touched, whatever their encoding; each targeted GEMM is followed
by `y += scale * B(A x)` in bf16 adapter weights and f32 accumulation, on every rank before the
all-reduce, so it works at any `--tp`.
own name (or no name) runs the base, and any other name is a 404 that lists what is served.
Requests for different adapters and for the base share one batch. The base weights are never
touched, whatever their encoding; each targeted GEMM is followed by `y += scale * B(A x)` in bf16
adapter weights and f32 accumulation, on every rank before the all-reduce, so it works at any
`--tp`, and on the CPU (libavx) as on a card. A step that carries no adapter request runs no adapter
op, so base requests cost what they cost without `--lora`; the one exception is the fused GEMM
below.
- `--max-loras N` reserves N slots (default: the number of `--lora`). Each slot holds one adapter's
A and B for every targeted weight; startup prints the size. With free slots, adapters load and
@@ -1156,18 +1220,21 @@ all-reduce, so it works at any `--tp`.
already on the card may still read it), which a load waits for by itself.
- `--max-lora-rank R` (default 16) is the rank every slot is sized for. A smaller rank is padded,
a larger one refused.
- `--lora-target-modules q_proj,k_proj,...` names what adapters may target. Default: what the
`--lora` adapters target. Needed with `--max-loras` and no `--lora`.
- `--lora-target-modules q_proj,k_proj,...` names what adapters may target, as module leaf names.
Default: what the `--lora` adapters target. Needed with `--max-loras` and no `--lora`. A name
that is no trunk linear of the model is refused at startup.
- `/v1/models` lists each adapter as its own model, `parent` naming the base.
- The prefix cache keys every block on the adapter, so KV is never shared across adapters, and a
reload under the same name starts cold.
Refused at startup or load, by name: DoRA, embedding or `lm_head` LoRA, `modules_to_save`, trained
biases, a module the base does not have, and a module some op cannot carry -- a routed MoE expert,
a rotated (ParoQuant) or otherwise transformed weight. A fused GEMM over a targeted weight (the fp8
gated gate_up fold) is not used while LoRA is on; the unfused pair runs instead. A drafter keeps the
base's weights: proposals are still verified by the adapter, so output is exact and only the
acceptance rate can drop.
biases, PEFT's `layer_replication`, QA-LoRA and activated LoRA, a module the base does not have, and
a module some op cannot carry -- a routed MoE expert, a rotated (ParoQuant) or otherwise transformed
weight, a GEMM fed int8 codes in the WMMA's step order (`w4a8`, `w8a8`, `w2a8`). Adapters serve models that generate text: an
image, audio or video generator and an embedding model refuse `--lora` and `--max-loras`. A fused
GEMM over a targeted weight (the fp8 gated gate_up fold) is not used while LoRA is on, for base
requests too; the unfused pair runs instead. A drafter keeps the base's weights: proposals are
still verified by the adapter, so output is exact and only the acceptance rate can drop.
### 4.10 Every flag
@@ -1229,7 +1296,7 @@ acceptance rate can drop.
| `--deterministic` | off | pin placement to the loader's plan, so the resident set cannot change under the heat engine |
| `--checkpoint-interval N` | 2048 | linear-attention state checkpoint interval, in tokens |
| `--prefill-span N` | 1 | checkpoint intervals one step may carry of a prefill alone in its step, from the prompt's second interval on; needs `--max-num-batched-tokens` of N intervals. Every other step is planned at the budget less the extra intervals, and the checkpoints inside a span are not written (§4.5) |
| `--checkpoint-slots N` | 8 | linear-state (hybrid) or sliding-window snapshots the server may hold at once, in total, not per sequence. They live in pinned host memory, allocated at startup: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`; on Gemma 4 31B the 1024-token window of every sliding layer, 406 MiB at `--tp 2`). A full store retires its least recently used snapshot. A store the host memory cannot hold or pin stops the start, and a table placed in host memory leaves room for it; `0` serves with none, every prefix hit then prefilling from the start |
| `--checkpoint-slots N` | auto | linear-state (hybrid) or sliding-window snapshots the server may hold at once, in total, not per sequence. They live in pinned host memory, allocated at startup: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`, 144 MiB on Qwen3.8-27B; on Gemma 4 31B the 1024-token window of every sliding layer, 406 MiB at `--tp 2`). `auto` gives each of `--max-num-seqs` what `--checkpoint-policy` keeps for a `--max-model-len` session plus one (10 at 200K tokens under geometric backoff), within an eighth of host memory and what the host can pin; the startup line and the report say what it chose and why (§4.8). A full store retires its least recently used snapshot. A count is taken as given: a store the host memory cannot hold or pin stops the start, and a table placed in host memory leaves room for it; `0` serves with none, every prefix hit then prefilling from the start |
| `--checkpoint-policy NAME` | geometric-backoff | also `tip-only`, `keep-all` |
| `--no-prefix-cache` | prefix cache on | disable prefix caching |
@@ -1313,6 +1380,8 @@ a model that takes no images or video. A Qwen-VL container that states none uses
| `--kld-ref DIR` | score this model against the reference in `DIR`: mean, median, 99/99.9/99.99th percentile KL divergence and top-1 agreement |
| `--kld-corpus FILE` | JSONL, one `{"prompt", "score_from"?, "source"?}` a line; `--kld-record` only |
| `--kld-out FILE` | the `--kld-ref` report as JSON, and every position's numbers in `FILE.rows` |
| `--kld-lora NAME` | run the documents through the `--lora` adapter `NAME` (§4.9.1), e.g. against a reference recorded from the merged checkpoint |
| `--kld-lora-sources PREFIX` | with `--kld-lora`, only the documents whose `source` starts with `PREFIX` run through the adapter; the rest run as the base, in the same steps |
**Diagnostics**
@@ -1341,6 +1410,9 @@ a model that takes no images or video. A Qwen-VL container that states none uses
| `POST /v1/systemone` | LiquidAI d1's decisions over a state: named yes/no, choice and score questions answered as probabilities, nothing generated; needs a container converted as d1, else 501 (§5.13) |
| `POST /v1/audio/transcriptions` | OpenAI's speech to text, for a model whose plugin transcribes (Qwen3-ASR), else 501 (§5.14) |
| `GET /v1/realtime` (WebSocket) | OpenAI's realtime transcription session: audio streamed in, the words back as they are spoken (§5.14) |
| `POST /v1/audio/speech` | OpenAI's speech API, whole or streamed: speech from a speech model (Breeze-TTS-2), `instructions` describing the voice; songs from a music model (MiniMax-Music3), `input` the lyrics and `instructions` the song; else 501 (§5.15) |
| `GET /v1/audio/speech/stream` (WebSocket) | vLLM-Omni's realtime speech session: text streamed in, each sentence's audio streamed out as soon as the sentence is complete; needs an audio generation model (§5.15) |
| `POST /v1/videos`, `GET /v1/videos[/:id[/content]]`, `DELETE /v1/videos/:id` | OpenAI's video jobs: a video with its soundtrack from a prompt, made in the background and downloaded as MP4; needs a video model (MiniMax-H3), else 501 (§5.16) |
| `POST /v1/messages`, `POST /v1/messages/count_tokens` | Anthropic's Messages API, for Claude Code and the Anthropic SDKs (§5.9, §5.11) |
| `POST /v1/responses`, `POST /v1/responses/input_tokens` | OpenAI's Responses API, for Codex and the OpenAI SDKs' `responses` client (§5.9) |
| `POST /completion`, `/completions`, `POST /infill` | llama-server's native completion and fill-in-the-middle, for llama.vim, llama.vscode and clients of llama-server's own API (§5.9) |
@@ -1363,9 +1435,10 @@ a model that takes no images or video. A Qwen-VL container that states none uses
Methods follow vLLM's: `/tokenize` is POST because its input is a body, and `/ping` answers GET and
POST because load balancers differ. As in llama-server, `/chat/completions`,
`/chat/completions/input_tokens`, `/embeddings`, `/images/generations`, `/images/edits`,
`/audio/transcriptions`, `/models`, `/responses` and `/responses/input_tokens` also answer without
`/v1`, for a client configured with the bare host as its base URL; `/completions` without `/v1` is
llama-server's native completion, as it is there. A path nothing serves is a JSON 404.
`/audio/transcriptions`, `/audio/speech`, `/models`, `/responses` and `/responses/input_tokens` also
answer without `/v1`, for a client configured with the bare host as its base URL; `/completions`
without `/v1` is llama-server's native completion, as it is there. A path nothing serves is a JSON
404.
A text prompt to `/v1/completions`, `/v1/embeddings` or `/tokenize` reads the model's control tokens
as tokens, as vLLM and llama.cpp do: a client that renders its own chat template can send
@@ -1702,7 +1775,7 @@ fall into four kinds:
| `post_sampling_probs` | false | logprobs are the raw distribution's; the sampler's are not returned |
| `best_of` | ≤ 1 | not implemented |
| `suffix` | empty | infilling through `/v1/completions` is not implemented |
| `lora` | empty | out of scope |
| `lora` | empty | an adapter is chosen by `model` (§4.9.1), not by a per-request list |
| `modalities`, `audio` | `["text"]`, null | output other than text is not implemented |
| `n_indent`, `t_max_predict_ms`, `return_tokens` | 0, ≤ 0, false | not implemented (`return_tokens` is served on `/completion`, §5.9) |
| `grammar_lazy`, `grammar_triggers`, `preserved_tokens` | off, empty, empty | the chat format decides them |
@@ -2083,6 +2156,181 @@ socket.
---
### 5.15 Speech and music: `/v1/audio/speech`
An audio generation model answers OpenAI's `POST /v1/audio/speech`: a speech model (Breeze-TTS-2)
speaks `input`, in a voice `instructions` may describe; a music model (MiniMax-Music3) sings `input`
as lyrics, as `instructions` describe the song (SGLang-Omni's reading of the route). Both are
converted from their release directories (§3.2).
#### Speech: Breeze-TTS-2
```sh
radiance --model breeze-tts2-bf16.rad # one card
curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json' -d '{
"input": "The quick brown fox jumps over the lazy dog."}' -o fox.wav # 24 kHz mono, 16-bit
curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json' -d '{
"input": "It was a bright cold day in April.",
"instructions": "A calm, warm female narrator, speaking slowly.", "guidance_scale": 4}' -o april.wav
```
- **`input`** is the text to speak, as written. **`instructions`**, optional, describe the voice
(who speaks, how); BreezeBlue suggests `guidance_scale` 4 with them, against a voice without the
description (1, the default, is none).
- **The length** is `duration` in seconds or `max_new_tokens` in frames (12.5 a second), up to two
minutes; the model ends the speech at the end of the text. The prompt holds at most 512 tokens.
- **`seed`**, **`response_format`**, **`speed`** and **`voice`** are read as for music below
(`voice` is ignored here too: the instructions say who speaks); `num_inference_steps` is refused
(the model has no denoiser). Cloning a voice from a recording is not served.
Speech is played four frames (0.32 s) at a time as it is made, so the streamed forms below carry it
as it is spoken. On one R9700 a sentence is made at 0.6 of the time it plays (5.1 s of speech in
3.1 s), and a stream's first audio comes 0.21 s after the request; four speak at once at about the
speed they play (43 s of speech in 12.1 s). Breeze-TTS-2 is licensed for research and
non-commercial use only, and BreezeBlue counts hosting it as an API as commercial.
#### Music: MiniMax-Music3
```sh
radiance --model minimax-music3-bf16.rad --tp 2
curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json' -d '{
"input": "[verse]\nMorning light filtering through the pine\n[chorus]\nSoftly the world begins to breathe",
"instructions": "Genre: acoustic pop. BPM: 96. Warm and intimate. Vocals: soft female lead.",
"duration": 30, "seed": 7}' -o song.wav # 44.1 kHz stereo, 16-bit
curl -sN http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json' -d '{
"input": "...", "instructions": "...", "stream_format": "audio",
"response_format": "pcm"}' | ffplay -nodisp -f s16le -ar 44100 -ch_layout stereo - # as made
```
- **`input`** (the lyrics, with the model's section tags such as `[verse]` and `[chorus]`) and
**`instructions`** (genre, tempo, key, mood, vocals, instruments) are both required. Each is
rewritten into the form the model was trained on and read as plain text, so neither can carry
the model's control tokens.
- **The length** is `duration` in seconds or `max_new_tokens` in frames (25 a second), up to six
minutes; without either the song runs until the model ends it, which it usually does at the end
of the lyrics. Give one, not both.
- **`seed`** makes a song repeatable: the same seed, text and length give the same samples again
on the same deployment. Another card count rounds differently, and a song can then take another
turn. Absent or -1 picks one; the `X-Seed` response header says which.
- **`num_inference_steps`** (30) and **`guidance_scale`** (1.7) are the denoiser's.
- **`response_format`** is `wav` (the default) or `pcm`, 16-bit little-endian at the model's rate
and channels, which the `X-Audio-Sample-Rate` and `X-Audio-Channels` headers state. `voice` is
accepted and ignored (the description says who sings); `speed` must be 1.
A song's first window comes once its 200 frames are written and denoised; each later one follows
a hundred frames on. On two R9700s a song is made at about the speed it plays: 10 s of audio in
10.8 s with the first audio at 8.5 s, 12 s in 12.7 s; on one card, 4 s in 7.3 s. Up to four songs
are made at once.
#### Streaming
Without a stream field the response is the whole audio once it is finished. A song is played eight
seconds at a time (a 200-frame window, a new one every 100 frames), speech four frames at a time,
and two streamed forms send each piece as it is played, as vLLM-Omni's speech route does:
- `"stream_format": "audio"` sends the bytes themselves; a `wav` stream's header states no length.
- `"stream": true` or `"stream_format": "sse"` sends Server-Sent Events: `speech.audio.delta` with
base64 PCM in `audio` (`response_format` must be `pcm`), then `speech.audio.done` with the usage
(prompt tokens in, frames out), or `speech.audio.error`.
#### Live: `/v1/audio/speech/stream`
The same model speaks text while it is still being written, over a WebSocket at
`/v1/audio/speech/stream` speaking vLLM-Omni's realtime speech protocol: the client streams the
text in (a language model's reply token by token, say), and each sentence is spoken as soon as it
is complete, so the first audio waits for the first sentence rather than the whole text.
| client sends | server answers |
|---|---|
| `session.config` — first, and again only between utterances | nothing, or `error` naming the field it refused |
| `input.text` `{"text": "..."}` — any piece of the text | for each sentence it completes: `audio.start`, the audio as binary messages, `audio.done` |
| `input.done` — the utterance's text has ended | the rest of the text as its last sentence, then `session.done` |
| `session.close` | the socket closes (1000); a sentence being spoken is cancelled |
- **`session.config`** takes the fields of `POST /v1/audio/speech` but `input` (`instructions`,
`voice`, `seed`, `guidance_scale`, `max_new_tokens` or `duration` for each sentence, `speed`,
`num_inference_steps` where the model has a denoiser), checked as that route checks them, and
four of its own: `response_format` `pcm` (the default) or `wav`; `stream_audio`, false (the
default) for one binary message a sentence or true for the audio as the model makes it;
`split_granularity`, `sentence` (the default), `clause` (also at commas and semicolons) or `none`
(the whole utterance at `input.done`); and `text_input_mode`, whose only value here is
`buffered` (vLLM-Omni's `commitment` mode is refused by name). Every sentence is one request made
with these fields; with a `seed`, every sentence uses it.
- **`audio.start`** carries `utterance_index`, `sentence_index` (from 0 in each utterance),
`sentence_text`, `format`, `sample_rate` and `channels`. The audio is 16-bit little-endian PCM at
that rate and channel count; a `wav` sentence is one file, whose header states its length, or
while it streams a header that states none before the samples. **`audio.done`** carries
`utterance_index`, `sentence_index`, `total_bytes` (of the binary messages) and `error`, true when
the sentence failed, after an `error` event saying why. **`session.done`** carries
`utterance_index` and `total_sentences`; the session then takes the next utterance.
- **Sentences** end after `.`, `!` and `?` followed by whitespace, and after their CJK (`。!?…`),
Indic (`।॥`) and Arabic (`؟`) forms followed by anything, since those scripts put no space there;
`clause` also ends one after `,` `;` and `,;،؛`. A decimal point, a common abbreviation (Dr.,
Mr., e.g., etc.) and an initial (J., J.R.) end none, and a run of punctuation or a closing quote
or bracket stays with its sentence. A stop at the end of what has arrived waits for the next
piece, or for `input.done`.
**Limits.** A server holds as many sessions as the model has lanes (four for both models), each
holding one admission place (`--max-queued-requests`) for its whole life; a session refused either
way gets an `error` event and a 1013 close. A session speaks its sentences one at a time, in order.
An utterance holds at most 128 KiB of text that no sentence has ended yet; a piece past that is
refused with an `error` and dropped. A message that is not JSON, or a binary one, is an `error`,
and the session goes on.
### 5.16 Video: `/v1/videos`
A video generation model (MiniMax-H3) answers OpenAI's video jobs: `POST /v1/videos` queues a video
with its stereo soundtrack and answers at once with the video object; `GET /v1/videos/{id}` reports
its `status` (`queued`, `in_progress`, `completed`, `failed`) and `progress` (0 to 100);
`GET /v1/videos/{id}/content` downloads the MP4 once it is completed (`?variant=thumbnail` gives the
first frame as WebP). `GET /v1/videos` lists the jobs, newest first (`limit`, `after`, `order`), and
`DELETE /v1/videos/{id}` removes one, cancelling it if it is still running.
```sh
radiance --model minimax-h3-fp8.rad --tp 2 --vision-tower-placement ram
curl -s http://localhost:8000/v1/videos -H 'Content-Type: application/json' -d '{
"prompt": "A red fox trotting through a snowy pine forest, snow crunching underfoot",
"seconds": "5", "size": "1344x768", "seed": 7}' # -> {"id": "video_...", "status": "queued", ...}
curl -s http://localhost:8000/v1/videos/video_... # poll until "status": "completed"
curl -s http://localhost:8000/v1/videos/video_.../content -o fox.mp4
```
- **`prompt`** is read as written, with no template; MiniMax-H3 was trained on long structured
descriptions (a shot, its soundscape, its music), which follow it best. At most 2048 tokens.
- **`seconds`** is rounded up to the model's length steps (17 frames, 0.71 s, at 24 frames a
second): 5.17 to 14.4 seconds, 5.17 by default. The video object's `seconds` is what is made.
- **`size`** is the frame's `WIDTHxHEIGHT`: both sides multiples of 32 from 256, at most
1344 x 768 pixels of area, at most 4:1. By default 1344x768. SGLang's `target`
`{"aspect_ratio": "9:16", "short_edge": 768, "duration_seconds": 8}` lays the model's own canvas
over a ratio instead (768 on the short side, the area capped, rounded to 32).
- **`seed`** makes a video repeatable on the same deployment (absent or -1 picks one);
**`num_inference_steps`** counts sigma grid points as diffusers and SGLang do (50, so 49 model
evaluations, by default; at most 65). The model is guidance-distilled, so there is no guidance
scale and no negative prompt. A step-distilled release (FastH3, below) runs only the schedule it
was trained on: 9 grid points, and any other count is refused with a 400.
- Only text is read: `input_reference` and non-empty `conditions` are refused, as is a `task`
other than `t2va`. Fields are JSON or a multipart form (OpenAI's clients send the form).
**FastH3.** FastVideo's FastH3 8-Step V2 (`FastVideo/FastVideo-FastH3-8-Step-V2`) is the same model
distilled to eight steps with video sparse attention; it is converted with the same recipe, its text
encoder and decoders taken from a MiniMax-H3 container (`data/recipes/minimax-h3-fp8.recipe` says
how), served the same way and named `fastvideo-fasth3-8-step-v2`. Its card notes that difficult
motion, fine detail and some audio may fall below the base model's; it serves text to video only.
On two R9700s (`--tp 2`, 300 W) a 5.17 s clip at 1344x768 takes about 68 s with FastH3 and about
8.8 minutes with MiniMax-H3's default 50 steps. Both attentions run their scores in int8 and
P.V in fp8 (docs/ARCHITECTURES.md); a step's cost grows with the square of the rows, so a longer
clip or a larger frame costs more than in proportion. The text encoder and the modulation
projections (17.9 GiB a rank) and the token embedding (1.5 GiB a rank) are read from pinned host
memory, about 39 GiB of it in all, which `--vision-tower-placement ram` requires at two ranks.
The MP4 holds H.264 video (yuv420p, BT.709) and AAC audio at 32 kHz stereo. A finished file is kept
for an hour (`expires_at`), at most 32 of them. MiniMax-H3's license excludes use in the EU, the UK,
the Republic of Korea and the USA without a separate license from MiniMax.
## 6. Operation
### 6.1 The dashboard
@@ -2265,7 +2513,7 @@ is the part of a log to paste into an issue. Its sections:
warning is also printed as a `W` line of its own.
```
I STARTUP REPORT -- radiance 1.7.0
I STARTUP REPORT -- radiance 1.8.0
I CONFIGURATION -- every option, the value in force, and where it came from
I --model /models/flashnext.rad [command line]
I --tp 2 [command line]
@@ -2310,7 +2558,7 @@ curl -s -H "Authorization: Bearer $KEY" localhost:8000/diagnostics | jq '.findin
| `out of memory` / `the carve reserved N of address space and the card would not back it` | Something else is holding VRAM | Check with `rocm-smi` and stop the other process. The budget is stated before allocation, so the log says what it asked for |
| `pool allocation refused` with `backing allocation of … refused` on the second card, after the first card's pools succeeded | The VRAM budget is measured before any rank allocates, so a card that refuses its weights pool lost that memory to another process in between (the next line says how much is free now). A refused `host_pool` is pinned memory: every rank pins its own `--host-pool-mib` (twice at `--tp 2`), and the amdgpu driver caps what all processes together pin at RAM less 1/64 and 1.5 GiB. It is locked user memory, which `ttm.pages_limit` does not count | Stop the other process (`rocm-smi --showpids`). For the host pool, keep `--tp` × `--host-pool-mib` under both the cap and the available RAM the refusal names. `amdgpu.no_system_mem_limit=1` lifts the driver's cap, but not the RAM |
| `host_pool: backing allocation of … refused: rad_dev_alloc(…): locking piece K of N`, and `failed to pin userptr` in `journalctl -k` | The IOMMU would not DMA-map one piece of the pinned host pool. Pinned host memory is locked in pieces of at most 1 GiB because an Intel VT-d host in scalable mode can refuse a single pin above about 2.5 GiB; a failing piece means this machine refuses smaller pins still, or a total its IOMMU will not map | Keep IOMMU translation on: `iommu=pt` lets every pin through, but on such a host it can also remove peer access between the cards, moving every all-reduce onto the slower host-memory path. Report the kernel version, the IOMMU mode and the refusal line |
| `device: a synchronisation has waited 5 s; the queues:` with the packet each queue is on, then `device: no queue has advanced`, then `HW Exception … GPU Hang` and a reset in `journalctl -k` (`MES failed to respond to msg=REMOVE_QUEUE`, `MODE1 reset`) | The card stopped running the queue; the kernel named is where it stopped, not necessarily why. The driver resets the whole card, VRAM included, and the engine is aborted. The usual cause is compute wave save/restore being off: the driver evicts a process's queues whenever host memory the card maps moves under memory pressure, and with `cwsr_enable=0` it cannot preempt a running queue, so the eviction waits on a queue that never drains. Clock instability (a voltage offset) is the other cause seen on R9700s. If the follow-up line says the queues advanced, the wait was long, not stuck | `cat /sys/module/amdgpu/parameters/cwsr_enable` must print `1` (the startup report warns when it is `0`); set `amdgpu.cwsr_enable=1`, rebuild the initramfs and reboot. Remove any `OD_VDDGFX_OFFSET` (`pp_od_clk_voltage`). A reset restores the power cap, fan curve and voltage offset to firmware defaults; re-apply them before every start. Keep the devcoredump under `/sys/class/drm/card*/device/devcoredump/data`, which a reboot loses. `docker inspect` shows exit code 0 for a container Docker already restarted, whatever ended the old process |
| `device: a synchronisation has seen no queue advance for 5 s; the queues:` with the packet each queue is on, then `device: no queue has advanced`, then `HW Exception … GPU Hang` and a reset in `journalctl -k` (`MES failed to respond to msg=REMOVE_QUEUE`, `MODE1 reset`) | The card stopped running the queue; the kernel named is where it stopped, not necessarily why. The driver resets the whole card, VRAM included, and the engine is aborted. The usual cause is compute wave save/restore being off: the driver evicts a process's queues whenever host memory the card maps moves under memory pressure, and with `cwsr_enable=0` it cannot preempt a running queue, so the eviction waits on a queue that never drains. Clock instability (a voltage offset) is the other cause seen on R9700s. A wait that is only long (a deep prefill, a video's denoising pass) reports nothing while any queue advances | `cat /sys/module/amdgpu/parameters/cwsr_enable` must print `1` (the startup report warns when it is `0`); set `amdgpu.cwsr_enable=1`, rebuild the initramfs and reboot. Remove any `OD_VDDGFX_OFFSET` (`pp_od_clk_voltage`). A reset restores the power cap, fan curve and voltage offset to firmware defaults; re-apply them before every start. Keep the devcoredump under `/sys/class/drm/card*/device/devcoredump/data`, which a reboot loses. `docker inspect` shows exit code 0 for a container Docker already restarted, whatever ended the old process |
| `--draft-model is not implemented` | The engine loads its drafter from the container | `rad-convert --draft-model DIR` at conversion time |
| `context_length_exceeded` on a request | The prompt alone does not fit the context. `max_tokens` is clamped rather than refused, so this fires only when there is no room left to generate | Shorten the prompt by the number of tokens the message names, or raise `--max-model-len` if the model allows it |
| `unknown option '--foo'` and the engine exits | An unknown flag is an error, so a typo in a budget flag cannot silently change the plan | Check `radiance --help` |
+371 -17
View File
@@ -193,7 +193,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c
| `layernorm` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `w`w, `b`w? → `y` |
| `grid_embed` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` |
| `grid_embed_aa` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` |
| `add` | `M`(range) `n` `dtype` | `a`, `b` → `y` |
| `add` | `M`(range) `n` `dtype` `div`:f64/opt | `a`, `b` → `y` |
| `mul` | `M`(range) `n` `dtype` | `a`, `b` → `y` |
| `silu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gate·up) |
| `mul_weight` | `M`(range) `n` `dtype` `scalar`/opt | `x`, `w`w → `y` (w one element or one row) |
@@ -204,7 +204,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c
| `clamp` | `M`(range) `n` `dtype` | `x`, `lo`w, `hi`w → `y` |
| `conv2d` | `M`(range) `width` `cin` `cout` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `dtype` `t_last`/opt `act`/opt | `x`, `w`w, `cu_seqlens`, `valid`? → `y`; `b`w? |
| `conv2d_unfold` | `M`(range) `width` `cin` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `t_last`/opt `dtype` | `x`, `cu_seqlens`, `valid`? → `y` |
| `conv1d_dw` | `M`(range) `n` `k` `cu_div`/opt `dtype` | `x`, `w`w, `cu_seqlens` → `y` |
| `conv1d_dw` | `M`(range) `n` `k` `cu_div`/opt `dtype` | `x`, `w`w, `cu_seqlens` → `y`; `b`w? |
| `rel_sinusoid` | `M`(range) `n` `max_timescale`:f64/opt `dtype` | → `y` |
| `gelu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gelu·up, tanh approx) |
| `seg_sinusoid` | `M`(range) `n` `period` `max_timescale`:f64/opt `cu_div`/opt `dtype` | `cu_seqlens` → `y` |
@@ -237,7 +237,10 @@ does it. A plugin asks for it first and falls back to `add` + `rmsnorm` (`spec.m
with the gate in the first half.
**`add` and `mul`** broadcast a `b` of exactly `n` elements along the rows of a taller output (a
bias add). Nothing else broadcasts, in these or any other elementwise op.
bias add). Nothing else broadcasts, in these or any other elementwise op. `add`'s `div` divides
the sum after its rounding, `y = rd(rd(a + b) / div)` with `rd` `y`'s dtype (absent, 1: the plain
sum): the last step of a mean summed pairwise, as a vocoder averages its residual blocks,
`add(add(b0, b1), b2, div 3)` for `(b0 + b1 + b2) / 3`. A `div` of 0 is refused.
**`sigmoid`**, with `mul`, gates a shared expert (`ffn_gate_inp_shexp`). Without it the shared
expert runs ungated, which is a different model.
@@ -326,8 +329,8 @@ is easy to miss.
With `valid`, input row `t` reads as zeros unless `valid[t * valid_stride] != 0`: the frame mask
the subsampler applies before each convolution. f32 sum, one rounding.
- **`conv1d_dw`** is a causal depthwise convolution over time,
`y[t, c] = sum_j w[c, 0, j] * x[t - (k - 1) + j, c]`, with rows before the segment's start
reading as zeros.
`y[t, c] = sum_j w[c, 0, j] * x[t - (k - 1) + j, c] + b[c]`, with rows before the segment's start
reading as zeros and `b` zero when unbound.
- **`rel_sinusoid`** writes the sinusoidal relative-position table, row `d` for distance `d`:
`sin(d * inv[i])` over the first half and `cos(d * inv[i])` over the second,
`inv[i] = exp(i * -log(max_timescale) / max(n/2 - 1, 1))`, each step in f32 as the reference's
@@ -485,6 +488,7 @@ and is optional.
| op | params | operands |
|---|---|---|
| `quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` |
| `quant_cols_fp8` | `M` `n` `dtype` | `x` → `y`, `scale` |
| `had_quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` |
| `givens_dense_quant` | `M` `n` `group` `dtype` `parts` `out`:str | `x`, `tdense`w, `rscale`w → `q`, `scale` |
| `givens_rotate` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `y` |
@@ -492,6 +496,11 @@ and is optional.
| `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? |
| `gemm_nt_q_gated` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? |
`quant_cols_fp8` is the same E4M3 quantiser with one scale per column over all `M` rows,
`scale[c] = amax_r |x[r, c]| * (1/448)` (1 for an all-zero column), `scale` `[n]` f32: an
attention's values for its fp8 P.V form, where a column is one dimension of one head and its scale
multiplies out of the sum over keys.
`gemm_nt_q_gated` is `gemm_nt_q` over a `[N, K]` gate_up plane (`N` is the weight's rows, twice the
fused width, gate half first) with `gated_quant_fp8`'s pass in the epilogue, so the `[M, N]` bf16
tensor between them is never written. It is a separate schema, not a flag on `gemm_nt_q`, because
@@ -629,7 +638,8 @@ implementation reads `res` before it stores the product over it.
| `lora_expand` | `M`(range) `N` `R` `S` `dtype` | `t`, `slot`, `lora_b`, `scale`, `y`:inout |
The two halves of `y += scale ⊙ (B · (A · x))` at a trunk GEMM, issued by the core right after the
GEMM in the GEMM's own row slice, with several adapters and no adapter mixed in one step. `slot` is
GEMM in the GEMM's own row slice, with several adapters and no adapter mixed in one step; a step
with no adapter row issues neither. `slot` is
an i32 per row naming its adapter's pool slot -- the step batch's `RadBatch::lora_slot` from the
GEMM's first row on; **a row with `slot < 0 || slot >= S` is a base row and neither op touches
it**: `lora_shrink` writes nothing into its `t` row, and `lora_expand` does not read or write its
@@ -665,12 +675,12 @@ bytes).
| op | params | operands |
|---|---|---|
| `attn_paged` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` |
| `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt `window`/opt `cu_div`/opt `block`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` |
| `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt `window`/opt `cu_div`/opt `block`/opt `window_right`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` |
| `attn_local_rel` | `M`(range) `head_dim` `n_head` `left` `right` `softcap`:f64 `cu_div`/opt `dtype` | `q`, `k`, `v`, `relk`, `pds`w, `cu_seqlens` → `out` |
| `kv_store` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout |
| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt | `qkv`:inout, `positions` |
| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/opt | `qkv`:inout, `positions` |
| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `head_dim`/opt `ladder`/opt | `positions` → `cos_sin` |
| `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`, `q_w`w, `k_w`w |
| `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`?, `q_w`w?, `k_w`w? |
| `qkv_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `dtype` | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w |
**`attn_paged`**'s band is `q_len`, not `M`: one query row at decode, `1 + n_spec` at a speculative
@@ -689,7 +699,9 @@ maximum, which selects the band; the per-sequence lengths come from `cu_seqlens`
or one input per entry so a whole batch is one launch. `window` is `attn_paged`'s rule over a
segment's own positions (causal: key `j` is visible to query `i` when `i - j < window`; non-causal:
when `|i - j| < window`), and 0 is no window. A bidirectional encoder's sliding layer of radius `r`
(`|i - j| <= r`) is `window = r + 1`. `q`, `k` and `v` may each be `[tokens, heads, head_dim]` or
(`|i - j| <= r`) is `window = r + 1`; one that sees `l` keys behind and `r` ahead is `window = l + 1`
with `window_right = r + 1` (non-causal only: key `j` visible when `i - j < window` and
`j - i < window_right`). `q`, `k` and `v` may each be `[tokens, heads, head_dim]` or
`[tokens, heads * head_dim]`, and the second form may be a column slice of a fused projection read
at its row pitch, so a tower's `[q|k|v]` row needs no copy.
@@ -717,6 +729,19 @@ owns:
With `[M]` positions every component is that one position, so `mrope` and `imrope` over a text batch
are exactly `neox`.
**Positions** are integers or floats, and the operand's dtype says which. An integer `positions`
(i32) is read as an integer; an f32 one (bf16 and f16 too) as the value it holds, a fractional
coordinate such as a video decoder's normalised grid already multiplied by `2 pi`. Either way the
angle is `f32(pos / scale) * inv` in f32. `[C, M]` positions are read at the operand's own strides,
so a `[C, M]` view of a wider `[C, max]` plane is read in place.
**`llama3_*`** applies Llama 3's frequency scaling (transformers' `rope_type` `llama3`) to `rope`'s
ladder: with wavelength `2 pi / inv`, a frequency shorter than `llama3_orig / llama3_high` is kept,
one longer than `llama3_orig / llama3_low` is divided by `llama3_factor`, and those between blend,
`s = (llama3_orig / wavelength - llama3_low) / (llama3_high - llama3_low)`,
`(1 - s) inv / llama3_factor + s inv`, in f32 (`abi/rad_yarn.h`, `RadLlama3`). It does not combine
with YaRN or a multi-component mode.
**`ladder`** names the width the base frequency ladder is measured in. Absent or `rotary`, the
exponent divides by `rotary_dim`: a partial rotary is a complete rotation of its own width. `head`
divides by `head_dim` instead (the proportional variant), so the `rotary_dim / 2` frequencies are a
@@ -726,8 +751,12 @@ ladders), and the head past `rotary_dim` is untouched either way. `rope_table` t
the same reason: its angles must stay `rope`'s exactly.
**`qk_norm_rope`** RMS-norms each q and k head of a fused `[q | k | v]` row against its gain (plus
`wadd`), rounds, and rotates in place.
`wadd`), rounds, and rotates in place. `positions` is read as `rope` reads it, integer or f32.
- An absent `q_w` or `k_w` is a unit gain, without `wadd`: the head is `x rsqrt(mean(x^2) + eps)`,
rounded (a video decoder's weightless q and k norms).
- `rotary_dim` 0 is the norm alone: nothing rotates, and `positions` may be absent (`M` is then
`qkv`'s rows). A rotation with no positions is refused.
- `v_norm` 1 also RMS-norms every v head with a unit gain and does not rotate it: Gemma 4's value
norm, which has no weight.
- `mode` `blocks` rotates each section as its own block of channels: section `c` is `sections[c]`
@@ -740,6 +769,14 @@ the same reason: its angles must stay `rope`'s exactly.
a 3-axis image rotary's complex form.
- `mode` `imrope` is `rope`'s `imrope` over NeoX pairs, reading three position planes (Qwen3-VL's
text attention).
- `mode` `axial` is `rope`'s `axial` over NeoX pairs `(i, i + rotary_dim / 2)`: the
`rotary_dim / 2` frequencies split into contiguous `sections` (summing to `rotary_dim / 2`),
section `c`'s `j`-th frequency `theta^(-2j / (2 sections[c]))` turned by position component `c`.
`positions` is `[C, M]` with `C` at least the section count, or `[M]`, every component then that
one position on the same per-section ladders (unlike `rope`, whose `[M]` positions fall back to
the plain ladder). MiniMax-H3's DiT rotates 96 of its 128 channels with sections `16 16 16`
(theta 1e4) over f32 `(t, h, w)` positions; its video decoder 48 of 64 with `8 8 8` (theta 100)
over positions `grid_pos3` writes.
**`qkv_norm_rope`** (device-only) is the same prologue over separate `q`, `k` and `v` projections
(Gemma 4's text attention, three GEMMs): the q and k norms, the unit-gain value norm and the rotary
@@ -819,7 +856,7 @@ says which (`libref/ref_gen.cpp`).
| op | params | operands |
|---|---|---|
| `ln_mod` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `s`, `cu_seqlens` → `y` |
| `gate_add` | `M`(range) `n` `dtype` | `y`, `g`, `cu_seqlens`, `x`:inout |
| `gate_add` | `M`(range) `n` `dtype` `act`/opt | `y`, `g`, `cu_seqlens`, `x`:inout |
| `ln_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` | `y`?, `g`?, `s`, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? |
| `timestep_embed` | `M`(range) `n` `scale`:f64 `max_period`:f64 `round`/opt `dtype` | `t` → `y` |
| `gather_rows2` | `M`(range) `n` `dtype` | `a`, `b`, `idx` → `y` |
@@ -827,7 +864,7 @@ says which (`libref/ref_gen.cpp`).
| `lane_store` | `M`(range) `n` `stride` `dtype` | `src`, `lane`, `dst`:inout |
| `randn_lanes` | `M`(range) `n` `stride` `dtype` | `flags`, `seed`, `lane`, `cu_seqlens`, `dst`:inout |
| `flow_euler` | `M`(range) `n` `stride` `dtype` | `v`, `sigma`, `sigma_next`, `cfg`, `pair`, `lane`, `flags`, `seed`, `cu_seqlens`, `inp_lat`?, `inp_mask`?, `state`:inout, `preview`:inout? |
| `chan_affine` | `M`(range) `n` `mul` `add` `mode` `dtype` | `x` → `y` |
| `chan_affine` | `M`(range) `n` `mul` `add` `mode` `dtype` `round`/opt | `x` → `y` |
| `conv2d_nhwc` | `M`(range) `cin` `cout` `k` `stride` `pad` `up` `dtype` | `x`, `w`w, `b`w → `y` |
| `l2norm_chan` | `M`(range) `n` `act` `dtype` | `x`, `gamma`w → `y` |
| `d2s_add` | `M`(range) `cin` `cout` `ft` `dtype` | `x`, `y`:inout |
@@ -835,7 +872,7 @@ says which (`libref/ref_gen.cpp`).
| `to_rgba8` | `M`(range) `n` `dtype` | `x` → `y` |
| `gelu_tanh` | `M`(range) `n` `dtype` | `x` → `y` |
| `scatter_add_rows` | `M`(range) `n` `dtype` | `v`, `idx`, `x`:inout |
| `attn_prefix_self` | `q_len` `head_dim` `gqa` `block_size`/der `causal` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt `qk`/opt | `q`, `k`, `v`, `kv_cache`, `block_table`, `seqused`, `cu_seqlens`, `k_descale`?, `v_descale`?, `k_i8`?, `k_scale`? → `out` |
| `attn_prefix_self` | `q_len` `head_dim` `gqa` `block_size`/der `causal` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt `qk`/opt `pv`/opt | `q`, `k`, `v`, `kv_cache`?, `block_table`?, `seqused`?, `cu_seqlens`, `k_descale`?, `v_descale`?, `k_i8`?, `k_scale`? → `out`, `v_scale`? |
**Sequences and lanes.** `cu_seqlens` partitions the rows into entries (`[n_seq+1]` i32, entry `e`
owning `[cu[e], cu[e+1])`; it need not start at 0). `ln_mod` and `gate_add` take each row's
@@ -845,7 +882,10 @@ apart: `lane_gather` copies entry `e`'s rows out of lane `lane[e]`, and `lane_st
source into every listed lane (a repainted picture's latent into each of its images).
- `ln_mod`: `y = bf16(bf16(LN(x)) * bf16(1 + s[seq]))`, a layer norm with no gain and no bias.
- `gate_add`: `x = bf16(x + bf16(bf16(tanh(g[seq])) * y))`.
- `gate_add`: `x = bf16(x + bf16(bf16(tanh(g[seq])) * y))`. `act` names the gate's activation,
`tanh` (the default) or `none`, the gate as it is and not rounded first:
`x = bf16(x + bf16(g[seq] * y))` (MiniMax-H3's last block, whose gates have no tanh). The
roundings are to `x`'s dtype.
- `ln_mod_quant_fp8`: with `gated` 1, `gate_add` first; then `z = ln_mod(x)` and
`(q, scale) = quant_act_fp8(z, group)`, `z` written when bound. Each value is rounded as its own
store would round it, so the bytes are the three ops'.
@@ -873,7 +913,10 @@ shapes: an image's size belongs to a request, and a parameter is fixed at declar
- `l2norm_chan`: each pixel's channels to unit L2 (eps 1e-12), times `sqrt(n)`, times `gamma`
(three roundings), then `act` `none` or `silu`.
- `chan_affine`: `mul` and `add` are space-separated lists of `n` values, each rounded to bf16;
`fma` is `bf16(bf16(x * mul) + add)`, `inv` is `bf16(bf16(x - add) / mul)`.
`fma` is `bf16(bf16(x * mul) + add)`, `inv` is `bf16(bf16(x - add) / mul)`, the roundings to
`y`'s dtype. With `round` 0 (default 1) the lists stay f32 and so does the arithmetic, rounded
once into `y`: `fma` is `rd(f32(x * mul) + add)`, `inv` `rd(f32(x - add) / mul)` (MiniMax-H3
denormalises its f32 audio latents with an f32 deviation and mean).
- `d2s_add` (Wan's DupUp3D on one frame): `y[2r+i, 2c+j, o] += x[r, c, (o F + off + 2i + j) / rep]`,
`F = 4 ft`, `off = 4` when `ft` is 2, `rep = cout F / cin`.
- `s2d_avg_add` (AvgDown3D on one frame): `y` gains the mean of each output channel's group of
@@ -889,7 +932,318 @@ segments before it. `qk` `"i8"` is the int8 score form and takes `k_i8` `[tokens
head_dim]` and `k_scale` `[tokens, kv_heads]` f32, the own keys as `quant_act_i8g` writes them at
group `head_dim`. The query and every prefix key are quantised inside the op by the same rule
(scale `amax/127`, 1 for an all-zero row; code `rint(clamp(x * (1/scale), ±127))`), a score is the
exact integer dot product times both scales, and `k` is not read for the own rows.
exact integer dot product times both scales, and `k` is not read for the own rows. The prefix's
three operands come together or not at all: without them every entry's prefix is empty and the op
is self attention over each entry's rows (`max_ctx` 0 declares that form), which is how a single
long sequence takes the int8 score form.
`pv` `"fp8"` is the fp8 P.V form, prefix-free only: `v` holds E4M3 codes and `v_scale`
`[kv_heads * head_dim]` their column scales (`quant_cols_fp8`). Over a row's visible keys, with
`p = exp(s - max)` against the row's max, each weight is taken to E4M3 as `w = e4m3(448 p)` and
o = (sum w v) v_scale / (448 sum p) f32 sums in key order
A kernel may take `p` against its running max in its own key order as long as every `p <= 1`
(E4M3's top is 448), which differs from this only by where each weight was rounded.
## Audio generation
The ops an audio generator declares (`rad_declare_audio_generator`, `abi/rad_builder.h`) beyond a
language model's and an image generator's: a frame sampler with guidance between branches over
residual codebooks, the frame embeddings, the window states of a latent denoiser, and a
vocoder's 1-D convolutions. Each rounds where the reference model materialises a bf16 tensor; the
libref function says which (`libref/ref_audio.cpp`).
| op | params | operands |
|---|---|---|
| `conv1d` | `M`(range) `cin` `cout` `k` `dil` `act`/opt `dtype` `causal`/opt | `x`, `w`w, `cu_seqlens`, `res`? → `y`; `b`w? |
| `conv_t1d` | `M`(range) `cin` `cout` `stride` `dtype` `pad`/opt `k`/opt | `x`, `w`w, `b`w, `cu_seqlens` → `y` |
| `snake` | `M`(range) `n` `dtype` `log`/opt | `x`, `alpha`w → `y`; `beta`w? |
| `snake_aa` | `M`(range) `n` `ratio` `k` `log`/opt `dtype` | `x`, `alpha`w, `beta`w, `f_up`w, `f_down`w, `cu_seqlens` → `y` |
| `cfg_topk_sample` | `M`(range) `n_vocab` `k` `rep` `cond_k`/opt `cfg`:f64 `temp`:f64/opt `stream` `dtype` `sup_lo`/opt `sup_hi`/opt `penalty`:f64/opt | `logits`, `seed`, `frame` → `ids`; `cfg`?, `lane`?, `hist`:inout? |
| `rvq_embed` | `M`(range) `n_embd` `n_codes` `vocab` `off0` `scale`:f64 `dtype` `round`/opt | `codes`, `t0`w, `t1`w → `y` |
| `frame_mix_store` | `M`(range) `n_embd` `L` `stride` `rep`/opt `dtype` | `hid`, `logits`w, `scale`w, `lane`, `frame`, `status`, `dst`:inout |
| `end_status` | `M`(range) `end` `rep` | `ids`, `lane`, `status`:inout |
| `frame_store` | `M`(range) `n_codes` `stride` `rep`/opt `skip`/opt | `codes`, `lane`, `frame`, `status`, `dst`:inout |
| `resample_nearest` | `M`(range) `n` `dtype` | `x` → `y` |
| `fourier_embed` | `M`(range) `n` `round`/opt `dtype` | `t`, `w`w → `y` |
| `win_input` | `M`(range) `n_lat` `n_zero` `n_cond` `stride` `dtype` | `lat`, `cond`, `lat_cu`, `win_lane`, `pair` → `y` |
| `win_prep` | `M`(range) `n` `stride` `ov` `dtype` | `flags`, `t`, `seed`, `win_index`, `win_lane`, `pair`, `lat_cu`, `prev`, `noise`:inout, `lat`:inout |
| `win_finish` | `M`(range) `n` `n_cond` `stride` `ov` `dtype` | `flags`, `pair`, `win_lane`, `lat_cu`, `cond`, `lat`:inout, `prev`:inout, `prev_cond`:inout |
| `chan_split` | `M`(range) `n` `parts` `dtype` | `x` → `y` |
| `interleave2` | `M`(range) `dtype` | `a`, `b` → `y` |
| `iota` | `M`(range) `start` `step` `period`/opt | → `y` |
| `cu_repeat` | `M`(range) `mult` | `len` → `y` |
**Frames.** A lane is one piece; a frame is one step of its language model, whose branches (the
conditional first, then the unconditional) are consecutive rows, `rep` of them a lane.
- `cfg_topk_sample`: per lane, `g = u + cfg (c - u)` between its first two branch rows (`c` alone
at `rep` 1), `cfg` the operand's value for the lane when it is bound. With `hist`
`[lanes, n_vocab]` i32 and `lane` `[n]`, the lane's history row is cleared at frame 0 and every id
it holds is penalised, `g > 0 ? g / penalty : g * penalty` (a repetition penalty over the lane's
earlier picks); the pick is recorded in it. Ids in `[sup_lo, sup_hi)` are never candidates; with
`cond_k` > 0 only the entries where `c` reaches its `cond_k`-th largest value are. The `k`
largest `g` (ties to the lower index) are kept, divided by `temp`, softmaxed in f32 and drawn by
inverse CDF in descending `g`, `u = rad_philox_uniform_s(seed, 2^32 + frame, stream)`
(`abi/rad_philox.h`); the pick goes to every one of the lane's `rep` slots. `logits`
`[rep n, n_vocab]` f32 or bf16, `seed` `[n, 2]` u32 low word first, `frame` `[n]`.
- `end_status`: `status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]`.
- `rvq_embed`: `codes` is code-major `[n_codes, rows]`, read at the operand's own strides (a block
of a wider plane is a view);
`y = bf16(bf16(t0[c_0 + off0] + bf16(sum_k t1[c_k + (k - 1) vocab])) * scale)`, or with `round` 1
one f32 sum of every codebook's row in codebook order, times `scale`, rounded once to `y`'s dtype.
A first code outside `t0` leaves its row unwritten; a later code outside `t1` adds nothing.
- `frame_store`: `dst[(lane n_codes + k) stride + frame - skip] = codes[k, rep i]` for every `k`,
when `frame >= skip` and `status[lane] >= 0`: a frame's codes into its lane's history, each
codebook a row over the lane's frames, so a run of a lane's frames is a block of `n_codes`
rows.
- `frame_mix_store`: `m = bf16(bf16(sum_l w_l h_l) * bf16(scale))`, `w = bf16(softmax(bf16(logits)))`
over the `L` planes of `hid` `[L, rows, n_embd]`, row `rep i` of each plane being lane `i`'s
conditional row; stored at `dst[lane * stride + frame - 1]` for `frame >= 1` and
`status[lane] >= 0` (frame 0 only moves past the prompt; a negative status ended the piece).
- `iota`: `y[i] = start + i * step`, or `start + (i % period) * step` with `period` (the
positions of equal sequences laid end to end). `cu_repeat`: `y[j] = j * len[0] * mult`, the bounds of equal
sequences whose length lives on the device.
**Windows.** The denoiser runs over windows of frames, each entry of a window step a lane's latent
in a state buffer `stride` rows a lane (`lat_cu` bounds each entry's rows, `win_lane` names its
lane, `pair` is -2 for an unconditional branch, which moves no lane). `flags` carries 1 (the
window's first step), 8 (its last) and 16 (it overlaps the previous window by `ov` rows).
- `win_input`: `y = [lat | zeros(n_zero) | cond]` from the entry's lane; an entry with `pair` -2
takes zeros for `cond`.
- `win_prep`: flag 1 fills the lane with `rad_philox_normal_s(seed, 1 + win_index, k n + c)` as
bf16, keeping its first `ov` rows in `noise` with flag 16; flag 16 then binds the first
`min(ov, rows)` rows to the previous window's end,
`bf16(bf16(1 - bf16((1 - 1e-6) t)) noise + bf16(t prev))`, `t = bf16(t[e])`.
- `win_finish` (flag 8): with flag 16 the first `min(ov, rows)` rows become `prev` exactly; then
rows `[max(0, rows - 2 ov), max(.., rows - ov))` of the latent and of `cond` are kept as the next
window's `prev` and `prev_cond`.
- `fourier_embed`: `[cos(2 pi t w) | sin(2 pi t w)]`, `t` f32 `[M]`, `w` `[n / 2]`; with `round` 1
`t`, `2 pi t`, the product and each cosine and sine are rounded to bf16.
- `resample_nearest`: output row `j` reads input row `min(floor(j * in / out), in - 1)`, the row
counts read off the operands (torch's `interpolate(mode="nearest")`).
**The vocoder.** Rows are samples, channels innermost; `cu_seqlens` bounds each sequence and the
input reads zero outside it.
- `conv1d`: PyTorch's `[cout, cin, k]` weight, `k` odd, dilation `dil` and padding
`dil (k - 1) / 2` a side, or with `causal` 1 (any `k`) `dil (k - 1)` on the left; `res` is added
after the bias, then `act` `none`, `tanh` or `clamp`, `min(max(y, -1), 1)` (BigVGAN's output
clamp; a NaN stays NaN). f32 accumulation, one rounding.
- `conv_t1d`: PyTorch's `[cin, cout, k]` transposed weight, any `k` of at least a stride (two
strides by default), padding `pad` (`(k - stride) / 2` by default, which needs `k - stride` even;
0 is the causal form, whose full output's last `k - stride` rows are dropped; it may exceed a
stride): output row `o` of a sequence is `b + sum_i x[i] w[(o + pad) - i stride]` over the
sequence's input rows `i` with `0 <= (o + pad) - i stride < k`, summed in f32 as
`q = (o + pad) / stride`, `r = (o + pad) % stride` and taps `t = 0, 1, ..` while
`r + t stride < k` reading `x[q - t] w[r + t stride]`; one rounding. Sequence `e`'s rows
`[cu[e], cu[e+1])` become `[stride cu[e], stride cu[e+1])`, `stride L` rows from `L`. BigVGAN
upsamples with `(k 9, stride 5, pad 2)` and `(k 4, stride 2)`.
- `snake`: `x + sin(alpha x)^2 / (alpha + 1e-9)`, `alpha` per channel; with `beta` the SnakeBeta
form `x + (1 / (beta + 1e-9)) sin(alpha x)^2`. `log` 1 reads both as logarithms, exponentiated
first.
- `snake_aa`: BigVGAN's alias-free SnakeBeta (diffusers' `MiniMaxH3AudioActivation1d`: an
upsampler, the activation, a low-pass downsampler) over each sequence, in f32. For channel `c`
of a sequence of `L` rows, `P = k / ratio - 1`:
- `xp` is the sequence replicate-padded by `P` rows on each side;
- `u_full[o] = sum_i f_up[o - i ratio] xp[i]` over the rows `i` with `0 <= o - i ratio < k`, in
ascending `i` (a depthwise `conv_transpose1d` at stride `ratio`), and
`u = ratio u_full[P ratio + (k - ratio) / 2 + m]` for `m < L ratio` (the full output cropped by
`P ratio + (k - ratio) / 2` rows at the start and `P ratio + (k - ratio + 1) / 2` at the end);
- `a = u + (1 / (B + 1e-9)) sin(A u)^2` as `snake`'s `beta` form evaluates it, `A = exp(alpha[c])`
and `B = exp(beta[c])` with `log` 1, the values themselves otherwise;
- `ap` is `a` replicate-padded by `k / 2` rows on the right and `k / 2` on the left less one for
an even `k`, and `y[o] = sum_j f_down[j] ap[o ratio + j]` over `j < k` in ascending `j`, for
`o < L`.
`f_up` and `f_down` are the checkpoint's `[1, 1, k]` Kaiser filters, one for every channel
(MiniMax-H3: `k` 12, `ratio` 2). A sequence keeps its length.
- `chan_split`: `y[p rows + r] = x[r, p n .. p n + n)`, a stereo latent's halves as two streams.
- `interleave2`: `y [rows, 2] = (a[r], b[r])`, f32.
## Video generation
The ops a video generator (MiniMax-H3) needs beyond a language model's, an image generator's and
an audio generator's: its diffusion transformer's modulated RMS norm and its sampler step, and the
video decoder's patch unfold, the tiles it runs over, their stitch back into frames and their
rotary positions. The transformer's attention is `qk_norm_rope` `axial` (its step-distilled form's
is [video sparse attention](#video-sparse-attention)) and its gated residual
`gate_add` `act` none; the soundtrack's vocoder is `conv_t1d`, `snake_aa` and `conv1d` `clamp`
([Audio generation](#audio-generation)). Each op rounds where the reference model materialises a
bf16 tensor and keeps f32 where it computes in f32; the libref function says which
(`libref/ref_gen.cpp`, `libref/ref_video.cpp`).
| op | params | operands |
|---|---|---|
| `rms_mod` | `M`(range) `n` `eps`:f64 `gated`/opt `dtype` | `y`?, `g`?, `s`, `w`w, `cu_seqlens`, `x`:inout → `z` |
| `rms_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` | `y`?, `g`?, `s`, `w`w, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? |
| `flow_x0_step` | `M`(range) `n` `dtype` | `v`, `t`, `sigma`, `sigma_next`, `x`:inout |
| `patch_unfold` | `M`(range) `C` `pt` `ph` `pw` `mul` `add` `dtype` | `x`, `geom` → `y` |
| `vtile_gather` | `M`(range) `n` `tile` `overlap` `frames` `period` `n_reg` `dtype` | `x`, `reg`w, `geom` → `y` |
| `vtile_stitch` | `M`(range) `tile` `overlap` `scale` `pt` `skip` `keep` `blend` `period` `mean` `std` | `x`, `geom`, `prev`:inout → `y` |
| `grid_pos3` | `M`(range) `T` `H` `W` `period` `scale`:f64 | → `y` |
**The transformer.** `cu_seqlens` partitions the rows into entries as for `ln_mod`, and each row
reads its entry's rows of `s` and `g`.
- `rms_mod` is `norm(h) (1 + scale) + shift` after the branch before it is added: with `gated` 1
first `x = bf16(x + bf16(g[e] y))`, no tanh, stored back to `x`; then
`n1 = bf16(x rsqrt(mean(x^2) + eps))` (the sum of squares f32 in ascending order, over the
stored `x`), `n2 = bf16(n1 w)`, `m = bf16(n2 bf16(1 + scale[e]))`, `z = bf16(m + shift[e])`.
`s` is `[n_seq, >= 2n]` at its own row pitch, `shift = s[e, 0:n]` and `scale = s[e, n:2n]` (a
column slice of the modulation table); `g` is `[n_seq, >= n]` at its own pitch; `w` is `[n]`.
The residual rounds to `x`'s dtype and the norm chain to `z`'s.
- `rms_mod_quant_fp8` is `rms_mod` with the norm chain in bf16, then `quant_act_fp8` of that bf16
row per `group` as `ln_mod_quant_fp8` takes it; `z` written when bound.
- `flow_x0_step` is MiniMax-H3's sampler step over a lane's rows, all f32, each product and sum
one rounding: the velocity points at the data, so the clean estimate is `d = x + (1 - t) v` and
the step blends toward it, `st = f32(1 - t)`, `d = f32(x + f32(st v))`,
`r = f32(sigma_next / sigma)`, `x = f32(f32(r x) + f32(f32(1 - r) d))`. `t` (the timestep the
transformer was conditioned on), `sigma` and `sigma_next` (the schedule's entries) are one f32
value each; `v` is f32 or bf16, `x` f32.
**The decoder** runs over a request's latent geometry, which `geom`, i32 on the device, carries
(the parameters are fixed at declare). `mul`, `add`, `mean` and `std` are space-separated lists
kept in f32. An output holds at least the rows the geometry writes; rows past them are not
written.
- `patch_unfold`: patch rows `x [F Hp Wp, C pt ph pw]` (row `(f, i, j)` frame-major then
row-major, column `(c, a, b, d)` at `c pt ph pw + a ph pw + b pw + d`, `geom` = `(F, Hp, Wp)`)
to voxel rows `y [(F pt) (Hp ph) (Wp pw), C]`, row `(t, yy, xx)` row-major:
`y[(t, yy, xx), c] = f32(f32(x[(t/pt, yy/ph, xx/pw), (c, t%pt, yy%ph, xx%pw)] mul[c]) + add[c])`,
the latent denormalised with f32 statistics. `M` is the output's rows.
- The tiles of an axis of `L` latent units are diffusers' `_split_tiles` in latent units: a `tile`
at least as long as the axis is one tile `[0, L)`, refused unless `L == tile`; otherwise
`n = ceil(L / tile)`, raised while `tile n - overlap (n - 1) < L`; `ov = [overlap] * (n - 1)`,
the slack `tile n - sum(ov) - L` added one unit at a time to `ov[i % (n - 1)]` for
`i = 0, 1, ..`; `start[0] = 0`, `start[i + 1] = start[i] + tile - ov[i]`. `overlap` must be
below `tile`. A frame's tiles are row-major over (row band, column band).
- `vtile_gather`: the tiles out of voxel rows `x [frames H W, n]` (`(t, yy, xx)` row-major,
`geom` = `(frames, H, W)`, its frames the parameter's). Tile `k` is rows
`[k period, (k + 1) period)` of `y`: its `frames tile tile` voxels `(t, ty, tx)` row-major from
`x`'s row `(t, start_y + ty, start_x + tx)`, then `reg`'s first `n_reg` rows in `y`'s dtype (a
decoder's register tokens), then zero rows to the period, which holds at least
`frames tile tile + n_reg` rows. `M` is `y`'s rows, `n_tiles period`.
- `vtile_stitch`: a decoded chunk's tiles into RGB bytes. `x [>= n_tiles period, 3 pt scale^2]`:
tile `k`'s row `k period + (lt tile + ty) tile + tx`, column
`c pt scale^2 + a scale^2 + b scale + d`, is colour `c` of pixel `(ty scale + b, tx scale + d)`
of clip frame `lt pt + a`. `geom` = `(frames, H, W, first, last)`: the chunk's latent geometry,
and whether it is its video's first and its last chunk (nonzero). Pixel `(Y, X)` belongs to the
tile `(i, j)` whose kept range holds it, `[start_i scale, start_{i+1} scale)` on each axis (the
last tile to its end), at `(ly, lx)` within it, `T(i, j, ly, lx)` that tile's decoded value. With
every product and sum rounded to `x`'s dtype (`rd`), `wb(p, e) = rd(p / e)` and
`wa(p, e) = rd(1 - wb(p, e))`, the spatial stitch blends with the tile above, then with the tile
to the left, both as decoded:
V = rd(rd(T(i-1, j, ly + tile scale - ev, lx) wa(ly, ev)) + rd(T(i, j, ly, lx) wb(ly, ev)))
when i > 0 and ly < ev = ov_y[i-1] scale, else T(i, j, ly, lx)
S = rd(rd(T(i, j-1, ly, lx + tile scale - eh) wa(lx, eh)) + rd(V wb(lx, eh)))
when j > 0 and lx < eh = ov_x[j-1] scale, else V
Output frame `k < keep` is clip frame `skip + k`, its first `blend` frames blended with the
previous chunk's tail unless the chunk is first,
`v = rd(rd(prev[k] wa(k, blend)) + rd(S wb(k, blend)))`; then `prev[k'] = S(2 skip + keep + k')`
for `k' < blend` (`prev` `[blend, H scale, W scale, 3]`), which a last chunk also writes as
frames `keep + k'`. A byte is `round_half_even(255 clamp(f32(f32(v std[c]) + mean[c]), 0, 1))`
(a NaN is 0). `y` is u8 `[frames_out, H scale, W scale, 3]`, `frames_out` `keep` or
`keep + blend`; `M` is its pixels. Refused: `blend` past `keep`, clip frames (`frames pt`) short
of `2 skip + keep + blend`, a `period` short of `frames tile tile`. MiniMax-H3: `tile` 16,
`overlap` 4, `scale` 16, `pt` 4, `skip` 3, `keep` 17, `blend` 5, `period` 1797, ImageNet's
`mean` and `std`.
- `grid_pos3`: a ViT decoder's rotary positions over consecutive tiles of `period` rows, the
tile's `T x H x W` tokens first, then the period's other rows (register tokens). Row `m` is
token `k = m % period`; for `k < T H W`, `(t, i, j) = (k / (H W), (k / W) % H, k % W)` and
`y[0][m] = f32(f32(scale) g(t, T))`, `y[1][m] = f32(f32(scale) g(i, H))`,
`y[2][m] = f32(f32(scale) g(j, W))`, `g(c, n) = f32(f32(2 f32((c + 0.5) / n)) - 1)` (torch's
`2 * (arange(0.5, n) / n) - 1`); otherwise all three are 0. `y` is f32 `[3, >= M]`,
component-major, at its own row pitch: a `[3, M]` view of a wider plane, which `qk_norm_rope`
`axial` then reads as f32 positions. MiniMax-H3: `T` 7, `H` 16, `W` 16, `period` 1797,
`scale` `2 pi`.
### Video sparse attention
MiniMax-H3's step-distilled form (FastH3) was trained with FastVideo's video sparse attention: a
video query sees the dense rows and only the video tiles it scores highest, scored per head from
tile means, and a coarse branch adds attention over every tile's mean, gated per element.
`vsa_select` makes the selection and the coarse term, `attn_vsa` the attention over them. They
share their parameters; `attn_vsa` recomputes `k` from `sparsity`.
| op | params | operands |
|---|---|---|
| `vsa_select` | `M`(range) `head_dim` `tile_t` `tile_h` `tile_w` `patch` `sparsity`:f64 `scale`:f64/opt | `q`, `k`, `v`?, `segs`, `geom` → `sel`, `coarse`? |
| `attn_vsa` | `M`(range) `head_dim` `tile_t` `tile_h` `tile_w` `patch` `sparsity`:f64 `scale`:f64/opt `qk`/opt `pv`/opt | `q`, `k`, `v`, `segs`, `geom`, `sel`, `coarse`?, `gate`? → `out`, `k_i8`?, `k_scale`?, `v_scale`? |
**The tiles.** A pass's `R` rows (`M` is their band) are one packed sequence. `segs`, i32
`[n_seg + 1]`, cuts it into segments: `segs[0] = 0`, non-decreasing, `segs[n_seg] = R`; every
segment but the last is dense (the text, the soundtrack), the last is the video grid of
`F x Hp x Wp` rows in `(t, h, w)` order, `w` fastest. `geom` is the request's geometry on the
device, i32 `[RAD_VGEOM_N]` (`abi/rad_runtime.h`): `F = geom[RAD_VGEOM_LAT_FRAMES]`,
`Hp = geom[RAD_VGEOM_LAT_H] / patch`, `Wp = geom[RAD_VGEOM_LAT_W] / patch`. With
`TT = tile_t tile_h tile_w`:
- each dense segment, on its own, is cut into chunks of `TT` rows from its start, the last chunk
shorter, an empty segment none: the prefix tiles `0 .. P-1`, in segment order;
- the grid is cut into `ceil(F / tile_t) x ceil(Hp / tile_h) x ceil(Wp / tile_w)` boxes. Box
`(a, b, c)` holds `t` in `[a tile_t, min(F, (a + 1) tile_t))` and likewise `h` and `w`, edge boxes
smaller, and is tile `P + (a nb + b) nc + c` (`nb = ceil(Hp / tile_h)`, `nc = ceil(Wp / tile_w)`):
`V` video tiles, `N = P + V` in all;
- a tile's rows are taken in its `(t, h, w)` raster order (a prefix tile's in row order), which
fixes the order of every f32 sum over a tile. `size(i)` is tile `i`'s row count.
`k = max(1, min(ceil((1 - sparsity) V), V))`, computed in f64 from the f64 `sparsity`, as the
trained schedule computes it: `(1 - 0.8) 660` is `131.99999999999997`, so MiniMax-H3's 660 video
tiles at 1344 x 768 keep 132, and `(1 - 0.7) 10` keeps 4.
Both ops refuse with `RAD_E_SHAPE` a `segs` that does not start at 0, decreases, or covers no row
or more rows than the operands hold; a last segment of other than `F Hp Wp` rows; a box extent or
`patch` below 1; a `sparsity` outside `[0, 1)`; and an optional operand without its partner. `sel`
must be i32 (`RAD_E_DTYPE`). Rows past `segs[n_seg]` are neither read nor written. `q`, `k`, `v`,
`gate` and `out` are `[R, n_head head_dim]`, a column slice of a wider projection read at its own
row pitch, or `[R, n_head, head_dim]`; the head count is read off `q`.
**`vsa_select`.** Per head `h` and tile `i`, the tile means and the scores, in f32:
qp[h][i] = (sum over the rows r of tile i, in raster order, of q[r, h, :]) / size(i)
kp[h][i], and vp[h][i] (read for `coarse` alone), likewise from k and v
S[h][i][j] = (qp[h][i] . kp[h][j]) scale the dot a sum over d ascending, then the product
For a video query tile `i >= P`, `sel[h][i][0 .. k)` is the `k` video tiles `j` (`P <= j < N`) of
largest `S[h][i][j]`, written in ascending tile order; equal scores go to the lower tile, and a NaN
ranks above every number (`torch.topk`'s ranking). The prefix query tiles' rows of `sel` and its
slots past `k` are not written. `sel` is `[n_head, tiles_cap >= N, k_cap >= k]`. With `coarse`
(and `v`: both or neither), for every tile `i`, prefix tiles too:
e_j = exp(S[h][i][j] - max over all N tiles of S[h][i][:])
p[h][i][j] = e_j / (sum over all N tiles, j ascending, of e_j)
coarse[h][i][:] = (sum over j ascending of p[h][i][j] vp[h][j][:]), rounded once to its dtype
`coarse` is `[n_head, tiles_cap >= N, head_dim]`. At `sparsity` 0, `k = V` and every video tile is
selected.
**`attn_vsa`.** A query row of tile `i` sees the rows of every tile when `i < P` (dense prefix
queries), else of the prefix tiles and of the tiles `sel[h][i][0 .. k)`. Each such row of `sel` must
hold `k` ascending video tiles, `RAD_E_INVAL` otherwise, checked before anything is written; `sel`'s
other entries are not read. Per head (`q`, `k` and `v` have the same heads), `o` is the softmax over
the visible keys of `(q . k) scale` times `v`, accumulated in f32, and
out[r, h, :] = o without coarse and gate
out[r, h, :] = rd(rd(o) + coarse[h][i][:] gate[r, h, :]) with them, in f32
`rd` rounding to `out`'s dtype: FastVideo's inference epilogue, the sparse output in bf16, then
`out.addcmul_(coarse, gate)` in bf16 with f32 arithmetic. Two bf16 values multiply exactly in f32,
so that is one f32 add between the two roundings. `gate` comes with `coarse`, both or neither. At
`sparsity` 0 (with `vsa_select`'s selection) `attn_vsa` is `attn_dense` over the whole sequence.
libref takes the keys by ascending tile, each tile in raster order, in `attn_dense`'s two passes.
`qk` `"i8"` is `attn_prefix_self`'s int8 score form: `k_i8` `[M, n_head * head_dim]` and `k_scale`
`[M, n_head]` f32 are k as `quant_act_i8g` writes it at group `head_dim`, each query row is
quantised inside the op by the same rule, a score is `((dot * q_scale) * k_scale) * scale` in f32
with `dot` the codes' exact integer sum, and `k` is not read. `pv` `"fp8"` is `attn_prefix_self`'s
fp8 P.V form (`v` E4M3 codes, `v_scale` `[n_head * head_dim]`), before the epilogue.
MiniMax-H3: `tile_t`, `tile_h` and `tile_w` 4, `patch` 2, `sparsity` 0.8, `head_dim` 128, the
default `scale` `1 / sqrt(head_dim)`.
## Mixture of experts
+9 -1
View File
@@ -180,8 +180,9 @@ also matches a norm leaves the norm as it is.
| `paroquant` | a channel scaling and `stages` rounds of Givens pair rotations, learned against the Hessian, then AutoRound on the rotated weight; the encoding's `givens` transform |
| `ggml` | `type=` one of llama.cpp's formats (q4_0, q4_1, q5_0, q5_1, q8_0, q2_K..q6_K, iq4_nl, iq4_xs, iq2_xxs, iq2_xs, iq2_s, iq3_xxs, iq3_s, iq1_s, iq1_m), chosen by llama.cpp's own search, imatrix-weighted; the codes are byte for byte llama.cpp's, stored as each type's affine planes. iq2_xxs, iq2_xs and iq1_s need `--imatrix` |
| `cast` | a float weight in another float dtype (`dtype=` f32, bf16, f16, fp8_e4m3, fp8_e5m2), no scale |
| `import` | rad-convert's own, not a plugin: the numbers a quantised release ships, in the spelling the kernels read, instead of quantising again. `codes=uN` makes a symmetric grid's signed codes unsigned under a zero point of 2^(N-1); `zero=` is the zero plane's dtype (u4, u8); `scale=` the scale's (f16, bf16, f32), each shipped scale rounded to nearest; `block=RxC` repeats an FP8 scale shipped per row or per tensor over that block grid. It reads an imported integer grid (GPTQ, CT-INT4) or an FP8 weight with a scale per row or per tensor, refuses any other quantised form by name, and keeps a plain float weight as it is. The run reports per rule how many weights it re-expressed and how many scales the new dtype rounded |
Every quantiser except `ggml` and `cast` takes the grid options:
Every quantiser except `ggml`, `cast` and `import` takes the grid options:
| option | |
|---|---|
@@ -781,6 +782,13 @@ reference with the exact wire and a bf16 KV cache.
agreement to `FILE.rows` (`[positions, 4]` f32, reference row order), so two candidates can be
compared position by position.
A runtime LoRA adapter (GUIDE.md §4.9.1) is scored the same way: `--lora NAME=DIR --kld-lora NAME`
runs every document through the adapter, against a reference recorded from the merged checkpoint
(or from PEFT itself). `--kld-lora-sources PREFIX` runs only the documents whose `source` starts
with `PREFIX` through it and the rest as the base, in the same steps. The steps are those of the
all-adapter and all-base runs with the same flags, so each document's rows should be byte for byte
theirs: that is how a mixed batch is checked.
---
## The shell harnesses
+3
View File
@@ -50,6 +50,9 @@ set(AVX_KERNEL_SRC
avx_misc.cpp
avx_gen.cpp
avx_gen_attn.cpp
avx_video.cpp
avx_vsa.cpp
avx_audio.cpp
)
# The flag sets, written out because each states which instructions the object may contain.
+80 -4
View File
@@ -3,7 +3,7 @@
The conventional op vocabulary in hand-written x86 SIMD, dispatched at run time by CPU feature.
libavx is a kernel plugin beside `libref` and `libr4d`. libref is the only other host
implementation, and it is a slow reference. libavx implements all 123 of libref's ops with the
implementation, and it is a slow reference. libavx implements all 150 of libref's ops with the
same schemas and the same answers to a tolerance, the image generator's included (below).
cmake -S libavx -B build-avx -DCMAKE_PREFIX_PATH=<radiance prefix> && cmake --build build-avx -j4
@@ -64,7 +64,7 @@ four levels and the engine never reaches it.
Every op `libref` implements, `libavx` implements, so the selector resolves no op of a CPU-only
deployment to libref: Flash-Next's QSA indexer, the DFlash2 drafters' convolution and the image
generator included. `rad-avx-check` fails on any missing op, and reports a row that returns
and audio generators included. `rad-avx-check` fails on any missing op, and reports a row that returns
`RAD_E_UNSUPPORTED` separately from one that is absent: a declining row is worse than none, because
the selector resolves to it and the step fails at issue rather than at declare.
@@ -76,6 +76,7 @@ Every `RAD_E_UNSUPPORTED` a libavx kernel returns, beside libref's answer to the
| `attn_local_rel` | a right context; head_dim or left context + 1 over 2048 | the same |
| `rope`, `qk_norm_rope`, `qsa_block_key` | an unknown `mode`; for `rope`, an unknown `ladder` | the same |
| `rope` | YaRN with `axial` or a position scale | the same |
| `rope` | Llama 3 scaling beside YaRN, with `axial`, or over multi-component positions | the same |
| `rope` | a rotary half-width over 1024 | the same |
| `had_quant_act_i8`, `had_quant_act_fp8`, `rmsnorm_had_quant_i8`, `gated_had_quant_i8`, `hc_read` | a Hadamard group over 4096 | the same (`REF_HAD_MAX`) |
| `gdn_conv_prep`, `gdn_conv_update` | a convolution history over 16 | the same |
@@ -91,8 +92,10 @@ Every `RAD_E_UNSUPPORTED` a libavx kernel returns, beside libref's answer to the
Everything but the last two rows refuses exactly where libref does, so the selector never
resolves a geometry to libavx that libref would have served. The per-entry image ops
(`lane_gather`, `lane_store`, `randn_lanes`, `flow_euler`) check every entry before writing any,
where libref writes the entries before a bad one; they return libref's code, and refuse (with
(`lane_gather`, `lane_store`, `randn_lanes`, `flow_euler`) and the audio generator's
(`frame_mix_store`, `end_status`, `frame_store`, `win_input`, `win_prep`, `win_finish`, and
`cfg_topk_sample` with a lane history or a suppressed id range) check every entry before writing
any, where libref writes the entries before a bad one; they return libref's code, and refuse (with
`RAD_E_SHAPE`) the entries libref would read or write past an operand for.
`moe_gemm_q` and `moe_gemm_q_mod4` carry layout hooks for Qwen3.8-Flash-Next's codebook experts
@@ -566,6 +569,76 @@ activation. With a bf16-pair path for block fp8 the fp8 container would cost abo
one does. The decoder takes about 1.3 s at 512 x 512 and 5 s at 1024 x 1024, the condition (the
8B text encoder and the DiT over about 100 prompt tokens) about 0.6 s in bf16 and 8 s in fp8.
## Audio generation
MiniMax-Music3 (`arch/minimaxmusic3`) adds 16 ops (`avx_audio.cpp`), and a speech model's frame
loop and causal codec one more (`frame_store`) and these forms: a causal `conv1d`, the causal
`conv_t1d` (`pad` 0, odd strides, a kernel of one stride), SnakeBeta (`snake` with `beta`, both as
logarithms with `log`), and a sampler that suppresses reserved ids, takes each lane's guidance and
penalises a lane's earlier picks (`hist`, cleared at frame 0). The sampler (`cfg_topk_sample`),
the window noise and its overlap binding (`win_prep`), the frame embeddings (`rvq_embed` in both
roundings, `frame_mix_store`, `fourier_embed`), the code history (`frame_store`), the window copies
and the index helpers are libref's bit for bit, held to zero error by the hand-built cases: a seed
gives the same codes, the same noise and the same piece on both host libraries. With a history the
sampler takes its lanes in order, as libref does, since two entries may share a lane's row.
`cfg_topk_sample` and `frame_mix_store` keep libref's two roundings where they multiply and add
(`keep`). The vocoder's three ops reduce in other orders and are held to the tolerance table:
- **`conv1d`** is GEMMs over bands of patch rows, as `conv2d_nhwc`: the weight re-laid once a launch
as `[cout][k][cin]`, an output row's patch its k input rows' channel runs (zeros outside its own
sequence), each band one `gemm_nt_into` into f32 rows, then the residual and the tanh or the
clamp, rounded once. A 1-wide kernel over a dense input reads x in place.
- **`conv_t1d`** is one GEMM per phase: output row q s + r - pad reads input rows q, q - 1, ..
against taps r, r + s, .. below k (phases of one kernel may differ by a tap: kernel 9 at stride 5
takes two taps in phases 0 to 3 and one in phase 4), so a phase's rows are a GEMM over
`[x[q] | x[q - 1] | ..]` patch rows and the weight re-laid per phase as `[cout][taps][cin]`.
- **`snake`** squares a sine reduced to [-pi/2, pi/2] (the sign does not matter once squared) and
evaluated as an odd Taylor polynomial through r^13; a row with an argument past 8192, where the
three-part pi stops being exact, is computed again with the libm sine. SnakeBeta's multiplier
1 / (beta + 1e-9) is taken once a channel, as libref takes it.
- **`snake_aa`** (BigVGAN's alias-free SnakeBeta, MiniMax-H3's vocoder) works on bands of 64 output
rows, channels innermost: a band computes the upsampled rows its filter reads into scratch (a
row a function of its index, so neighbouring bands agree where they overlap), with `snake`'s
sine, and filters them down; both sums run in libref's order.
At the vocoder's third stage (384 channels), bf16, this machine (`rad-avx-bench --op <op>`):
| op | geometry | libref, 1 thread | avx512, 1 thread | avx512, 16 threads |
|---|---|---|---|---|
| conv1d | 7 taps, dilation 3, 384 -> 384, 8192 rows | 10.9 s | 56.8 ms, 298 GFLOP/s | 6.5 ms, 2.6 TFLOP/s |
| conv1d | 1 x 1, 384 -> 384, 8192 rows | 1.57 s | 9.7 ms, 250 GFLOP/s | 1.4 ms, 1.7 TFLOP/s |
| conv_t1d | stride 4, 768 -> 384, 2048 -> 8192 rows | 6.33 s | 34.7 ms, 279 GFLOP/s | 3.8 ms, 2.5 TFLOP/s |
| snake | 8192 x 384 | 20.3 ms | 1.2 ms, 10.5 GB/s | 0.32 ms, 39 GB/s |
A window's vocode (two streams, 689 latents to 705536 samples each, four upsampling stages of
three residual units) is about 2.2 TFLOP, of the order of a second on 16 cores at these rates; the
96-channel last stage was not timed. On one thread the convolutions reach 36-43% of the bf16
dot-product ceiling, against the image decoder's 70-88%; they have not been tuned.
## Video generation
MiniMax-H3 adds eight ops (`avx_gen.cpp`, `avx_video.cpp`, and `snake_aa` in `avx_audio.cpp`)
and these forms: `qk_norm_rope`
`axial` over f32 positions (its positions a view of a wider plane), with absent gains and as the
norm alone; `rope` over f32 positions; `gate_add` without tanh; `add` with `div`; `chan_affine` in
f32; `conv_t1d` at any kernel of a stride or more; `conv1d` with its clamp; and `snake_aa` above.
The sampler step (`flow_x0_step`), the patch unfold, the decoder's tiles (`vtile_gather`), their
stitch into bytes (`vtile_stitch`) and their positions (`grid_pos3`) are libref's bit for bit, held
to zero error by the hand-built cases: a seed gives the same video bytes on both host libraries.
The stitch blends a line of a tile at a time, each product and sum a pass of the line through x's
dtype; the frames that refill the overlap run after the frames that read it, so no row is read
after another task rewrote it. `rms_mod` and its quantised form reduce in another order and are
held to the tolerance table.
Its step-distilled form's video sparse attention adds two (`avx_vsa.cpp`). `vsa_select`'s
selection is libref's bit for bit, since one tile more or less changes what a whole query tile
sees: the tile means sum rows in libref's order with the vector lanes across the head, and each
score's dot runs over the head in libref's order with the vector lanes across tiles and every
product rounded before its add. Its coarse branch is held to the tolerance. `attn_vsa` is one task
per (head, query tile), 64 keys of a visible tile packed at a time for broadcast products and an
online softmax, as `attn_prefix_self`'s f32 form; a prefix query tile sees every tile, so the tasks
are scheduled dynamically.
## Design choices
Each choice below was measured on the platform above. The variants that did not pay are recorded
@@ -628,6 +701,9 @@ and spills a 16-register file, costing more than the FMA saves, so the AVX and A
avx_{elementwise,norm,hc,quant,gemm,attn,qsa,moe,gdn,sample,misc}.cpp the kernels; compiled 4x
avx_gen.cpp the image generator's norms, sampler, lanes and decoder ops; compiled 4x
avx_gen_attn.cpp attn_prefix_self, the generator's attention; compiled 4x
avx_video.cpp the video decoder's patch unfold, tiles, stitch and positions; compiled 4x
avx_vsa.cpp video sparse attention: the tile selection and the attention; compiled 4x
avx_audio.cpp the audio generator's vocoder, sampler, embeddings and window ops; compiled 4x
avx_harness.h plugin loading, row selection, the operand draw, guarded buffers, the
geometry table -- shared by both tools
avx_cases.cpp the geometries; one table so the check and the bench cannot disagree
+85 -42
View File
@@ -532,7 +532,8 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
const RadTensor* v, const RadTensor* cu,
const RadTensor* o, int64_t D, int64_t gqa,
int64_t kv_heads, int causal, int64_t window,
int64_t block, int64_t cdiv, float scale, int64_t q_rs, int64_t q_hs, int64_t q_ds,
int64_t wright, int64_t block, int64_t cdiv,
float scale, int64_t q_rs, int64_t q_hs, int64_t q_ds,
int64_t k_rs, int64_t k_hs, int64_t k_ds, int64_t v_rs,
int64_t v_hs, int64_t v_ds, int64_t o_rs, int64_t o_hs,
int64_t o_ds) {
@@ -589,7 +590,7 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
int64_t jbeg = 0, jend = causal ? q1 : len;
if (window > 0) {
jbeg = std::max<int64_t>(0, q0 - window + 1);
if (!causal) jend = std::min<int64_t>(len, q1 - 1 + window);
if (!causal) jend = std::min<int64_t>(len, q1 - 1 + wright);
}
if (block > 0) {
jbeg = std::max<int64_t>(jbeg, q0 / block * block);
@@ -617,7 +618,8 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
for (int64_t j = 0; j < kt; ++j) {
const int64_t d = i - (j0 + j);
bool ok = !causal || d >= 0;
if (window > 0) ok = ok && (causal ? d < window : (d < window && -d < window));
if (window > 0)
ok = ok && (causal ? d < window : (d < window && -d < wright));
if (block > 0) ok = ok && i / block == (j0 + j) / block;
if (!ok) S[r * KT + j] = -INFINITY;
}
@@ -729,12 +731,16 @@ AVX_KERNEL(attn_dense) {
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
const int64_t gqa = p_int(a, "gqa", 1);
const int causal = (int)p_int(a, "causal", 0);
/* As libref: causal, i - j < window; non-causal, |i - j| < window; 0 means none. A `block`
* cuts a segment into blocks attending within themselves; `cu_div` reads cu_seqlens in units
* that many rows apart. */
const int64_t window = p_int(a, "window", 0);
/* As libref: causal, i - j < window; non-causal, |i - j| < window, or i - j < window and
* j - i < window_right when that is given; 0 means none. A `block` cuts a segment into blocks
* attending within themselves; `cu_div` reads cu_seqlens in units that many rows apart. */
const int64_t window = p_int(a, "window", 0), wright_p = p_int(a, "window_right", 0);
const int64_t block = p_int(a, "block", 0), cdiv = p_int(a, "cu_div", 1);
if (head_dim <= 0 || gqa <= 0 || window < 0 || block < 0 || cdiv <= 0) return RAD_E_SHAPE;
if (head_dim <= 0 || gqa <= 0 || window < 0 || block < 0 || cdiv <= 0 || wright_p < 0 ||
(wright_p > 0 && (causal || window == 0)))
return RAD_E_SHAPE;
/* The right side of a non-causal window. */
const int64_t wright = wright_p > 0 ? wright_p : window;
if (head_dim > AVX_HD_MAX) return RAD_E_UNSUPPORTED;
/* A rank-2 operand is [tokens, heads * head_dim]: its head count is width / head_dim. */
@@ -768,8 +774,8 @@ AVX_KERNEL(attn_dense) {
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
#if AVX_LEVEL == 3
if (attn_dense_bf16(q, k, v, cu, o, head_dim, gqa, kv_heads, causal, window, block, cdiv,
scale, q_rs,
if (attn_dense_bf16(q, k, v, cu, o, head_dim, gqa, kv_heads, causal, window, wright, block,
cdiv, scale, q_rs,
q_hs, q_ds, k_rs, k_hs, k_ds, v_rs, v_hs, v_ds, o_rs, o_hs, o_ds))
return RAD_OK;
#endif
@@ -792,7 +798,7 @@ AVX_KERNEL(attn_dense) {
int64_t jbeg = b0, jend = causal ? (i + 1) : b1;
if (window > 0) {
jbeg = std::max<int64_t>(b0, i - window + 1);
if (!causal) jend = std::min<int64_t>(b1, i + window);
if (!causal) jend = std::min<int64_t>(b1, i + wright);
}
if (block > 0) {
const int64_t blk = b0 + (i - b0) / block * block;
@@ -1067,6 +1073,14 @@ AVX_KERNEL(kv_store) {
* frequencies, and for `axial` a frequency ladder per section. Same rule as libref's rope_freqs. */
enum { ROPE_NEOX = 0, ROPE_GPTJ = 1, ROPE_MROPE = 2, ROPE_IMROPE = 3, ROPE_AXIAL = 4 };
/* A position as libref's rope_pos reads it, divided by the position scale: a float operand's own
* value (a fractional coordinate), an integer operand's integer. */
static inline float rope_pos(const RadTensor* pos, int64_t off, float div) {
const uint32_t dt = pos->dtype;
const bool flt = dt == RAD_F32 || dt == RAD_BF16 || dt == RAD_F16;
return (flt ? ldt(pos, off) : (float)ldi(pos, off)) / div;
}
/* cos in [0, half), sin in [half, rot): the layout `rope_table` writes.
*
* Not sincosf: it gives the same bits but glibc's joint wrapper is slower than two separate
@@ -1218,6 +1232,14 @@ AVX_KERNEL(rope) {
if (mode == ROPE_AXIAL || rscale != 1.0f) return RAD_E_UNSUPPORTED;
for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i);
}
/* Llama 3's frequency scaling, refused beside YaRN or a multi-component mode as libref
* refuses it. */
const RadLlama3 l3 = rad_llama3_args(a);
if (!rad_llama3_valid(l3) || (l3.factor != 0.0f && yarn.factor != 0.0f)) return RAD_E_INVAL;
if (l3.factor != 0.0f) {
if (mode == ROPE_AXIAL || multi) return RAD_E_UNSUPPORTED;
for (int64_t i = 0; i < half; ++i) invf[i] = l3.frequency(invf[i]);
}
for (int64_t i = nfreq; i < half; ++i) invf[i] = 0.0f;
const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0;
@@ -1229,10 +1251,10 @@ AVX_KERNEL(rope) {
float* buf = scratch_f32_b((size_t)rot);
if (multi) {
float pc[8];
for (int64_t c = 0; c < n_comp; ++c) pc[c] = (float)ldi(pos, c * pcs + m * pms) / div;
for (int64_t c = 0; c < n_comp; ++c) pc[c] = rope_pos(pos, c * pcs + m * pms, div);
angles_multi(cs, invf, comp, half, pc);
} else {
angles(cs, invf, half, (float)ldi(pos, offlin(pos, m)) / div);
angles(cs, invf, half, rope_pos(pos, offlin(pos, m), div));
}
if (yarn.factor != 0.0f)
for (int64_t i = 0; i < rot; ++i) cs[i] *= yarn.magnitude;
@@ -1244,14 +1266,16 @@ AVX_KERNEL(rope) {
}
/* ------------------------------------------------------------------ qk_norm_rope */
/* Per-head RMS norm with its own gain, then RoPE.
/* Per-head RMS norm with its own gain, then RoPE. An absent gain is a unit gain without `wadd`,
* and `rotary_dim` 0 is the norm alone, `positions` then optional (libref).
*
* The norm output is rounded to the tensor's dtype before the rotation, as the unfused pair does
* (and libr4d's r4d_qk_norm_rope_gate matches): it is stored with out_row and re-read by the
* rotation rather than kept in f32. */
AVX_KERNEL(qk_norm_rope) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *qkv = &a->t[0], *pos = &a->t[1], *qw = &a->t[2], *kw = &a->t[3];
if (!a || a->n_t < 4 || !rad_arg_in(a, 0)) return RAD_E_INVAL;
const RadTensor *qkv = &a->t[0], *pos = rad_arg_in(a, 1);
const RadTensor *qw = rad_arg_in(a, 2), *kw = rad_arg_in(a, 3);
const int64_t head_dim = p_int(a, "head_dim", 0);
const int64_t n_head = p_int(a, "n_head", 0);
@@ -1263,22 +1287,26 @@ AVX_KERNEL(qk_norm_rope) {
const int v_norm = (int)p_int(a, "v_norm", 0);
/* libref's modes: `gptj_blocks` is `blocks` with each section's pairs adjacent, (start + 2j,
* start + 2j + 1), Qwen-Image's 3-axis rotary; `imrope` is `rope`'s interleaved M-RoPE over
* NeoX pairs (Qwen3-VL's text attention). */
static const char* kModes[] = { "neox", "gptj", "blocks", "gptj_blocks", "imrope" };
const int mode = p_enum(a, "mode", kModes, 5, ROPE_NEOX);
* NeoX pairs (Qwen3-VL's text attention); `axial` is `rope`'s axial form, its section ladders
* over rank-1 positions too. */
static const char* kModes[] = { "neox", "gptj", "blocks", "gptj_blocks", "imrope", "axial" };
const int mode = p_enum(a, "mode", kModes, 6, ROPE_NEOX);
if (mode < 0) return RAD_E_UNSUPPORTED;
const bool blocks = mode == 2 || mode == 3;
const bool adjacent = mode == 3;
const bool im = mode == 4;
const bool axial = mode == 5;
const int64_t rot = p_int(a, "rotary_dim", head_dim);
if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE;
if (numel(qw) < head_dim || numel(kw) < head_dim) return RAD_E_SHAPE;
if (head_dim <= 0 || n_head <= 0 || rot < 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE;
if ((qw && numel(qw) < head_dim) || (kw && numel(kw) < head_dim)) return RAD_E_SHAPE;
const bool turn = rot > 0;
if (turn && !pos) return RAD_E_INVAL;
/* `blocks` mode (libref): section c is sec[c] pairs over its own 2 * sec[c] channels, paired
* (start + j, start + sec[c] + j), rotated by position component comps[c]. */
int64_t sec[8] = {}, comp[8] = {};
int n_sec = 0;
if (im) {
if (turn && (im || axial)) {
for (const char* v = p_str(a, "sections", nullptr); v && *v && n_sec < 8; ) {
char* end = nullptr;
const long long x = std::strtoll(v, &end, 10);
@@ -1287,9 +1315,9 @@ AVX_KERNEL(qk_norm_rope) {
sec[n_sec++] = x;
v = end;
}
if (n_sec < 3) return RAD_E_SHAPE;
if (n_sec < (im ? 3 : 1)) return RAD_E_SHAPE;
}
if (blocks) {
if (turn && blocks) {
for (const char* v = p_str(a, "sections", nullptr); v && *v && n_sec < 8; ) {
char* end = nullptr;
const long long x = std::strtoll(v, &end, 10);
@@ -1314,16 +1342,20 @@ AVX_KERNEL(qk_norm_rope) {
if (k != n_sec) return RAD_E_SHAPE;
}
}
const bool multi = pos->rank >= 2;
const bool multi = pos && pos->rank >= 2;
const int64_t n_comp = multi ? pos->shape[0] : 1;
if (multi && !blocks && !im) return RAD_E_SHAPE;
if (multi && im && n_comp < 3) return RAD_E_SHAPE;
for (int c = 0; blocks && c < n_sec; ++c)
if (comp[c] < 0 || comp[c] >= n_comp || n_comp > 8) return RAD_E_SHAPE;
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
if (turn) {
if (multi && !blocks && !im && !axial) return RAD_E_SHAPE;
if (multi && im && n_comp < 3) return RAD_E_SHAPE;
if (multi && axial && n_comp < n_sec) return RAD_E_SHAPE;
for (int c = 0; blocks && c < n_sec; ++c)
if (comp[c] < 0 || comp[c] >= n_comp || n_comp > 8) return RAD_E_SHAPE;
}
/* The component axis at the operand's own pitch: a [C, M] view of a wider plane. */
const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0;
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
const int64_t M = multi ? pos->shape[1] : numel(pos);
const int64_t M = !pos ? rows_of(qkv, stride_row) : multi ? pos->shape[1] : numel(pos);
if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE;
const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row;
const int64_t ds = laststride(qkv);
@@ -1337,9 +1369,19 @@ AVX_KERNEL(qk_norm_rope) {
float* gq = tab + 2 * half;
float* gk = tab + 2 * half + head_dim;
/* imrope's component per frequency, as libref's rope_freqs: 1 where i % 3 == 1 and
* i < 3 * sec[1], 2 where i % 3 == 2 and i < 3 * sec[2], 0 elsewhere. */
const bool by_comp = blocks || (im && multi);
if (!blocks) {
* i < 3 * sec[1], 2 where i % 3 == 2 and i < 3 * sec[2], 0 elsewhere. axial's sections are
* contiguous, each its own ladder theta^(-2j / (2 sec[c])) and filling rot / 2 exactly. */
const bool by_comp = blocks || (im && multi) || axial;
if (axial) {
int64_t i = 0;
for (int c = 0; c < n_sec; ++c)
for (int64_t j = 0; j < sec[c]; ++j, ++i) {
if (i >= half) return RAD_E_SHAPE;
invf[i] = 1.0f / sc_pow(theta, (float)(2 * j) / (float)(2 * sec[c]));
pcomp[i] = (float)c;
}
if (i != half) return RAD_E_SHAPE;
} else if (!blocks) {
for (int64_t i = 0; i < half; ++i) {
invf[i] = 1.0f / sc_pow(theta, (float)(2 * i) / (float)rot);
pcomp[i] = !im ? 0.0f
@@ -1355,19 +1397,19 @@ AVX_KERNEL(qk_norm_rope) {
}
}
for (int64_t d = 0; d < head_dim; ++d) {
gq[d] = ldt(qw, d * laststride(qw)) + wadd;
gk[d] = ldt(kw, d * laststride(kw)) + wadd;
gq[d] = qw ? ldt(qw, d * laststride(qw)) + wadd : 1.0f;
gk[d] = kw ? ldt(kw, d * laststride(kw)) + wadd : 1.0f;
}
AVX_PARALLEL_FOR_IF(M * (n_head + n_head_kv) * head_dim >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
const float div = rscale != 0.0f ? rscale : 1.0f;
float pc[8];
if (multi)
float pc[8] = {};
if (turn && multi)
for (int64_t c = 0; c < n_comp && c < 8; ++c)
pc[c] = (float)ldi(pos, c * pcs + m * pms) / div;
else
pc[0] = (float)ldi(pos, offlin(pos, m)) / div;
pc[c] = rope_pos(pos, c * pcs + m * pms, div);
else if (turn)
for (float& v : pc) v = rope_pos(pos, offlin(pos, m), div);
const int64_t row = m * rs;
/* cos and sin, then for adjacent pairs the same per rotated channel: cc[2i] = cc[2i+1]
* = cos_i, ss[2i] = -sin_i, ss[2i+1] = sin_i, so channel d becomes
@@ -1404,8 +1446,9 @@ AVX_KERNEL(qk_norm_rope) {
/* Store through the operand's dtype; the rotation re-reads it (see above). */
if (ds == 1) out_row(qkv, base, head_dim, rbuf);
else for (int64_t i = 0; i < head_dim; ++i) stt(qkv, base + i * ds, rbuf[i]);
if (!turn) continue;
if (!blocks) {
rope_head(qkv, base, ds, rot, im ? (int)ROPE_NEOX : mode, cs, half, rbuf);
rope_head(qkv, base, ds, rot, im || axial ? (int)ROPE_NEOX : mode, cs, half, rbuf);
continue;
}
if (pairs_vec) {
+1108
View File
File diff suppressed because it is too large. Load diff
+234 -9
View File
@@ -43,6 +43,8 @@ std::vector<Case> build_cases() {
add("layernorm", { HI("M", 5), HI("n", 645), HF("eps", 1e-5), HS("dtype", dt) },
EB(5, 645, w, 2));
add("add", { HI("M", 9), HI("n", 645), HS("dtype", dt) }, EB(9, 645, w, 3));
add("add", { HI("M", 9), HI("n", 645), HS("dtype", dt), HF("div", 3.0) },
EB(9, 645, w, 3));
add("mul", { HI("M", 9), HI("n", 640), HS("dtype", dt) }, EB(9, 640, w, 3));
add("silu_mul", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 3));
add("gelu_mul", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 3));
@@ -132,6 +134,10 @@ std::vector<Case> build_cases() {
}
add("ngram_ids", { HI("M", 9), HI("heads", 3), HI("ngram", 4), HI("eos", 2) });
/* One scale per column over the rows: no group. */
add("quant_cols_fp8", { HI("M", 5), HI("n", 256), HS("dtype", "bf16") }, EB(5, 256, 2, 1.5));
add("quant_cols_fp8", { HI("M", 7), HI("n", 96), HS("dtype", "f32") }, EB(7, 96, 4, 1.25));
/* Quantisation. 128 is the real grid; 64 tests a second block edge. n = 256 is divisible by
* both, which the had_* forms require (a rotation block may not straddle the row end). */
for (int group : { 64, 128 }) {
@@ -254,13 +260,12 @@ std::vector<Case> build_cases() {
2.0 * M * 192 * 256);
add("gemm_nt_q_gated", { HI("M", 7), HI("N", 512), HI("K", 256), HI("group", 128),
HS("dtype", "fp8a8"), HS("act", "silu") }, 0, 2.0 * 7 * 512 * 256);
/* Runtime LoRA. libref's description draws `slot` in [0, S], so S itself -- a base row --
* comes up in every case of more than one row and the comparison covers rows neither op may
* touch (a single row draws an adapter, or the case would compare nothing). M = 1 takes the
* shrink's team-over-columns arm and 9 and 65 its team-over-rows one; K = 1000
* leaves a partial scale group and a vector tail at every level; R = 48 is not a power of two.
* The dtype is `a`'s for shrink -- the coded ones with their scale stream -- and `y`'s for
* expand. */
/* Runtime LoRA. libref's description draws `slot` in [0, S], so S itself, a base row, comes
* up in every case of more than one row (a single row draws an adapter, or the case would
* compare nothing). M = 1 takes the shrink's team-over-columns arm and 9 and 65 its
* team-over-rows one; K = 1000 leaves a partial scale group and a vector tail at every level;
* R = 48 is not a power of two. The dtype is `a`'s for shrink (the coded ones with their scale
* stream) and `y`'s for expand. */
for (int M : { 1, 9, 65 }) {
for (const char* dt : { "f32", "bf16", "f16", "fp8_e4m3", "i8" })
for (int K : { 256, 1000 })
@@ -300,6 +305,12 @@ std::vector<Case> build_cases() {
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2),
HI("causal", causal), HS("dtype", dt), HF("scale", 0.125),
HI("max_seqlen", 24), HI("window", 5) });
/* A non-causal window reaching further right than left (a sliding encoder layer that sees 4
* keys behind and 7 ahead). */
for (const char* dt : { "f32", "bf16" })
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2), HI("causal", 0),
HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24),
HI("window", 5), HI("window_right", 8) });
/* Blocks: each segment cut into blocks of 7 rows that attend within themselves (a chunked
* encoder's windows), the last block of a segment short. */
for (const char* dt : { "f32", "bf16" })
@@ -436,6 +447,13 @@ std::vector<Case> build_cases() {
}
add("rope_table", { HI("M", 12), HI("rot", 32), HF("theta", 10000.0), HF("scale", 1.0),
HS("dtype", "f32"), HI("head_dim", 64), HS("ladder", "head") });
/* Llama 3's frequency scaling at a depth decoder's settings (theta 5e5, factor 32, original
* length 16): kept, blended and divided frequencies all present. */
for (const char* dt : { "f32", "bf16" })
add("rope", { HI("M", 12), HI("head_dim", 128), HI("n_head", 4), HI("n_head_kv", 2),
HF("theta", 500000.0), HF("scale", 1.0), HS("mode", "neox"),
HF("llama3_factor", 32.0), HF("llama3_low", 0.001953125),
HF("llama3_high", 0.0078125), HF("llama3_orig", 16.0), HS("dtype", dt) });
/* A rotary wider than 1024 (libref takes up to 2048, i.e. 1024 frequencies), plain and with
* contiguous sections, and QSA's key at the same width. */
add("rope", { HI("M", 3), HI("head_dim", 1280), HI("n_head", 1), HI("n_head_kv", 1),
@@ -456,6 +474,18 @@ std::vector<Case> build_cases() {
add("rope", { HI("M", 12), HI("head_dim", 72), HI("n_head", 4), HI("n_head_kv", 4),
HF("theta", 10000.0), HF("scale", 1.0), HS("mode", "axial"),
HI("rotary_dim", 72), HS("sections", "18 18"), HS("dtype", dt) });
/* MiniMax-H3's: the DiT's 3-axis rotary over 96 of 128 channels, the video decoder's
* over 48 of 64; and the norm alone (rotary_dim 0, no positions). f32 positions and
* absent gains are avx_check_hand.cpp's. */
add("qk_norm_rope", { HI("M", 12), HI("head_dim", 128), HI("n_head", 2), HI("n_head_kv", 2),
HF("theta", 10000.0), HF("eps", 1e-5), HS("mode", "axial"),
HI("rotary_dim", 96), HS("sections", "16 16 16"), HS("dtype", dt) });
add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 4),
HF("theta", 100.0), HF("eps", 1e-5), HS("mode", "axial"),
HI("rotary_dim", 48), HS("sections", "8 8 8"), HS("dtype", dt) });
add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 2),
HF("theta", 10000.0), HF("eps", 1e-6), HI("rotary_dim", 0),
HI("v_norm", 1), HS("dtype", dt) });
add("grid_embed", { HI("M", 20), HI("n", 72), HI("side", 6), HS("dtype", dt) });
/* Two table sides. A drawn grid never exceeds the table, so upscaling is covered by
* avx_check's hand-built case. */
@@ -617,6 +647,8 @@ std::vector<Case> build_cases() {
EB(7, 645, dt[0] == 'f' ? 4 : 2, 2));
add("gate_add", { HI("M", 7), HI("n", 645), HS("dtype", dt) },
EB(7, 645, dt[0] == 'f' ? 4 : 2, 3));
add("gate_add", { HI("M", 7), HI("n", 645), HS("dtype", dt), HS("act", "none") },
EB(7, 645, dt[0] == 'f' ? 4 : 2, 3));
for (int gated : { 1, 0 })
add("ln_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-6), HI("group", 128),
HI("gated", gated), HS("dtype", dt) });
@@ -631,8 +663,10 @@ std::vector<Case> build_cases() {
HS("dtype", dt) });
add("flow_euler", { HI("M", 24), HI("n", 64), HI("stride", 16), HS("dtype", dt) });
for (const char* mode : { "fma", "inv" })
add("chan_affine", { HI("M", 9), HI("n", 67), HS("mul", kMul.c_str()),
HS("add", kAdd.c_str()), HS("mode", mode), HS("dtype", dt) });
for (int round : { 1, 0 })
add("chan_affine", { HI("M", 9), HI("n", 67), HS("mul", kMul.c_str()),
HS("add", kAdd.c_str()), HS("mode", mode), HS("dtype", dt),
HI("round", round) });
for (const char* act : { "silu", "none" })
add("l2norm_chan", { HI("M", 9), HI("n", 645), HS("act", act), HS("dtype", dt) });
add("to_rgba8", { HI("M", 9), HI("n", 4), HS("dtype", dt) });
@@ -671,6 +705,187 @@ std::vector<Case> build_cases() {
HI("n_head", 4), HS("qk", qk) });
}
/* ================================================================== video generation
*
* MiniMax-H3's DiT row ops at an odd width, both gated forms; its sampler step over an f32
* state; the decoder's patch unfold, tiles, stitch and positions over the cube geometry
* libref describes (one value in every `geom` entry). Uneven grids, a chunk between two
* others and views of wider planes are avx_check_hand.cpp's. */
static const std::string kStd24 = [] {
std::string s;
for (int i = 0; i < 24; ++i) s += (i ? " " : "") + std::to_string(0.4 + 0.07 * i);
return s;
}();
static const std::string kMean24 = [] {
std::string s;
for (int i = 0; i < 24; ++i) s += (i ? " " : "") + std::to_string(0.031 * i - 0.37);
return s;
}();
for (const char* dt : { "f32", "bf16" }) {
for (int gated : { 1, 0 }) {
add("rms_mod", { HI("M", 7), HI("n", 645), HF("eps", 1e-5), HI("gated", gated),
HS("dtype", dt) });
add("rms_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-5), HI("group", 128),
HI("gated", gated), HS("dtype", dt) });
}
add("flow_x0_step", { HI("M", 9), HI("n", 645), HS("dtype", dt) });
for (int pt : { 1, 4 })
add("patch_unfold", { HI("M", 8 * 4 * pt), HI("C", 24), HI("pt", pt), HI("ph", 2),
HI("pw", 2), HS("mul", kStd24.c_str()),
HS("add", kMean24.c_str()), HS("dtype", dt) });
/* Three frames of 3 x 3: two tiles of 2 a side overlapping by 1, two register rows and
* one zero row a tile. */
add("vtile_gather", { HI("M", 60), HI("n", 37), HI("tile", 2), HI("overlap", 1),
HI("frames", 3), HI("period", 15), HI("n_reg", 2), HS("dtype", dt) });
}
/* A 3 x 3 latent of 3 frames, 2 x 2 tiles a row apart past their voxels, decoded at scale 2
* and two clip frames a latent one: the kept frames and the overlap of a video's only
* chunk. */
add("vtile_stitch", { HI("M", 108), HI("tile", 2), HI("overlap", 1), HI("scale", 2),
HI("pt", 2), HI("skip", 1), HI("keep", 2), HI("blend", 1),
HI("period", 13), HS("mean", "0.485 0.456 0.406"),
HS("std", "0.229 0.224 0.225") });
add("grid_pos3", { HI("M", 40), HI("T", 2), HI("H", 3), HI("W", 4), HI("period", 27),
HF("scale", 6.283185307179586) });
/* Video sparse attention over the cubes libref describes: a 3 x 3 x 3 grid in boxes of 2
* after two dense segments of as many rows (P 8, V 8; sparsity 0.8 keeps 2), with and without
* the coarse operands; and MiniMax-H3's boxes of 4 at patch 2 over a 10 x 5 x 5 grid after
* one segment (P 4, V 12). attn_vsa at k = 1, the one selection a description draws; the
* others are avx_check_hand.cpp's. `n_head`, `coarse` and `dtype` are the description's. */
for (const char* dt : { "f32", "bf16" }) {
for (int coarse : { 1, 0 }) {
add("vsa_select", { HI("M", 81), HI("head_dim", 64), HI("tile_t", 2), HI("tile_h", 2),
HI("tile_w", 2), HI("patch", 1), HF("sparsity", 0.8),
HI("n_head", 2), HI("coarse", coarse), HS("dtype", dt) });
add("attn_vsa", { HI("M", 81), HI("head_dim", 64), HI("tile_t", 2), HI("tile_h", 2),
HI("tile_w", 2), HI("patch", 1), HF("sparsity", 0.9),
HI("n_head", 2), HI("coarse", coarse), HS("dtype", dt) });
}
for (double sp : { 0.5, 0.0 })
add("vsa_select", { HI("M", 500), HI("head_dim", 128), HI("tile_t", 4), HI("tile_h", 4),
HI("tile_w", 4), HI("patch", 2), HF("sparsity", sp),
HI("n_head", 2), HS("dtype", dt) });
add("attn_vsa", { HI("M", 500), HI("head_dim", 128), HI("tile_t", 4), HI("tile_h", 4),
HI("tile_w", 4), HI("patch", 2), HF("sparsity", 0.95), HI("n_head", 2),
HS("dtype", dt) });
}
/* ================================================================== audio generation
*
* The vocoder's convolutions over two sequences (a stereo latent's halves as libref describes
* them), odd channel counts, the codec's kernel widths and dilations and every stride an
* upsampling block uses; the sampler at both branch counts, with and without the conditional
* candidate cut; the window ops over three and four entries, so the drawn flags reach FIRST,
* JOIN and LAST in several combinations. The first case of each op stays inside libref's four
* lanes at twice its rows, which the zero-row check describes. */
for (const char* dt : { "f32", "bf16", "f16" }) {
for (int dil : { 1, 3 })
for (const char* act : { "none", "tanh" })
add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 7),
HI("dil", dil), HS("act", act), HS("dtype", dt) });
add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 3), HI("dil", 9),
HS("dtype", dt) });
add("conv1d", { HI("M", 9), HI("cin", 33), HI("cout", 17), HI("k", 1), HI("dil", 1),
HS("dtype", dt) });
/* Causal: all of the padding on the left (odd k; an even k is a hand-built case, which
* libref's description does not draw). */
for (int dil : { 1, 3 })
add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 7),
HI("dil", dil), HI("causal", 1), HS("dtype", dt) });
for (int s : { 2, 4, 8 })
add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", s),
HS("dtype", dt) });
/* The causal transposed form, a codec's upsampler: no padding, a sequence's first
* output rows reading its first input row alone. */
for (int s : { 2, 4, 8 })
add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", s),
HI("pad", 0), HS("dtype", dt) });
/* A kernel of one stride (one tap a phase), without padding and with some. An odd stride
* is a hand-built case, which libref's description does not draw. */
add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", 2),
HI("k", 2), HS("dtype", dt) });
add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", 4),
HI("k", 4), HI("pad", 1), HS("dtype", dt) });
/* BigVGAN's upsamplers: kernel 9 at stride 5 (three taps in some phases, two in
* others), and a kernel of six strides whose padding passes a stride. */
add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", 5),
HI("k", 9), HS("dtype", dt) });
add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", 2),
HI("k", 12), HS("dtype", dt) });
add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 7), HI("dil", 1),
HS("act", "clamp"), HS("dtype", dt) });
add("snake", { HI("M", 6), HI("n", 645), HS("dtype", dt) });
add("snake", { HI("M", 6), HI("n", 645), HI("log", 1), HS("dtype", dt) });
/* The alias-free SnakeBeta at BigVGAN's 12-tap filters over two sequences, and an odd
* filter at ratio 3. */
for (int lg : { 0, 1 })
add("snake_aa", { HI("M", 24), HI("n", 37), HI("ratio", 2), HI("k", 12),
HI("log", lg), HS("dtype", dt) });
add("snake_aa", { HI("M", 10), HI("n", 645), HI("ratio", 3), HI("k", 7), HS("dtype", dt) });
add("resample_nearest", { HI("M", 9), HI("n", 645), HS("dtype", dt) });
add("resample_nearest", { HI("M", 4), HI("n", 64), HS("dtype", dt) });
add("chan_split", { HI("M", 9), HI("n", 645), HI("parts", 2), HS("dtype", dt) });
add("chan_split", { HI("M", 5), HI("n", 64), HI("parts", 3), HS("dtype", dt) });
add("interleave2", { HI("M", 645), HS("dtype", dt) });
}
for (int rep : { 1, 2 })
for (int ck : { 0, 40 })
add("cfg_topk_sample", { HI("M", 4 * rep), HI("n_vocab", 645), HI("k", 50),
HI("rep", rep), HI("cond_k", ck), HF("cfg", 1.5),
HI("stream", 3), HS("dtype", "f32") });
add("cfg_topk_sample", { HI("M", 6), HI("n_vocab", 645), HI("k", 645), HI("rep", 2),
HF("cfg", 1.7), HF("temp", 0.8), HI("stream", 0),
HS("dtype", "f32") });
/* A speech model's backbone pick: reserved ids suppressed (the vocabulary's last class stays a
* candidate), a temperature, the penalty idle without a history. */
for (int rep : { 1, 2 })
add("cfg_topk_sample", { HI("M", 2 * rep), HI("n_vocab", 645), HI("k", 50),
HI("rep", rep), HF("cfg", 4.0), HF("temp", 0.9), HI("stream", 0),
HI("sup_lo", 600), HI("sup_hi", 644), HF("penalty", 1.1),
HS("dtype", "f32") });
for (const char* dt : { "f32", "bf16" }) {
for (double sc : { 1.0, 0.7 })
add("rvq_embed", { HI("M", 7), HI("n_embd", 645), HI("n_codes", 8), HI("vocab", 64),
HI("off0", 5), HF("scale", sc), HS("dtype", dt) });
/* One rounding of the whole sum: sixteen codebooks, as a speech model's frame embedding. */
for (double sc : { 1.0, 0.7 })
add("rvq_embed", { HI("M", 7), HI("n_embd", 645), HI("n_codes", 16), HI("vocab", 64),
HI("off0", 0), HF("scale", sc), HI("round", 1), HS("dtype", dt) });
add("frame_mix_store", { HI("M", 2), HI("n_embd", 645), HI("L", 9), HI("stride", 5),
HI("rep", 2), HS("dtype", dt) });
add("frame_mix_store", { HI("M", 4), HI("n_embd", 64), HI("L", 3), HI("stride", 2),
HI("rep", 1), HS("dtype", dt) });
for (int round : { 1, 0 })
add("fourier_embed", { HI("M", 5), HI("n", 256), HI("round", round),
HS("dtype", dt) });
add("win_input", { HI("M", 24), HI("n_lat", 37), HI("n_zero", 0), HI("n_cond", 64),
HI("stride", 12), HS("dtype", dt) });
add("win_input", { HI("M", 36), HI("n_lat", 64), HI("n_zero", 3), HI("n_cond", 37),
HI("stride", 16), HS("dtype", dt) });
for (int ov : { 6, 16 })
add("win_prep", { HI("M", 32), HI("n", 64), HI("stride", 16), HI("ov", ov),
HS("dtype", dt) });
add("win_prep", { HI("M", 64), HI("n", 37), HI("stride", 16), HI("ov", 4),
HS("dtype", dt) });
add("win_finish", { HI("M", 32), HI("n", 64), HI("n_cond", 37), HI("stride", 16),
HI("ov", 6), HS("dtype", dt) });
add("win_finish", { HI("M", 64), HI("n", 64), HI("n_cond", 37), HI("stride", 16),
HI("ov", 4), HS("dtype", dt) });
add("win_finish", { HI("M", 36), HI("n", 37), HI("n_cond", 64), HI("stride", 12),
HI("ov", 5), HS("dtype", dt) });
}
add("end_status", { HI("M", 2), HI("end", 5), HI("rep", 2) });
add("end_status", { HI("M", 4), HI("end", 3), HI("rep", 1) });
add("frame_store", { HI("M", 2), HI("n_codes", 16), HI("stride", 9), HI("rep", 2),
HI("skip", 0) });
add("frame_store", { HI("M", 4), HI("n_codes", 3), HI("stride", 5), HI("rep", 1),
HI("skip", 1) });
add("iota", { HI("M", 645), HI("start", 3), HI("step", 2) });
add("iota", { HI("M", 7), HI("start", -5), HI("step", 1) });
add("cu_repeat", { HI("M", 5), HI("mult", 3) });
add("cu_repeat", { HI("M", 9), HI("mult", 1) });
/* ================================================================== speed-only, at model size
*
* Timed by rad-avx-bench, skipped by rad-avx-check. The cases above are sized to break kernels;
@@ -880,6 +1095,16 @@ std::vector<Case> build_cases() {
2.0 * 1024 * 12288 * 4096);
speed("gemm_nt_q", { HI("M", 1024), HI("N", 12288), HI("K", 4096), HI("group", 128),
HS("dtype", "fp8a8") }, 0, 2.0 * 1024 * 12288 * 4096);
/* The music vocoder's third stage (384 channels; a window's two streams there are 88192 rows,
* timed over 8192): a residual unit's dilated 7-tap convolution and its 1 x 1, the stage's
* stride-4 upsampling from 768 channels, and the snake before each. */
speed("conv1d", { HI("M", 8192), HI("cin", 384), HI("cout", 384), HI("k", 7), HI("dil", 3),
HS("dtype", "bf16") }, 0, 2.0 * 8192 * 384 * 384 * 7);
speed("conv1d", { HI("M", 8192), HI("cin", 384), HI("cout", 384), HI("k", 1), HI("dil", 1),
HS("dtype", "bf16") }, 0, 2.0 * 8192 * 384 * 384);
speed("conv_t1d", { HI("M", 2048), HI("cin", 768), HI("cout", 384), HI("stride", 4),
HS("dtype", "bf16") }, 0, 2.0 * 8192 * 384 * 2 * 768);
speed("snake", { HI("M", 8192), HI("n", 384), HS("dtype", "bf16") }, 8192.0 * 384 * 2 * 2, 0);
return c;
}
+872
View File
@@ -19,6 +19,7 @@
* be unchanged, and the parallel rerun applies as for the table (avx_check.cpp). */
#include "avx_check.h"
#include "rad_planes.h"
#include "rad_runtime.h" /* RAD_VGEOM_* */
#include "rad_sample.h"
#ifdef AVX_CHECK_CORE_DECODER
#include "format/encoding.h"
@@ -1944,6 +1945,45 @@ void gen_cases(std::vector<Hand>& hs) {
.pf("scale", 1.0 / std::sqrt((double)hd)).ps("qk", i8 ? "i8" : "bf16");
hs.push_back(std::move(h));
}
/* ---- the prefix-free form: no cache, block table or prefix lengths; two entries of
* 37 and 8 rows, bf16 and int8 scores, columns of a fused projection. */
for (const bool pv8 : { false, true })
for (const bool i8 : { false, true })
for (const int causal : { 0, 1 }) {
const int64_t T = 45, kvh = 2, gqa = 1, qh = 2, hd = 64;
const int64_t W = (qh + 2 * kvh) * hd;
char nm[128];
std::snprintf(nm, sizeof nm, "no prefix, 2 entries%s%s%s%s", i8 ? ", i8" : "",
pv8 ? ", fp8 P.V" : "", causal ? ", causal" : "", sfx.c_str());
Hand h(nm, "attn_prefix_self", dt == RAD_F32 ? 1e-4 : 2e-2);
h.view(dt, { T, qh * hd }, { W, 1 }, T * W, hfill(280))
.view(dt, { T, kvh * hd }, { W, 1 }, T * W, hfill(281));
if (pv8) h.dense(RAD_F8E4M3, { T, kvh * hd }, hfill(282, 64.0f));
else h.view(dt, { T, kvh * hd }, { W, 1 }, T * W, hfill(282));
h.none().none().none()
.idx({ 0, 37, T })
.none().none();
if (i8) {
h.dense(RAD_I8, { T, kvh * hd }, [](int64_t i) {
return (float)((int)((i * 41) % 255) - 127);
})
.dense(RAD_F32, { T, kvh }, [](int64_t i) {
return 0.004f + 0.0005f * (float)(i % 5);
});
} else {
h.none().none();
}
h.view(dt, { T, qh * hd }, { W, 1 }, T * W, zero, true);
if (pv8) h.dense(RAD_F32, { kvh * hd }, [](int64_t i) {
return 0.01f + 0.001f * (float)(i % 11);
});
else h.none();
h.pi("q_len", T).pi("head_dim", hd).pi("gqa", gqa).pi("block_size", 16)
.pi("causal", causal).ps("q_dtype", dn).ps("kv_dtype", dn).pi("max_ctx", 0)
.pf("scale", 1.0 / std::sqrt((double)hd)).ps("qk", i8 ? "i8" : "bf16")
.ps("pv", pv8 ? "fp8" : "bf16");
hs.push_back(std::move(h));
}
{
/* One segment of a longer sequence: cu is its two bounding offsets, rows [5, 30), and
* the rows outside it stay as they were. */
@@ -2004,6 +2044,360 @@ void gen_cases(std::vector<Hand>& hs) {
}
}
/* ================================================================== the video generator */
/* Forms libref's descriptions do not draw: f32 positions as a [3, M] view of a wider plane, absent
* gains and a partial rotary; the DiT's norm over three entries (one empty) with [shift | scale] a
* column slice of a wider modulation table; a latent grid of different extents on every axis, so
* the tiles overlap unevenly; a chunk between two others (the temporal blend and the overlap it
* hands on), a last one and a first one; positions into a view of a wider plane. Everything but
* the norms and the rotaries is held to zero error: libref's arithmetic bit for bit. */
void video_cases(std::vector<Hand>& hs) {
const auto zero = [](int64_t) { return 0.0f; };
for (const uint32_t dt : { (uint32_t)RAD_F32, (uint32_t)RAD_BF16 }) {
const char* dn = dt == RAD_F32 ? "f32" : "bf16";
const std::string sfx = std::string(", ") + dn;
const double norm_tol = dt == RAD_F32 ? 1e-5 : 6e-3;
/* ---- the rotaries: positions f32, component-major, rows 32 apart ------------------- */
{
const int64_t M = 9, hd = 128, nh = 2, nkv = 2, W = (nh + 2 * nkv) * hd;
const auto pos = [](int64_t i) { return 0.37f * (float)(i % 32) - 2.5f; };
Hand h(("the DiT's axial 16 16 16 over 96 of 128, f32 positions" + sfx).c_str(),
"qk_norm_rope", norm_tol);
h.dense(dt, { M, W }, hfill(400), true)
.view(RAD_F32, { 3, M }, { 32, 1 }, 96, pos)
.dense(dt, { hd }, hfill(401, 0.1f))
.dense(dt, { hd }, hfill(402, 0.1f))
.pi("M", M).pi("head_dim", hd).pi("n_head", nh).pi("n_head_kv", nkv)
.pf("theta", 10000.0).pf("eps", 1e-5).ps("mode", "axial").pi("rotary_dim", 96)
.ps("sections", "16 16 16");
hs.push_back(std::move(h));
/* The decoder's: no gains, positions 2 pi (2 (c + 0.5) / n - 1), theta 100. */
const int64_t hv = 64, Wv = 3 * 4 * hv;
const auto vpos = [](int64_t i) {
const int64_t c = i / 32, m = i % 32;
const int64_t n = c == 0 ? 3 : 4, k = c == 0 ? m % 3 : c == 1 ? (m / 4) % 4 : m % 4;
return 6.2831855f * (2.0f * (((float)k + 0.5f) / (float)n) - 1.0f);
};
Hand g(("the decoder's axial 8 8 8 over 48 of 64, no gains" + sfx).c_str(),
"qk_norm_rope", norm_tol);
g.dense(dt, { M, Wv }, hfill(403), true)
.view(RAD_F32, { 3, M }, { 32, 1 }, 96, vpos)
.none().none()
.pi("M", M).pi("head_dim", hv).pi("n_head", 4).pi("n_head_kv", 4)
.pf("theta", 100.0).pf("eps", 1e-5).ps("mode", "axial").pi("rotary_dim", 48)
.ps("sections", "8 8 8");
hs.push_back(std::move(g));
Hand r(("rope over fractional f32 positions, scale 2" + sfx).c_str(), "rope",
norm_tol);
r.dense(dt, { M, 4 * 64 }, hfill(404), true)
.dense(RAD_F32, { M }, [](int64_t i) { return 0.73f * (float)i - 1.1f; })
.pi("M", M).pi("head_dim", 64).pi("n_head", 2).pi("n_head_kv", 1)
.pf("theta", 10000.0).pf("scale", 2.0).ps("mode", "neox");
hs.push_back(std::move(r));
}
/* ---- the DiT's norm: three entries (one empty), [shift | scale] at a 6n pitch ------- */
{
const int64_t R = 11, D = 160, W6 = 6 * D;
for (const bool gated : { true, false }) {
Hand h((std::string(gated ? "gated" : "ungated") + ", three entries, s at a 6n "
"pitch" + sfx).c_str(), "rms_mod", norm_tol);
if (gated) {
h.dense(dt, { R, D }, hfill(410))
.view(dt, { 3, D }, { W6, 1 }, 3 * W6, hfill(411, 0.5f));
} else {
h.none().none();
}
h.view(dt, { 3, 2 * D }, { W6, 1 }, 3 * W6, hfill(412, 0.5f))
.dense(dt, { D }, [](int64_t i) { return 0.8f + 0.003f * (float)i; })
.idx({ 0, 4, 4, R })
.dense(dt, { R, D }, hfill(413, 2.0f), true)
.dense(dt, { R, D }, zero, true)
.pi("M", R).pi("n", D).pf("eps", 1e-5).pi("gated", gated ? 1 : 0)
.ps("dtype", dn);
hs.push_back(std::move(h));
Hand q((std::string(gated ? "gated" : "ungated") + ", quantised, three entries" +
sfx).c_str(), "rms_mod_quant_fp8", 1e-2);
if (gated) {
q.dense(dt, { R, D }, hfill(414))
.view(dt, { 3, D }, { W6, 1 }, 3 * W6, hfill(415, 0.5f));
} else {
q.none().none();
}
q.view(dt, { 3, 2 * D }, { W6, 1 }, 3 * W6, hfill(416, 0.5f))
.dense(dt, { D }, [](int64_t i) { return 0.8f + 0.003f * (float)i; })
.idx({ 0, 4, 4, R })
.dense(dt, { R, D }, hfill(417, 2.0f), true)
.dense(RAD_F8E4M3, { R, D }, zero, true)
.dense(RAD_F32, { R, D / 32 }, zero, true)
.dense(RAD_BF16, { R, D }, zero, true)
.pi("M", R).pi("n", D).pf("eps", 1e-5).pi("group", 32)
.pi("gated", gated ? 1 : 0).ps("dtype", dn);
hs.push_back(std::move(q));
}
}
/* ---- the sampler: a bf16 velocity into an f32 state ------------------------------- */
{
Hand h(("bf16 velocity, f32 state, rows at a wider pitch" + sfx).c_str(),
"flow_x0_step", 0.0);
h.dense(dt, { 7, 96 }, hfill(420, 2.0f))
.dense(RAD_F32, { 1 }, [](int64_t) { return 0.3046875f; })
.dense(RAD_F32, { 1 }, [](int64_t) { return 0.6953125f; })
.dense(RAD_F32, { 1 }, [](int64_t) { return 0.4413f; })
.view(RAD_F32, { 7, 96 }, { 101, 1 }, 7 * 101, hfill(421), true)
.pi("M", 7).pi("n", 96).ps("dtype", dn);
hs.push_back(std::move(h));
}
/* ---- the decoder's geometry: 3 frames of 6 x 9 latents, tiles of 4 over 1 ------------ *
* Rows split 6 -> starts 0, 2 (overlap 2); columns 9 -> 0, 2, 5 (overlaps 2, 1). */
{
Hand h(("2 x 3 x 2 patches of 2 x 2 x 2, rows past the voxels" + sfx).c_str(),
"patch_unfold", 0.0);
h.dense(RAD_F32, { 12, 5 * 8 }, hfill(430, 3.0f))
.idx({ 2, 3, 2 })
.dense(dt, { 100, 5 }, hfill(431), true)
.pi("M", 100).pi("C", 5).pi("pt", 2).pi("ph", 2).pi("pw", 2)
.ps("mul", "0.5 1.25 -2 0.3 1.7").ps("add", "0.1 -0.2 0.3 0 2.5").ps("dtype", dn);
hs.push_back(std::move(h));
/* Two register rows and two zero rows a tile. */
const int64_t n = 37, period = 52, tiles = 6;
Hand g(("6 x 9 in tiles of 4 over 1, registers and zero rows" + sfx).c_str(),
"vtile_gather", 0.0);
g.dense(dt, { 3 * 6 * 9, n }, hfill(432))
.dense(dt, { 2, n }, hfill(433))
.idx({ 3, 6, 9 })
.dense(dt, { tiles * period, n }, hfill(434), true)
.pi("M", tiles * period).pi("n", n).pi("tile", 4).pi("overlap", 1).pi("frames", 3)
.pi("period", period).pi("n_reg", 2).ps("dtype", dn);
hs.push_back(std::move(g));
/* The decoded tiles at scale 2, two clip frames a latent one: skip 1, keep 3, blend 1;
* each tile's 48 token rows, then 4 rows the stitch does not read. */
struct Chunk { int first, last; const char* what; };
static const Chunk kChunks[] = { { 0, 0, "a chunk between two others" },
{ 0, 1, "a video's last chunk" },
{ 1, 0, "a video's first chunk" } };
const int64_t npx = 12 * 18;
for (const Chunk& ch : kChunks) {
const int64_t fout = 3 + (ch.last ? 1 : 0);
Hand s((std::string(ch.what) + ", 6 x 9 in tiles of 4 over 1" + sfx).c_str(),
"vtile_stitch", 0.0);
s.dense(dt, { tiles * period, 3 * 2 * 2 * 2 }, hfill(435, 2.0f))
.idx({ 3, 6, 9, ch.first, ch.last })
.dense(RAD_BF16, { npx, 3 }, hfill(436, 2.0f), true)
.dense(RAD_U8, { fout * npx, 3 }, zero, true)
.pi("M", fout * npx).pi("tile", 4).pi("overlap", 1).pi("scale", 2).pi("pt", 2)
.pi("skip", 1).pi("keep", 3).pi("blend", 1).pi("period", period)
.ps("mean", "0.485 0.456 0.406").ps("std", "0.229 0.224 0.225");
hs.push_back(std::move(s));
}
}
}
/* ---- positions into a [3, 40] view of a [3, 64] plane ---------------------------------- */
{
Hand h("two periods of 2 x 3 x 4 and its registers, rows 64 apart", "grid_pos3", 0.0);
h.view(RAD_F32, { 3, 40 }, { 64, 1 }, 192, [](int64_t) { return -7.0f; }, true)
.pi("M", 40).pi("T", 2).pi("H", 3).pi("W", 4).pi("period", 27)
.pf("scale", 6.283185307179586);
hs.push_back(std::move(h));
}
}
/* ================================================================== video sparse attention
* What libref's descriptions cannot draw: uneven dense segments (13 and 14 rows: a tile each in
* boxes of 4, two each in boxes of 2) before a 6 x 5 x 7 grid (a 10 x 14 latent at patch 2) with
* edge boxes on every axis, and `geom`'s other entries holding values no tile reads; q, k, v and
* the gate at a fused projection's row pitch and the output at a pitch of its own; `sel` and
* `coarse` wider than the tiles and the selection; attn_vsa over selections of every size from 1
* to V that are not a top-k of anything; and what both refuse. Outputs start as a sentinel, so an
* element one side writes and the other leaves shows as a difference, and attn_vsa's `sel` holds
* one wherever the op must not read. */
/* attn_vsa's `sel`, [nh, cap, kc]: per head and video query tile, k distinct video tiles of
* [P, N) in ascending order, drawn from `seed`; `fill` everywhere else. */
std::vector<float> vsa_selection(int64_t nh, int64_t cap, int64_t kc, int64_t P, int64_t N,
int64_t k, uint64_t seed, float fill) {
std::vector<float> s((size_t)(nh * cap * kc), fill);
std::vector<int64_t> pool;
uint64_t x = seed;
for (int64_t h = 0; h < nh; ++h)
for (int64_t i = P; i < N; ++i) {
pool.clear();
for (int64_t j = P; j < N; ++j) pool.push_back(j);
for (int64_t a = 0; a < k; ++a) {
const int64_t b = a + (int64_t)(hsplitmix(x) % (uint64_t)(N - P - a));
std::swap(pool[(size_t)a], pool[(size_t)b]);
}
std::sort(pool.begin(), pool.begin() + k);
for (int64_t a = 0; a < k; ++a)
s[(size_t)((h * cap + i) * kc + a)] = (float)pool[(size_t)a];
}
return s;
}
void vsa_cases(std::vector<Hand>& hs) {
const int64_t R = 237, NH = 2, HD = 64, W = 4 * NH * HD, WO = NH * HD + 24;
const auto sentinel = [](int64_t) { return -7.0f; };
const auto geom = [](int64_t i) {
return i == RAD_VGEOM_LAT_FRAMES ? 6.0f : i == RAD_VGEOM_LAT_H ? 10.0f
: i == RAD_VGEOM_LAT_W ? 14.0f : (float)(1000 + i);
};
struct Geo { int64_t tt, P, V; const char* what; };
static const Geo kGeo[] = { { 4, 2, 8, "boxes of 4" }, { 2, 4, 36, "boxes of 2" } };
for (const uint32_t dt : { (uint32_t)RAD_F32, (uint32_t)RAD_BF16 }) {
const char* dn = dt == RAD_F32 ? "f32" : "bf16";
const double sel_tol = dt == RAD_F32 ? 1e-5 : 6e-3, att_tol = dt == RAD_F32 ? 1e-4 : 2e-2;
for (const Geo& g : kGeo)
for (const double sp : { 0.8, 0.0, 0.95 }) {
const int64_t N = g.P + g.V;
const int64_t k = std::max<int64_t>(
1, std::min<int64_t>((int64_t)std::ceil((1.0 - sp) * (double)g.V), g.V));
char sfx[96];
std::snprintf(sfx, sizeof sfx, ", 13 | 14 then 6 x 5 x 7, %s, sparsity %g, %s",
g.what, sp, dn);
for (const bool coarse : { true, false }) {
Hand h((std::string(coarse ? "q, k, v at a pitch, coarse" : "q, k at a pitch, "
"no coarse") + sfx).c_str(), "vsa_select", sel_tol);
h.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(500))
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(501));
if (coarse) h.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(502, 2.0f));
else h.none();
h.idx({ 0, 13, 27, R })
.dense(RAD_I32, { RAD_VGEOM_N }, geom)
.dense(RAD_I32, { NH, N + 2, k + 2 }, sentinel, true);
if (coarse) h.dense(dt, { NH, N + 1, HD }, sentinel, true);
else h.none();
h.pi("M", R).pi("head_dim", HD).pi("tile_t", g.tt).pi("tile_h", g.tt)
.pi("tile_w", g.tt).pi("patch", 2).pf("sparsity", sp);
hs.push_back(std::move(h));
const std::vector<float> sv =
vsa_selection(NH, N + 1, k + 1, g.P, N, k, 503 + (uint64_t)k, -9.0f);
Hand a((std::string(coarse ? "q, k, v, gate at a pitch, coarse, out at its "
"own" : "q, k, v at a pitch, out at its own") + sfx +
", a drawn selection").c_str(), "attn_vsa", att_tol);
a.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(504))
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(505))
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(506, 2.0f))
.idx({ 0, 13, 27, R })
.dense(RAD_I32, { RAD_VGEOM_N }, geom)
.dense(RAD_I32, { NH, N + 1, k + 1 },
[sv](int64_t i) { return sv[(size_t)i]; });
if (coarse) {
a.dense(dt, { NH, N + 1, HD }, hfill(507, 0.5f))
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(508));
} else {
a.none().none();
}
a.view(dt, { R, NH * HD }, { WO, 1 }, R * WO, sentinel, true)
.pi("M", R).pi("head_dim", HD).pi("tile_t", g.tt).pi("tile_h", g.tt)
.pi("tile_w", g.tt).pi("patch", 2).pf("sparsity", sp);
hs.push_back(std::move(a));
if (!coarse) continue;
/* The int8 score form: k's codes and per-(row, head) scales beside it. */
Hand q8((std::string("int8 scores, coarse") + sfx + ", a drawn selection").c_str(),
"attn_vsa", att_tol);
q8.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(504))
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(505))
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(506, 2.0f))
.idx({ 0, 13, 27, R })
.dense(RAD_I32, { RAD_VGEOM_N }, geom)
.dense(RAD_I32, { NH, N + 1, k + 1 },
[sv](int64_t i) { return sv[(size_t)i]; })
.dense(dt, { NH, N + 1, HD }, hfill(507, 0.5f))
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(508))
.view(dt, { R, NH * HD }, { WO, 1 }, R * WO, sentinel, true)
.dense(RAD_I8, { R, NH * HD }, [](int64_t i) {
return (float)((int)((i * 53) % 255) - 127);
})
.dense(RAD_F32, { R, NH }, [](int64_t i) { return 0.004f + 0.0005f * (float)(i % 9); })
.pi("M", R).pi("head_dim", HD).pi("tile_t", g.tt).pi("tile_h", g.tt)
.pi("tile_w", g.tt).pi("patch", 2).pf("sparsity", sp).ps("qk", "i8");
hs.push_back(std::move(q8));
/* The same with the fp8 P.V form: E4M3 values and a scale per column. */
Hand p8((std::string("int8 scores, fp8 P.V, coarse") + sfx +
", a drawn selection").c_str(), "attn_vsa", att_tol);
p8.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(504))
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(505))
.dense(RAD_F8E4M3, { R, NH * HD }, hfill(506, 64.0f))
.idx({ 0, 13, 27, R })
.dense(RAD_I32, { RAD_VGEOM_N }, geom)
.dense(RAD_I32, { NH, N + 1, k + 1 },
[sv](int64_t i) { return sv[(size_t)i]; })
.dense(dt, { NH, N + 1, HD }, hfill(507, 0.5f))
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(508))
.view(dt, { R, NH * HD }, { WO, 1 }, R * WO, sentinel, true)
.dense(RAD_I8, { R, NH * HD }, [](int64_t i) {
return (float)((int)((i * 53) % 255) - 127);
})
.dense(RAD_F32, { R, NH }, [](int64_t i) {
return 0.004f + 0.0005f * (float)(i % 9);
})
.dense(RAD_F32, { NH * HD }, [](int64_t i) {
return 0.01f + 0.001f * (float)(i % 13);
})
.pi("M", R).pi("head_dim", HD).pi("tile_t", g.tt).pi("tile_h", g.tt)
.pi("tile_w", g.tt).pi("patch", 2).pf("sparsity", sp).ps("qk", "i8")
.ps("pv", "fp8");
hs.push_back(std::move(p8));
}
}
}
/* ---- refusals: nothing written --------------------------------------------------------- */
const int64_t N = 10, k = 2;
std::vector<float> sv = vsa_selection(NH, N, k, 2, N, k, 509, -9.0f);
std::swap(sv[(size_t)(5 * k)], sv[(size_t)(5 * k + 1)]); /* head 0, tile 5: descending */
struct Bad { const char* what; int rc; bool gate; float frames; };
static const Bad kBad[] = {
{ "a selection row out of order", RAD_E_INVAL, true, 6.0f },
{ "coarse without its gate", RAD_E_SHAPE, false, 6.0f },
{ "a grid of 5 frames short of the last segment", RAD_E_SHAPE, true, 5.0f },
};
for (const Bad& b : kBad) {
const float fr = b.frames;
const std::vector<float> sel = b.rc == RAD_E_INVAL
? sv : vsa_selection(NH, N, k, 2, N, k, 509, -9.0f);
Hand a((std::string("refused: ") + b.what).c_str(), "attn_vsa", 2e-2);
a.dense(RAD_BF16, { R, NH * HD }, hfill(510))
.dense(RAD_BF16, { R, NH * HD }, hfill(511))
.dense(RAD_BF16, { R, NH * HD }, hfill(512))
.idx({ 0, 13, 27, R })
.dense(RAD_I32, { RAD_VGEOM_N },
[fr, geom](int64_t i) { return i == RAD_VGEOM_LAT_FRAMES ? fr : geom(i); })
.dense(RAD_I32, { NH, N, k }, [sel](int64_t i) { return sel[(size_t)i]; })
.dense(RAD_BF16, { NH, N, HD }, hfill(513));
if (b.gate) a.dense(RAD_BF16, { R, NH * HD }, hfill(514));
else a.none();
a.dense(RAD_BF16, { R, NH * HD }, sentinel, true)
.pi("M", R).pi("head_dim", HD).pi("tile_t", 4).pi("tile_h", 4).pi("tile_w", 4)
.pi("patch", 2).pf("sparsity", 0.8).refuses(b.rc);
hs.push_back(std::move(a));
}
{
Hand s("refused: a grid of 5 frames short of the last segment", "vsa_select", 6e-3);
s.dense(RAD_BF16, { R, NH * HD }, hfill(515))
.dense(RAD_BF16, { R, NH * HD }, hfill(516))
.none()
.idx({ 0, 13, 27, R })
.dense(RAD_I32, { RAD_VGEOM_N },
[geom](int64_t i) { return i == RAD_VGEOM_LAT_FRAMES ? 5.0f : geom(i); })
.dense(RAD_I32, { NH, N, k }, sentinel, true)
.none()
.pi("M", R).pi("head_dim", HD).pi("tile_t", 4).pi("tile_h", 4).pi("tile_w", 4)
.pi("patch", 2).pf("sparsity", 0.8).refuses(RAD_E_SHAPE);
hs.push_back(std::move(s));
}
}
/* ================================================================== the QSA indexer and DFlash2
* What libref's descriptions cannot draw: cu not starting at 0 and rows no sequence holds, -1
* pages, the score plane as a column slice of the declared width, the block keys in the KV
@@ -3013,6 +3407,481 @@ void encoder_cases(std::vector<Hand>& hs) {
}
}
/* ================================================================== the audio generator */
/* Forms libref's descriptions do not draw: weights at a trained snake's scale (the drawn 0.02
* leaves the sine almost linear) and arguments past the polynomial's range, SnakeBeta, several
* sequences of uneven length starting past row 0 with an empty one, a convolution without its bias
* and residual, a causal one with an even kernel, a depthwise one with a bias, transposed ones at
* odd strides and at a kernel of one stride, sampler rows full of ties, a sampler with per-lane
* guidance and a history (one lane twice), the window entries the run phase issues: unconditional
* branches (pair -2), every flag combination, a window shorter than its overlap, a frame 0, an
* ended lane; codes as a block of a wider plane; and refusals that must write nothing. Everything
* but the convolutions and snake is held to zero error. */
void audio_cases(std::vector<Hand>& hs) {
const auto zero = [](int64_t) { return 0.0f; };
for (const uint32_t dt : { (uint32_t)RAD_F32, (uint32_t)RAD_BF16 }) {
const char* dn = dt == RAD_F32 ? "f32" : "bf16";
const std::string sfx = std::string(", ") + dn;
const double norm_tol = dt == RAD_F32 ? 1e-5 : 6e-3;
{
/* alpha 0.25 .. 4.2 and x in [-8, 8]: arguments to about 34. Row 3 holds 30000 (past
* the polynomial's range, so the row takes the libm sine), row 2 a NaN, row 4 an
* infinity. */
const int64_t n = 67;
Hand h(("trained alphas, a large argument, NaN and infinity" + sfx).c_str(), "snake",
norm_tol);
h.dense(dt, { 5, n }, [n](int64_t i) {
if (i == 3 * n + 4) return 30000.0f;
if (i == 2 * n + 10) return NAN;
if (i == 4 * n + 66) return INFINITY;
return hfill(260, 8.0f)(i);
})
.dense(RAD_F32, { n }, [](int64_t c) { return 0.25f + 0.06f * (float)c; })
.dense(dt, { 5, n }, zero, true)
.pi("M", 5).pi("n", n).ps("dtype", dn);
hs.push_back(std::move(h));
}
{
/* Three sequences from row 2, the second empty, no bias and no residual; rows 0, 1,
* 16 and 17 of y are outside every sequence and keep their bytes. */
const int64_t cin = 20, cout = 13;
Hand h(("rows 2..16 in three sequences, no bias or residual, tanh" + sfx).c_str(),
"conv1d", norm_tol);
h.dense(dt, { 18, cin }, hfill(261))
.dense(dt, { cout, cin, 5 }, hfill(262, 0.3f))
.idx({ 2, 7, 7, 16 })
.none()
.dense(dt, { 18, cout }, hfill(263), true)
.none()
.pi("M", 18).pi("cin", cin).pi("cout", cout).pi("k", 5).pi("dil", 2)
.ps("act", "tanh").ps("dtype", dn);
hs.push_back(std::move(h));
/* x rows at a wider pitch than its channels, with the residual and the bias. */
Hand g(("input rows at a wider pitch, residual and bias" + sfx).c_str(), "conv1d",
norm_tol);
g.view(dt, { 16, cin }, { cin + 3, 1 }, 16 * (cin + 3), hfill(264))
.dense(dt, { cout, cin, 3 }, hfill(265, 0.3f))
.idx({ 0, 9, 16 })
.dense(dt, { 16, cout }, hfill(266))
.dense(dt, { 16, cout }, zero, true)
.dense(dt, { cout }, hfill(267, 0.5f))
.pi("M", 16).pi("cin", cin).pi("cout", cout).pi("k", 3).pi("dil", 1)
.ps("dtype", dn);
hs.push_back(std::move(g));
}
for (const int64_t s : { 4, 2 }) {
/* Sequences of 3, 1 and 5 rows from row 1: output rows [s, 10 s); the first s rows of
* y keep their bytes. */
const int64_t cin = 12, cout = 7;
Hand h(("three uneven sequences from row 1, stride " + std::to_string(s) + sfx).c_str(),
"conv_t1d", norm_tol);
h.dense(dt, { 10, cin }, hfill(268))
.dense(dt, { cin, cout, 2 * s }, hfill(269, 0.3f))
.dense(dt, { cout }, hfill(270, 0.5f))
.idx({ 1, 4, 5, 10 })
.dense(dt, { 10 * s, cout }, hfill(271), true)
.pi("M", 10).pi("cin", cin).pi("cout", cout).pi("stride", s).ps("dtype", dn);
hs.push_back(std::move(h));
}
{
/* Lanes 2, 0, 1, 3 of four ten-row lanes, overlap 4, seven channels (a Philox block of
* four straddles rows): FIRST | JOIN over a whole window; the same flags on an
* unconditional branch, which moves nothing; JOIN alone over a window of 3 rows,
* shorter than the overlap; FIRST alone over 6 rows. */
static const uint32_t kSeeds[8] = { 0x9e3779b9u, 1u, 7u, 0u, 3u, 0xfffffffeu, 11u,
0x80000001u };
Hand h(("every flag combination, an unconditional entry, a short window" + sfx).c_str(),
"win_prep", 0.0);
h.idx({ 17, 17, 16, 1 })
.dense(RAD_F32, { 4 }, [](int64_t i) { return 0.7f - 0.13f * (float)i; })
.raw(RAD_U32, { 8 }, kSeeds)
.idx({ 0, 5, 2, 9 })
.idx({ 2, 0, 1, 3 })
.idx({ 1, -2, -1, -1 })
.idx({ 0, 10, 20, 23, 29 })
.dense(RAD_BF16, { 16, 7 }, hfill(272))
.dense(RAD_BF16, { 16, 7 }, hfill(273), true)
.dense(RAD_BF16, { 40, 7 }, hfill(274), true)
.pi("M", 29).pi("n", 7).pi("stride", 10).pi("ov", 4).ps("dtype", dn);
hs.push_back(std::move(h));
}
{
/* LAST | JOIN over a whole window; LAST over 7 rows (rows - 2 ov < 0, so the kept
* overlap starts at row 0); LAST on an unconditional branch; JOIN without LAST. */
Hand h(("LAST with and without JOIN, a short window, two skipped" + sfx).c_str(),
"win_finish", 0.0);
h.idx({ 24, 8, 8, 16 })
.idx({ -1, -1, -2, 0 })
.idx({ 1, 3, 2, 0 })
.idx({ 0, 10, 17, 20, 25 })
.dense(dt, { 40, 5 }, hfill(275))
.dense(RAD_BF16, { 40, 7 }, hfill(276), true)
.dense(RAD_BF16, { 16, 7 }, hfill(277), true)
.dense(dt, { 16, 5 }, hfill(278), true)
.pi("M", 25).pi("n", 7).pi("n_cond", 5).pi("stride", 10).pi("ov", 4)
.ps("dtype", dn);
hs.push_back(std::move(h));
}
{
/* Lane 1 twice, the second an unconditional branch (zeros for its conditioning). */
Hand h(("an unconditional entry beside its conditional one" + sfx).c_str(),
"win_input", 0.0);
h.dense(dt, { 24, 9 }, hfill(279))
.dense(dt, { 24, 5 }, hfill(280))
.idx({ 0, 6, 12, 15 })
.idx({ 1, 1, 0 })
.idx({ 1, -2, -1 })
.dense(dt, { 15, 16 }, hfill(281), true)
.pi("M", 15).pi("n_lat", 9).pi("n_zero", 2).pi("n_cond", 5).pi("stride", 8)
.ps("dtype", dn);
hs.push_back(std::move(h));
}
{
/* Four lanes, two branch rows each: entry 0 at frame 0 (moves past the prompt only),
* entry 1 on an ended lane, entries 2 and 3 stored. */
Hand h(("frame 0, an ended lane, two stored" + sfx).c_str(), "frame_mix_store", 0.0);
h.dense(dt, { 3 * 8, 37 }, hfill(282, 4.0f))
.dense(RAD_F32, { 3 }, [](int64_t l) { return l == 0 ? 0.3f : l == 1 ? -1.2f : 2.0f; })
.dense(RAD_F32, { 1 }, [](int64_t) { return 1.7f; })
.idx({ 2, 0, 3, 1 })
.idx({ 0, 3, 2, 5 })
.idx({ -1, 2, 5, 7 })
.dense(dt, { 20, 37 }, hfill(283), true)
.pi("M", 4).pi("n_embd", 37).pi("L", 3).pi("stride", 5).pi("rep", 2)
.ps("dtype", dn);
hs.push_back(std::move(h));
}
{
/* Codes past either table: row 1's first code (its row is not written), row 2's
* second (skipped in the sum). Code-major [3, 4]. */
static const int32_t kCodes[12] = { 3, 10, 0, -2, 4, 1, -15, 7, 9, 2, 5, 0 };
Hand h(("codes past either table" + sfx).c_str(), "rvq_embed", 0.0);
h.raw(RAD_I32, { 3, 4 }, kCodes)
.dense(RAD_BF16, { 12, 9 }, hfill(284))
.dense(RAD_BF16, { 20, 9 }, hfill(285))
.dense(dt, { 4, 9 }, hfill(286), true)
.pi("M", 4).pi("n_embd", 9).pi("n_codes", 3).pi("vocab", 10).pi("off0", 2)
.pf("scale", 0.75).ps("dtype", dn);
hs.push_back(std::move(h));
}
for (int round : { 1, 0 }) {
/* A trained projection's scale: angles to about 25 radians. */
Hand h(("trained frequencies, round " + std::to_string(round) + sfx).c_str(),
"fourier_embed", 0.0);
h.dense(RAD_F32, { 5 }, [](int64_t i) { return i == 4 ? 1.0f : 0.23f * (float)i; })
.dense(RAD_F32, { 32 }, hfill(287, 4.0f))
.dense(dt, { 5, 64 }, zero, true)
.pi("M", 5).pi("n", 64).pi("round", round).ps("dtype", dn);
hs.push_back(std::move(h));
}
{
Hand h(("ten rows down to four" + sfx).c_str(), "resample_nearest", 0.0);
h.dense(dt, { 10, 7 }, hfill(288))
.dense(dt, { 4, 7 }, zero, true)
.pi("M", 4).pi("n", 7).ps("dtype", dn);
hs.push_back(std::move(h));
}
{
Hand h(("three groups of input rows at a wider pitch" + sfx).c_str(), "chan_split",
0.0);
h.view(dt, { 5, 21 }, { 25, 1 }, 125, hfill(289))
.dense(dt, { 15, 7 }, zero, true)
.pi("M", 5).pi("n", 7).pi("parts", 3).ps("dtype", dn);
hs.push_back(std::move(h));
}
for (int lg : { 0, 1 }) {
/* SnakeBeta over x in [-8, 8]: alpha and beta as a codec stores them (logarithms in
* [-1, 1], `log` 1) or as positive values. */
const int64_t n = 37;
const std::function<float(int64_t)> al =
lg ? hfill(291) : std::function<float(int64_t)>([](int64_t c) {
return 0.3f + 0.05f * (float)c;
});
const std::function<float(int64_t)> be =
lg ? hfill(292) : std::function<float(int64_t)>([](int64_t c) {
return 0.2f + 0.03f * (float)c;
});
Hand h(("SnakeBeta, alpha and beta as " + std::string(lg ? "logarithms" : "values") +
sfx).c_str(), "snake", norm_tol);
h.dense(dt, { 4, n }, hfill(293, 8.0f))
.dense(RAD_F32, { n }, al)
.dense(dt, { 4, n }, zero, true)
.dense(RAD_F32, { n }, be)
.pi("M", 4).pi("n", n).pi("log", lg).ps("dtype", dn);
hs.push_back(std::move(h));
}
{
/* Two segments from row 1, with a bias; row 0 keeps its bytes. */
const int64_t C = 21;
Hand h(("two segments from row 1, with a bias" + sfx).c_str(), "conv1d_dw", norm_tol);
h.dense(dt, { 12, C }, hfill(294))
.dense(dt, { C, 1, 5 }, hfill(295, 0.4f))
.idx({ 1, 6, 12 })
.dense(dt, { 12, C }, zero, true)
.dense(dt, { C }, hfill(296, 0.5f))
.pi("M", 12).pi("n", C).pi("k", 5).ps("dtype", dn);
hs.push_back(std::move(h));
}
for (int dil : { 1, 3 }) {
/* Causal with an even kernel (a codec's), two sequences, a bias. */
const int64_t cin = 20, cout = 13;
Hand h(("causal, k 4, dilation " + std::to_string(dil) + sfx).c_str(), "conv1d",
norm_tol);
h.dense(dt, { 16, cin }, hfill(296 + dil))
.dense(dt, { cout, cin, 4 }, hfill(300, 0.3f))
.idx({ 0, 7, 16 })
.none()
.dense(dt, { 16, cout }, zero, true)
.dense(dt, { cout }, hfill(301, 0.5f))
.pi("M", 16).pi("cin", cin).pi("cout", cout).pi("k", 4).pi("dil", dil)
.pi("causal", 1).ps("dtype", dn);
hs.push_back(std::move(h));
}
for (const int64_t s : { 5, 3 }) {
/* A codec's odd strides at kernel 2 stride, causal, over sequences of 3, 1 and 5 rows
* from row 1. */
const int64_t cin = 12, cout = 7;
Hand h(("odd stride " + std::to_string(s) + ", causal" + sfx).c_str(), "conv_t1d",
norm_tol);
h.dense(dt, { 10, cin }, hfill(314 + s))
.dense(dt, { cin, cout, 2 * s }, hfill(320, 0.3f))
.dense(dt, { cout }, hfill(321, 0.5f))
.idx({ 1, 4, 5, 10 })
.dense(dt, { 10 * s, cout }, hfill(322), true)
.pi("M", 10).pi("cin", cin).pi("cout", cout).pi("stride", s).pi("pad", 0)
.ps("dtype", dn);
hs.push_back(std::move(h));
}
for (const int64_t s : { 5, 2 }) {
/* BigVGAN's upsamplers (kernel 9 at stride 5, pad 2; kernel 12 at stride 2, its
* default pad 5 past a stride) over sequences of 3, 1 and 5 rows from row 1. */
const int64_t cin = 12, cout = 7, K = s == 5 ? 9 : 12;
Hand h(("kernel " + std::to_string(K) + " at stride " + std::to_string(s) +
", three uneven sequences" + sfx).c_str(), "conv_t1d", norm_tol);
h.dense(dt, { 10, cin }, hfill(330 + s))
.dense(dt, { cin, cout, K }, hfill(336, 0.3f))
.dense(dt, { cout }, hfill(337, 0.5f))
.idx({ 1, 4, 5, 10 })
.dense(dt, { 10 * s, cout }, hfill(338), true)
.pi("M", 10).pi("cin", cin).pi("cout", cout).pi("stride", s).pi("k", K)
.ps("dtype", dn);
hs.push_back(std::move(h));
}
for (const int64_t k : { 12, 7 }) {
/* The alias-free SnakeBeta over sequences of 5, 1 and 9 rows from row 1 (row 0 and
* rows past 16 keep their bytes), at a trained scale: alpha and beta logarithms,
* x in [-4, 4], a smooth low-pass pair of filters. */
const int64_t n = 21;
const auto lowpass = [k](int64_t j) {
const float t = ((float)j + 0.5f) / (float)k - 0.5f;
return (1.0f - 4.0f * t * t) / (float)k * 1.5f;
};
Hand h(("three uneven sequences, filters of " + std::to_string(k) + sfx).c_str(),
"snake_aa", norm_tol);
h.dense(dt, { 18, n }, hfill(340, 4.0f))
.dense(RAD_F32, { n }, hfill(341, 0.8f))
.dense(RAD_F32, { n }, hfill(342, 0.8f))
.dense(RAD_F32, { 1, 1, k }, lowpass)
.dense(RAD_F32, { 1, 1, k }, lowpass)
.idx({ 1, 6, 7, 16 })
.dense(dt, { 18, n }, hfill(343), true)
.pi("M", 18).pi("n", n).pi("ratio", 2).pi("k", k).pi("log", 1).ps("dtype", dn);
hs.push_back(std::move(h));
}
{
/* A kernel of one stride at an odd stride: each output row reads one input row. */
const int64_t cin = 12, cout = 7, s = 3;
Hand h(("kernel 3 at stride 3" + sfx).c_str(), "conv_t1d", norm_tol);
h.dense(dt, { 10, cin }, hfill(323))
.dense(dt, { cin, cout, s }, hfill(324, 0.3f))
.dense(dt, { cout }, hfill(325, 0.5f))
.idx({ 1, 4, 5, 10 })
.dense(dt, { 10 * s, cout }, hfill(326), true)
.pi("M", 10).pi("cin", cin).pi("cout", cout).pi("stride", s).pi("k", s)
.ps("dtype", dn);
hs.push_back(std::move(h));
}
{
/* The causal transposed form over sequences of 3, 1 and 5 rows from row 1. */
const int64_t cin = 12, cout = 7, s = 4;
Hand h(("the causal form over three uneven sequences" + sfx).c_str(), "conv_t1d",
norm_tol);
h.dense(dt, { 10, cin }, hfill(302))
.dense(dt, { cin, cout, 2 * s }, hfill(303, 0.3f))
.dense(dt, { cout }, hfill(304, 0.5f))
.idx({ 1, 4, 5, 10 })
.dense(dt, { 10 * s, cout }, hfill(305), true)
.pi("M", 10).pi("cin", cin).pi("cout", cout).pi("stride", s).pi("pad", 0)
.ps("dtype", dn);
hs.push_back(std::move(h));
}
{
/* One rounding of the whole sum, with codes past either table (row 1's first code
* leaves its row unwritten, row 2's second adds nothing). Code-major [3, 4]. */
static const int32_t kCodes1[12] = { 3, 10, 0, -2, 4, 1, -15, 7, 9, 2, 5, 0 };
Hand h(("one rounding, codes past either table" + sfx).c_str(), "rvq_embed", 0.0);
h.raw(RAD_I32, { 3, 4 }, kCodes1)
.dense(RAD_BF16, { 12, 9 }, hfill(306))
.dense(RAD_BF16, { 20, 9 }, hfill(307))
.dense(dt, { 4, 9 }, hfill(308), true)
.pi("M", 4).pi("n_embd", 9).pi("n_codes", 3).pi("vocab", 10).pi("off0", 2)
.pf("scale", 0.75).pi("round", 1).ps("dtype", dn);
hs.push_back(std::move(h));
/* The codes as a block of a wider plane (a lane's history over a run of frames): rows
* at pitch 11, read at the operand's strides. */
Hand g(("one rounding, codes a block of a wider plane" + sfx).c_str(), "rvq_embed",
0.0);
g.view(RAD_I32, { 3, 5 }, { 11, 1 }, 33, [](int64_t i) { return (float)(i % 9); })
.dense(RAD_BF16, { 12, 9 }, hfill(309))
.dense(RAD_BF16, { 20, 9 }, hfill(310))
.dense(dt, { 5, 9 }, zero, true)
.pi("M", 5).pi("n_embd", 9).pi("n_codes", 3).pi("vocab", 10).pi("off0", 2)
.pf("scale", 1.0).pi("round", 1).ps("dtype", dn);
hs.push_back(std::move(g));
}
}
{
/* Logits on a grid of 0.05 over [-1, 1]: ties throughout, at the k-th place and at the
* conditional's cond_k-th. Three lanes, two branches each. */
static const uint32_t kSeeds[6] = { 5u, 0u, 0xdeadbeefu, 7u, 1u, 1u };
const auto grid = [](int64_t i) { return std::round(hfill(290)(i) * 20.0f) / 20.0f; };
Hand h("ties at the cut and in the guided order", "cfg_topk_sample", 0.0);
h.dense(RAD_F32, { 6, 40 }, grid)
.raw(RAD_U32, { 6 }, kSeeds)
.idx({ 0, 17, 123456 })
.dense(RAD_I32, { 6 }, zero, true)
.pi("M", 6).pi("n_vocab", 40).pi("k", 12).pi("rep", 2).pi("cond_k", 9).pf("cfg", 1.5)
.pi("stream", 2).ps("dtype", "f32");
hs.push_back(std::move(h));
Hand g("one branch, every entry a candidate, a temperature", "cfg_topk_sample", 0.0);
g.dense(RAD_F32, { 3, 40 }, grid)
.raw(RAD_U32, { 6 }, kSeeds)
.idx({ 4, 4, 9 })
.dense(RAD_I32, { 3 }, zero, true)
.pi("M", 3).pi("n_vocab", 40).pi("k", 40).pi("rep", 1).pf("cfg", 1.0).pf("temp", 0.6)
.pi("stream", 0).ps("dtype", "f32");
hs.push_back(std::move(g));
}
{
/* A speech model's frame: three lanes with their own guidance, each lane's history of
* earlier picks penalised (lane 2 at frame 0, its row cleared first), reserved ids
* suppressed; the picks recorded in the history. */
static const uint32_t kSeeds[6] = { 5u, 0u, 0xdeadbeefu, 7u, 1u, 1u };
Hand h("guidance a lane, a history, reserved ids", "cfg_topk_sample", 0.0);
h.dense(RAD_F32, { 6, 40 }, hfill(311, 3.0f))
.raw(RAD_U32, { 6 }, kSeeds)
.idx({ 4, 0, 9 })
.dense(RAD_I32, { 6 }, zero, true)
.dense(RAD_F32, { 3 }, [](int64_t i) { return 1.0f + 1.5f * (float)i; })
.idx({ 1, 2, 3 })
.dense(RAD_I32, { 4, 40 }, [](int64_t i) { return (float)((i * 7) % 3 == 0); }, true)
.pi("M", 6).pi("n_vocab", 40).pi("k", 12).pi("rep", 2).pf("cfg", 1.0).pf("temp", 0.9)
.pi("stream", 0).pi("sup_lo", 36).pi("sup_hi", 39).pf("penalty", 1.1)
.ps("dtype", "f32");
hs.push_back(std::move(h));
/* One lane twice, in order: logits 4 - 0.5 j at temperature 0.01, so each entry takes its
* best candidate; the first takes id 0, which the second sees penalised (4 / 1.5 falls
* below id 1's 3.5). */
static const uint32_t kSeeds2[4] = { 9u, 0u, 9u, 0u };
Hand g("one lane twice: the second entry sees the first's pick", "cfg_topk_sample", 0.0);
g.dense(RAD_F32, { 2, 40 }, [](int64_t i) { return 4.0f - 0.5f * (float)(i % 40); })
.raw(RAD_U32, { 4 }, kSeeds2)
.idx({ 3, 4 })
.dense(RAD_I32, { 2 }, zero, true)
.none()
.idx({ 1, 1 })
.dense(RAD_I32, { 2, 40 }, zero, true)
.pi("M", 2).pi("n_vocab", 40).pi("k", 3).pi("rep", 1).pf("cfg", 1.0).pf("temp", 0.01)
.pi("stream", 0).pf("penalty", 1.5).ps("dtype", "f32")
.expect(3, { 0, 1 });
hs.push_back(std::move(g));
/* Refusals before anything is written: a lane past the history, every id suppressed, and
* the conditional's best ids all suppressed. */
Hand r1("a lane past the history", "cfg_topk_sample", 0.0);
r1.dense(RAD_F32, { 2, 40 }, hfill(312))
.raw(RAD_U32, { 2 }, kSeeds)
.idx({ 0 })
.dense(RAD_I32, { 2 }, zero, true)
.none()
.idx({ 5 })
.dense(RAD_I32, { 4, 40 }, zero, true)
.pi("M", 2).pi("n_vocab", 40).pi("k", 5).pi("rep", 2).pf("cfg", 2.0)
.pi("stream", 0).pf("penalty", 1.1).ps("dtype", "f32")
.refuses(RAD_E_SHAPE);
hs.push_back(std::move(r1));
Hand r2("every id suppressed", "cfg_topk_sample", 0.0);
r2.dense(RAD_F32, { 1, 40 }, hfill(313))
.raw(RAD_U32, { 2 }, kSeeds)
.idx({ 2 })
.dense(RAD_I32, { 1 }, zero, true)
.pi("M", 1).pi("n_vocab", 40).pi("k", 5).pi("rep", 1).pf("cfg", 1.0)
.pi("stream", 0).pi("sup_lo", 0).pi("sup_hi", 40).ps("dtype", "f32")
.refuses(RAD_E_SHAPE);
hs.push_back(std::move(r2));
Hand r3("the conditional's best ids all suppressed", "cfg_topk_sample", 0.0);
r3.dense(RAD_F32, { 2, 40 }, [](int64_t i) {
const int64_t j = i % 40;
return j >= 10 && j < 15 ? 5.0f : -0.01f * (float)j;
})
.raw(RAD_U32, { 2 }, kSeeds)
.idx({ 2 })
.dense(RAD_I32, { 2 }, zero, true)
.pi("M", 2).pi("n_vocab", 40).pi("k", 5).pi("rep", 2).pi("cond_k", 5).pf("cfg", 1.5)
.pi("stream", 0).pi("sup_lo", 10).pi("sup_hi", 20).ps("dtype", "f32")
.refuses(RAD_E_SHAPE);
hs.push_back(std::move(r3));
}
{
/* Four entries, codes a block of a wider plane (pitch 11, each lane's two branch columns):
* entry 0 at frame 0 under skip 1 (moves past the prompt), entry 3 on an ended lane,
* entries 1 and 2 stored. */
Hand h("frame 0 under skip, an ended lane, codes a block", "frame_store", 0.0);
h.view(RAD_I32, { 3, 8 }, { 11, 1 }, 33, [](int64_t i) { return (float)(100 + i); })
.idx({ 2, 0, 3, 1 })
.idx({ 0, 3, 2, 5 })
.idx({ 1, -1, 4, 2 })
.dense(RAD_I32, { 12, 6 }, [](int64_t) { return -7.0f; }, true)
.pi("M", 4).pi("n_codes", 3).pi("stride", 6).pi("rep", 2).pi("skip", 1);
hs.push_back(std::move(h));
/* Refusals before anything is written: a frame past its lane's row, a lane past the
* status. */
Hand r1("a frame past its lane's row", "frame_store", 0.0);
r1.idx({ 1, 2, 3, 4, 5, 6 })
.idx({ 0, 1 })
.idx({ 7, 2 })
.idx({ 0, 0 })
.dense(RAD_I32, { 6, 6 }, [](int64_t) { return -7.0f; }, true)
.pi("M", 2).pi("n_codes", 3).pi("stride", 6).pi("rep", 1).pi("skip", 1)
.refuses(RAD_E_SHAPE);
hs.push_back(std::move(r1));
Hand r2("a lane past the status", "frame_store", 0.0);
r2.idx({ 1, 2, 3 })
.idx({ 4 })
.idx({ 2 })
.idx({ 0, 0, 0, 0 })
.dense(RAD_I32, { 12, 6 }, [](int64_t) { return -7.0f; }, true)
.pi("M", 1).pi("n_codes", 3).pi("stride", 6).pi("rep", 1).pi("skip", 0)
.refuses(RAD_E_SHAPE);
hs.push_back(std::move(r2));
}
{
/* Lane 2 ends (its pick is `end`), lanes 0 and 1 continue, lane 3 is not in the frame. */
Hand h("an ending lane among continuing ones", "end_status", 0.0);
h.idx({ 5, 5, 3, 3, 5, 5 })
.idx({ 2, 0, 1 })
.idx({ 7, 7, 7, 7 }, true)
.pi("M", 3).pi("end", 5).pi("rep", 2)
.expect(2, { 3, -1, -1, 7 });
hs.push_back(std::move(h));
}
}
} // namespace
bool hand_cases(const Check& ck) {
@@ -3022,8 +3891,11 @@ bool hand_cases(const Check& ck) {
anchor_cases(hs);
packed_cases(hs);
gen_cases(hs);
video_cases(hs);
vsa_cases(hs);
qsa_cases(hs);
encoder_cases(hs);
audio_cases(hs);
Broken broken;
planes_cases(ck, hs, broken);
+22 -5
View File
@@ -32,12 +32,15 @@ static inline void roundtrip(uint32_t dt, float* v, int64_t n, void* tmp) {
/* ------------------------------------------------------------------ add / mul */
/* y = a op b over the output's extent. A one-row `b` is broadcast down the rows; nothing else
* broadcasts, so a shape bug fails instead of producing plausible numbers. */
* broadcasts, so a shape bug fails instead of producing plausible numbers. `add`'s `div` divides
* the sum rounded through y's dtype, as libref rounds it. */
template <bool MUL>
static int elementwise2(const RadArgs* a) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2];
const int64_t n = p_int(a, "n", numel(Y));
const float div = MUL ? 1.0f : p_f32(a, "div", 1.0f);
if (!(div != 0.0f) || !std::isfinite(div)) return RAD_E_INVAL;
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(A) < rows * n) return RAD_E_SHAPE;
@@ -57,6 +60,13 @@ static int elementwise2(const RadArgs* a) {
vf_storeu(sy + i, MUL ? vf_mul(u, v) : vf_add(u, v));
}
for (; i < n; ++i) sy[i] = MUL ? x[i] * y[i] : x[i] + y[i];
if (div != 1.0f) {
/* sa is free once x is read: the sum's narrowing goes through it. */
roundtrip(Y->dtype, sy, n, sa);
const vf vd = vf_set1(div);
for (i = 0; i + VF_N <= n; i += VF_N) vf_storeu(sy + i, vf_div(vf_loadu(sy + i), vd));
for (; i < n; ++i) sy[i] /= div;
}
out_row(Y, rowoff(Y, r, n), n, sy);
}
return RAD_OK;
@@ -371,22 +381,27 @@ AVX_KERNEL(conv2d_unfold) {
}
/* ------------------------------------------------------------------ conv1d_dw */
/* libref's causal depthwise convolution over time. The weight is transposed to [k][C] once per
* launch so each tap is a vector FMA over the row. */
/* libref's causal depthwise convolution over time, plus the optional bias. The weight is
* transposed to [k][C] once per launch so each tap is a vector FMA over the row. */
AVX_KERNEL(conv1d_dw) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Wt = &a->t[1], *cu = &a->t[2], *Y = &a->t[3];
const RadTensor* B = rad_arg_in(a, 4);
const int64_t C = p_int(a, "n", 0), K = p_int(a, "k", 0), cdiv = p_int(a, "cu_div", 1);
if (C <= 0 || K <= 0 || cdiv <= 0 || numel(Wt) < C * K) return RAD_E_SHAPE;
if (C <= 0 || K <= 0 || cdiv <= 0 || numel(Wt) < C * K || (B && numel(B) < C))
return RAD_E_SHAPE;
const int64_t S = numel(cu) - 1;
if (S <= 0) return RAD_E_SHAPE;
const int64_t Mx = rows_of(X, C), My = rows_of(Y, C);
if (Mx <= 0 || My <= 0 || ldi(cu, offlin(cu, S)) <= ldi(cu, offlin(cu, 0)))
return RAD_E_SHAPE; /* zero rows is not a call (docs/OPS.md) */
float* wt = (float*)scratch_raw((size_t)(K * C) * sizeof(float) + 64);
/* The taps tap-major, then the bias (zeros when unbound), once a launch. */
float* wt = (float*)scratch_raw((size_t)((K + 1) * C) * sizeof(float) + 64);
float* bias = wt + K * C;
for (int64_t c = 0; c < C; ++c)
for (int64_t j = 0; j < K; ++j) wt[j * C + c] = ldt(Wt, (c * K + j) * laststride(Wt));
for (int64_t c = 0; c < C; ++c) bias[c] = B ? ldt(B, c) : 0.0f;
for (int64_t s = 0; s < S; ++s) {
const int64_t c0 = ldi(cu, offlin(cu, s)), c1 = ldi(cu, offlin(cu, s + 1));
@@ -409,6 +424,8 @@ AVX_KERNEL(conv1d_dw) {
vf_storeu(acc + c, vf_fma(vf_loadu(xr + c), vf_loadu(wr + c), vf_loadu(acc + c)));
for (; c < C; ++c) acc[c] += xr[c] * wr[c];
}
if (B)
for (int64_t c = 0; c < C; ++c) acc[c] += bias[c];
out_row(Y, rowoff(Y, t, C), C, acc);
}
}
+159 -18
View File
@@ -1,18 +1,19 @@
/* avx_gen.cpp -- the image generator's ops (docs/OPS.md, "Image generation") except
* attn_prefix_self (avx_gen_attn.cpp): the diffusion transformer's adaptive norms and gated
* residual, the timestep embedding, the per-image latent lanes and the flow-matching sampler, and
* the image decoder's convolution, channel norm, resampling shortcuts and pixel output.
* the image decoder's convolution, channel norm, resampling shortcuts and pixel output; and a video
* generator's modulated RMS norms and sampler step ("Video generation").
*
* Each op rounds where libref/ref_gen.cpp rounds, which is where the upstream bf16 model stores a
* tensor. Rows are computed in f32 scratch and every such rounding is a pass through the stored
* dtype (`narrow_row`), so a fused kernel produces the bytes of the unfused chain.
*
* Bit-exact with libref, not only within tolerance: randn_lanes and flow_euler (a seed gives the
* same picture on every plugin, and the sampler's state feeds every later step), gate_add,
* chan_affine, to_rgba8, s2d_avg_add, d2s_add, the lane copies and timestep_embed. Where libref
* multiplies and then adds in two roundings, `keep` stops the compiler from fusing the pair (this
* plugin is built with -ffp-contract=fast, libref without contraction). The norms reduce in a
* different order from libref's and are held to the tolerance table.
* Bit-exact with libref, not only within tolerance: randn_lanes, flow_euler and flow_x0_step (a
* seed gives the same picture on every plugin, and the sampler's state feeds every later step),
* gate_add, chan_affine, to_rgba8, s2d_avg_add, d2s_add, the lane copies and timestep_embed.
* Where libref multiplies and then adds in two roundings, `keep` stops the compiler from fusing
* the pair (this plugin is built with -ffp-contract=fast, libref without contraction). The norms
* reduce in a different order from libref's and are held to the tolerance table.
*
* Per-entry tables (a sequence's modulation row, its tanh gate) are built once per launch before
* the parallel region, in scratch_raw; the row loops use only scratch_f32 / _b / _c, so the
@@ -107,6 +108,12 @@ inline void mul_rows(float* v, const float* w, int64_t n) {
for (; i < n; ++i) v[i] *= w[i];
}
inline void mul_into(float* out, const float* a, const float* b, int64_t n) {
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N) vf_storeu(out + i, vf_mul(vf_loadu(a + i), vf_loadu(b + i)));
for (; i < n; ++i) out[i] = a[i] * b[i];
}
inline void add_rows(float* v, const float* w, int64_t n) {
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N) vf_storeu(v + i, vf_add(vf_loadu(v + i), vf_loadu(w + i)));
@@ -116,7 +123,8 @@ inline void add_rows(float* v, const float* w, int64_t n) {
/* An entry's modulation row through `f`, rounded to `dt`, for every entry: [n_seq][n] floats in
* scratch_raw. `s` is [n_seq, >= n] at its own row pitch (a column slice of the shared
* modulation projection), read as libref reads it. `f` 0 is 1 + s, 1 is tanh(s), the exact libm
* tanh: a gate is per entry and column, so n_seq * n tanh calls per launch, not one per element. */
* tanh: a gate is per entry and column, so n_seq * n tanh calls per launch, not one per element.
* `f` 2 is s itself, unrounded. */
float* entry_rows(const RadTensor* s, int64_t n_seq, int64_t n, uint32_t dt, int f) {
float* t = (float*)scratch_raw((size_t)(n_seq * n + 16) * sizeof(float));
const int64_t rs = row_stride(s, n), cs = laststride(s);
@@ -124,7 +132,7 @@ float* entry_rows(const RadTensor* s, int64_t n_seq, int64_t n, uint32_t dt, int
float* row = t + e * n;
for (int64_t i = 0; i < n; ++i) {
const float v = ldt(s, e * rs + i * cs);
row[i] = narrow1(dt, f ? sc_tanh(v) : 1.0f + v);
row[i] = f == 2 ? v : narrow1(dt, f ? sc_tanh(v) : 1.0f + v);
}
}
return t;
@@ -173,14 +181,15 @@ inline uint64_t seed_of(const RadTensor* seed, int64_t e) {
((uint64_t)(uint32_t)ldi(seed, offlin(seed, 2 * e + 1)) << 32);
}
/* The bf16 values of a space-separated list (libref's parse_list): up to `cap` into out. */
int64_t parse_list(const char* s, float* out, int64_t cap) {
/* The bf16 values of a space-separated list (libref's parse_list), or with `bf16` false its f32
* values: up to `cap` into out. */
int64_t parse_list(const char* s, float* out, int64_t cap, bool bf16 = true) {
int64_t k = 0;
while (s && *s) {
char* end = nullptr;
const double v = std::strtod(s, &end);
if (end == s) break;
if (k < cap) out[k] = narrow1(RAD_BF16, (float)v);
if (k < cap) out[k] = bf16 ? narrow1(RAD_BF16, (float)v) : (float)v;
++k;
s = end;
}
@@ -217,15 +226,19 @@ AVX_KERNEL(ln_mod) {
}
/* ------------------------------------------------------------------ gate_add */
/* x = bf16( x + bf16( bf16(tanh(g[seq])) * y ) ), the roundings in x's dtype. */
/* x = bf16( x + bf16( bf16(tanh(g[seq])) * y ) ), the roundings in x's dtype; with `act` none the
* gate is g itself, unrounded. */
AVX_KERNEL(gate_add) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *Yv = &a->t[0], *G = &a->t[1], *cu = &a->t[2], *X = &a->t[3];
const int64_t n = p_int(a, "n", 0);
static const char* kActs[] = { "tanh", "none" };
const int act = p_enum(a, "act", kActs, 2, 0);
if (act < 0 || act > 1) return RAD_E_INVAL;
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Yv, n), n_seq = numel(cu) - 1;
if (rows <= 0 || n_seq <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE;
const float* gate = entry_rows(G, n_seq, n, X->dtype, 1);
const float* gate = entry_rows(G, n_seq, n, X->dtype, act ? 2 : 1);
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
@@ -308,6 +321,89 @@ AVX_KERNEL(ln_mod_quant_fp8) {
return RAD_OK;
}
/* ------------------------------------------------------------------ rms_mod / rms_mod_quant_fp8 */
/* Both forms: with `gated` the branch added through the gate row (no tanh) and the residual stored
* in x's dtype; then n1 = rd(x rsqrt(mean(x^2) + eps)), n2 = rd(n1 w), m = rd(n2 rd(1 + scale)),
* z = rd(m + shift), rd the norm chain's dtype (z's for rms_mod, bf16 for the quantised form,
* libref's rule). The sum of squares is the vector reduction, held to the tolerance table; every
* rounding is a pass through the stored dtype, so the rest is libref's arithmetic. The per-entry
* rows (1 + scale rounded, the shift and the gate) and the gain are built once a launch. */
static int rms_mod_run(const RadArgs* a, bool quant) {
if (a->n_t < (quant ? 9 : 7)) return RAD_E_INVAL;
const RadTensor *Yv = rad_arg_in(a, 0), *G = rad_arg_in(a, 1), *S = &a->t[2], *W = &a->t[3];
const RadTensor *cu = &a->t[4], *X = &a->t[5];
const RadTensor *Q = quant ? &a->t[6] : nullptr, *SC = quant ? &a->t[7] : nullptr;
const RadTensor* Z = quant ? rad_arg_in(a, 8) : &a->t[6];
const int64_t n = p_int(a, "n", 0), grp = quant ? p_int(a, "group", 0) : 1;
const bool gated = p_int(a, "gated", 0) != 0;
const float eps = p_f32(a, "eps", 1e-6f);
if (n <= 0 || grp <= 0 || n % grp || (gated && (!Yv || !G))) return RAD_E_SHAPE;
const int64_t rows = rows_of(quant ? Q : Z, n), n_seq = numel(cu) - 1, ngrp = n / grp;
if (rows <= 0 || n_seq <= 0 || rows_of(X, n) < rows || numel(W) < n ||
numel(S) < n_seq * 2 * n)
return RAD_E_SHAPE;
if (gated && (rows_of(Yv, n) < rows || numel(G) < n_seq * n)) return RAD_E_SHAPE;
if (quant && (numel(SC) < rows * ngrp || (Z && rows_of(Z, n) < rows))) return RAD_E_SHAPE;
const uint32_t dt = quant ? (uint32_t)RAD_BF16 : Z->dtype;
/* The tables from one scratch_raw call, [gain | shift | gate] a sequence and the weight row:
* a second call may reallocate the first. */
const int64_t tw = gated ? 3 * n : 2 * n;
float* tabs = (float*)scratch_raw((size_t)(n_seq * tw + n + 32) * sizeof(float));
{
const int64_t s_rs = row_stride(S, 2 * n), s_cs = laststride(S);
const int64_t g_rs = gated ? row_stride(G, n) : 0, g_cs = gated ? laststride(G) : 0;
for (int64_t e = 0; e < n_seq; ++e)
for (int64_t i = 0; i < n; ++i) {
float* row = tabs + e * tw;
row[i] = narrow1(dt, 1.0f + ldt(S, e * s_rs + (n + i) * s_cs));
row[n + i] = ldt(S, e * s_rs + i * s_cs);
if (gated) row[2 * n + i] = ldt(G, e * g_rs + i * g_cs);
}
for (int64_t i = 0; i < n; ++i) tabs[n_seq * tw + i] = ldt(W, i * laststride(W));
}
const float* wrow = tabs + n_seq * tw;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* buf = scratch_f32((size_t)(5 * n + 80));
float *xs = buf, *v = buf + n + 16, *o = v + n + 16, *codes = o + n + 16;
float* tmp = codes + n + 16;
const float* ent = tabs + seq_of(cu, n_seq, r) * tw;
const float* xv = in_row(X, rowoff(X, r, n), n, xs);
if (gated) {
const float* yv = in_row(Yv, rowoff(Yv, r, n), n, codes);
mul_into(v, ent + 2 * n, yv, n);
narrow_row(X->dtype, v, n, tmp);
add_rows(v, xv, n);
narrow_row(X->dtype, v, n, tmp);
out_row(X, rowoff(X, r, n), n, v);
} else {
std::memcpy(v, xv, (size_t)n * sizeof(float));
}
const float rs = 1.0f / std::sqrt(row_sumsq(v, n) / (float)n + eps);
const vf vr = vf_set1(rs);
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N) vf_storeu(o + i, vf_mul(vf_loadu(v + i), vr));
for (; i < n; ++i) o[i] = v[i] * rs;
narrow_row(dt, o, n, tmp);
mul_rows(o, wrow, n);
narrow_row(dt, o, n, tmp);
mul_rows(o, ent, n);
narrow_row(dt, o, n, tmp);
add_rows(o, ent + n, n);
if (!quant) {
out_row(Z, rowoff(Z, r, n), n, o);
continue;
}
narrow_row(dt, o, n, tmp);
fp8_emit(o, codes, n, grp, Q, SC, Z, r);
}
return RAD_OK;
}
AVX_KERNEL(rms_mod) { return rms_mod_run(a, false); }
AVX_KERNEL(rms_mod_quant_fp8) { return rms_mod_run(a, true); }
/* ------------------------------------------------------------------ timestep_embed */
/* y[m] = [cos(t' f_0) .. cos(t' f_{h-1}) | sin(t' f_0) .. sin(t' f_{h-1})] with libref's libm
* calls: a pass embeds one row per entry, so this is a few thousand transcendentals. */
@@ -559,20 +655,60 @@ AVX_KERNEL(flow_euler) {
return RAD_OK;
}
/* ------------------------------------------------------------------ flow_x0_step */
/* x' = f32(f32(r x) + f32(f32(1 - r) d)) with d = f32(x + f32((1 - t) v)) and
* r = sigma_next / sigma: libref's f32 steps bit for bit, `keep` holding each product to its own
* rounding. */
AVX_KERNEL(flow_x0_step) {
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
const RadTensor *V = &a->t[0], *T = &a->t[1], *sg = &a->t[2], *sgn = &a->t[3], *X = &a->t[4];
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(X, n);
if (rows <= 0 || rows_of(V, n) < rows || numel(T) < 1 || numel(sg) < 1 || numel(sgn) < 1)
return RAD_E_SHAPE;
const float st = 1.0f - ldt(T, offlin(T, 0));
const float r = ldt(sgn, offlin(sgn, 0)) / ldt(sg, offlin(sg, 0));
const float omr = 1.0f - r;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t k = 0; k < rows; ++k) {
float* buf = scratch_f32((size_t)(3 * n + 48));
float *vs = buf, *xs = buf + n + 16, *o = xs + n + 16;
const float* v = in_row(V, rowoff(V, k, n), n, vs);
const float* x = in_row(X, rowoff(X, k, n), n, xs);
const vf vst = vf_set1(st), vr = vf_set1(r), vo = vf_set1(omr);
int64_t c = 0;
for (; c + VF_N <= n; c += VF_N) {
const vf xv = vf_loadu(x + c);
const vf d = vf_add(xv, keep(vf_mul(vst, vf_loadu(v + c))));
vf_storeu(o + c, vf_add(keep(vf_mul(vr, xv)), keep(vf_mul(vo, d))));
}
for (; c < n; ++c) {
const float d = x[c] + keep(st * v[c]);
o[c] = keep(r * x[c]) + keep(omr * d);
}
out_row(X, rowoff(X, k, n), n, o);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ chan_affine */
/* A per-channel affine from two lists of n bf16 values: `fma` is bf16(bf16(x * mul) + add), `inv`
* is bf16(bf16(x - add) / mul), the inner rounding in y's dtype. */
AVX_KERNEL(chan_affine) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
const int64_t n = p_int(a, "n", 0);
const int64_t n = p_int(a, "n", 0), rnd = p_int(a, "round", 1);
if (rnd < 0 || rnd > 1) return RAD_E_INVAL;
if (n <= 0) return RAD_E_SHAPE;
const char* ms = p_str(a, "mul", ""), *as = p_str(a, "add", "");
/* Each number takes at least two characters but the last, so this bounds the count. */
const int64_t cap = (int64_t)((std::strlen(ms) + std::strlen(as)) / 2 + 2);
float* lists = (float*)scratch_raw((size_t)(2 * cap + 16) * sizeof(float));
float *mul = lists, *add = lists + cap;
if (parse_list(ms, mul, cap) != n || parse_list(as, add, cap) != n) return RAD_E_SHAPE;
if (parse_list(ms, mul, cap, rnd) != n || parse_list(as, add, cap, rnd) != n)
return RAD_E_SHAPE;
const char* mode = p_str(a, "mode", "fma");
const bool inv = mode && !std::strcmp(mode, "inv");
if (!inv && mode && std::strcmp(mode, "fma")) return RAD_E_INVAL;
@@ -589,16 +725,21 @@ AVX_KERNEL(chan_affine) {
for (; c + VF_N <= n; c += VF_N)
vf_storeu(t + c, vf_sub(vf_loadu(x + c), vf_loadu(add + c)));
for (; c < n; ++c) t[c] = x[c] - add[c];
narrow_row(Y->dtype, t, n, tmp);
if (rnd) narrow_row(Y->dtype, t, n, tmp);
for (c = 0; c + VF_N <= n; c += VF_N)
vf_storeu(t + c, vf_div(vf_loadu(t + c), vf_loadu(mul + c)));
for (; c < n; ++c) t[c] /= mul[c];
} else {
} else if (rnd) {
for (; c + VF_N <= n; c += VF_N)
vf_storeu(t + c, vf_mul(vf_loadu(x + c), vf_loadu(mul + c)));
for (; c < n; ++c) t[c] = x[c] * mul[c];
narrow_row(Y->dtype, t, n, tmp);
add_rows(t, add, n);
} else {
for (; c + VF_N <= n; c += VF_N)
vf_storeu(t + c, vf_add(keep(vf_mul(vf_loadu(x + c), vf_loadu(mul + c))),
vf_loadu(add + c)));
for (; c < n; ++c) t[c] = keep(x[c] * mul[c]) + add[c];
}
out_row(Y, rowoff(Y, r, n), n, t);
}
+102 -12
View File
@@ -52,9 +52,18 @@ struct Geo {
int causal;
int64_t hd, gqa, kvh, qh, n_seq, bs, max_blocks, bt_rs, bt_cs;
int64_t q_rs, k_rs, v_rs, o_rs, k8_rs, ks_rs, sb, sh, so;
int64_t rows_total; /* the fp8 P.V form's rows */
float scale;
};
/* f32 to the nearest E4M3 and back. */
inline float e4m3_round(float x) {
const uint8_t c = rad_f32_to_fp8e4m3(x);
float y;
cvt_fp8e4m3_to_f32(&c, &y, 1);
return y;
}
inline int64_t cu_at(const RadTensor* cu, int64_t i) { return ldi(cu, offlin(cu, i)); }
/* One (entry, kv head)'s key sequence: P prefix keys then the entry's own rows from b0. */
@@ -532,12 +541,77 @@ PS_BF16 void task_bf16(const Geo& g, const Seq& q, const uint8_t* pack, int64_t
} /* namespace */
/* ------------------------------------------------------------------ attn_prefix_self, fp8 P.V */
/* libref's fp8 P.V form, prefix-free, row by row: every score (bf16 or int8 form, libref's
* order), the max, then p = exp(s - max) in f64 rounded to f32, w = e4m3(448 p), and
* o = (sum w v) v_scale / (448 sum p), sums in key order. Two passes, as libref's, because the
* weights are rounded against the row's final max. */
static int ps_pv8(const Geo& g, const RadTensor* vsc) {
const int64_t hd = g.hd, qh = g.qh;
AVX_PARALLEL_FOR_IF(g.rows_total * qh * hd >= AVX_PAR_MIN)
for (int64_t idx = 0; idx < g.rows_total * qh; ++idx) {
const int64_t h = idx % qh, r = cu_at(g.cu, 0) + idx / qh, kh = h / g.gqa;
int64_t s = 0;
while (s + 1 < g.n_seq && r >= cu_at(g.cu, s + 1)) ++s;
const int64_t b0 = cu_at(g.cu, s), b1 = cu_at(g.cu, s + 1), i = r - b0;
const int64_t nk = g.causal ? i + 1 : b1 - b0;
float* qf = scratch_f32((size_t)(3 * hd + nk));
float* kf = qf + hd;
float* acc = kf + hd;
float* sc = acc + hd;
for (int64_t d = 0; d < hd; ++d) qf[d] = ldt(g.q, r * g.q_rs + h * hd + d);
float sq = 1.0f;
if (g.i8) {
float am = 0.0f;
for (int64_t d = 0; d < hd; ++d) am = std::max(am, std::fabs(qf[d]));
sq = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f;
const float inv = 1.0f / sq;
for (int64_t d = 0; d < hd; ++d)
qf[d] = std::rint(std::min(std::max(qf[d] * inv, -127.0f), 127.0f));
}
float mx = -INFINITY;
for (int64_t j = 0; j < nk; ++j) {
const int64_t row = b0 + j;
float dot = 0.0f;
if (g.i8) {
for (int64_t d = 0; d < hd; ++d) kf[d] = ldt(g.k8, row * g.k8_rs + kh * hd + d);
for (int64_t d = 0; d < hd; ++d) dot += qf[d] * kf[d];
dot = dot * sq * ldt(g.ks, row * g.ks_rs + kh) * g.scale;
} else {
const int64_t kb = row * g.k_rs + kh * hd;
for (int64_t d = 0; d < hd; ++d) dot += qf[d] * ldt(g.k, kb + d);
dot *= g.scale;
}
sc[j] = dot;
mx = std::max(mx, dot);
}
for (int64_t d = 0; d < hd; ++d) acc[d] = 0.0f;
float sum = 0.0f;
for (int64_t j = 0; j < nk; ++j) {
const float p = (float)std::exp((double)(sc[j] - mx));
sum += p;
const float w = e4m3_round(448.0f * p);
const int64_t vb = (b0 + j) * g.v_rs + kh * hd;
for (int64_t d = 0; d < hd; ++d) acc[d] += w * ldt(g.v, vb + d);
}
const float inv8 = sum > 0.0f ? 1.0f / (448.0f * sum) : 0.0f;
for (int64_t d = 0; d < hd; ++d)
stt(g.o, r * g.o_rs + h * hd + d, acc[d] * ldt(vsc, offlin(vsc, kh * hd + d)) * inv8);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ attn_prefix_self */
AVX_KERNEL(attn_prefix_self) {
if (a->n_t < 12) return RAD_E_INVAL;
Geo g{};
g.q = &a->t[0]; g.k = &a->t[1]; g.v = &a->t[2]; g.kv = &a->t[3];
g.bt = &a->t[4]; g.su = &a->t[5]; g.cu = &a->t[6]; g.o = &a->t[11];
g.q = &a->t[0]; g.k = &a->t[1]; g.v = &a->t[2]; g.cu = &a->t[6]; g.o = &a->t[11];
/* The paged prefix, all three operands or none (every prefix empty). */
g.kv = rad_arg_in(a, 3);
g.bt = rad_arg_in(a, 4);
g.su = rad_arg_in(a, 5);
if ((g.kv == nullptr) != (g.bt == nullptr) || (g.kv == nullptr) != (g.su == nullptr))
return RAD_E_INVAL;
g.kdes = rad_arg_in(a, 7);
g.vdes = rad_arg_in(a, 8);
g.k8 = rad_arg_in(a, 9);
@@ -548,19 +622,22 @@ AVX_KERNEL(attn_prefix_self) {
g.hd = p_int(a, "head_dim", 0);
g.gqa = p_int(a, "gqa", 1);
g.causal = (int)p_int(a, "causal", 0);
g.bs = g.kv->rank == 4 ? g.kv->shape[2] : p_int(a, "block_size", 0);
g.bs = !g.kv ? 1 : g.kv->rank == 4 ? g.kv->shape[2] : p_int(a, "block_size", 0);
if (g.hd <= 0 || g.gqa <= 0 || g.bs <= 0) return RAD_E_SHAPE;
if (g.hd > PS_HD_MAX) return RAD_E_UNSUPPORTED;
g.kvh = g.kv->rank == 4 ? g.kv->shape[1] : 0;
/* Without a cache the key heads are the own keys' width over head_dim. */
g.kvh = g.kv ? (g.kv->rank == 4 ? g.kv->shape[1] : 0)
: g.k->rank >= 3 ? g.k->shape[g.k->rank - 2]
: g.k->rank == 2 ? g.k->shape[1] / g.hd : 0;
if (g.kvh <= 0) return RAD_E_SHAPE;
g.qh = g.kvh * g.gqa;
g.n_seq = numel(g.cu) - 1;
if (g.n_seq <= 0 || numel(g.su) < g.n_seq) return RAD_E_SHAPE;
if (g.n_seq <= 0 || (g.su && numel(g.su) < g.n_seq)) return RAD_E_SHAPE;
if (cu_at(g.cu, g.n_seq) - cu_at(g.cu, 0) <= 0) return RAD_E_SHAPE;
g.max_blocks = g.bt->rank >= 2 ? g.bt->shape[1] : numel(g.bt) / g.n_seq;
g.bt_rs = g.bt->rank >= 2 ? g.bt->stride[0] : g.max_blocks;
g.bt_cs = g.bt->rank >= 2 ? g.bt->stride[1] : 1;
for (int64_t s = 0; s < g.n_seq; ++s)
g.max_blocks = !g.bt ? 0 : g.bt->rank >= 2 ? g.bt->shape[1] : numel(g.bt) / g.n_seq;
g.bt_rs = g.bt && g.bt->rank >= 2 ? g.bt->stride[0] : g.max_blocks;
g.bt_cs = g.bt && g.bt->rank >= 2 ? g.bt->stride[1] : 1;
for (int64_t s = 0; g.su && s < g.n_seq; ++s)
if (ldi(g.su, offlin(g.su, s)) > g.max_blocks * g.bs) return RAD_E_SHAPE;
g.q_rs = row_stride(g.q, g.qh * g.hd);
g.k_rs = row_stride(g.k, g.kvh * g.hd);
@@ -568,15 +645,28 @@ AVX_KERNEL(attn_prefix_self) {
g.o_rs = row_stride(g.o, g.qh * g.hd);
g.k8_rs = g.i8 ? row_stride(g.k8, g.kvh * g.hd) : 0;
g.ks_rs = g.i8 ? row_stride(g.ks, g.kvh) : 0;
g.sb = g.kv->stride[0]; g.sh = g.kv->stride[1]; g.so = g.kv->stride[2];
if (g.kv) { g.sb = g.kv->stride[0]; g.sh = g.kv->stride[1]; g.so = g.kv->stride[2]; }
g.scale = p_f32(a, "scale", 1.0f / std::sqrt((float)g.hd));
/* The fp8 P.V form (libref's ref_attn_prefix_self): prefix-free, its own two-pass loop. */
{
const RadTensor* vsc = a->n_t > 12 ? rad_arg_in(a, 12) : nullptr;
const char* pv = p_str(a, "pv", "bf16");
const bool pv8 = std::strcmp(pv, "fp8") == 0;
if ((!pv8 && std::strcmp(pv, "bf16") != 0) || pv8 != (vsc != nullptr)) return RAD_E_INVAL;
if (pv8) {
if (g.kv || g.kdes || g.vdes) return RAD_E_UNSUPPORTED;
g.rows_total = cu_at(g.cu, g.n_seq) - cu_at(g.cu, 0);
return ps_pv8(g, vsc);
}
}
/* ---- which form, and each (entry, kv head)'s key sequence */
[[maybe_unused]] bool bf16 = false;
#if AVX_LEVEL == 3
static const bool have_bf16 = __builtin_cpu_supports("avx512bf16");
bf16 = have_bf16 && g.hd % 64 == 0 && g.gqa <= 16 && !g.kdes && !g.vdes &&
g.q->dtype == RAD_BF16 && g.kv->dtype == RAD_BF16 && g.v->dtype == RAD_BF16 &&
g.q->dtype == RAD_BF16 && (!g.kv || g.kv->dtype == RAD_BF16) &&
g.v->dtype == RAD_BF16 &&
(g.i8 || g.k->dtype == RAD_BF16);
#endif
const size_t tile_bytes =
@@ -594,7 +684,7 @@ AVX_KERNEL(attn_prefix_self) {
for (int64_t s = 0; s < g.n_seq; ++s) {
Seq q{};
q.s = s; q.kh = kh;
q.P = ldi(g.su, offlin(g.su, s));
q.P = g.su ? ldi(g.su, offlin(g.su, s)) : 0;
q.b0 = cu_at(g.cu, s);
q.len = std::max<int64_t>(0, cu_at(g.cu, s + 1) - q.b0);
/* A negative prefix count makes key j own row b0 + j - P, as libref indexes it. */
Loaded 100 of 179 files, more files were not shown because too many files have changed in this diff. Show more