Archived
radiance 1.9.0
New models: - LTX-2.5 (base and distilled): video with a stereo soundtrack from text or from text and a first frame, on one card, with its duration head, tiled VAE decoding, the diffusion decoder and the x2 latent upsampler - Krea 2 Raw and Turbo, and FLUX.3 [klein] and its base: text to image, and for FLUX.3 edits from up to ten reference pictures, on one card - GLM-5.3-Flash from AMD's Quark MXFP4 export, on eight cards (John McDonough, Nunze) - Gemma 3 / TranslateGemma 27B with an optional DFlash2 drafter (mici81) Engine: - --kv-cache-dtype fp8_v4 and k6_v4 for Gemma 3 and Qwen3.8-Flash-Next (mici81) - the rotated int8 trunk (i8a8h) for Qwen3.8-27B (eddie168168) - eight-rank all-reduce bands, weighted shards and pieces (Nunze); --host-headroom-mib (sfjes) - the dashboard shows the single-stream decode floor and its most recent window (Memoria) Fixes: prefix-cache reservations kept until their save lands (baKon), tool calls in Responses namespaces (#119), system messages merged when a template refuses several (#137), a prefill continued with no open step (#127), calibration of a Gram accumulation (#122), JSON Schema patterns read unanchored (davetha), GLM-style tool calls, the KV floor counting every sequence's state. Plugin ABI 24.
This commit is contained in:
1 parent
778cbf315e
commit
685ec5bd85
136 files changed
+18917
-3821
No files matched your search
+1
-1
@@ -1,7 +1,7 @@
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
# VERSION is the server release that /version reports. The plugin ABI version is separate and is
|
||||
# read from abi/rad_abi.h below.
|
||||
project(radiance VERSION 1.8.1 LANGUAGES C CXX)
|
||||
project(radiance VERSION 1.9.0 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
+6
-5
@@ -219,11 +219,12 @@ ARG TEST_EXCLUDE=
|
||||
# ctest --test-dir /build -L gpu --output-on-failure
|
||||
# Tests run TEST_JOBS at a time, else JOBS (default one per two hardware threads, about one per
|
||||
# core on an SMT machine: the per-binary CPU budgets in tests/CMakeLists.txt hold for tests that do
|
||||
# not share a core); the `perf` entries, which assert wall-clock costs, run alone (RUN_SERIAL). The build
|
||||
# sandbox forbids io_uring, so avx_check skips its file-backed gather case, and perf_event_open, so
|
||||
# the tests that bound work count CPU time rather than instructions (tests/work_counter.h). The
|
||||
# `oot` suite (every shipped plugin rebuilt against the installed package) repeats this stage's
|
||||
# whole compile, so it runs from the development tree instead (tests/oot_plugins.sh).
|
||||
# not share a core); the `perf` entries, which assert wall-clock costs, run alone (RUN_SERIAL). The
|
||||
# build sandbox forbids io_uring, so avx_check skips its file-backed gather case, and
|
||||
# perf_event_open, so the tests that bound work count CPU time rather than instructions
|
||||
# (tests/work_counter.h). The `oot` suite (every shipped plugin rebuilt against the installed
|
||||
# package) repeats this stage's whole compile, so it runs from the development tree instead
|
||||
# (tests/oot_plugins.sh).
|
||||
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
|
||||
bash /src/docker/llvm-check.sh /build \
|
||||
&& RAD_TEST_CPU_BUDGET_SCALE="${TEST_CPU_BUDGET_SCALE}" \
|
||||
|
||||
@@ -15,7 +15,8 @@ Written by Deadcode, with contributions from:
|
||||
adaptive draft window, the MoE prefill forms, the sorted operand's decode kernel, two K blocks a
|
||||
pass for up to 80 routed rows, --prefill-span, the towers' lookup tables counted once, and for
|
||||
Gemma 4 its assistant head as a drafter that reads the trunk's cache, bf16 checkpoints, the fused
|
||||
w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume
|
||||
w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume, and the
|
||||
Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files
|
||||
- mechkbfan: the token embedding in the pinned host pool
|
||||
- Code000: the n-gram gather on the card and the MTP head's history-pass skip
|
||||
- baKon: three-rank tensor parallelism, serving any world size from the shipped container, the
|
||||
@@ -23,7 +24,8 @@ Written by Deadcode, with contributions from:
|
||||
context length, root and capabilities, /props, the three-rank two-shot all-reduce and tiered-int8
|
||||
wire, the diagnosis of the three-rank lossy-wire crash, cardclock.py, --busy-prefill-chunk, curl,
|
||||
jq and a CA bundle in the image with hfget.sh under its busybox, rad-export, --prefill-interleave,
|
||||
and runtime LoRA adapters served beside the base model and picked per request
|
||||
runtime LoRA adapters served beside the base model and picked per request, and the prefix cache's
|
||||
reserved snapshots held until their save lands
|
||||
- hazyumps: static YaRN for the Qwen rotary paths
|
||||
- malic: ParoQuant, with its MXFP4, int5 and int4 checkpoints imported and served, the Givens
|
||||
rotation as stages and as dense per-group matrices on the matrix cores, and the 5- and 4-bit
|
||||
@@ -37,9 +39,27 @@ Written by Deadcode, with contributions from:
|
||||
- gearwave00001: /v1/messages as Claude Code sends it
|
||||
- devmilan: the NVFP4 and FP8 compressed-tensors imports
|
||||
- sfjes: Gemma 4 31B dense -- its plugin, its two attention classes and their kernels, and prefix
|
||||
reuse that leaves a windowed group alone
|
||||
reuse that leaves a windowed group alone -- and --host-headroom-mib
|
||||
- zivius: LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of their Codeberg
|
||||
PR 50, and Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime
|
||||
- mici81: Gemma 3 dense (TranslateGemma 27B) -- its plugin, the windowed h128 attention, the
|
||||
sandwich junction's all-reduce and its DFlash2 drafter -- the fp8_v4 and k6_v4 KV caches, GPTQ's
|
||||
factorisations through LAPACK and a column-split linear's Hessian from per-rank parts,
|
||||
R4D_AR_MAX_BLOCKS for two engines on one set of cards, and added tokens decoded as HuggingFace
|
||||
decodes them
|
||||
- eddie168168: the rotated int8 trunk (i8a8h) and the qwen35_w8a8 plugin serving it, and the
|
||||
out-of-tree test at the tree's VOPD setting
|
||||
- davetha: JSON Schema patterns read unanchored, with their shorthand classes and escapes
|
||||
- Nunze: the eight-rank all-reduce's bands, weighted shards from the PCIe links and pieces, the
|
||||
sampler's candidate width at eight ranks, the image test stage's parallelism, budgets and
|
||||
exclusions, jinja's dotted integer index, GLM-5.3-Flash's kernels in libr4d and tool calls whose
|
||||
name the opener opens
|
||||
- John McDonough: GLM-5.3-Flash -- its plugin, its blocks (mHC streams, KDA, the DSA indexer and
|
||||
sparse latent attention, f32-scaled FP8 and MXFP4 experts under sigmoid routing) and their
|
||||
reference and AVX ops -- a Quark export's block-FP8 layers, the signed QSA ranking, the
|
||||
one-sequence KV floor over the live plan, and prefill staging paid by expert residency
|
||||
- Memoria: the dashboard's decode floor and recent window, the sparklines' percentile range, and
|
||||
the bringup time in /stats
|
||||
|
||||
This product includes software from the following projects, each under the MIT License. The
|
||||
license text is in the file named beside each.
|
||||
|
||||
@@ -30,6 +30,12 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC
|
||||
| Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | `gemma4-31b-heretic-ara-w4a8.yaml` |
|
||||
| Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` |
|
||||
| Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` |
|
||||
| Krea 2 Turbo FP8: text to image, one card | `krea-2-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-fp8) | `krea-2-turbo.yaml` |
|
||||
| Krea 2 Raw FP8: the same, undistilled | `krea-2-raw-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-raw-radiance-fp8) | `krea-2-raw.yaml` |
|
||||
| FLUX.3 [klein] FP8: text to image and edits from up to ten pictures, one card | `flux-3-klein-fp8.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-fp8) | `flux-3-klein.yaml` |
|
||||
| FLUX.3 [klein] base FP8 | `flux-3-klein-base-fp8.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-base-fp8) | `flux-3-klein.yaml` |
|
||||
| LTX-2.5 distilled FP8: video with its stereo soundtrack from text or a first frame, one card | `ltx-2.5-distilled-fp8.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-distilled-fp8) | `ltx-2.5.yaml` |
|
||||
| LTX-2.5 base FP8 | `ltx-2.5-fp8.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-fp8) | `ltx-2.5.yaml` |
|
||||
| MiniMax-H3 FP8: video with its stereo soundtrack from text | `minimax-h3-fp8.rad` (60 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-fp8) | `minimax-h3.yaml` |
|
||||
| FastH3 8-Step V2 FP8: the same in eight steps | `fasth3-8-step-v2-fp8.rad` (62 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-fp8) | `fasth3.yaml` |
|
||||
| MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `minimax-music3.yaml` |
|
||||
|
||||
+1
-1
@@ -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 23u
|
||||
#define RAD_ABI_VERSION 24u
|
||||
|
||||
/* ================================================================== plugin identity */
|
||||
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
|
||||
|
||||
+115
-5
@@ -72,7 +72,8 @@ const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* df
|
||||
* [21HD/16, 22HD/16) V's scales (absmax / 7)
|
||||
*
|
||||
* Codes are two's complement (int4 -7..7, int6 -31..31). The group is declared at RAD_F8E4M3 with
|
||||
* head_dim the row's bytes / 2 so the core sizes pages from it; only the layout's kernels read it. */
|
||||
* head_dim the row's bytes / 2 so the core sizes pages from it; only the layout's kernels read
|
||||
* it. */
|
||||
enum {
|
||||
RAD_KVQ_NONE = 0,
|
||||
RAD_KVQ_V4 = 1,
|
||||
@@ -428,7 +429,7 @@ int rad_op_declared(RadBuilder* b, const char* op);
|
||||
* convert-time fusions (q/k/v into one qkv, gate and up into gate_up). It is the only component
|
||||
* that knows both sides, and rad-convert reads the map from it (spec §2.4). */
|
||||
enum { RAD_MAP_COPY = 0, RAD_MAP_CONCAT = 1, RAD_MAP_WNORM = 2, RAD_MAP_ROWS = 3,
|
||||
RAD_MAP_TRANSPOSE = 4, RAD_MAP_EMA = 5 };
|
||||
RAD_MAP_TRANSPOSE = 4, RAD_MAP_EMA = 5, RAD_MAP_TAP = 6 };
|
||||
|
||||
typedef struct RadNameMap {
|
||||
const char* declared; /* the name given to rad_decl_weight */
|
||||
@@ -472,7 +473,13 @@ typedef struct RadNameMap {
|
||||
* divided by max(usage, 1e-5), in f32. Successive EMA maps for one name stack their codebooks
|
||||
* along dim 0, as CONCAT maps extend (a residual quantiser's codebooks as one table).
|
||||
*
|
||||
* TRANSPOSE and EMA are computed at convert in f32, like WNORM, and stored as the recipe says. */
|
||||
* RAD_MAP_TAP keeps one index of one dimension of src[0], dropping that dimension: index
|
||||
* src_index[0] (negative counts from the end) of dimension `concat_dim`. A causal 3-D convolution
|
||||
* run on a single frame reads only its last temporal tap, so [cout, cin, kt, kh, kw] read at tap -1
|
||||
* of dimension 2 is the 2-D convolution it then is.
|
||||
*
|
||||
* TRANSPOSE, EMA and TAP are computed at convert in f32, like WNORM, and stored as the recipe
|
||||
* says. */
|
||||
|
||||
int rad_decl_name_map(RadBuilder* b, const RadNameMap* m);
|
||||
|
||||
@@ -653,8 +660,21 @@ enum { RAD_GEN_PASS_COND = 1, RAD_GEN_PASS_DENOISE = 2, RAD_GEN_PASS_DECODE = 3
|
||||
* in all three; a picture of h x w tokens holds the count in the first, and its row
|
||||
* and column, centred on zero (-(n - n/2) .. n/2 - 1), in the other two, after which
|
||||
* the count moves on by max(h, w). Text rows attend causally, a picture's rows to
|
||||
* each other both ways, every row to every row before it. */
|
||||
enum { RAD_GEN_LAYOUT_JOINT_GRID = 1 };
|
||||
* each other both ways, every row to every row before it.
|
||||
*
|
||||
* JOINT_STEP the conditioning is not cached as keys and values but rides in every denoising
|
||||
* step beside the image, since the model updates it as it goes. The conditioning
|
||||
* is the prompt's rows after `drop_prefix`, then `pad_token` rows up to a multiple
|
||||
* of `pad_multiple`, then each reference picture's latent tokens in raster order
|
||||
* (the pictures are not in the prompt; `tmpl_image` is unused). No KV group is
|
||||
* declared: the COND pass leaves the conditioning's rows in the plugin's own state,
|
||||
* once for every lane the request's images run in, and each DENOISE entry is that
|
||||
* conditioning followed by the image (RadGenBatch, "the joint layout"). Rotary
|
||||
* positions are four f32 components (t, h, w, l): a text or padding row is (0, 0,
|
||||
* 0, l), l its index with `rope_text_l` and 0 without; a picture's token at row h,
|
||||
* column w (from 0) is (0, s h, s w, l) with s `rope_hw_scale`, l -(1 + k) for
|
||||
* the k-th reference picture and 0 for the image being made. */
|
||||
enum { RAD_GEN_LAYOUT_JOINT_GRID = 1, RAD_GEN_LAYOUT_JOINT_STEP = 2 };
|
||||
|
||||
typedef struct RadGeneratorDecl {
|
||||
const char* name; /* "qwen-image" -- for messages */
|
||||
@@ -716,6 +736,25 @@ typedef struct RadGeneratorDecl {
|
||||
* pixels of the image a decode pass made. */
|
||||
int64_t max_lanes;
|
||||
rad_buf image_out;
|
||||
|
||||
/* ---- the JOINT_STEP layout (zero for JOINT_GRID) */
|
||||
/* The most rows one conditioning lays out (text, padding and reference latents together):
|
||||
* the plugin keeps `cond_rows` rows a lane a branch, and a longer prompt is refused. */
|
||||
int64_t cond_rows;
|
||||
double rope_hw_scale;
|
||||
int32_t rope_text_l;
|
||||
int32_t pad_multiple;
|
||||
int32_t pad_token;
|
||||
/* Guidance as the model's card states its scale s: 1 when s means cond + s (cond - uncond),
|
||||
* which the core runs as s + 1, 0 when it means uncond + s (cond - uncond). `default_cfg` is
|
||||
* in the card's terms. */
|
||||
int32_t cfg_original;
|
||||
/* The negative prompt guidance uses when a request names none ("" is a prompt); null when a
|
||||
* guided request must name its own. */
|
||||
const char* default_negative;
|
||||
/* 1: a reference picture is shrunk to `ref_area` only when larger and cut to `size_multiple`
|
||||
* by a centred crop; 0: resized to `ref_area` at its own aspect. */
|
||||
int32_t ref_shrink_only;
|
||||
} RadGeneratorDecl;
|
||||
|
||||
int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d);
|
||||
@@ -934,6 +973,77 @@ typedef struct RadVideoGenDecl {
|
||||
* and fewer than the default schedule's. */
|
||||
double upscale_max;
|
||||
int32_t upscale_refine;
|
||||
|
||||
/* ---- appended in ABI 24 (LTX-2.5) */
|
||||
/* The sampler's form. 0: the grid points above. 1: diffusers' FlowMatchEulerDiscrete as
|
||||
* LTX-2 runs it -- a request's `steps` are its evaluations n, between 1 and max_steps; sigmas
|
||||
* linspace(1, 1/n, n), computed in f64 and taken to f32, and with `dyn_shift` 1 shifted by mu
|
||||
* as exp(mu) / (exp(mu) + 1/s - 1) in f32, mu linear in the video's latent tokens from
|
||||
* `base_seq` (`base_shift`) to `max_seq` (`max_shift`); then, with `shift_terminal` > 0,
|
||||
* stretched so the last is shift_terminal; and a closing 0. A trained schedule (n_rungs > 0)
|
||||
* is the rungs taken to f32 and a closing 0, with default_steps and max_steps both n_rungs.
|
||||
* Both modalities step the same sigmas; shift_video and shift_audio are unused. */
|
||||
int32_t sched_kind;
|
||||
int32_t dyn_shift;
|
||||
double base_shift, max_shift;
|
||||
int64_t base_seq, max_seq;
|
||||
double shift_terminal;
|
||||
/* With latent upscaling under a trained schedule of form 1: the sigmas the evaluations after
|
||||
* the upscale step through (a second stage's own schedule, its first the sigma the upscaled
|
||||
* latents are re-noised to), instead of the schedule's tail. The small size then runs every
|
||||
* rung, its last to the clean estimate, and a request's refinement is n_refine_rungs. */
|
||||
int32_t n_refine_rungs;
|
||||
const double* refine_rungs;
|
||||
/* The text rows of every VSTEP pass, whatever the prompt's length (0: the prompt's tokens):
|
||||
* a model whose text encoder writes a fixed number of rows. */
|
||||
int64_t step_text_rows;
|
||||
/* Guidance terms (RadVideoGenBatch::guidance_h) when `guidance` is 1: the defaults a request
|
||||
* that names none gets, the video's scale, spatio-temporal scale, modality scale and rescale,
|
||||
* then the soundtrack's four. A request whose video or soundtrack scale is not 1 is guided
|
||||
* against a negative prompt: its own, else `default_negative` (null: ""). The VCOND pass then
|
||||
* carries both prompts, the positive first (two cu_seqlens entries). */
|
||||
int32_t guidance;
|
||||
double guidance_default[8];
|
||||
const char* default_negative;
|
||||
/* Image to video: 1 when the model can start from a first frame (OpenAI's
|
||||
* `input_reference`), handed to the VCOND pass resized to the size the first evaluations run
|
||||
* at (RadVideoGenBatch `image`), after an H.264 round trip at `image_crf` when that is > 0
|
||||
* (the compression the model was trained against). */
|
||||
int32_t image_cond;
|
||||
int32_t image_crf;
|
||||
/* A left-padded text encoder: the VCOND pass's positions count so that each prompt ends at
|
||||
* `text_left_pad` - 1, the place it holds in a sequence padded on the left to that length (0:
|
||||
* from 0). */
|
||||
int64_t text_left_pad;
|
||||
/* The soundtrack's latent rows a step carries for each latent (0: audio_channels, a stream of
|
||||
* rows a channel); a model whose latent holds every channel at once carries 1. */
|
||||
int32_t audio_streams;
|
||||
/* A latent upscaler of one fixed factor, upscale_max: a request's sides must then be
|
||||
* multiples of size_multiple x upscale_max, so the small size is exactly the full size over
|
||||
* the factor. */
|
||||
int32_t upscale_exact;
|
||||
/* A length head: a model that predicts from the prompt how long its video should be. With
|
||||
* `duration_out` set, every VCOND pass writes to it (f32 [1], device) the natural log of that
|
||||
* length in seconds. For a request that names no length the core takes its exponent, clamps it
|
||||
* to [duration_min, duration_max] seconds, rounds it to frames at the frame rate and floors
|
||||
* that to the chunk grid (frames_per_chunk n + frames_tail; one chunk more when the floor falls
|
||||
* under duration_min and duration_max allows it), then holds it to min_chunks..max_chunks and
|
||||
* to what a pass carries. Until that VCOND pass is done such a request is shaped at
|
||||
* `default_chunks`, so the pass may not depend on the length: its geometry carries the
|
||||
* provisional frame count, and `t_video` / `t_audio` the provisional schedule. 0: a request
|
||||
* that names no length is made at default_chunks. `duration_dtype` is the precision the model
|
||||
* takes the exponent in: RAD_F32, or RAD_BF16 for a head run in bf16, whose length is
|
||||
* exp(x) in f32 rounded to bf16. Frames round half to even, as Python's round(). */
|
||||
rad_buf duration_out;
|
||||
double duration_min, duration_max;
|
||||
uint32_t duration_dtype;
|
||||
/* Decoders: a model with more than one way to turn its latents into frames names them,
|
||||
* space-separated, its default first (LTX-2.5: "vae diffusion"). A request may name one; every
|
||||
* VDECODE pass carries its index (RadVideoGenBatch::decoder). `decoder_max_area`, when set,
|
||||
* holds each decoder's largest frame in pixels (0: max_area), and a request over it is refused.
|
||||
* Null: one decoder. */
|
||||
const char* decoders;
|
||||
const int64_t* decoder_max_area;
|
||||
} RadVideoGenDecl;
|
||||
|
||||
int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d);
|
||||
|
||||
+62
-2
@@ -315,6 +315,43 @@ typedef struct RadGenBatch {
|
||||
int32_t dec_lane;
|
||||
int32_t dec_height, dec_width; /* pixels */
|
||||
int32_t dec_preview; /* the lane's preview latent, not its state */
|
||||
|
||||
/* ---- the joint layout (RAD_GEN_LAYOUT_JOINT_STEP)
|
||||
* COND: `branch` is 0 for the prompt and 1 for the negative prompt, and `n_lane` / `lane_h` /
|
||||
* `lane` name every lane the conditioning's images run in; the plugin keeps the
|
||||
* conditioning's row r for lane l at its own row (2 l + branch) cond_rows + r. The prompt's
|
||||
* last `n_pad` tokens are the padding, and `valid_cu` is {0, the tokens before it}. `rope_f`
|
||||
* is the conditioning's positions, [4, rows] f32 component-major.
|
||||
* DENOISE: each entry's rows are its conditioning and then its image's latent tokens, so
|
||||
* `cu_seqlens` bounds both together. `src` [n_tok] names a row's source: >= 0 the plugin's
|
||||
* conditioning row (as above), < 0 the image row -(1 + k) of the compact image order, in
|
||||
* which `img_cu` [n_seq + 1] bounds each entry's image and `img_rows` [n_img] is each image
|
||||
* row's place in the pass. `mode_cu` [3 n_seq + 1] cuts each entry into its text (padding
|
||||
* included), its reference pictures and its image: entry e's text is rows [mode_cu[3e],
|
||||
* mode_cu[3e + 1]), its pictures [mode_cu[3e + 1], mode_cu[3e + 2]), its image up to
|
||||
* mode_cu[3e + 3]. `rope_f` is [4, n_tok]. Everything sigma, cfg, pair, lane, flags and seed
|
||||
* say is per entry as for JOINT_GRID, and the lane ops read `img_cu`. */
|
||||
int32_t branch;
|
||||
int32_t n_pad;
|
||||
const int32_t* valid_cu;
|
||||
int64_t n_img;
|
||||
const int32_t* img_cu;
|
||||
const int32_t* img_rows;
|
||||
const int32_t* mode_cu;
|
||||
const float* rope_f;
|
||||
/* DENOISE: the rows again in mode-major order -- every entry's text, then every entry's
|
||||
* pictures, then every entry's image (the compact image order) -- for a model whose early
|
||||
* blocks run each mode on its own. `mode_rows` [n_tok] is each one's place in the pass,
|
||||
* `mode_src` [n_tok] its source as `src` names it, and `mode_rope_f` holds the positions mode
|
||||
* by mode, mode m's a dense [4, n_m] block at 4 times its start;
|
||||
* `n_mode_h` [3] counts each mode's rows, so mode m starts at the sum of the counts before
|
||||
* it, and `mode_ccu` [3, n_seq + 1] bounds each entry's rows of each mode from that start
|
||||
* (mode m's cu_seqlens at mode_ccu + m (n_seq + 1), each beginning at 0). */
|
||||
const int32_t* mode_rows;
|
||||
const int32_t* mode_src;
|
||||
const int32_t* mode_ccu;
|
||||
const int64_t* n_mode_h;
|
||||
const float* mode_rope_f;
|
||||
} RadGenBatch;
|
||||
|
||||
/* An entry's flags on a DENOISE pass. */
|
||||
@@ -450,7 +487,8 @@ typedef struct RadVideoGenBatch {
|
||||
/* f32 [6]: the video's timestep, sigma and next sigma, then the soundtrack's. */
|
||||
const float* sched;
|
||||
const float* pos; /* f32 [3, n_tok]: RAD_VPOS_STEP */
|
||||
/* u32 [2, 2]: the video's noise seed and the soundtrack's, low word first. */
|
||||
/* u32 [2, 2]: the video's noise seed and the soundtrack's, low word first (VSTEP, VUPSCALE and
|
||||
* VDECODE passes; a decoder that denoises draws from it). */
|
||||
const uint32_t* seed;
|
||||
|
||||
/* ---- VDECODE */
|
||||
@@ -468,6 +506,24 @@ typedef struct RadVideoGenBatch {
|
||||
* soundtrack's) the latents are re-noised to; `seed` is a step's. */
|
||||
RadVideoGeom geom_from;
|
||||
const float* upscale; /* f32 [1]: the factor the network is told */
|
||||
|
||||
/* ---- appended in ABI 24 */
|
||||
/* VCOND with a negative prompt: `n_neg` of the pass's tokens, after the prompt's. */
|
||||
int32_t n_neg;
|
||||
/* The request's guidance, f32 [8] host: the video's scale, its spatio-temporal scale, its
|
||||
* modality scale and its rescale, then the soundtrack's four; a model's own defaults where
|
||||
* the request named none. */
|
||||
const float* guidance_h;
|
||||
/* VCOND with a first frame (RadVideoGenDecl::image_cond): `image` [height, width, 3] bf16 in
|
||||
* [-1, 1], device; null without one. Every later pass carries `has_image` 1 for such a
|
||||
* request. */
|
||||
const uint16_t* image;
|
||||
int32_t has_image;
|
||||
/* guidance_h on the device, f32 [8], for ops that read the terms. */
|
||||
const float* guidance;
|
||||
/* VDECODE: the decoder the request named (RadVideoGenDecl::decoders), its index; 0 the
|
||||
* default. */
|
||||
int32_t decoder;
|
||||
} RadVideoGenBatch;
|
||||
|
||||
/* RadVideoGenBatch::geom_d. The request's latent geometry, then a VDECODE pass's chunk: the latent
|
||||
@@ -483,7 +539,11 @@ enum {
|
||||
* first three are also the source volume; (frames, H, W) the target volume; then both in
|
||||
* patches, (frames, h / patch, w / patch) and (frames, H / patch, W / patch). */
|
||||
RAD_VGEOM_UP_SRC = 16, RAD_VGEOM_UP_DST = 21, RAD_VGEOM_UP_PSRC = 24, RAD_VGEOM_UP_PDST = 27,
|
||||
RAD_VGEOM_N = 32
|
||||
/* The soundtrack's latents as a volume of single latents, (n_audio, 1, 1); and the video's
|
||||
* rows cut at its first latent frame, {0, that frame's patches, every patch} (a first frame
|
||||
* a model conditions on at its own timestep). */
|
||||
RAD_VGEOM_AUDIO_VOL = 32, RAD_VGEOM_FIRST_CU = 35,
|
||||
RAD_VGEOM_N = 40
|
||||
};
|
||||
|
||||
/* ================================================================== operands */
|
||||
|
||||
@@ -450,6 +450,17 @@ inline int map_transpose(RadBuilder* b, const char* declared, const char* src) {
|
||||
return rad_decl_name_map(b, &m);
|
||||
}
|
||||
|
||||
/* One index of one dimension of a checkpoint tensor (RAD_MAP_TAP): a causal 3-D convolution's
|
||||
* last temporal tap is map_tap(b, name, src, 2, -1). */
|
||||
inline int map_tap(RadBuilder* b, const char* declared, const char* src, int dim, int index) {
|
||||
RadNameMap m = map_base(declared, RAD_MAP_TAP);
|
||||
m.n_src = 1;
|
||||
m.src[0] = src;
|
||||
m.src_index[0] = index;
|
||||
m.concat_dim = dim;
|
||||
return rad_decl_name_map(b, &m);
|
||||
}
|
||||
|
||||
/* An EMA codebook: the embedding sums over max(cluster usage, 1e-5), row by row (RAD_MAP_EMA). */
|
||||
inline int map_ema(RadBuilder* b, const char* declared, const char* sums, const char* usage) {
|
||||
RadNameMap m = map_base(declared, RAD_MAP_EMA);
|
||||
|
||||
@@ -72,8 +72,8 @@ struct ManifoldConn {
|
||||
}
|
||||
int declare_split(RadBuilder* b, Names& nm, const char* name) {
|
||||
const int64_t total = c.hc * g.n_embd / kChunk;
|
||||
split_rows = glm_tp_split_rows();
|
||||
if (g.world < 2 || g.n_embd != 4096 || c.hc != 4 || !split_rows || total % g.world) {
|
||||
split_rows = kGlmTpSplitRows;
|
||||
if (g.world < 2 || g.n_embd != 4096 || c.hc != 4 || total % g.world) {
|
||||
split_rows = 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -4,19 +4,12 @@
|
||||
#ifndef RAD_TP_SPLIT_H
|
||||
#define RAD_TP_SPLIT_H
|
||||
#include "rad_arch.h"
|
||||
#include <cstdlib>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
/* Rows from which a replicated F32 projection splits its columns over the ranks
|
||||
* (RADIANCE_GLM_TP_SPLIT_ROWS, 0 never). Below it the collective's latency outweighs the
|
||||
* saved arithmetic, so decode keeps the replicated form. */
|
||||
inline int64_t glm_tp_split_rows() {
|
||||
const char* e = std::getenv("RADIANCE_GLM_TP_SPLIT_ROWS");
|
||||
if (!e || !*e) return 256;
|
||||
const long long v = std::strtoll(e, nullptr, 10);
|
||||
return v > 0 ? (int64_t)v : 0;
|
||||
}
|
||||
/* Rows from which a replicated F32 projection splits its columns over the ranks. Below it the
|
||||
* collective's latency outweighs the saved arithmetic, so decode keeps the replicated form. */
|
||||
constexpr int64_t kGlmTpSplitRows = 256;
|
||||
|
||||
/* The split's ops are declared whatever the step size, and each gather's message as a range of
|
||||
* rows: the engine's arena levels declare again at a smaller max_tok and must get the same graph
|
||||
@@ -33,8 +26,8 @@ struct SplitF32Proj {
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t rows, int64_t n,
|
||||
int64_t width, rad_weight weight, rad_buf input, rad_buf output) {
|
||||
min_rows = glm_tp_split_rows();
|
||||
if (g.world < 2 || !min_rows || n % g.world || (n / g.world * 4) % 16) {
|
||||
min_rows = kGlmTpSplitRows;
|
||||
if (g.world < 2 || n % g.world || (n / g.world * 4) % 16) {
|
||||
min_rows = 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
/* rad_vae2d.h -- an image VAE (encoder or decoder) as a recorded list of ops over NHWC images.
|
||||
*
|
||||
* Image size varies per request, so a VAE's ops are declared once for the largest image and issued
|
||||
* with each pass's extents (`Vae::issue`). Qwen-Image 2.1's residual Wan-2.2 VAE, Qwen-Image's
|
||||
* and Krea 2's Wan-2.1 one and FLUX's GroupNorm one are each a few lines of `conv`, `norm`,
|
||||
* `resblock` and `attention` calls in their plugin.
|
||||
*/
|
||||
#pragma once
|
||||
#include <arch/rad_arch.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* ================================================================== the VAE as a recorded graph
|
||||
*
|
||||
* Image size varies per request, so the VAE's ops are declared once for the largest image and
|
||||
* issued with the actual extents: every image operand is a raw [height, width * channels] view of
|
||||
* its buffer (docs/OPS.md, "Image generation"), with extents from the pass's picture size and the
|
||||
* stage's scale. `Vae` records each op with what it needs to rebuild its operands, so declare()
|
||||
* and step() walk the same list.
|
||||
*
|
||||
* Every output is its own buffer, sized for its stage; the planner shares storage between those
|
||||
* whose lives do not overlap, and no buffer is reused by hand. This is sound because ops are issued
|
||||
* in declaration order. */
|
||||
struct VImg {
|
||||
rad_buf buf = 0;
|
||||
int64_t ch = 0;
|
||||
int lvl = 0; /* the side is the pass's base side times 2^lvl (decoder) or / 2^lvl (encoder) */
|
||||
};
|
||||
|
||||
struct VOp {
|
||||
enum Kind { CONV, NORM, ADD, D2S, S2D, ATTN, GNORM, LIN } kind = CONV;
|
||||
rad_op op = 0;
|
||||
VImg x{}, y{}, z{}; /* inputs x (and z for ADD), output y */
|
||||
rad_weight w = 0, b = 0;
|
||||
int k = 1, up = 1, stride = 1;
|
||||
int64_t qkv_ch = 0; /* ATTN: x is the [*, 3C] qkv rows, y the [*, C] output */
|
||||
};
|
||||
|
||||
/* What a checkpoint stores a VAE's convolutions as. */
|
||||
enum VaeConvForm {
|
||||
VAE_CONV_2D, /* [cout, cin, k, k] */
|
||||
VAE_CONV_CAUSAL, /* a causal 3-D convolution [cout, cin, kt, k, k], run on one frame: its
|
||||
* last temporal tap (RAD_MAP_TAP) */
|
||||
};
|
||||
|
||||
struct Vae {
|
||||
std::vector<VOp> ops;
|
||||
Names* nm = nullptr;
|
||||
RadBuilder* b = nullptr;
|
||||
const char* scope = ""; /* "dec" or "enc" */
|
||||
bool down = false; /* an encoder: a level halves the side */
|
||||
int64_t base_px = 0; /* pixels at level 0, the largest any pass hands it */
|
||||
int n_buf = 0;
|
||||
int first_group = 0;
|
||||
/* The banded tail. From op `band_from` on, every output pixel reads a bounded window of rows
|
||||
* (3x3 convolutions, nearest upsampling, per-pixel norms and adds, depth-to-space shortcuts),
|
||||
* so a rank can run the tail on its band of level-0 rows plus `halo` rows per side and get its
|
||||
* band's pixels bit for bit: rows spoiled by a conv's zero padding at the band edge never reach
|
||||
* the band. The ops before it include the mid-block's attention, which reads every pixel, and
|
||||
* run whole; `whole` holds their outputs, read by the tail at the band's row offset. -1: no
|
||||
* tail. */
|
||||
int band_from = -1;
|
||||
int64_t halo = 0;
|
||||
std::vector<rad_buf> whole;
|
||||
VaeConvForm form = VAE_CONV_2D;
|
||||
/* group_norm's statistics scratch, one for every GroupNorm op (they run one after another). */
|
||||
rad_buf gn_stats = 0;
|
||||
|
||||
int64_t px_at(int lvl) const {
|
||||
int64_t p = base_px;
|
||||
for (int i = 0; i < lvl; ++i) p = down ? (p + 3) / 4 : p * 4;
|
||||
return p;
|
||||
}
|
||||
VImg img(int64_t ch, int lvl) {
|
||||
VImg v;
|
||||
v.ch = ch;
|
||||
v.lvl = lvl;
|
||||
v.buf = decl_b(b, nm->f("%s.t%d", scope, n_buf++), RAD_BF16, { px_at(lvl), ch });
|
||||
return v;
|
||||
}
|
||||
rad_weight wt(const char* name, const char* src, std::initializer_list<int64_t> shape,
|
||||
bool tap = false) {
|
||||
if ((tap ? map_tap(b, name, src, 2, -1) : map_copy(b, name, src)) < 0) return 0;
|
||||
return decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE,
|
||||
grp_layer(first_group));
|
||||
}
|
||||
|
||||
/* y = conv(x): k x k, stride, `up` 2 reads x upsampled, `pad` same or down. */
|
||||
VImg conv(const VImg& x, int64_t cout, int k, int stride, int up, const char* pad,
|
||||
const char* ckpt) {
|
||||
VOp o;
|
||||
o.kind = VOp::CONV;
|
||||
o.x = x;
|
||||
o.up = up;
|
||||
o.stride = stride;
|
||||
int lvl = x.lvl;
|
||||
if (up == 2) lvl = down ? lvl - 1 : lvl + 1;
|
||||
if (stride == 2) lvl = down ? lvl + 1 : lvl - 1;
|
||||
o.y = img(cout, lvl);
|
||||
o.k = k;
|
||||
o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { cout, x.ch, k, k },
|
||||
form == VAE_CONV_CAUSAL);
|
||||
o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { cout });
|
||||
o.op = RAD_OP(b, "conv2d_nhwc",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px_at(lvl)), RAD_INT("cin", x.ch),
|
||||
RAD_INT("cout", cout), RAD_INT("k", k),
|
||||
RAD_INT("stride", stride), RAD_STR("pad", pad),
|
||||
RAD_INT("up", up), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(o.w, o.b));
|
||||
/* An input with no buffer is the picture the pass staged, read where it lies. */
|
||||
if (x.buf) rw(b, o.op, { x.buf }, { o.y.buf });
|
||||
else rw(b, o.op, {}, { o.y.buf });
|
||||
ops.push_back(o);
|
||||
return o.y;
|
||||
}
|
||||
/* The channel norm, `silu` or not. `gamma` is [C, 1, 1(, 1)] in the checkpoint. */
|
||||
VImg norm(const VImg& x, bool silu, const char* ckpt, int gamma_rank) {
|
||||
VOp o;
|
||||
o.kind = VOp::NORM;
|
||||
o.x = x;
|
||||
o.y = img(x.ch, x.lvl);
|
||||
const char* dn = nm->f("%s.gamma", ckpt);
|
||||
if (map_copy(b, dn, nm->ckpt("%s.gamma", ckpt)) < 0) return VImg{};
|
||||
o.w = gamma_rank == 4
|
||||
? decl_w(b, dn, RAD_BF16, { x.ch, 1, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group))
|
||||
: decl_w(b, dn, RAD_BF16, { x.ch, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group));
|
||||
o.op = rw(b, RAD_OP(b, "l2norm_chan",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
|
||||
RAD_STR("act", silu ? "silu" : "none"),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(o.w)),
|
||||
{ x.buf }, { o.y.buf });
|
||||
ops.push_back(o);
|
||||
return o.y;
|
||||
}
|
||||
VImg add(const VImg& x, const VImg& z) {
|
||||
VOp o;
|
||||
o.kind = VOp::ADD;
|
||||
o.x = x;
|
||||
o.z = z;
|
||||
o.y = img(x.ch, x.lvl);
|
||||
o.op = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ x.buf, z.buf }, { o.y.buf });
|
||||
ops.push_back(o);
|
||||
return o.y;
|
||||
}
|
||||
/* y += the resampling shortcut of x (in place on y). */
|
||||
void shortcut(const VImg& x, const VImg& y, int ft) {
|
||||
VOp o;
|
||||
o.kind = down ? VOp::S2D : VOp::D2S;
|
||||
o.x = x;
|
||||
o.y = y;
|
||||
o.up = ft;
|
||||
o.op = rw(b, RAD_OP(b, down ? "s2d_avg_add" : "d2s_add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px_at(y.lvl)), RAD_INT("cin", x.ch),
|
||||
RAD_INT("cout", y.ch), RAD_INT("ft", ft),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ x.buf, y.buf }, { y.buf });
|
||||
ops.push_back(o);
|
||||
}
|
||||
/* A residual block, in -> out channels. */
|
||||
VImg resblock(const VImg& x, int64_t out, const char* ckpt) {
|
||||
VImg h = x;
|
||||
if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->f("%s.conv_shortcut", ckpt));
|
||||
VImg t = norm(x, true, nm->f("%s.norm1", ckpt), 4);
|
||||
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv1", ckpt));
|
||||
t = norm(t, true, nm->f("%s.norm2", ckpt), 4);
|
||||
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv2", ckpt));
|
||||
return add(t, h);
|
||||
}
|
||||
/* The mid-block's single-head attention over every pixel. */
|
||||
VImg attention(const VImg& x, const char* ckpt) {
|
||||
const int64_t C = x.ch;
|
||||
VImg t = norm(x, false, nm->f("%s.norm", ckpt), 3);
|
||||
VImg qkv = conv(t, 3 * C, 1, 1, 1, "same", nm->f("%s.to_qkv", ckpt));
|
||||
VOp o;
|
||||
o.kind = VOp::ATTN;
|
||||
o.x = qkv;
|
||||
o.y = img(C, x.lvl);
|
||||
o.qkv_ch = 3 * C;
|
||||
o.op = rw(b, RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("head_dim", C),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)C))),
|
||||
RAD_NOWEIGHTS),
|
||||
{ qkv.buf }, { o.y.buf });
|
||||
ops.push_back(o);
|
||||
VImg p = conv(o.y, C, 1, 1, 1, "same", nm->f("%s.proj", ckpt));
|
||||
return add(p, x);
|
||||
}
|
||||
|
||||
/* PyTorch's GroupNorm over the whole picture, `silu` or not (FLUX's VAE). Not row-local, so a
|
||||
* VAE that has one runs whole (no banded tail). */
|
||||
VImg gnorm(const VImg& x, bool silu, const char* ckpt, int64_t groups, double eps) {
|
||||
VOp o;
|
||||
o.kind = VOp::GNORM;
|
||||
o.x = x;
|
||||
o.y = img(x.ch, x.lvl);
|
||||
o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { x.ch });
|
||||
o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { x.ch });
|
||||
if (!gn_stats)
|
||||
gn_stats = decl_b(b, nm->f("%s.gn_stats", scope), RAD_F32, { 64 * (2 + 3 * 1024) });
|
||||
o.k = (int)groups;
|
||||
o.op = RAD_OP(b, "group_norm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
|
||||
RAD_INT("groups", groups), RAD_F64("eps", eps),
|
||||
RAD_STR("act", silu ? "silu" : "none"), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(o.w, o.b));
|
||||
rw(b, o.op, { x.buf, gn_stats }, { o.y.buf, gn_stats });
|
||||
ops.push_back(o);
|
||||
return o.y;
|
||||
}
|
||||
/* A per-pixel linear with a bias (a 1x1 convolution kept as a Linear): `cout` from x's
|
||||
* channels. */
|
||||
VImg lin(const VImg& x, int64_t cout, const char* ckpt) {
|
||||
VOp o;
|
||||
o.kind = VOp::LIN;
|
||||
o.x = x;
|
||||
o.y = img(cout, x.lvl);
|
||||
o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { cout, x.ch });
|
||||
o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { cout });
|
||||
o.op = rw(b, RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("N", cout),
|
||||
RAD_INT("K", x.ch), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(o.w, o.b)),
|
||||
{ x.buf }, { o.y.buf });
|
||||
ops.push_back(o);
|
||||
return o.y;
|
||||
}
|
||||
/* A GroupNorm residual block (FLUX's VAE, diffusers' ResnetBlock2D): norm1, silu, conv1,
|
||||
* norm2, silu, conv2, plus the input or its 1x1 `conv_shortcut`. */
|
||||
VImg resblock_gn(const VImg& x, int64_t out, const char* ckpt, int64_t groups, double eps) {
|
||||
VImg h = x;
|
||||
if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->f("%s.conv_shortcut", ckpt));
|
||||
VImg t = gnorm(x, true, nm->f("%s.norm1", ckpt), groups, eps);
|
||||
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv1", ckpt));
|
||||
t = gnorm(t, true, nm->f("%s.norm2", ckpt), groups, eps);
|
||||
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv2", ckpt));
|
||||
return add(t, h);
|
||||
}
|
||||
/* diffusers' single-head VAE attention: GroupNorm, to_q / to_k / to_v linears with biases,
|
||||
* attention over every pixel, to_out.0, plus the input. */
|
||||
VImg attention_gn(const VImg& x, const char* ckpt, int64_t groups, double eps) {
|
||||
const int64_t C = x.ch;
|
||||
VImg t = gnorm(x, false, nm->f("%s.group_norm", ckpt), groups, eps);
|
||||
VImg q = lin(t, C, nm->f("%s.to_q", ckpt));
|
||||
VImg k = lin(t, C, nm->f("%s.to_k", ckpt));
|
||||
VImg v = lin(t, C, nm->f("%s.to_v", ckpt));
|
||||
VOp o;
|
||||
o.kind = VOp::ATTN;
|
||||
o.x = q;
|
||||
o.y = img(C, x.lvl);
|
||||
o.z = k;
|
||||
o.w = 0;
|
||||
o.qkv_ch = 0;
|
||||
o.k = 0;
|
||||
o.op = rw(b, RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("head_dim", C),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)C))),
|
||||
RAD_NOWEIGHTS),
|
||||
{ q.buf, k.buf, v.buf }, { o.y.buf });
|
||||
attn_v.push_back({ ops.size(), v });
|
||||
ops.push_back(o);
|
||||
VImg p = lin(o.y, C, nm->f("%s.to_out.0", ckpt));
|
||||
return add(p, x);
|
||||
}
|
||||
/* The value image of each separate-projection attention, by op index. */
|
||||
std::vector<std::pair<size_t, VImg>> attn_v;
|
||||
const VImg* value_of(size_t i) const {
|
||||
for (const auto& e : attn_v) if (e.first == i) return &e.second;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* The operands of op `o` for a pass whose level-0 picture is H0 x W0 pixels (or latent tokens,
|
||||
* for the decoder), in the op's schema order, and its ranged value. */
|
||||
static int64_t side(int64_t s0, int lvl, bool dn) {
|
||||
int64_t s = s0;
|
||||
for (int i = 0; i < lvl; ++i) s = dn ? s / 2 : s * 2;
|
||||
return s;
|
||||
}
|
||||
/* Declares `cu`, a buffer of the plugin's, as read by every attention: issue() hands it to
|
||||
* them. */
|
||||
int attn_reads(rad_buf cu) const {
|
||||
for (const VOp& o : ops)
|
||||
if (o.kind == VOp::ATTN) RAD_ARCH_TRY(rad_op_reads(b, o.op, &cu, 1));
|
||||
return RAD_OK;
|
||||
}
|
||||
/* `cu` is {0, pixels} at the attention's level -- the pass's latent tokens -- and `input` the
|
||||
* level-0 picture when the first op reads one the pass staged. Ops [from, to) are issued; with
|
||||
* `row0`, H0 is a band's rows and a `whole` buffer is read from its level-0 row `row0`. */
|
||||
void issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu, const void* input,
|
||||
size_t from = 0, size_t to = (size_t)-1, int64_t row0 = 0) const;
|
||||
|
||||
bool is_whole(rad_buf v) const {
|
||||
for (rad_buf w : whole) if (w == v) return true;
|
||||
return false;
|
||||
}
|
||||
/* The tail's halo in level-0 rows: walked back from the last op, a buffer's margin is the most
|
||||
* any reader of it needs, in its own rows -- a k x k conv adds k/2, reading through a 2x
|
||||
* upsample halves it rounding up, and the depth-to-space shortcut halves it. -1 when the tail
|
||||
* holds an op that is not row-local, or reads a whole buffer above level 0. */
|
||||
int64_t band_halo() const {
|
||||
if (band_from < 0 || ops.empty()) return -1;
|
||||
std::vector<std::pair<rad_buf, int64_t>> need{ { ops.back().y.buf, 0 } };
|
||||
auto get = [&](rad_buf v) -> int64_t {
|
||||
for (const auto& e : need) if (e.first == v) return e.second;
|
||||
return 0;
|
||||
};
|
||||
auto want = [&](rad_buf v, int64_t m) {
|
||||
for (auto& e : need) if (e.first == v) { e.second = std::max(e.second, m); return; }
|
||||
need.push_back({ v, m });
|
||||
};
|
||||
for (size_t i = ops.size(); i-- > (size_t)band_from;) {
|
||||
const VOp& o = ops[i];
|
||||
const int64_t my = get(o.y.buf);
|
||||
switch (o.kind) {
|
||||
case VOp::CONV: {
|
||||
if (o.stride != 1) return -1;
|
||||
const int64_t m = my + o.k / 2;
|
||||
want(o.x.buf, o.up == 2 ? (m + 1) / 2 : m);
|
||||
break;
|
||||
}
|
||||
case VOp::NORM: want(o.x.buf, my); break;
|
||||
case VOp::LIN: want(o.x.buf, my); break;
|
||||
case VOp::ADD: want(o.x.buf, my); want(o.z.buf, my); break;
|
||||
case VOp::D2S: want(o.x.buf, (my + 1) / 2); break;
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
int64_t h = 0;
|
||||
for (size_t i = (size_t)band_from; i < ops.size(); ++i) {
|
||||
const VOp& o = ops[i];
|
||||
for (const VImg* v : { &o.x, &o.z })
|
||||
if (v->buf && is_whole(v->buf)) {
|
||||
if (v->lvl != 0) return -1;
|
||||
h = std::max(h, get(v->buf));
|
||||
}
|
||||
}
|
||||
return h;
|
||||
}
|
||||
};
|
||||
|
||||
inline void Vae::issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu,
|
||||
const void* input, size_t from, size_t to, int64_t row0) const {
|
||||
auto ptr = [&](const VImg& v) -> const void* {
|
||||
if (!v.buf) return input;
|
||||
const char* p = (const char*)rad_buf_ptr(c, v.buf);
|
||||
return row0 && is_whole(v.buf) ? p + row0 * W0 * v.ch * (int64_t)sizeof(uint16_t) : p;
|
||||
};
|
||||
auto view = [&](const VImg& v, int64_t* H, int64_t* W) {
|
||||
*H = side(H0, v.lvl, down);
|
||||
*W = side(W0, v.lvl, down);
|
||||
return RAD_P_T2(ptr(v), RAD_BF16, *H, *W * v.ch);
|
||||
};
|
||||
auto rows = [&](const VImg& v, int64_t cols) {
|
||||
const int64_t H = side(H0, v.lvl, down), W = side(W0, v.lvl, down);
|
||||
return RAD_P_T2(ptr(v), RAD_BF16, H * W * v.ch / cols, cols);
|
||||
};
|
||||
for (size_t i = from; i < to && i < ops.size(); ++i) {
|
||||
const VOp& o = ops[i];
|
||||
int64_t Hx, Wx, Hy, Wy;
|
||||
switch (o.kind) {
|
||||
case VOp::CONV: {
|
||||
const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy);
|
||||
RAD_ISSUE_N(c, o.op, Hy * Wy, x, RAD_W(o.w), RAD_W(o.b), y);
|
||||
break;
|
||||
}
|
||||
case VOp::NORM: {
|
||||
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
|
||||
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), rows(o.y, o.y.ch));
|
||||
break;
|
||||
}
|
||||
case VOp::ADD: {
|
||||
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
|
||||
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), rows(o.z, o.z.ch), rows(o.y, o.y.ch));
|
||||
break;
|
||||
}
|
||||
case VOp::D2S:
|
||||
case VOp::S2D: {
|
||||
const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy);
|
||||
RAD_ISSUE_N(c, o.op, Hy * Wy, x, y);
|
||||
break;
|
||||
}
|
||||
case VOp::ATTN: {
|
||||
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
|
||||
const int64_t C = o.y.ch, n = H * W;
|
||||
if (const VImg* v = value_of(i)) {
|
||||
/* Separate q, k and v images. */
|
||||
RAD_ISSUE_N(c, o.op, n, rows(o.x, C), rows(o.z, C), rows(*v, C), cu,
|
||||
brows(o.y.buf, n));
|
||||
} else {
|
||||
/* q, k and v are column slices of the qkv rows, at its 3C pitch. */
|
||||
RAD_ISSUE_N(c, o.op, n, bcol(o.x.buf, 0, C, n), bcol(o.x.buf, C, C, n),
|
||||
bcol(o.x.buf, 2 * C, C, n), cu, brows(o.y.buf, n));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case VOp::GNORM: {
|
||||
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
|
||||
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), RAD_W(o.b), RAD_NONE,
|
||||
RAD_P_T2(rad_buf_ptr(c, gn_stats), RAD_F32, 1, 64 * (2 + 3 * 1024)),
|
||||
rows(o.y, o.y.ch));
|
||||
break;
|
||||
}
|
||||
case VOp::LIN: {
|
||||
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
|
||||
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), RAD_W(o.b), RAD_NONE,
|
||||
rows(o.y, o.y.ch));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/flux3 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(flux3 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(flux3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/flux3.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,11 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/flux3distilled -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see
|
||||
# cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(flux3distilled LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(flux3distilled architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/flux3distilled.cpp)
|
||||
@@ -0,0 +1,13 @@
|
||||
/* flux3distilled -- arch/flux3 under the architecture name of FLUX.3 [klein]'s step-distilled
|
||||
* release.
|
||||
*
|
||||
* The released pipeline is a `Flux3DistilledModularPipeline` and its base a
|
||||
* `Flux3ModularPipeline`, so rad-convert names them `flux3distilled` and `flux3`. Both hold the same
|
||||
* networks; the transformer's `flow_map` flag is what tells them apart inside the plugin. A
|
||||
* separate .so because a plugin answers to one architecture name (spec §2.4). Everything else is
|
||||
* arch/flux3/flux3.cpp.
|
||||
*/
|
||||
#define FLUX3_NS flux3distilled
|
||||
#define FLUX3_ID "flux3distilled"
|
||||
|
||||
#include "../flux3/flux3.cpp"
|
||||
@@ -867,13 +867,12 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
dw.ds = decl_b(b, nm.f("df_ds"), RAD_F32, {sr, 1});
|
||||
dw.dsum = decl_b(b, nm.f("df_dsum"), RAD_F32, {dg.n_embd / 128, spad});
|
||||
dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, Dflash2::head_rows(dg)});
|
||||
/* Rescoring against the trunk's head needs logit_rerank to read its rows; RADIANCE_G3_DF_RERANK=0
|
||||
* keeps the coarse head's scores. */
|
||||
/* Candidates are rescored against the trunk's head when logit_rerank can read its rows (fp8
|
||||
* or int8) and every candidate a rank proposes is one it owns; the planes are then kRerankR
|
||||
* wide and the selector reads the first sel_topk. */
|
||||
{
|
||||
const char* rr = std::getenv("RADIANCE_G3_DF_RERANK");
|
||||
const uint32_t hd = weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16);
|
||||
if (!(rr && rr[0] == '0') && (hd == RAD_F8E4M3 || hd == RAD_I8) &&
|
||||
(Dflash2::head_sharded(dg) || dg.world <= 1)) {
|
||||
if ((hd == RAD_F8E4M3 || hd == RAD_I8) && (Dflash2::head_sharded(dg) || dg.world <= 1)) {
|
||||
m.df.w_lm = m.w_lm;
|
||||
m.df.top_w = Dflash2::kRerankR;
|
||||
}
|
||||
|
||||
@@ -43,7 +43,6 @@ struct Model {
|
||||
rad_op mprev = 0, membed = 0, membed_ar = 0, men = 0, mhn = 0, meh = 0, mnorm_op = 0,
|
||||
mselect = 0, mback = 0, mcopy = 0, mhead = 0;
|
||||
bool have_mtp = false;
|
||||
bool fuse_router = false, fuse_swiglu = false, gather_inverse = false;
|
||||
};
|
||||
static std::unique_ptr<Model> models[MAX_RANKS];
|
||||
static thread_local std::unique_ptr<Model> probe_model;
|
||||
@@ -159,7 +158,7 @@ static int buffers(RadBuilder* b, Model& m) {
|
||||
m.mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { 289 });
|
||||
m.mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 });
|
||||
m.mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { R * 8 });
|
||||
if (m.gather_inverse) m.mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { R * 8 });
|
||||
m.mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { R * 8 });
|
||||
m.mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { R * 8, 2 * F });
|
||||
m.mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { R * 8, F });
|
||||
RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "expert_ff", F, R * 8));
|
||||
@@ -242,7 +241,7 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
|
||||
nm.ckpt("%s.mlp.gate_proj.weight", pre),
|
||||
nm.ckpt("%s.mlp.up_proj.weight", pre),
|
||||
nm.ckpt("%s.mlp.down_proj.weight", pre) };
|
||||
lay.dense.swiglu_quant = m.fuse_swiglu;
|
||||
lay.dense.swiglu_quant = true;
|
||||
RAD_ARCH_TRY(lay.dense.declare(b, nm, g, l, w, s, false, draft, kArNone, false, 10));
|
||||
} else {
|
||||
auto w = m.mw;
|
||||
@@ -261,8 +260,8 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
|
||||
s.cfg.route_scale = 2.5;
|
||||
s.cfg.swiglu_limit = 10;
|
||||
s.cfg.shared_ungated = 1;
|
||||
s.cfg.router_fuse = m.fuse_router;
|
||||
s.cfg.swiglu_quant = m.fuse_swiglu;
|
||||
s.cfg.router_fuse = 1;
|
||||
s.cfg.swiglu_quant = 1;
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
s.cfg.ff_lo[q] = g.rank * (2048 / g.world);
|
||||
s.cfg.ff_hi[q] = (g.rank + 1) * (2048 / g.world);
|
||||
@@ -273,19 +272,6 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
|
||||
if (!draft) RAD_ARCH_TRY(lay.ffn_hc.declare_post(b));
|
||||
return RAD_OK;
|
||||
}
|
||||
/* A decode fusion of the MoE block, on unless its variable is 0. Each is byte-identical to the
|
||||
* launches it replaces, so the switch is about speed alone; 0 restores the separate launches. */
|
||||
static int fusion_switch(const char* name, bool* out) {
|
||||
const char* e = std::getenv(name);
|
||||
*out = true;
|
||||
if (!e || !*e || !std::strcmp(e, "1")) return RAD_OK;
|
||||
if (!std::strcmp(e, "0")) {
|
||||
*out = false;
|
||||
return RAD_OK;
|
||||
}
|
||||
fprintf(stderr, "radiance: %s='%s'; it is 0 or 1\n", name, e);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS)
|
||||
return RAD_E_INVAL;
|
||||
@@ -326,9 +312,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
g.wire_exact = !ctx->tp_wire_lossy;
|
||||
g.wire_min_bytes = ctx->tp_wire_min_bytes;
|
||||
if (g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1 || g.eps <= 0) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(fusion_switch("RADIANCE_GLM_ROUTER_FUSE", &m.fuse_router));
|
||||
RAD_ARCH_TRY(fusion_switch("RADIANCE_GLM_SWIGLU_QUANT", &m.fuse_swiglu));
|
||||
RAD_ARCH_TRY(fusion_switch("RADIANCE_GLM_GATHER_INVERSE", &m.gather_inverse));
|
||||
RAD_ARCH_TRY(buffers(b, m));
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_FULL;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/krea2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(krea2 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(krea2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/krea2.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/ltx2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(ltx2 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(ltx2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/ltx2.cpp)
|
||||
+4193
File diff suppressed because it is too large.
Load diff
@@ -649,8 +649,36 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
fd.n_head_kv = g.n_head_kv;
|
||||
fd.head_dim = g.head_dim;
|
||||
/* --kv-cache-dtype fp8_v4 / k6_v4 (RadBuildCtx::kv_quant): V as int4 in groups of 32 with
|
||||
* f16 scales, K E4M3 as above or int6 the same way (libr4d's gqa12 and four-rank gqa6
|
||||
* rows for these layers). A token's row is 25 or 22 * head_dim / 16 bytes instead of
|
||||
* 2 * head_dim, so the group is declared at half that and the core sizes pages from it;
|
||||
* only those kernels read the layout. The MTP head's layer shares this group. The engine
|
||||
* asks only for a layout probe() offered. */
|
||||
const int kvq = fd.dtype == RAD_F8E4M3 ? ctx->kv_quant : RAD_KVQ_NONE;
|
||||
const char* kvq_name = kvq == RAD_KVQ_V4 ? "fp8_v4" : kvq == RAD_KVQ_K6V4 ? "k6_v4"
|
||||
: nullptr;
|
||||
if (kvq != RAD_KVQ_NONE && !kvq_name) {
|
||||
fprintf(stderr, "radiance: KV cache layout %d is not one this plugin knows\n", kvq);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* A rank's ratio: twelve at one and two ranks, six at four (each KV head replicated
|
||||
* across a rank pair). */
|
||||
if (kvq_name && !(g.head_dim == 256 && (g.gqa() == 12 || g.gqa() == 6))) {
|
||||
fprintf(stderr, "radiance: --kv-cache-dtype %s has libr4d rows at head_dim 256 and a "
|
||||
"rank's gqa 12 or 6 only; this rank is head_dim %lld, gqa %lld\n",
|
||||
kvq_name, (long long)g.head_dim, (long long)g.gqa());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const int64_t row16 = kvq == RAD_KVQ_V4 ? 25 : kvq == RAD_KVQ_K6V4 ? 22 : 32;
|
||||
fd.head_dim = g.head_dim * row16 / 32;
|
||||
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
|
||||
g.kv_dtype = rad_dtype_name(fd.dtype);
|
||||
g.kv_dtype = kvq_name ? kvq_name : rad_dtype_name(fd.dtype);
|
||||
if (kvq_name)
|
||||
rad_note(b, "kv cache %s: %s K, int4 V, in groups of 32 with f16 scales, %lld bytes a "
|
||||
"token and head instead of %lld", kvq_name,
|
||||
kvq == RAD_KVQ_V4 ? "E4M3" : "int6", (long long)(g.head_dim * row16 / 16),
|
||||
(long long)(2 * g.head_dim));
|
||||
|
||||
RadKVGroupDecl sd{};
|
||||
sd.kind = RAD_KV_LINEAR;
|
||||
@@ -1622,6 +1650,16 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (meta_int2(meta, "qwen4exp.mtp_num_hidden_layers", "mtp_num_hidden_layers", 0) > 0)
|
||||
out->draft_depth = 3;
|
||||
out->shape_probe_ok = 1; /* declare() writes scratch under shape_probe */
|
||||
/* --kv-cache-dtype fp8_v4 / k6_v4: libr4d has their rows for the QSA layers' geometry
|
||||
* (head_dim 256, twelve queries per KV head; gqa6 with 4-token pages at four ranks), so other
|
||||
* geometries are refused at startup rather than in declare. */
|
||||
{
|
||||
const long long hd = meta->head_dim ? meta->head_dim
|
||||
: (meta->n_head ? meta->n_embd / meta->n_head : 0);
|
||||
const long long nkv = meta->n_head_kv ? meta->n_head_kv : meta->n_head;
|
||||
if (hd == 256 && nkv > 0 && meta->n_head == 12 * nkv)
|
||||
out->kv_quant_ok = (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
@@ -47,6 +47,7 @@
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
#include <arch/rad_block_vit.h>
|
||||
#include <arch/rad_vae2d.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
@@ -75,291 +76,6 @@ static inline int64_t ref_tokens_max() { return (int64_t)kRefArea / 256 * 11 / 1
|
||||
|
||||
static const char* kSysPrompt = "Comprehend and analyze the provided prompt.";
|
||||
|
||||
/* ================================================================== the VAE as a recorded graph
|
||||
*
|
||||
* Image size varies per request, so the VAE's ops are declared once for the largest image and
|
||||
* issued with the actual extents: every image operand is a raw [height, width * channels] view of
|
||||
* its buffer (docs/OPS.md, "Image generation"), with extents from the pass's picture size and the
|
||||
* stage's scale. `Vae` records each op with what it needs to rebuild its operands, so declare()
|
||||
* and step() walk the same list.
|
||||
*
|
||||
* Every output is its own buffer, sized for its stage; the planner shares storage between those
|
||||
* whose lives do not overlap, and no buffer is reused by hand. This is sound because ops are issued
|
||||
* in declaration order. */
|
||||
struct VImg {
|
||||
rad_buf buf = 0;
|
||||
int64_t ch = 0;
|
||||
int lvl = 0; /* the side is the pass's base side times 2^lvl (decoder) or / 2^lvl (encoder) */
|
||||
};
|
||||
|
||||
struct VOp {
|
||||
enum Kind { CONV, NORM, ADD, D2S, S2D, ATTN } kind = CONV;
|
||||
rad_op op = 0;
|
||||
VImg x{}, y{}, z{}; /* inputs x (and z for ADD), output y */
|
||||
rad_weight w = 0, b = 0;
|
||||
int k = 1, up = 1, stride = 1;
|
||||
int64_t qkv_ch = 0; /* ATTN: x is the [*, 3C] qkv rows, y the [*, C] output */
|
||||
};
|
||||
|
||||
struct Vae {
|
||||
std::vector<VOp> ops;
|
||||
Names* nm = nullptr;
|
||||
RadBuilder* b = nullptr;
|
||||
const char* scope = ""; /* "dec" or "enc" */
|
||||
bool down = false; /* an encoder: a level halves the side */
|
||||
int64_t base_px = 0; /* pixels at level 0, the largest any pass hands it */
|
||||
int n_buf = 0;
|
||||
int first_group = 0;
|
||||
/* The banded tail. From op `band_from` on, every output pixel reads a bounded window of rows
|
||||
* (3x3 convolutions, nearest upsampling, per-pixel norms and adds, depth-to-space shortcuts),
|
||||
* so a rank can run the tail on its band of level-0 rows plus `halo` rows per side and get its
|
||||
* band's pixels bit for bit: rows spoiled by a conv's zero padding at the band edge never reach
|
||||
* the band. The ops before it include the mid-block's attention, which reads every pixel, and
|
||||
* run whole; `whole` holds their outputs, read by the tail at the band's row offset. -1: no
|
||||
* tail. */
|
||||
int band_from = -1;
|
||||
int64_t halo = 0;
|
||||
std::vector<rad_buf> whole;
|
||||
|
||||
int64_t px_at(int lvl) const {
|
||||
int64_t p = base_px;
|
||||
for (int i = 0; i < lvl; ++i) p = down ? (p + 3) / 4 : p * 4;
|
||||
return p;
|
||||
}
|
||||
VImg img(int64_t ch, int lvl) {
|
||||
VImg v;
|
||||
v.ch = ch;
|
||||
v.lvl = lvl;
|
||||
v.buf = decl_b(b, nm->f("%s.t%d", scope, n_buf++), RAD_BF16, { px_at(lvl), ch });
|
||||
return v;
|
||||
}
|
||||
rad_weight wt(const char* name, const char* src, std::initializer_list<int64_t> shape) {
|
||||
if (map_copy(b, name, src) < 0) return 0;
|
||||
return decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE,
|
||||
grp_layer(first_group));
|
||||
}
|
||||
|
||||
/* y = conv(x): k x k, stride, `up` 2 reads x upsampled, `pad` same or down. */
|
||||
VImg conv(const VImg& x, int64_t cout, int k, int stride, int up, const char* pad,
|
||||
const char* ckpt) {
|
||||
VOp o;
|
||||
o.kind = VOp::CONV;
|
||||
o.x = x;
|
||||
o.up = up;
|
||||
o.stride = stride;
|
||||
int lvl = x.lvl;
|
||||
if (up == 2) lvl = down ? lvl - 1 : lvl + 1;
|
||||
if (stride == 2) lvl = down ? lvl + 1 : lvl - 1;
|
||||
o.y = img(cout, lvl);
|
||||
o.k = k;
|
||||
o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { cout, x.ch, k, k });
|
||||
o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { cout });
|
||||
o.op = RAD_OP(b, "conv2d_nhwc",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px_at(lvl)), RAD_INT("cin", x.ch),
|
||||
RAD_INT("cout", cout), RAD_INT("k", k),
|
||||
RAD_INT("stride", stride), RAD_STR("pad", pad),
|
||||
RAD_INT("up", up), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(o.w, o.b));
|
||||
/* An input with no buffer is the picture the pass staged, read where it lies. */
|
||||
if (x.buf) rw(b, o.op, { x.buf }, { o.y.buf });
|
||||
else rw(b, o.op, {}, { o.y.buf });
|
||||
ops.push_back(o);
|
||||
return o.y;
|
||||
}
|
||||
/* The channel norm, `silu` or not. `gamma` is [C, 1, 1(, 1)] in the checkpoint. */
|
||||
VImg norm(const VImg& x, bool silu, const char* ckpt, int gamma_rank) {
|
||||
VOp o;
|
||||
o.kind = VOp::NORM;
|
||||
o.x = x;
|
||||
o.y = img(x.ch, x.lvl);
|
||||
const char* dn = nm->f("%s.gamma", ckpt);
|
||||
if (map_copy(b, dn, nm->ckpt("%s.gamma", ckpt)) < 0) return VImg{};
|
||||
o.w = gamma_rank == 4
|
||||
? decl_w(b, dn, RAD_BF16, { x.ch, 1, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group))
|
||||
: decl_w(b, dn, RAD_BF16, { x.ch, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group));
|
||||
o.op = rw(b, RAD_OP(b, "l2norm_chan",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
|
||||
RAD_STR("act", silu ? "silu" : "none"),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(o.w)),
|
||||
{ x.buf }, { o.y.buf });
|
||||
ops.push_back(o);
|
||||
return o.y;
|
||||
}
|
||||
VImg add(const VImg& x, const VImg& z) {
|
||||
VOp o;
|
||||
o.kind = VOp::ADD;
|
||||
o.x = x;
|
||||
o.z = z;
|
||||
o.y = img(x.ch, x.lvl);
|
||||
o.op = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ x.buf, z.buf }, { o.y.buf });
|
||||
ops.push_back(o);
|
||||
return o.y;
|
||||
}
|
||||
/* y += the resampling shortcut of x (in place on y). */
|
||||
void shortcut(const VImg& x, const VImg& y, int ft) {
|
||||
VOp o;
|
||||
o.kind = down ? VOp::S2D : VOp::D2S;
|
||||
o.x = x;
|
||||
o.y = y;
|
||||
o.up = ft;
|
||||
o.op = rw(b, RAD_OP(b, down ? "s2d_avg_add" : "d2s_add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px_at(y.lvl)), RAD_INT("cin", x.ch),
|
||||
RAD_INT("cout", y.ch), RAD_INT("ft", ft),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ x.buf, y.buf }, { y.buf });
|
||||
ops.push_back(o);
|
||||
}
|
||||
/* A residual block, in -> out channels. */
|
||||
VImg resblock(const VImg& x, int64_t out, const char* ckpt) {
|
||||
VImg h = x;
|
||||
if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->f("%s.conv_shortcut", ckpt));
|
||||
VImg t = norm(x, true, nm->f("%s.norm1", ckpt), 4);
|
||||
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv1", ckpt));
|
||||
t = norm(t, true, nm->f("%s.norm2", ckpt), 4);
|
||||
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv2", ckpt));
|
||||
return add(t, h);
|
||||
}
|
||||
/* The mid-block's single-head attention over every pixel. */
|
||||
VImg attention(const VImg& x, const char* ckpt) {
|
||||
const int64_t C = x.ch;
|
||||
VImg t = norm(x, false, nm->f("%s.norm", ckpt), 3);
|
||||
VImg qkv = conv(t, 3 * C, 1, 1, 1, "same", nm->f("%s.to_qkv", ckpt));
|
||||
VOp o;
|
||||
o.kind = VOp::ATTN;
|
||||
o.x = qkv;
|
||||
o.y = img(C, x.lvl);
|
||||
o.qkv_ch = 3 * C;
|
||||
o.op = rw(b, RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("head_dim", C),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)C))),
|
||||
RAD_NOWEIGHTS),
|
||||
{ qkv.buf }, { o.y.buf });
|
||||
ops.push_back(o);
|
||||
VImg p = conv(o.y, C, 1, 1, 1, "same", nm->f("%s.proj", ckpt));
|
||||
return add(p, x);
|
||||
}
|
||||
|
||||
/* The operands of op `o` for a pass whose level-0 picture is H0 x W0 pixels (or latent tokens,
|
||||
* for the decoder), in the op's schema order, and its ranged value. */
|
||||
static int64_t side(int64_t s0, int lvl, bool dn) {
|
||||
int64_t s = s0;
|
||||
for (int i = 0; i < lvl; ++i) s = dn ? s / 2 : s * 2;
|
||||
return s;
|
||||
}
|
||||
/* `cu` is {0, pixels} at the attention's level -- the pass's latent tokens -- and `input` the
|
||||
* level-0 picture when the first op reads one the pass staged. Ops [from, to) are issued; with
|
||||
* `row0`, H0 is a band's rows and a `whole` buffer is read from its level-0 row `row0`. */
|
||||
void issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu, const void* input,
|
||||
size_t from = 0, size_t to = (size_t)-1, int64_t row0 = 0) const;
|
||||
|
||||
bool is_whole(rad_buf v) const {
|
||||
for (rad_buf w : whole) if (w == v) return true;
|
||||
return false;
|
||||
}
|
||||
/* The tail's halo in level-0 rows: walked back from the last op, a buffer's margin is the most
|
||||
* any reader of it needs, in its own rows -- a k x k conv adds k/2, reading through a 2x
|
||||
* upsample halves it rounding up, and the depth-to-space shortcut halves it. -1 when the tail
|
||||
* holds an op that is not row-local, or reads a whole buffer above level 0. */
|
||||
int64_t band_halo() const {
|
||||
if (band_from < 0 || ops.empty()) return -1;
|
||||
std::vector<std::pair<rad_buf, int64_t>> need{ { ops.back().y.buf, 0 } };
|
||||
auto get = [&](rad_buf v) -> int64_t {
|
||||
for (const auto& e : need) if (e.first == v) return e.second;
|
||||
return 0;
|
||||
};
|
||||
auto want = [&](rad_buf v, int64_t m) {
|
||||
for (auto& e : need) if (e.first == v) { e.second = std::max(e.second, m); return; }
|
||||
need.push_back({ v, m });
|
||||
};
|
||||
for (size_t i = ops.size(); i-- > (size_t)band_from;) {
|
||||
const VOp& o = ops[i];
|
||||
const int64_t my = get(o.y.buf);
|
||||
switch (o.kind) {
|
||||
case VOp::CONV: {
|
||||
if (o.stride != 1) return -1;
|
||||
const int64_t m = my + o.k / 2;
|
||||
want(o.x.buf, o.up == 2 ? (m + 1) / 2 : m);
|
||||
break;
|
||||
}
|
||||
case VOp::NORM: want(o.x.buf, my); break;
|
||||
case VOp::ADD: want(o.x.buf, my); want(o.z.buf, my); break;
|
||||
case VOp::D2S: want(o.x.buf, (my + 1) / 2); break;
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
int64_t h = 0;
|
||||
for (size_t i = (size_t)band_from; i < ops.size(); ++i) {
|
||||
const VOp& o = ops[i];
|
||||
for (const VImg* v : { &o.x, &o.z })
|
||||
if (v->buf && is_whole(v->buf)) {
|
||||
if (v->lvl != 0) return -1;
|
||||
h = std::max(h, get(v->buf));
|
||||
}
|
||||
}
|
||||
return h;
|
||||
}
|
||||
};
|
||||
|
||||
inline void Vae::issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu,
|
||||
const void* input, size_t from, size_t to, int64_t row0) const {
|
||||
auto ptr = [&](const VImg& v) -> const void* {
|
||||
if (!v.buf) return input;
|
||||
const char* p = (const char*)rad_buf_ptr(c, v.buf);
|
||||
return row0 && is_whole(v.buf) ? p + row0 * W0 * v.ch * (int64_t)sizeof(uint16_t) : p;
|
||||
};
|
||||
auto view = [&](const VImg& v, int64_t* H, int64_t* W) {
|
||||
*H = side(H0, v.lvl, down);
|
||||
*W = side(W0, v.lvl, down);
|
||||
return RAD_P_T2(ptr(v), RAD_BF16, *H, *W * v.ch);
|
||||
};
|
||||
auto rows = [&](const VImg& v, int64_t cols) {
|
||||
const int64_t H = side(H0, v.lvl, down), W = side(W0, v.lvl, down);
|
||||
return RAD_P_T2(ptr(v), RAD_BF16, H * W * v.ch / cols, cols);
|
||||
};
|
||||
for (size_t i = from; i < to && i < ops.size(); ++i) {
|
||||
const VOp& o = ops[i];
|
||||
int64_t Hx, Wx, Hy, Wy;
|
||||
switch (o.kind) {
|
||||
case VOp::CONV: {
|
||||
const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy);
|
||||
RAD_ISSUE_N(c, o.op, Hy * Wy, x, RAD_W(o.w), RAD_W(o.b), y);
|
||||
break;
|
||||
}
|
||||
case VOp::NORM: {
|
||||
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
|
||||
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), rows(o.y, o.y.ch));
|
||||
break;
|
||||
}
|
||||
case VOp::ADD: {
|
||||
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
|
||||
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), rows(o.z, o.z.ch), rows(o.y, o.y.ch));
|
||||
break;
|
||||
}
|
||||
case VOp::D2S:
|
||||
case VOp::S2D: {
|
||||
const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy);
|
||||
RAD_ISSUE_N(c, o.op, Hy * Wy, x, y);
|
||||
break;
|
||||
}
|
||||
case VOp::ATTN: {
|
||||
/* q, k and v are column slices of the qkv rows, at its 3C pitch. */
|
||||
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
|
||||
const int64_t C = o.y.ch, n = H * W;
|
||||
RAD_ISSUE_N(c, o.op, n, bcol(o.x.buf, 0, C, n), bcol(o.x.buf, C, C, n),
|
||||
bcol(o.x.buf, 2 * C, C, n), cu, brows(o.y.buf, n));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the model */
|
||||
struct TeLayer {
|
||||
|
||||
+134
-21
@@ -14,6 +14,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
@@ -940,7 +941,8 @@ int Builder::decl_name_map(const RadNameMap* m) {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (m->mode != RAD_MAP_COPY && m->mode != RAD_MAP_CONCAT && m->mode != RAD_MAP_WNORM &&
|
||||
m->mode != RAD_MAP_ROWS && m->mode != RAD_MAP_TRANSPOSE && m->mode != RAD_MAP_EMA) {
|
||||
m->mode != RAD_MAP_ROWS && m->mode != RAD_MAP_TRANSPOSE && m->mode != RAD_MAP_EMA &&
|
||||
m->mode != RAD_MAP_TAP) {
|
||||
err(RAD_E_INVAL, "name map for '%s': unknown mode %d", m->declared, m->mode);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
@@ -951,9 +953,9 @@ int Builder::decl_name_map(const RadNameMap* m) {
|
||||
: "the magnitude and the direction", m->n_src);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (m->mode == RAD_MAP_TRANSPOSE && m->n_src != 1) {
|
||||
err(RAD_E_INVAL, "name map for '%s': a transpose map names one source, not %d",
|
||||
m->declared, m->n_src);
|
||||
if ((m->mode == RAD_MAP_TRANSPOSE || m->mode == RAD_MAP_TAP) && m->n_src != 1) {
|
||||
err(RAD_E_INVAL, "name map for '%s': a %s map names one source, not %d", m->declared,
|
||||
m->mode == RAD_MAP_TAP ? "tap" : "transpose", m->n_src);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
@@ -1192,16 +1194,27 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
|
||||
: prog_.is_audio_generator() ? "an audio generator" : "a video generator");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID) {
|
||||
if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID && d->layout != RAD_GEN_LAYOUT_JOINT_STEP) {
|
||||
err(RAD_E_INVAL, "declare_generator '%s': layout %d is not one this engine builds", nm,
|
||||
(int)d->layout);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const bool joint = d->layout == RAD_GEN_LAYOUT_JOINT_STEP;
|
||||
auto has = [](const char* t, const char* what) { return t && std::strstr(t, what); };
|
||||
if (!has(d->tmpl_text, "{prompt}") || !has(d->tmpl_edit, "{prompt}") ||
|
||||
!has(d->tmpl_edit, "{images}") || !has(d->tmpl_image, "{image}")) {
|
||||
err(RAD_E_INVAL, "declare_generator '%s': tmpl_text needs {prompt}, tmpl_edit {images} and "
|
||||
"{prompt}, and tmpl_image {image}, where the picture's tokens go", nm);
|
||||
if (joint ? !has(d->tmpl_text, "{prompt}") || !has(d->tmpl_edit, "{prompt}")
|
||||
: !has(d->tmpl_text, "{prompt}") || !has(d->tmpl_edit, "{prompt}") ||
|
||||
!has(d->tmpl_edit, "{images}") || !has(d->tmpl_image, "{image}")) {
|
||||
err(RAD_E_INVAL, "declare_generator '%s': tmpl_text and tmpl_edit need {prompt}, and "
|
||||
"with the pictures in the prompt tmpl_edit needs {images} and tmpl_image "
|
||||
"{image}, where the picture's tokens go", nm);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (joint && (d->cond_rows <= 0 || !(d->rope_hw_scale > 0) || d->pad_multiple < 0 ||
|
||||
(d->pad_multiple > 0 && d->pad_token < 0))) {
|
||||
err(RAD_E_INVAL, "declare_generator '%s': the joint layout needs cond_rows, a positive "
|
||||
"rope_hw_scale and, with padding, a pad token (cond_rows %lld, scale %g, "
|
||||
"pad %d to a multiple of %d)", nm, (long long)d->cond_rows,
|
||||
d->rope_hw_scale, (int)d->pad_token, (int)d->pad_multiple);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->latent_channels <= 0 || d->latent_scale <= 0 || d->size_multiple <= 0 ||
|
||||
@@ -1220,7 +1233,8 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->n_sigmas < 0 || (d->n_sigmas > 0 && !d->sigmas) ||
|
||||
(d->n_sigmas == 0 && d->default_steps <= 0) || !(d->default_cfg >= 1.0) ||
|
||||
(d->n_sigmas == 0 && d->default_steps <= 0) ||
|
||||
!(d->default_cfg >= (d->cfg_original ? 0.0 : 1.0)) ||
|
||||
(d->dyn_shift && (d->max_seq <= d->base_seq || d->base_seq <= 0)) ||
|
||||
(!d->dyn_shift && !(d->shift > 0)) || d->shift_terminal < 0 || d->shift_terminal >= 1) {
|
||||
err(RAD_E_INVAL, "declare_generator '%s': the sampler is incomplete (%d fixed sigmas, %lld "
|
||||
@@ -1255,17 +1269,19 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
|
||||
g.name = nm;
|
||||
g.tmpl_text = d->tmpl_text;
|
||||
g.tmpl_edit = d->tmpl_edit;
|
||||
g.tmpl_image = d->tmpl_image;
|
||||
g.tmpl_image = d->tmpl_image ? d->tmpl_image : "";
|
||||
g.tmpl_image_sep = d->tmpl_image_sep ? d->tmpl_image_sep : "";
|
||||
g.drop_prefix = d->drop_prefix ? d->drop_prefix : "";
|
||||
g.tmpl_transparent = d->tmpl_transparent ? d->tmpl_transparent : "";
|
||||
g.has_default_negative = d->default_negative != nullptr;
|
||||
g.default_negative = d->default_negative ? d->default_negative : "";
|
||||
g.sigmas.assign(d->sigmas, d->sigmas + d->n_sigmas);
|
||||
prog_.generator = *d;
|
||||
/* The Program is moved after declare, which would invalidate pointers into gen_str, so the
|
||||
* decl's string fields are cleared; read them only through gen_str. */
|
||||
RadGeneratorDecl& c = prog_.generator;
|
||||
c.name = c.tmpl_text = c.tmpl_edit = c.tmpl_image = c.tmpl_image_sep = nullptr;
|
||||
c.drop_prefix = c.tmpl_transparent = nullptr;
|
||||
c.drop_prefix = c.tmpl_transparent = c.default_negative = nullptr;
|
||||
c.sigmas = nullptr;
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -1461,22 +1477,78 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) {
|
||||
(long long)d->audio_latent_channels);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->default_steps <= 0 || d->max_steps < d->default_steps || !(d->shift_video > 0.0) ||
|
||||
!(d->shift_audio > 0.0) || d->max_lanes <= 0) {
|
||||
/* Form 1 (LTX-2's FlowMatchEulerDiscrete) steps both modalities the same sigmas and reads
|
||||
* no per-modality shift. */
|
||||
const bool shifts = d->sched_kind == 1 || (d->shift_video > 0.0 && d->shift_audio > 0.0);
|
||||
if (d->default_steps <= 0 || d->max_steps < d->default_steps || !shifts || d->max_lanes <= 0) {
|
||||
err(RAD_E_INVAL, "declare_video_generator '%s': the sampler is incomplete (%lld steps by "
|
||||
"default, %lld at most, shifts %g and %g, %lld lanes)", nm,
|
||||
(long long)d->default_steps, (long long)d->max_steps, d->shift_video, d->shift_audio,
|
||||
(long long)d->max_lanes);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->n_rungs < 0 || (d->n_rungs > 0 && !d->rungs) ||
|
||||
(d->n_rungs > 0 && (d->default_steps != d->n_rungs + 1 || d->max_steps != d->n_rungs + 1))) {
|
||||
err(RAD_E_INVAL, "declare_video_generator '%s': a trained schedule of %d rungs runs %d grid "
|
||||
"points, which default_steps and max_steps must both be (%lld, %lld)", nm,
|
||||
(int)d->n_rungs, (int)d->n_rungs + 1, (long long)d->default_steps,
|
||||
/* Form 0 counts grid points, form 1 evaluations. */
|
||||
const int64_t rung_steps = d->sched_kind == 1 ? d->n_rungs : d->n_rungs + 1;
|
||||
if (d->sched_kind < 0 || d->sched_kind > 1 || d->n_rungs < 0 || (d->n_rungs > 0 && !d->rungs) ||
|
||||
(d->n_rungs > 0 && (d->default_steps != rung_steps || d->max_steps != rung_steps))) {
|
||||
err(RAD_E_INVAL, "declare_video_generator '%s': a trained schedule of %d rungs runs %lld "
|
||||
"steps, which default_steps and max_steps must both be (%lld, %lld)", nm,
|
||||
(int)d->n_rungs, (long long)rung_steps, (long long)d->default_steps,
|
||||
(long long)d->max_steps);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->sched_kind == 1 && d->dyn_shift &&
|
||||
(!(d->max_seq > d->base_seq) || !std::isfinite(d->base_shift) ||
|
||||
!std::isfinite(d->max_shift))) {
|
||||
err(RAD_E_INVAL, "declare_video_generator '%s': the dynamic shift runs from %lld tokens "
|
||||
"(%g) to %lld (%g); the second length must be the larger", nm,
|
||||
(long long)d->base_seq, d->base_shift, (long long)d->max_seq, d->max_shift);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!(d->shift_terminal >= 0.0 && d->shift_terminal < 1.0)) {
|
||||
err(RAD_E_INVAL, "declare_video_generator '%s': shift_terminal %g is outside [0, 1)", nm,
|
||||
d->shift_terminal);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->n_refine_rungs < 0 || (d->n_refine_rungs > 0 && (!d->refine_rungs ||
|
||||
d->sched_kind != 1 || d->n_rungs == 0 || !(d->upscale_max > 1.0)))) {
|
||||
err(RAD_E_INVAL, "declare_video_generator '%s': refinement rungs need a trained schedule of "
|
||||
"form 1 and a latent upscaler", nm);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int i = 0; i < d->n_refine_rungs; ++i)
|
||||
if (!(d->refine_rungs[i] > 0.0 && d->refine_rungs[i] <= 1.0) ||
|
||||
(i > 0 && !(d->refine_rungs[i] < d->refine_rungs[i - 1]))) {
|
||||
err(RAD_E_INVAL, "declare_video_generator '%s': refinement rung %d (%g) is outside "
|
||||
"(0, 1] or not below the one before it", nm, i, d->refine_rungs[i]);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->step_text_rows < 0 || d->step_text_rows > d->max_text * 64 || d->image_crf < 0 ||
|
||||
d->image_crf > 51 || (d->image_cond != 0 && d->image_cond != 1) ||
|
||||
(d->guidance != 0 && d->guidance != 1)) {
|
||||
err(RAD_E_INVAL, "declare_video_generator '%s': step_text_rows %lld, image_cond %d, "
|
||||
"image_crf %d (0..51) or guidance %d is out of range", nm,
|
||||
(long long)d->step_text_rows, (int)d->image_cond, (int)d->image_crf, (int)d->guidance);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->text_left_pad < 0 || (d->text_left_pad > 0 && d->text_left_pad < d->max_text) ||
|
||||
d->audio_streams < 0 ||
|
||||
(d->upscale_exact && (!(d->upscale_max > 1.0) ||
|
||||
d->upscale_max != std::floor(d->upscale_max)))) {
|
||||
err(RAD_E_INVAL, "declare_video_generator '%s': text_left_pad %lld must hold the longest "
|
||||
"prompt (%lld), audio_streams %d may not be negative, and an exact "
|
||||
"upscaler's factor (%g) is a whole number above 1", nm,
|
||||
(long long)d->text_left_pad, (long long)d->max_text, (int)d->audio_streams,
|
||||
d->upscale_max);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->guidance)
|
||||
for (int i = 0; i < 8; ++i)
|
||||
if (!std::isfinite(d->guidance_default[i]) || d->guidance_default[i] < 0.0) {
|
||||
err(RAD_E_INVAL, "declare_video_generator '%s': default guidance term %d (%g) must "
|
||||
"be finite and not negative", nm, i, d->guidance_default[i]);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int i = 0; i < d->n_rungs; ++i)
|
||||
if (!(d->rungs[i] > 0.0 && d->rungs[i] <= 1.0) ||
|
||||
(i > 0 && !(d->rungs[i] < d->rungs[i - 1]))) {
|
||||
@@ -1486,9 +1558,13 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) {
|
||||
}
|
||||
/* An upscaler needs a schedule it can split: one evaluation at the small size at least, and
|
||||
* `upscale_refine` of them after it by default. */
|
||||
const int64_t def_evals = d->n_rungs > 0 ? d->n_rungs : d->default_steps - 1;
|
||||
const int64_t def_evals = d->n_rungs > 0 ? d->n_rungs
|
||||
: d->sched_kind == 1 ? d->default_steps : d->default_steps - 1;
|
||||
const bool own_refine = d->n_refine_rungs > 0;
|
||||
if (d->upscale_max != 0.0 &&
|
||||
(!(d->upscale_max > 1.0) || d->upscale_refine < 1 || d->upscale_refine >= def_evals)) {
|
||||
(!(d->upscale_max > 1.0) ||
|
||||
(!own_refine && (d->upscale_refine < 1 || d->upscale_refine >= def_evals)) ||
|
||||
(own_refine && d->upscale_refine != d->n_refine_rungs))) {
|
||||
err(RAD_E_INVAL, "declare_video_generator '%s': a latent upscaler of factor %g at most, "
|
||||
"refining %d evaluations of %lld by default; the factor must be above 1 "
|
||||
"and the refinement 1 to %lld", nm, d->upscale_max, (int)d->upscale_refine,
|
||||
@@ -1521,15 +1597,52 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) {
|
||||
if (!buf_ok(d->frames_out, RAD_U8, chunk_px, "frames_out") ||
|
||||
!buf_ok(d->audio_out, RAD_F32, max_samples * d->audio_channels, "audio_out"))
|
||||
return RAD_E_INVAL;
|
||||
if (d->duration_out != RAD_NULL_HANDLE) {
|
||||
if (!buf_ok(d->duration_out, RAD_F32, 1, "duration_out")) return RAD_E_INVAL;
|
||||
if (!(d->duration_min > 0.0 && d->duration_max > d->duration_min) ||
|
||||
!std::isfinite(d->duration_max) ||
|
||||
(d->duration_dtype != RAD_F32 && d->duration_dtype != RAD_BF16)) {
|
||||
err(RAD_E_INVAL, "declare_video_generator '%s': a length head clamps to "
|
||||
"[%g, %g] seconds in dtype %u; the bounds must be positive, finite "
|
||||
"and in order, the dtype f32 or bf16", nm, d->duration_min,
|
||||
d->duration_max, (unsigned)d->duration_dtype);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
prog_.vgen_str.name = nm;
|
||||
prog_.vgen_str.tmpl = d->tmpl;
|
||||
prog_.vgen_str.rungs.assign(d->rungs, d->rungs + d->n_rungs);
|
||||
prog_.vgen_str.refine_rungs.assign(d->refine_rungs, d->refine_rungs + d->n_refine_rungs);
|
||||
prog_.vgen_str.default_negative = d->default_negative ? d->default_negative : "";
|
||||
prog_.vgen_str.decoders.clear();
|
||||
prog_.vgen_str.decoder_max_area.clear();
|
||||
for (const char* s = d->decoders; s && *s;) {
|
||||
while (*s == ' ') ++s;
|
||||
const char* e = s;
|
||||
while (*e && *e != ' ') ++e;
|
||||
if (e > s) prog_.vgen_str.decoders.emplace_back(s, e);
|
||||
s = e;
|
||||
}
|
||||
for (size_t i = 0; i < prog_.vgen_str.decoders.size(); ++i) {
|
||||
const int64_t a = d->decoder_max_area ? d->decoder_max_area[i] : 0;
|
||||
if (a < 0 || a > d->max_area) {
|
||||
err(RAD_E_INVAL, "declare_video_generator '%s': decoder '%s' makes frames of %lld pixels "
|
||||
"at most, outside 0..max_area", nm,
|
||||
prog_.vgen_str.decoders[i].c_str(), (long long)a);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
prog_.vgen_str.decoder_max_area.push_back(a > 0 ? a : d->max_area);
|
||||
}
|
||||
prog_.video_gen = *d;
|
||||
/* As for the other generators: the Program is moved after declare; strings and the rungs live
|
||||
* in vgen_str. */
|
||||
prog_.video_gen.name = nullptr;
|
||||
prog_.video_gen.tmpl = nullptr;
|
||||
prog_.video_gen.rungs = nullptr;
|
||||
prog_.video_gen.refine_rungs = nullptr;
|
||||
prog_.video_gen.default_negative = nullptr;
|
||||
prog_.video_gen.decoders = nullptr;
|
||||
prog_.video_gen.decoder_max_area = nullptr;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -73,7 +73,7 @@ static const Flag g_flags[] = {
|
||||
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" },
|
||||
{ "--kv-cache-dtype", "T", "bf16 | fp8 | fp8_v4 | k6_v4 -- fp8 halves what a token of\n"
|
||||
"context costs; fp8_v4 keeps V in 4 bits (0.78 of fp8), k6_v4\n"
|
||||
"also K in 6 (0.69); both Qwen3.8-27B" },
|
||||
"also K in 6 (0.69); both Qwen3.8-27B and -Flash-Next" },
|
||||
{ "--host-pool-mib", "N", "pinned host tier" },
|
||||
{ "--host-headroom-mib", "N", "host RAM to leave free for the system when radiance\n"
|
||||
" pins its host memory at startup (default 4096)" },
|
||||
|
||||
+28
-2
@@ -8,6 +8,7 @@
|
||||
#include "gen/video_driver.h"
|
||||
#include "kld.h"
|
||||
#include "mm/processor.h"
|
||||
#include "mm/media.h"
|
||||
|
||||
#include "build/startup.h"
|
||||
#include "build/rad_build.h"
|
||||
@@ -2375,8 +2376,11 @@ int Engine::run_server() {
|
||||
in.size_multiple = gd.size_multiple;
|
||||
in.pixel_channels = gd.pixel_channels;
|
||||
in.max_tokens = gd.max_tokens;
|
||||
/* Edits need the conditioning network to read pictures. */
|
||||
in.max_refs = mm_proc ? gd.max_refs : 0;
|
||||
/* Edits need the conditioning network to read pictures, unless only the generator's
|
||||
* own encoder reads them. */
|
||||
in.refs_encoder_only = gd.layout == RAD_GEN_LAYOUT_JOINT_STEP;
|
||||
in.max_refs = mm_proc || in.refs_encoder_only ? gd.max_refs : 0;
|
||||
in.ref_shrink_only = gd.ref_shrink_only != 0;
|
||||
in.ref_area = gd.ref_area;
|
||||
in.default_width = gd.default_width;
|
||||
in.default_height = gd.default_height;
|
||||
@@ -2386,6 +2390,9 @@ int Engine::run_server() {
|
||||
in.fixed_schedule = !pg.gen_str.sigmas.empty();
|
||||
in.fixed_steps = (int64_t)pg.gen_str.sigmas.size();
|
||||
in.default_cfg = gd.default_cfg;
|
||||
in.cfg_original = gd.cfg_original != 0;
|
||||
in.has_default_negative = pg.gen_str.has_default_negative;
|
||||
in.default_negative = pg.gen_str.default_negative;
|
||||
image_bridge.drv = img_gen_;
|
||||
image_bridge.proc = mm_proc.get();
|
||||
d.images = &image_bridge;
|
||||
@@ -2497,6 +2504,19 @@ int Engine::run_server() {
|
||||
in.fixed_steps = vd.n_rungs > 0;
|
||||
in.upscale_max = vd.upscale_max;
|
||||
in.upscale_refine = vd.upscale_refine;
|
||||
in.step_evals = vd.sched_kind == 1;
|
||||
in.guidance = vd.guidance != 0;
|
||||
for (int i = 0; i < 8; ++i) in.guidance_default[i] = vd.guidance_default[i];
|
||||
in.default_negative = pg.vgen_str.default_negative;
|
||||
in.image_cond = vd.image_cond != 0;
|
||||
in.image_crf = vd.image_crf;
|
||||
in.length_head = vd.duration_out != RAD_NULL_HANDLE;
|
||||
in.decoders = pg.vgen_str.decoders;
|
||||
in.decoder_max_area = pg.vgen_str.decoder_max_area;
|
||||
if (in.image_cond && in.image_crf > 0 && !mm::h264_roundtrip_available())
|
||||
RAD_WARN("video: '%s' prepares a first frame with an H.264 round trip at crf %d, which "
|
||||
"needs libx264; this build's libavcodec has none, so input_reference is "
|
||||
"refused", in.name.c_str(), (int)in.image_crf);
|
||||
in.max_lanes = vd.max_lanes;
|
||||
video_bridge.drv = vid_gen_;
|
||||
d.videos = &video_bridge;
|
||||
@@ -2555,6 +2575,12 @@ int Engine::run_server() {
|
||||
RAD_INFO("chat: the template takes reasoning_effort %s, and none or minimal turn "
|
||||
"thinking off%s%s", list.c_str(), mapped.empty() ? "" : "; mapped: ",
|
||||
mapped.c_str());
|
||||
/* What a request naming no effort gets, which a client cannot see: Qwen3.8's template
|
||||
* renders xhigh into a system prompt (#113). */
|
||||
const std::string& dflt = srv.template_default_effort();
|
||||
if (cfg_.reasoning_effort.empty() && !dflt.empty())
|
||||
RAD_INFO("chat: a request naming no reasoning_effort renders as '%s', the "
|
||||
"template's own default (--reasoning-effort sets another)", dflt.c_str());
|
||||
} else if (!mapped.empty()) {
|
||||
RAD_INFO("chat: reasoning_effort mapped: %s", mapped.c_str());
|
||||
}
|
||||
|
||||
@@ -162,6 +162,10 @@ static bool dump_at(Ctx& ctx, int step, const char* phase, const std::string& na
|
||||
return true;
|
||||
}
|
||||
|
||||
/* A buffer is read where it lives after the pass, and the arena shares a transient's bytes with
|
||||
* every buffer whose lifetime does not overlap it. So a dump after a drafter's context pass shows
|
||||
* a tap buffer (dflash_src) already overwritten by a later one in that pass (df_c), and only the
|
||||
* step loop's dump, after the trunk, shows the taps as written. A PERSIST buffer is never shared. */
|
||||
void dump_buffers(Ctx& ctx, int step, const char* phase) {
|
||||
if ((int)log_level() < (int)Log::Trace) return;
|
||||
static const char* const names = std::getenv("RADIANCE_DUMP_BUF");
|
||||
|
||||
+54
-18
@@ -56,6 +56,25 @@ void MetaOwn::finish() {
|
||||
* path, and typed fields are read from `text_config.X`, falling back to `X`, so a plugin finds
|
||||
* `vision_config.depth` under that name either way.
|
||||
*/
|
||||
/* An array's scalars appended to `s` space-separated, nested arrays flattened row-major (a
|
||||
* vocoder's per-resnet dilations, [[1, 3, 5], [1, 3, 5]], read as "1 3 5 1 3 5"); false for an
|
||||
* array holding an object or a null. */
|
||||
static bool join_scalars(const nlohmann::json& v, std::string* s) {
|
||||
for (const auto& e : v) {
|
||||
if (e.is_array()) {
|
||||
if (!join_scalars(e, s)) return false;
|
||||
continue;
|
||||
}
|
||||
if (!s->empty()) *s += ' ';
|
||||
if (e.is_number_integer()) *s += fmt("%lld", (long long)e.get<int64_t>());
|
||||
else if (e.is_number()) *s += fmt("%.17g", e.get<double>());
|
||||
else if (e.is_string()) *s += e.get<std::string>();
|
||||
else if (e.is_boolean()) *s += e.get<bool>() ? "1" : "0";
|
||||
else return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static void flatten_json(const nlohmann::json& j, const std::string& prefix, MetaOwn* out) {
|
||||
for (auto it = j.begin(); it != j.end(); ++it) {
|
||||
const std::string key = prefix.empty() ? it.key() : prefix + "." + it.key();
|
||||
@@ -74,19 +93,10 @@ static void flatten_json(const nlohmann::json& j, const std::string& prefix, Met
|
||||
else if (v.is_string()) out->kv(key, v.get<std::string>());
|
||||
else if (v.is_array()) {
|
||||
/* An array of scalars becomes a space-separated string (mrope_section "11 11 10",
|
||||
* layer_types "linear_attention full_attention ..."). Arrays of objects are
|
||||
* skipped. */
|
||||
* layer_types "linear_attention full_attention ..."), nested arrays row-major.
|
||||
* Arrays of objects are skipped. */
|
||||
std::string s;
|
||||
bool ok = true;
|
||||
for (const auto& e : v) {
|
||||
if (!s.empty()) s += ' ';
|
||||
if (e.is_number_integer()) s += fmt("%lld", (long long)e.get<int64_t>());
|
||||
else if (e.is_number()) s += fmt("%.17g", e.get<double>());
|
||||
else if (e.is_string()) s += e.get<std::string>();
|
||||
else if (e.is_boolean()) s += e.get<bool>() ? "1" : "0";
|
||||
else { ok = false; break; }
|
||||
}
|
||||
if (ok) out->kv(key, s);
|
||||
if (join_scalars(v, &s)) out->kv(key, s);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -590,7 +600,9 @@ int Checkpoint::open_diffusers() {
|
||||
RAD_TRY(meta_merge_json_file(dir_ + "/" + sc + "/scheduler_config.json", sc, true,
|
||||
&meta_));
|
||||
}
|
||||
for (const char* sub : { "processor", "tokenizer" }) {
|
||||
/* The tokenizer's own folder, or the text encoder's when the release keeps it there (FLUX.3
|
||||
* [klein]'s modular pipeline points its tokenizer at text_encoder/). */
|
||||
for (const char* sub : { "processor", "tokenizer", "text_encoder" }) {
|
||||
const std::string d = dir_ + "/" + sub;
|
||||
if (!path_exists(d + "/tokenizer.json")) continue;
|
||||
tok_dir_ = d;
|
||||
@@ -1552,9 +1564,9 @@ static int resolve_wnorm(Checkpoint& ck, const RadNameMap& m, bool optional, Ckp
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* RAD_MAP_TRANSPOSE (src[0] [.., a, b] read as [.., b, a]) and RAD_MAP_EMA (src[0] the embedding
|
||||
* sums [bins, ...], src[1] the cluster usage [bins]; each row over max(usage, 1e-5)), computed in
|
||||
* f32 into `derived`. */
|
||||
/* RAD_MAP_TRANSPOSE (src[0] [.., a, b] read as [.., b, a]), RAD_MAP_EMA (src[0] the embedding
|
||||
* sums [bins, ...], src[1] the cluster usage [bins]; each row over max(usage, 1e-5)) and
|
||||
* RAD_MAP_TAP (one index of one dimension of src[0]), computed in f32 into `derived`. */
|
||||
static int resolve_derived(Checkpoint& ck, const std::vector<const RadNameMap*>& maps,
|
||||
bool optional, CkptWeight* out, std::string* why) {
|
||||
auto refuse = [&](int rc, std::string msg) {
|
||||
@@ -1618,7 +1630,30 @@ static int resolve_derived(Checkpoint& ck, const std::vector<const RadNameMap*>&
|
||||
return refuse(RAD_E_FORMAT, "'" + a->name + "' cannot be read as f32");
|
||||
out->rank = (uint32_t)rank;
|
||||
for (size_t i = 0; i < rank; ++i) out->shape[i] = a->shape[i];
|
||||
if (ema) {
|
||||
if (m.mode == RAD_MAP_TAP) {
|
||||
const int d = m.concat_dim;
|
||||
if (d < 0 || (size_t)d >= rank || rank < 3)
|
||||
return refuse(RAD_E_SHAPE, "'" + a->name + "' has rank " + std::to_string(rank) +
|
||||
"; a tap of dimension " + std::to_string(d) +
|
||||
" leaves no matrix");
|
||||
const int64_t k = a->shape[(size_t)d];
|
||||
const int64_t t = m.src_index[0] < 0 ? k + m.src_index[0] : m.src_index[0];
|
||||
if (t < 0 || t >= k)
|
||||
return refuse(RAD_E_SHAPE, "tap " + std::to_string(m.src_index[0]) + " of '" +
|
||||
a->name + "' dimension " + std::to_string(d) + " of " +
|
||||
std::to_string(k));
|
||||
int64_t outer = 1, inner = 1;
|
||||
for (int i = 0; i < d; ++i) outer *= a->shape[(size_t)i];
|
||||
for (size_t i = (size_t)d + 1; i < rank; ++i) inner *= a->shape[i];
|
||||
out->derived.resize((size_t)(outer * inner));
|
||||
for (int64_t o = 0; o < outer; ++o)
|
||||
std::memcpy(&out->derived[(size_t)(o * inner)], &src[(size_t)((o * k + t) * inner)],
|
||||
(size_t)inner * sizeof(float));
|
||||
out->rank = (uint32_t)(rank - 1);
|
||||
for (size_t i = (size_t)d; i + 1 < rank; ++i) out->shape[i] = a->shape[i + 1];
|
||||
out->why = "it is tap " + std::to_string(t) + " of '" + a->name + "' dimension " +
|
||||
std::to_string(d) + ", at convert -- a recipe rule stores it";
|
||||
} else if (ema) {
|
||||
const int64_t bins = a->shape[0], per = n / bins;
|
||||
int64_t un = 1;
|
||||
for (int64_t x : u->shape) un *= x;
|
||||
@@ -1673,7 +1708,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
if (maps.empty()) return refuse(RAD_E_NOTFOUND, "the name map has no entry for it");
|
||||
if (maps.front()->mode == RAD_MAP_WNORM)
|
||||
return resolve_wnorm(ck, *maps.front(), optional, out, why);
|
||||
if (maps.front()->mode == RAD_MAP_TRANSPOSE || maps.front()->mode == RAD_MAP_EMA)
|
||||
if (maps.front()->mode == RAD_MAP_TRANSPOSE || maps.front()->mode == RAD_MAP_EMA ||
|
||||
maps.front()->mode == RAD_MAP_TAP)
|
||||
return resolve_derived(ck, maps, optional, out, why);
|
||||
struct Src1 { const char* name; int index; int64_t rows; };
|
||||
std::vector<Src1> srcs;
|
||||
|
||||
+229
-52
@@ -24,6 +24,7 @@ int64_t ref_tokens_max(const RadGeneratorDecl& d) {
|
||||
|
||||
struct Sizes {
|
||||
int64_t T = 0, S = 0, EP = 0, PD = 0, R = 0, P = 0, PX = 0, NT = 0, NB = 0;
|
||||
bool joint = false;
|
||||
};
|
||||
|
||||
Sizes sizes_of(const Program& prog, int64_t block_size) {
|
||||
@@ -34,7 +35,10 @@ Sizes sizes_of(const Program& prog, int64_t block_size) {
|
||||
z.EP = prog.encoder.modalities ? prog.ctx.max_enc_patches : 0;
|
||||
z.PD = prog.encoder.modalities ? prog.encoder.patch_dim : 0;
|
||||
z.R = d.max_refs;
|
||||
z.P = z.T + z.R * ref_tokens_max(d);
|
||||
z.joint = d.layout == RAD_GEN_LAYOUT_JOINT_STEP;
|
||||
/* The longest conditioning: in the joint layout, the declared bound (its rows ride in the
|
||||
* step, which the step size bounds anyway). */
|
||||
z.P = z.joint ? std::min(d.cond_rows, z.T) : z.T + z.R * ref_tokens_max(d);
|
||||
const int64_t s2 = d.latent_scale * d.latent_scale;
|
||||
z.PX = z.R * (ref_tokens_max(d) * s2) + d.max_tokens * s2;
|
||||
z.NT = d.max_tokens;
|
||||
@@ -47,6 +51,7 @@ Sizes sizes_of(const Program& prog, int64_t block_size) {
|
||||
int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
|
||||
const int64_t I = 4, H = 2;
|
||||
const int64_t rope_rows = std::max(z.P, z.T);
|
||||
const int64_t J = z.joint ? 1 : 0; /* the joint layout's regions, empty otherwise */
|
||||
const int64_t want[][2] = {
|
||||
{ 0, z.T * I }, /* R_TOK */
|
||||
{ 0, z.T * I }, /* R_POS */
|
||||
@@ -56,7 +61,7 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
|
||||
{ 0, z.EP * z.PD * H }, /* R_ENCPIX */
|
||||
{ 0, 4 * z.EP * I }, /* R_ENCCRD */
|
||||
{ 0, (z.R + 2) * I }, /* R_ENCCU */
|
||||
{ 0, z.P * I }, /* R_SRC */
|
||||
{ 0, rope_rows * I }, /* R_SRC: a COND's rows, or a joint DENOISE's */
|
||||
{ 0, 3 * rope_rows * I }, /* R_GROPE */
|
||||
{ 0, (12 * z.R + 24) * I }, /* R_SEG: offsets; per segment a {0, length} pair and a start; per picture a {0, tokens} pair */
|
||||
{ 0, z.P * I }, /* R_SLOT */
|
||||
@@ -71,6 +76,15 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
|
||||
{ 0, 2 * z.S * 4 }, /* R_SEED */
|
||||
{ 0, z.S * z.NB * I }, /* R_BT */
|
||||
{ 0, z.S * I }, /* R_USED */
|
||||
{ 0, J * 4 * rope_rows * 4 }, /* R_ROPEF */
|
||||
{ 0, J * (z.S + 1) * I }, /* R_ICU */
|
||||
{ 0, J * z.T * I }, /* R_IROWS */
|
||||
{ 0, J * (3 * z.S + 1) * I }, /* R_MCU */
|
||||
{ 0, J * 2 * I }, /* R_VCU */
|
||||
{ 0, J * z.T * I }, /* R_MROWS */
|
||||
{ 0, J * z.T * I }, /* R_MSRC */
|
||||
{ 0, J * 3 * (z.S + 1) * I }, /* R_MCCU */
|
||||
{ 0, J * 4 * z.T * 4 }, /* R_MROPE */
|
||||
};
|
||||
int64_t off = 0;
|
||||
for (int r = 0; r < n; ++r) {
|
||||
@@ -84,8 +98,10 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
|
||||
} /* namespace */
|
||||
|
||||
int64_t Driver::device_bytes(const Program& prog) {
|
||||
if (!prog.is_generator() || prog.kv_groups.size() < 2) return 0;
|
||||
const Sizes z = sizes_of(prog, prog.kv_groups[1].block_size);
|
||||
if (!prog.is_generator()) return 0;
|
||||
const bool joint = prog.generator.layout == RAD_GEN_LAYOUT_JOINT_STEP;
|
||||
if (!joint && prog.kv_groups.size() < 2) return 0;
|
||||
const Sizes z = sizes_of(prog, joint ? 0 : prog.kv_groups[1].block_size);
|
||||
int64_t b[R_N][2];
|
||||
return carve(z, prog.generator.pixel_channels, b, R_N);
|
||||
}
|
||||
@@ -97,16 +113,26 @@ int Driver::init(const Program& prog, IKVManager* kv, const std::vector<RankIO>&
|
||||
fixed_ = prog.gen_str.sigmas;
|
||||
kv_ = kv;
|
||||
ranks_ = ranks;
|
||||
/* Exactly one paged full-attention KV group, holding the conditioning. Group handles start at
|
||||
* 1 (group 0 is the null handle); the KV manager and a batch both index by handle. */
|
||||
if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL ||
|
||||
prog.kv_groups[1].block_size <= 0) {
|
||||
/* Exactly one paged full-attention KV group, holding the conditioning; none in the joint
|
||||
* layout, where the conditioning rides in the steps. Group handles start at 1 (group 0 is the
|
||||
* null handle); the KV manager and a batch both index by handle. */
|
||||
if (joint()) {
|
||||
if (prog.kv_groups.size() > 1) {
|
||||
RAD_ERR("image generator: the joint layout keeps its conditioning in the plugin's "
|
||||
"state, and the program declares %zu KV group(s)", prog.kv_groups.size() - 1);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
kv_group_ = 0;
|
||||
block_size_ = 0;
|
||||
} else if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL ||
|
||||
prog.kv_groups[1].block_size <= 0) {
|
||||
RAD_ERR("image generator: the program declares %zu KV group(s); the driver stages exactly "
|
||||
"one full-attention group, the conditioning's", prog.kv_groups.size() - 1);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
} else {
|
||||
kv_group_ = 1;
|
||||
block_size_ = prog.kv_groups[1].block_size;
|
||||
}
|
||||
kv_group_ = 1;
|
||||
block_size_ = prog.kv_groups[1].block_size;
|
||||
const Sizes z = sizes_of(prog, block_size_);
|
||||
max_tok_ = z.T;
|
||||
max_seqs_ = z.S;
|
||||
@@ -181,9 +207,9 @@ int Driver::submit(std::unique_ptr<Request> r, std::string* why) {
|
||||
" latent tokens (" + std::to_string(d.max_tokens * d.latent_scale * d.latent_scale) +
|
||||
" pixels)");
|
||||
if (tokens * nb > max_tok_)
|
||||
return no("an image of this size with guidance needs " + std::to_string(tokens * nb) +
|
||||
" rows a step and a step carries " + std::to_string(max_tok_) +
|
||||
" (--max-num-batched-tokens)");
|
||||
return no("an image of this size" + std::string(nb > 1 ? " with guidance" : "") +
|
||||
" needs " + std::to_string(tokens * nb) + " rows a step and a step carries " +
|
||||
std::to_string(max_tok_) + " (--max-num-batched-tokens)");
|
||||
if (r->n < 1 || r->n > d.max_lanes)
|
||||
return no("n must be 1.." + std::to_string(d.max_lanes));
|
||||
if ((int64_t)r->refs.size() > d.max_refs)
|
||||
@@ -293,22 +319,36 @@ int Driver::admit_locked() {
|
||||
for (const Pixels& p : r.refs)
|
||||
j.ref_hw.push_back({ (int32_t)(p.h / decl_.latent_scale),
|
||||
(int32_t)(p.w / decl_.latent_scale) });
|
||||
int64_t step_rows = 0;
|
||||
for (int b = 0; b < j.n_branch; ++b) {
|
||||
std::string why;
|
||||
const int s = build_layout(b ? r.neg : r.pos, decl_.slot_rows, j.ref_hw,
|
||||
&j.cond[b].lay, &why);
|
||||
const int s = joint()
|
||||
? build_joint_layout(b ? r.neg : r.pos, decl_.pad_multiple,
|
||||
decl_.rope_hw_scale, decl_.rope_text_l != 0, j.ref_hw,
|
||||
&j.cond[b].lay, &why)
|
||||
: build_layout(b ? r.neg : r.pos, decl_.slot_rows, j.ref_hw, &j.cond[b].lay,
|
||||
&why);
|
||||
if (s < 0) { fail_locked(j, s, why); break; }
|
||||
if (j.cond[b].lay.rows > max_rows_) {
|
||||
fail_locked(j, RAD_E_INVAL, "the conditioning is " +
|
||||
std::to_string(j.cond[b].lay.rows) + " rows; the driver stages " +
|
||||
std::to_string(j.cond[b].lay.rows) + " rows (the prompt" +
|
||||
std::string(r.refs.empty() ? "" : " and its pictures") +
|
||||
"); this model conditions on at most " +
|
||||
std::to_string(max_rows_));
|
||||
break;
|
||||
}
|
||||
step_rows += entry_rows(j, b);
|
||||
}
|
||||
if (j.failed) continue;
|
||||
if (step_rows > max_tok_) {
|
||||
fail_locked(j, RAD_E_INVAL, "an image with its conditioning needs " +
|
||||
std::to_string(step_rows) + " rows a step and a step carries " +
|
||||
std::to_string(max_tok_) + " (--max-num-batched-tokens)");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
bool ok = true;
|
||||
for (int b = 0; b < j.n_branch && ok; ++b) {
|
||||
for (int b = 0; b < j.n_branch && ok && !joint(); ++b) {
|
||||
Cond& c = j.cond[b];
|
||||
if (c.have_kv) continue;
|
||||
if (!kv_->can_ever_fit(c.lay.rows)) {
|
||||
@@ -337,8 +377,14 @@ int Driver::admit_locked() {
|
||||
const int32_t n_steps = (int32_t)j.sigmas.size() - 1;
|
||||
for (int b = 0; b < j.n_branch; ++b) {
|
||||
Cond& c = j.cond[b];
|
||||
c.rope_img.assign((size_t)(3 * j.tokens), 0);
|
||||
image_rope(c.lay.next_pos, j.h_lat, j.w_lat, c.rope_img.data(), j.tokens);
|
||||
if (joint()) {
|
||||
c.rope_img_f.assign((size_t)(4 * j.tokens), 0.0f);
|
||||
grid_rope_f(decl_.rope_hw_scale, 0.0f, j.h_lat, j.w_lat, c.rope_img_f.data(),
|
||||
j.tokens);
|
||||
} else {
|
||||
c.rope_img.assign((size_t)(3 * j.tokens), 0);
|
||||
image_rope(c.lay.next_pos, j.h_lat, j.w_lat, c.rope_img.data(), j.tokens);
|
||||
}
|
||||
}
|
||||
for (int32_t i = 0; i < r.n; ++i) {
|
||||
const int32_t l = free_lanes_.back();
|
||||
@@ -413,8 +459,8 @@ void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int ste
|
||||
K.seqused = dptr<int32_t>(ri, R_USED);
|
||||
K.block_size = block_size_;
|
||||
K.max_blocks = max_blocks_;
|
||||
B.n_kv_groups = 1;
|
||||
B.kv = &K;
|
||||
B.n_kv_groups = joint() ? 0 : 1;
|
||||
B.kv = joint() ? nullptr : &K;
|
||||
B.gen_b = &G;
|
||||
G.src = dptr<int32_t>(ri, R_SRC);
|
||||
G.rope = dptr<int32_t>(ri, R_GROPE);
|
||||
@@ -431,6 +477,20 @@ void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int ste
|
||||
G.lane_dh = hptr<int32_t>(R_LANE);
|
||||
G.flags = dptr<int32_t>(ri, R_FLAGS);
|
||||
G.seed = dptr<uint32_t>(ri, R_SEED);
|
||||
/* The joint layout's fields, which only the passes that use them set. */
|
||||
G.branch = 0;
|
||||
G.n_pad = 0;
|
||||
G.valid_cu = nullptr;
|
||||
G.n_img = 0;
|
||||
G.img_cu = nullptr;
|
||||
G.img_rows = nullptr;
|
||||
G.mode_cu = nullptr;
|
||||
G.rope_f = nullptr;
|
||||
G.mode_rows = nullptr;
|
||||
G.mode_src = nullptr;
|
||||
G.mode_ccu = nullptr;
|
||||
G.n_mode_h = nullptr;
|
||||
G.mode_rope_f = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,7 +542,8 @@ const RadBatch* Driver::next(int step) {
|
||||
for (int32_t l : j.lanes) {
|
||||
const Lane& ln = lanes_[(size_t)l];
|
||||
if (ln.finished || ln.final_due || ln.preview_due || ln.step >= n_steps) continue;
|
||||
const int64_t need = j.tokens * j.n_branch;
|
||||
int64_t need = 0;
|
||||
for (int b = 0; b < j.n_branch; ++b) need += entry_rows(j, b);
|
||||
if (rows + need > max_tok_ || entries + j.n_branch > max_seqs_) break;
|
||||
rows += need;
|
||||
entries += j.n_branch;
|
||||
@@ -503,15 +564,19 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
|
||||
const Request& r = *j.req;
|
||||
const Branch& br = branch ? r.neg : r.pos;
|
||||
const Cond& c = j.cond[branch];
|
||||
const int64_t T = (int64_t)br.tokens.size(), P = c.lay.rows;
|
||||
/* The joint layout's padding tokens follow the prompt's; each sits at position 1 and sees
|
||||
* only the prompt (`valid_cu`), as a masked padding token does in the reference. */
|
||||
const int64_t T_valid = (int64_t)br.tokens.size();
|
||||
const int64_t T = T_valid + (joint() ? c.lay.n_pad : 0), P = c.lay.rows;
|
||||
|
||||
int32_t* tok = hptr<int32_t>(R_TOK);
|
||||
int32_t* pos = hptr<int32_t>(R_POS);
|
||||
int32_t* rope = hptr<int32_t>(R_ROPE);
|
||||
std::memcpy(tok, br.tokens.data(), (size_t)T * 4);
|
||||
for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)i;
|
||||
std::memcpy(tok, br.tokens.data(), (size_t)T_valid * 4);
|
||||
for (int64_t i = T_valid; i < T; ++i) tok[i] = decl_.pad_token;
|
||||
for (int64_t i = 0; i < T; ++i) pos[i] = i < T_valid ? (int32_t)i : 1;
|
||||
for (int64_t i = 0; i < T; ++i) {
|
||||
int32_t p3[3] = { (int32_t)i, (int32_t)i, (int32_t)i };
|
||||
int32_t p3[3] = { pos[i], pos[i], pos[i] };
|
||||
if (br.media) br.media->rope.at(i, p3);
|
||||
rope[i] = p3[0];
|
||||
rope[T + i] = p3[1];
|
||||
@@ -571,7 +636,8 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
|
||||
std::memcpy(segp, c.lay.seg.data(), (size_t)(nsg + 1) * 4);
|
||||
for (int64_t s = 0; s < nsg; ++s) {
|
||||
const int32_t a = c.lay.seg[(size_t)s], len = c.lay.seg[(size_t)s + 1] - a;
|
||||
for (int cc = 0; cc < 3; ++cc)
|
||||
/* The joint layout's positions are f32, staged whole below. */
|
||||
for (int cc = 0; cc < 3 && !joint(); ++cc)
|
||||
std::memcpy(grope + 3 * (int64_t)a + cc * (int64_t)len,
|
||||
&c.lay.rope[(size_t)(cc * P + a)], (size_t)len * 4);
|
||||
segp[nsg + 1 + 2 * s] = 0;
|
||||
@@ -579,21 +645,31 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
|
||||
segp[nsg + 1 + 2 * nsg + s] = a;
|
||||
}
|
||||
reg_[R_SRC].used = P * 4;
|
||||
reg_[R_GROPE].used = 3 * P * 4;
|
||||
reg_[R_GROPE].used = joint() ? 0 : 3 * P * 4;
|
||||
reg_[R_SEG].used = (4 * nsg + 1) * 4;
|
||||
const std::vector<int32_t>& bt = kv_->block_table(c.seq, kv_group_);
|
||||
int32_t* slot = hptr<int32_t>(R_SLOT);
|
||||
for (int64_t p = 0; p < P; ++p) {
|
||||
const int64_t bi = p / block_size_;
|
||||
slot[p] = bi < (int64_t)bt.size() ? (int32_t)(bt[(size_t)bi] * block_size_ + p % block_size_)
|
||||
: -1;
|
||||
static const std::vector<int32_t> no_bt;
|
||||
const std::vector<int32_t>& bt = joint() ? no_bt : kv_->block_table(c.seq, kv_group_);
|
||||
if (joint()) {
|
||||
std::memcpy(hptr<float>(R_ROPEF), c.lay.rope_f.data(), (size_t)(4 * P) * 4);
|
||||
reg_[R_ROPEF].used = 4 * P * 4;
|
||||
int32_t* vcu = hptr<int32_t>(R_VCU);
|
||||
vcu[0] = 0;
|
||||
vcu[1] = (int32_t)T_valid;
|
||||
reg_[R_VCU].used = 2 * 4;
|
||||
} else {
|
||||
int32_t* slot = hptr<int32_t>(R_SLOT);
|
||||
for (int64_t p = 0; p < P; ++p) {
|
||||
const int64_t bi = p / block_size_;
|
||||
slot[p] = bi < (int64_t)bt.size()
|
||||
? (int32_t)(bt[(size_t)bi] * block_size_ + p % block_size_) : -1;
|
||||
}
|
||||
reg_[R_SLOT].used = P * 4;
|
||||
int32_t* btab = hptr<int32_t>(R_BT);
|
||||
for (size_t i = 0; i < bt.size(); ++i) btab[i] = bt[i];
|
||||
reg_[R_BT].used = (int64_t)bt.size() * 4;
|
||||
hptr<int32_t>(R_USED)[0] = (int32_t)P;
|
||||
reg_[R_USED].used = 4;
|
||||
}
|
||||
reg_[R_SLOT].used = P * 4;
|
||||
int32_t* btab = hptr<int32_t>(R_BT);
|
||||
for (size_t i = 0; i < bt.size(); ++i) btab[i] = bt[i];
|
||||
reg_[R_BT].used = (int64_t)bt.size() * 4;
|
||||
hptr<int32_t>(R_USED)[0] = (int32_t)P;
|
||||
reg_[R_USED].used = 4;
|
||||
|
||||
/* Pictures again for the generator's own encoder, plus the inpainting source when masked.
|
||||
* Only the positive conditioning's pass writes the lanes. */
|
||||
@@ -632,7 +708,8 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
|
||||
* for the life of the pass. */
|
||||
host_bidi_ = c.lay.bidi;
|
||||
host_px_ = pxh;
|
||||
host_lanes_ = inp ? j.lanes : std::vector<int32_t>{};
|
||||
/* The joint layout's conditioning goes to every lane of the request. */
|
||||
host_lanes_ = inp || joint() ? j.lanes : std::vector<int32_t>{};
|
||||
/* The lanes on the device too: an op copies the inpainting latent and mask into each. */
|
||||
if (!host_lanes_.empty()) {
|
||||
std::memcpy(hptr<int32_t>(R_LANE), host_lanes_.data(), host_lanes_.size() * 4);
|
||||
@@ -681,6 +758,16 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
|
||||
G.n_lane = (int64_t)host_lanes_.size();
|
||||
G.lane_h = host_lanes_.data();
|
||||
G.lane = G.n_lane ? dptr<int32_t>(ri, R_LANE) : nullptr;
|
||||
if (joint()) {
|
||||
B.n_kv_groups = 0;
|
||||
B.kv = nullptr;
|
||||
G.slot_mapping = nullptr;
|
||||
G.branch = branch;
|
||||
G.n_pad = c.lay.n_pad;
|
||||
G.valid_cu = dptr<int32_t>(ri, R_VCU);
|
||||
G.rope = nullptr;
|
||||
G.rope_f = dptr<float>(ri, R_ROPEF);
|
||||
}
|
||||
}
|
||||
pass_.kind = RAD_GEN_PASS_COND;
|
||||
pass_.job = j.id;
|
||||
@@ -699,15 +786,28 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
|
||||
for (int b = 0; b < j->n_branch; ++b) es.push_back({ j, l, b });
|
||||
}
|
||||
const int64_t S = (int64_t)es.size();
|
||||
int64_t n_tok = 0;
|
||||
int64_t n_tok = 0, n_img = 0;
|
||||
int32_t max_q = 0, max_ctx = 0;
|
||||
int64_t pitch = 1;
|
||||
for (const E& e : es) {
|
||||
n_tok += e.j->tokens;
|
||||
max_q = std::max<int32_t>(max_q, (int32_t)e.j->tokens);
|
||||
const int64_t rows = entry_rows(*e.j, e.branch);
|
||||
n_tok += rows;
|
||||
n_img += e.j->tokens;
|
||||
max_q = std::max<int32_t>(max_q, (int32_t)rows);
|
||||
max_ctx = std::max<int32_t>(max_ctx, (int32_t)e.j->cond[e.branch].lay.rows);
|
||||
pitch = std::max<int64_t>(pitch, (int64_t)kv_->block_table(e.j->cond[e.branch].seq, kv_group_).size());
|
||||
if (!joint())
|
||||
pitch = std::max<int64_t>(pitch, (int64_t)kv_->block_table(e.j->cond[e.branch].seq,
|
||||
kv_group_).size());
|
||||
}
|
||||
/* The joint layout's per-row arrays: each row's source, the compact image order's bounds and
|
||||
* rows, each entry's three modes, and the f32 positions. */
|
||||
int32_t* src = hptr<int32_t>(R_SRC);
|
||||
int32_t* icu = hptr<int32_t>(R_ICU);
|
||||
int32_t* irows = hptr<int32_t>(R_IROWS);
|
||||
int32_t* mcu = hptr<int32_t>(R_MCU);
|
||||
float* ropef = hptr<float>(R_ROPEF);
|
||||
int64_t img = 0;
|
||||
if (joint()) icu[0] = 0;
|
||||
int32_t* cu = hptr<int32_t>(R_CU);
|
||||
int32_t* pos = hptr<int32_t>(R_POS);
|
||||
int32_t* tok = hptr<int32_t>(R_TOK);
|
||||
@@ -731,9 +831,37 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
|
||||
const Lane& ln = lanes_[(size_t)e.lane];
|
||||
const Cond& c = j.cond[e.branch];
|
||||
const int64_t N = j.tokens;
|
||||
for (int64_t k = 0; k < N; ++k) { pos[row + k] = (int32_t)k; tok[row + k] = 0; }
|
||||
for (int cc = 0; cc < 3; ++cc)
|
||||
std::memcpy(grope + cc * n_tok + row, c.rope_img.data() + cc * N, (size_t)N * 4);
|
||||
if (joint()) {
|
||||
/* [conditioning | image]: the conditioning's rows from the plugin's copy at this lane
|
||||
* and branch, the image's from the compact order. */
|
||||
const int64_t P = c.lay.rows;
|
||||
const int64_t base = (2 * (int64_t)e.lane + e.branch) * decl_.cond_rows;
|
||||
for (int64_t k = 0; k < P; ++k) {
|
||||
src[row + k] = (int32_t)(base + k);
|
||||
pos[row + k] = (int32_t)k;
|
||||
tok[row + k] = 0;
|
||||
}
|
||||
for (int cc = 0; cc < 4; ++cc)
|
||||
std::memcpy(ropef + cc * n_tok + row, c.lay.rope_f.data() + cc * P, (size_t)P * 4);
|
||||
mcu[3 * i] = (int32_t)row;
|
||||
mcu[3 * i + 1] = (int32_t)(row + c.lay.text);
|
||||
mcu[3 * i + 2] = (int32_t)(row + P);
|
||||
row += P;
|
||||
for (int64_t k = 0; k < N; ++k) {
|
||||
src[row + k] = (int32_t)(-(1 + img + k));
|
||||
irows[img + k] = (int32_t)(row + k);
|
||||
pos[row + k] = (int32_t)k;
|
||||
tok[row + k] = 0;
|
||||
}
|
||||
for (int cc = 0; cc < 4; ++cc)
|
||||
std::memcpy(ropef + cc * n_tok + row, c.rope_img_f.data() + cc * N, (size_t)N * 4);
|
||||
img += N;
|
||||
icu[i + 1] = (int32_t)img;
|
||||
} else {
|
||||
for (int64_t k = 0; k < N; ++k) { pos[row + k] = (int32_t)k; tok[row + k] = 0; }
|
||||
for (int cc = 0; cc < 3; ++cc)
|
||||
std::memcpy(grope + cc * n_tok + row, c.rope_img.data() + cc * N, (size_t)N * 4);
|
||||
}
|
||||
row += N;
|
||||
cu[i + 1] = (int32_t)row;
|
||||
sig[i] = j.sigmas[(size_t)ln.step];
|
||||
@@ -758,6 +886,7 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
|
||||
flags[i] = f;
|
||||
seed[2 * i] = (uint32_t)(ln.seed & 0xffffffffu);
|
||||
seed[2 * i + 1] = (uint32_t)(ln.seed >> 32);
|
||||
if (joint()) continue;
|
||||
const std::vector<int32_t>& bt = kv_->block_table(c.seq, kv_group_);
|
||||
for (int64_t b = 0; b < pitch; ++b)
|
||||
btab[i * pitch + b] = b < (int64_t)bt.size() ? bt[(size_t)b] : -1;
|
||||
@@ -765,12 +894,46 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
|
||||
}
|
||||
reg_[R_CU].used = (S + 1) * 4;
|
||||
reg_[R_POS].used = reg_[R_TOK].used = n_tok * 4;
|
||||
reg_[R_GROPE].used = 3 * n_tok * 4;
|
||||
if (joint()) {
|
||||
mcu[3 * S] = (int32_t)n_tok;
|
||||
/* The mode-major order: every entry's text, then pictures, then image. */
|
||||
int32_t* mrows = hptr<int32_t>(R_MROWS);
|
||||
int32_t* msrc = hptr<int32_t>(R_MSRC);
|
||||
int32_t* mccu = hptr<int32_t>(R_MCCU);
|
||||
float* mrope = hptr<float>(R_MROPE);
|
||||
int64_t k = 0;
|
||||
for (int mode = 0; mode < 3; ++mode) {
|
||||
const int64_t k0 = k;
|
||||
int64_t nm = 0;
|
||||
for (int64_t i = 0; i < S; ++i) nm += mcu[3 * i + mode + 1] - mcu[3 * i + mode];
|
||||
for (int64_t i = 0; i < S; ++i) {
|
||||
mccu[mode * (S + 1) + i] = (int32_t)(k - k0);
|
||||
for (int32_t r = mcu[3 * i + mode]; r < mcu[3 * i + mode + 1]; ++r, ++k) {
|
||||
mrows[k] = r;
|
||||
msrc[k] = src[r];
|
||||
for (int cc = 0; cc < 4; ++cc)
|
||||
mrope[4 * k0 + cc * nm + (k - k0)] = ropef[cc * n_tok + r];
|
||||
}
|
||||
}
|
||||
mccu[mode * (S + 1) + S] = (int32_t)(k - k0);
|
||||
host_nmode_[mode] = k - k0;
|
||||
}
|
||||
reg_[R_MROWS].used = reg_[R_MSRC].used = n_tok * 4;
|
||||
reg_[R_MCCU].used = 3 * (S + 1) * 4;
|
||||
reg_[R_MROPE].used = 4 * n_tok * 4;
|
||||
reg_[R_SRC].used = n_tok * 4;
|
||||
reg_[R_IROWS].used = n_img * 4;
|
||||
reg_[R_ICU].used = (S + 1) * 4;
|
||||
reg_[R_MCU].used = (3 * S + 1) * 4;
|
||||
reg_[R_ROPEF].used = 4 * n_tok * 4;
|
||||
} else {
|
||||
reg_[R_GROPE].used = 3 * n_tok * 4;
|
||||
}
|
||||
reg_[R_SIG].used = reg_[R_SIGN].used = reg_[R_CFG].used = S * 4;
|
||||
reg_[R_PAIR].used = reg_[R_LANE].used = reg_[R_FLAGS].used = S * 4;
|
||||
reg_[R_SEED].used = 2 * S * 4;
|
||||
reg_[R_BT].used = S * pitch * 4;
|
||||
reg_[R_USED].used = S * 4;
|
||||
reg_[R_BT].used = joint() ? 0 : S * pitch * 4;
|
||||
reg_[R_USED].used = joint() ? 0 : S * 4;
|
||||
if (upload() < 0) return nullptr;
|
||||
finish_batches(n_tok, S, max_q, step);
|
||||
for (size_t rr = 0; rr < ranks_.size(); ++rr) {
|
||||
@@ -789,8 +952,22 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
|
||||
G.inpaint = 0;
|
||||
G.n_lane = 0;
|
||||
G.lane_h = nullptr;
|
||||
G.rope = dptr<int32_t>(ri, R_GROPE);
|
||||
G.rope = joint() ? nullptr : dptr<int32_t>(ri, R_GROPE);
|
||||
G.lane_dh = hptr<int32_t>(R_LANE);
|
||||
if (joint()) {
|
||||
G.src = dptr<int32_t>(ri, R_SRC);
|
||||
G.n_img = n_img;
|
||||
G.img_cu = dptr<int32_t>(ri, R_ICU);
|
||||
G.img_rows = dptr<int32_t>(ri, R_IROWS);
|
||||
G.mode_cu = dptr<int32_t>(ri, R_MCU);
|
||||
G.rope_f = dptr<float>(ri, R_ROPEF);
|
||||
G.slot_mapping = nullptr;
|
||||
G.mode_rows = dptr<int32_t>(ri, R_MROWS);
|
||||
G.mode_src = dptr<int32_t>(ri, R_MSRC);
|
||||
G.mode_ccu = dptr<int32_t>(ri, R_MCCU);
|
||||
G.n_mode_h = host_nmode_;
|
||||
G.mode_rope_f = dptr<float>(ri, R_MROPE);
|
||||
}
|
||||
}
|
||||
pass_.kind = RAD_GEN_PASS_DENOISE;
|
||||
return &out_[0];
|
||||
|
||||
+10
-1
@@ -75,6 +75,7 @@ private:
|
||||
bool have_kv = false;
|
||||
bool encoded = false;
|
||||
std::vector<int32_t> rope_img; /* [3, image tokens]: the image's rows at this sequence */
|
||||
std::vector<float> rope_img_f; /* JOINT_STEP: [4, image tokens] */
|
||||
};
|
||||
struct Job {
|
||||
uint64_t id = 0;
|
||||
@@ -117,7 +118,7 @@ private:
|
||||
struct Region { int64_t off = 0, bytes = 0, used = 0; };
|
||||
enum { R_TOK, R_POS, R_ROPE, R_CU, R_MMROW, R_ENCPIX, R_ENCCRD, R_ENCCU, R_SRC, R_GROPE,
|
||||
R_SEG, R_SLOT, R_PX, R_MASK, R_SIG, R_SIGN, R_CFG, R_PAIR, R_LANE, R_FLAGS, R_SEED,
|
||||
R_BT, R_USED, R_N };
|
||||
R_BT, R_USED, R_ROPEF, R_ICU, R_IROWS, R_MCU, R_VCU, R_MROWS, R_MSRC, R_MCCU, R_MROPE, R_N };
|
||||
|
||||
int layout_regions();
|
||||
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
|
||||
@@ -133,6 +134,13 @@ private:
|
||||
void fail_locked(Job& j, int status, const std::string& why);
|
||||
Job* job_locked(uint64_t id);
|
||||
|
||||
/* The JOINT_STEP layout: the conditioning rides in every denoising entry, and no KV. */
|
||||
bool joint() const { return decl_.layout == RAD_GEN_LAYOUT_JOINT_STEP; }
|
||||
/* An entry's rows in a denoising pass. */
|
||||
int64_t entry_rows(const Job& j, int branch) const {
|
||||
return j.tokens + (joint() ? j.cond[branch].lay.rows : 0);
|
||||
}
|
||||
|
||||
const RadBatch* build_cond(Job& j, int branch, int step);
|
||||
const RadBatch* build_denoise(const std::vector<int32_t>& lanes, int step);
|
||||
const RadBatch* build_decode(int32_t lane, bool preview, int step);
|
||||
@@ -162,6 +170,7 @@ private:
|
||||
Pass pass_;
|
||||
/* Host arrays a COND pass's plugin reads on the host (RadGenBatch's _h fields). */
|
||||
std::vector<int32_t> host_bidi_, host_px_, host_lanes_;
|
||||
int64_t host_nmode_[3] = { 0, 0, 0 };
|
||||
|
||||
mutable std::mutex mu_;
|
||||
std::deque<std::unique_ptr<Job>> jobs_; /* arrival order */
|
||||
|
||||
@@ -106,6 +106,67 @@ void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_to
|
||||
}
|
||||
}
|
||||
|
||||
void grid_rope_f(double hw_scale, float l, int32_t h, int32_t w, float* planes, int64_t n_total) {
|
||||
const float s = (float)hw_scale;
|
||||
int64_t k = 0;
|
||||
for (int32_t r = 0; r < h; ++r)
|
||||
for (int32_t c = 0; c < w; ++c, ++k) {
|
||||
planes[k] = 0.0f;
|
||||
planes[n_total + k] = s * (float)r;
|
||||
planes[2 * n_total + k] = s * (float)c;
|
||||
planes[3 * n_total + k] = l;
|
||||
}
|
||||
}
|
||||
|
||||
int build_joint_layout(const Branch& b, int32_t pad_multiple, double hw_scale, bool text_l,
|
||||
const std::vector<std::pair<int32_t, int32_t>>& ref_hw, Layout* out,
|
||||
std::string* why) {
|
||||
*out = Layout{};
|
||||
const int64_t T = (int64_t)b.tokens.size();
|
||||
if (b.n_drop < 0 || b.n_drop >= T) {
|
||||
if (why) *why = "the conditioning prompt is no longer than its fixed prefix";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (b.media) {
|
||||
if (why) *why = "the joint layout reads no pictures in the prompt";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t text = T - b.n_drop;
|
||||
const int64_t padded = pad_multiple > 0 ? (text + pad_multiple - 1) / pad_multiple * pad_multiple
|
||||
: text;
|
||||
int64_t refs = 0;
|
||||
for (const auto& hw : ref_hw) refs += (int64_t)hw.first * hw.second;
|
||||
const int64_t rows = padded + refs;
|
||||
out->rows = rows;
|
||||
out->text = padded;
|
||||
out->n_pad = (int32_t)(padded - text);
|
||||
out->src.resize((size_t)rows);
|
||||
out->rope_f.assign((size_t)(4 * rows), 0.0f);
|
||||
for (int64_t i = 0; i < padded; ++i) {
|
||||
out->src[(size_t)i] = (int32_t)(b.n_drop + i);
|
||||
if (text_l) out->rope_f[(size_t)(3 * rows + i)] = (float)i;
|
||||
}
|
||||
out->seg.push_back(0);
|
||||
out->bidi.push_back(0);
|
||||
int64_t row = padded, lat = 0;
|
||||
for (size_t k = 0; k < ref_hw.size(); ++k) {
|
||||
const int32_t h = ref_hw[k].first, w = ref_hw[k].second;
|
||||
const int64_t n = (int64_t)h * w;
|
||||
std::vector<float> pl((size_t)(4 * n));
|
||||
grid_rope_f(hw_scale, -(float)(1 + k), h, w, pl.data(), n);
|
||||
for (int cc = 0; cc < 4; ++cc)
|
||||
std::memcpy(&out->rope_f[(size_t)(cc * rows + row)], &pl[(size_t)(cc * n)],
|
||||
(size_t)n * sizeof(float));
|
||||
for (int64_t i = 0; i < n; ++i) out->src[(size_t)(row + i)] = (int32_t)(-(1 + lat + i));
|
||||
out->seg.push_back((int32_t)row);
|
||||
out->bidi.push_back(1);
|
||||
row += n;
|
||||
lat += n;
|
||||
}
|
||||
out->seg.push_back((int32_t)rows);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int build_layout(const Branch& b, int64_t slot_rows,
|
||||
const std::vector<std::pair<int32_t, int32_t>>& ref_hw, Layout* out,
|
||||
std::string* why) {
|
||||
|
||||
@@ -129,6 +129,11 @@ struct Layout {
|
||||
std::vector<int32_t> seg; /* [n_seg + 1] */
|
||||
std::vector<int32_t> bidi; /* [n_seg] */
|
||||
int32_t next_pos = 0; /* the rotary count after the last row: the image's frame */
|
||||
/* JOINT_STEP only: the text's rows (padding included), the padding rows among them, and the
|
||||
* f32 positions, [4, rows] component-major (`rope` is then empty). */
|
||||
int64_t text = 0;
|
||||
int32_t n_pad = 0;
|
||||
std::vector<float> rope_f;
|
||||
};
|
||||
/* `ref_hw` is each reference's latent grid (h, w), in media order. RAD_E_INVAL with `why` when the
|
||||
* prompt does not start with its drop prefix or a picture's slots do not tile its latent grid. */
|
||||
@@ -137,5 +142,16 @@ int build_layout(const Branch& b, int64_t slot_rows, const std::vector<std::pair
|
||||
/* The rotary positions of an h x w image at frame `pos`: [3, h * w] component-major. */
|
||||
void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_total);
|
||||
|
||||
/* A conditioning in the JOINT_STEP layout (RadGeneratorDecl): the prompt's rows after its drop
|
||||
* prefix, padding to a multiple of `pad_multiple` (0: none), then each reference picture's latent
|
||||
* tokens. `src` is the prompt row behind a text row -- a padding row's is past the prompt's last,
|
||||
* where the COND pass appends the padding tokens -- or -(1 + i) for reference latent row i. One
|
||||
* text segment (causal) and a segment per picture (bidirectional). */
|
||||
int build_joint_layout(const Branch& b, int32_t pad_multiple, double hw_scale, bool text_l,
|
||||
const std::vector<std::pair<int32_t, int32_t>>& ref_hw, Layout* out,
|
||||
std::string* why);
|
||||
/* The f32 positions (0, s h, s w, l) of an h x w grid: [4, h * w] component-major. */
|
||||
void grid_rope_f(double hw_scale, float l, int32_t h, int32_t w, float* planes, int64_t n_total);
|
||||
|
||||
} /* namespace gen */
|
||||
} /* namespace rad */
|
||||
+25
-7
@@ -10,6 +10,7 @@
|
||||
#include "rad_core.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <memory>
|
||||
@@ -22,12 +23,13 @@ namespace gen {
|
||||
|
||||
/* One thing a request has made. */
|
||||
struct VideoEvent {
|
||||
enum Kind { STEP = 1, AUDIO = 2, FRAMES = 3 };
|
||||
enum Kind { STEP = 1, AUDIO = 2, FRAMES = 3, LENGTH = 4 };
|
||||
int kind = 0;
|
||||
int32_t steps_done = 0; /* STEP: denoising steps finished */
|
||||
/* AUDIO: the whole soundtrack, interleaved, in [-1, 1]. */
|
||||
std::vector<float> samples;
|
||||
/* FRAMES: frames [first, first + n) of the video, each [height, width, 3] u8 RGB. */
|
||||
/* FRAMES: frames [first, first + n) of the video, each [height, width, 3] u8 RGB. LENGTH:
|
||||
* the `n` frames the model chose for a request that named no length, before any step. */
|
||||
int32_t first = 0, n = 0;
|
||||
std::vector<uint8_t> rgb;
|
||||
};
|
||||
@@ -49,7 +51,8 @@ public:
|
||||
std::atomic<bool> cancel{false};
|
||||
|
||||
/* What the request makes, written by the driver at submit: the frames and their size, the
|
||||
* steps, and the soundtrack's rate and channels. */
|
||||
* steps, and the soundtrack's rate and channels. A request whose length the model predicts
|
||||
* has its `frames`, `steps` and `rows` rewritten once, before its LENGTH event. */
|
||||
int32_t frames = 0, width = 0, height = 0, steps = 0;
|
||||
int64_t sample_rate = 0, channels = 0;
|
||||
double fps = 0.0;
|
||||
@@ -81,6 +84,17 @@ struct VideoRequest {
|
||||
double upscale = 0.0;
|
||||
int32_t refine = 0;
|
||||
uint64_t seed = 0;
|
||||
/* Guidance (RadVideoGenDecl::guidance): the eight terms, NaN for the model's default, and the
|
||||
* negative prompt, rendered and tokenised; `has_neg` false for the model's default. */
|
||||
double guidance[8] = { NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN };
|
||||
std::vector<int32_t> neg_tokens;
|
||||
bool has_neg = false;
|
||||
/* A first frame (RadVideoGenDecl::image_cond): [height, width, 3] u8 RGB at the size the
|
||||
* first evaluations run at (video_small_size under upscaling, else the video's), already
|
||||
* prepared as the model's pipeline prepares it; empty for none. */
|
||||
std::vector<uint8_t> image;
|
||||
/* The decoder (RadVideoGenDecl::decoders) by its index; 0 the model's default. */
|
||||
int32_t decoder = 0;
|
||||
std::shared_ptr<VideoTicket> ticket;
|
||||
};
|
||||
|
||||
@@ -98,14 +112,18 @@ VideoShape video_shape(const RadVideoGenDecl& d, int32_t width, int32_t height,
|
||||
void video_small_size(const RadVideoGenDecl& d, int32_t width, int32_t height, double factor,
|
||||
int32_t* small_w, int32_t* small_h);
|
||||
|
||||
/* The two schedules a request of `steps` grid points runs (RadVideoGenDecl, "The sampler"): each
|
||||
* the f32 sigmas, last 0, and the model evaluations it takes, the shorter of the two. With a
|
||||
* trained schedule any other step count than n_rungs + 1 gives no steps. */
|
||||
/* The two schedules a request of `steps` runs (RadVideoGenDecl, "The sampler": grid points under
|
||||
* form 0, evaluations under form 1): each the f32 sigmas, last 0, and the model evaluations it
|
||||
* takes, the shorter of the two. With a trained schedule any other step count than the declared
|
||||
* one gives no steps. `video_tokens` are the video's latent tokens, which form 1's dynamic shift
|
||||
* reads. With `refine` (form 1 and refinement rungs) the rungs are followed by the refinement
|
||||
* rungs instead of a 0, the evaluations their sum. */
|
||||
struct VideoSchedule {
|
||||
std::vector<float> sig_v, sig_a;
|
||||
int32_t steps = 0;
|
||||
};
|
||||
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps);
|
||||
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps, int64_t video_tokens = 0,
|
||||
bool refine = false);
|
||||
|
||||
} /* namespace gen */
|
||||
} /* namespace rad */
|
||||
+309
-86
@@ -2,6 +2,7 @@
|
||||
* waits on, and a request's shape and schedule (video.h). */
|
||||
#include "video_driver.h"
|
||||
#include "rad_internal.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
@@ -75,7 +76,7 @@ VideoShape video_shape(const RadVideoGenDecl& d, int32_t width, int32_t height,
|
||||
if (r2 > den || (r2 == den && (q & 1))) ++q;
|
||||
s.n_audio = (int32_t)q;
|
||||
s.video_rows = (int64_t)s.lat_frames * (s.lat_h / d.patch) * (s.lat_w / d.patch);
|
||||
s.audio_rows = d.audio_channels * (int64_t)s.n_audio;
|
||||
s.audio_rows = (d.audio_streams > 0 ? d.audio_streams : d.audio_channels) * (int64_t)s.n_audio;
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -120,8 +121,47 @@ static std::vector<float> rung_sigmas(double shift, const double* rungs, int32_t
|
||||
return s;
|
||||
}
|
||||
|
||||
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps) {
|
||||
/* Form 1 (RadVideoGenDecl::sched_kind): FlowMatchEulerDiscreteScheduler.set_timesteps with
|
||||
* LTX-2's sigmas. numpy's linspace in f64 (i * step + start, the last exactly the stop) taken to
|
||||
* f32; the shift and the terminal stretch in f32, as numpy computes on an f32 array with Python
|
||||
* scalars. */
|
||||
static std::vector<float> flow_sigmas(const RadVideoGenDecl& d, int32_t n, int64_t tokens) {
|
||||
std::vector<float> s((size_t)n);
|
||||
const double stop = 1.0 / n, step = n > 1 ? (stop - 1.0) / (n - 1) : 0.0;
|
||||
for (int32_t i = 0; i < n; ++i) s[(size_t)i] = (float)(i == n - 1 && n > 1 ? stop : i * step + 1.0);
|
||||
if (d.dyn_shift) {
|
||||
const double m = (d.max_shift - d.base_shift) / (double)(d.max_seq - d.base_seq);
|
||||
const double mu = (double)tokens * m + (d.base_shift - m * (double)d.base_seq);
|
||||
const float e = (float)std::exp(mu);
|
||||
for (float& v : s) v = e / (e + (1.0f / v - 1.0f));
|
||||
}
|
||||
if (d.shift_terminal > 0.0) {
|
||||
const float sf = (1.0f - s.back()) / (float)(1.0 - d.shift_terminal);
|
||||
for (float& v : s) v = 1.0f - (1.0f - v) / sf;
|
||||
}
|
||||
s.push_back(0.0f);
|
||||
return s;
|
||||
}
|
||||
|
||||
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps, int64_t video_tokens,
|
||||
bool refine) {
|
||||
VideoSchedule v;
|
||||
if (d.sched_kind == 1) {
|
||||
if (d.n_rungs > 0) {
|
||||
if (steps != d.n_rungs) return v;
|
||||
for (int32_t i = 0; i < d.n_rungs; ++i) v.sig_v.push_back((float)d.rungs[i]);
|
||||
if (refine)
|
||||
for (int32_t i = 0; i < d.n_refine_rungs; ++i)
|
||||
v.sig_v.push_back((float)d.refine_rungs[i]);
|
||||
v.sig_v.push_back(0.0f);
|
||||
} else {
|
||||
if (steps < 1) return v;
|
||||
v.sig_v = flow_sigmas(d, steps, video_tokens);
|
||||
}
|
||||
v.sig_a = v.sig_v;
|
||||
v.steps = (int32_t)v.sig_v.size() - 1;
|
||||
return v;
|
||||
}
|
||||
if (d.n_rungs > 0) {
|
||||
if (steps != d.n_rungs + 1) return v;
|
||||
v.sig_v = rung_sigmas(d.shift_video, d.rungs, d.n_rungs);
|
||||
@@ -146,10 +186,12 @@ 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) {
|
||||
/* A guided model's VCOND carries the negative prompt after the positive. */
|
||||
const int64_t prompts = d.guidance ? 2 : 1;
|
||||
const int64_t want[] = {
|
||||
d.max_text * 4, /* R_TOK */
|
||||
d.max_text * 4, /* R_POS */
|
||||
2 * 4, /* R_CU */
|
||||
prompts * d.max_text * 4, /* R_TOK */
|
||||
prompts * d.max_text * 4, /* R_POS */
|
||||
3 * 4, /* R_CU */
|
||||
3 * max_tok * 4, /* R_ROPE: a step's rotary positions */
|
||||
RAD_VGEOM_N * 4, /* R_GEOM */
|
||||
6 * 4, /* R_SCHED */
|
||||
@@ -161,6 +203,8 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t (*bytes)[2], in
|
||||
4 * 4, /* R_SEG */
|
||||
4 * 4, /* R_LAT */
|
||||
4, /* R_UP */
|
||||
d.image_cond ? d.max_area * 3 * 2 : 0, /* R_IMG: a first frame, bf16 */
|
||||
8 * 4, /* R_GUIDE */
|
||||
};
|
||||
int64_t off = 0;
|
||||
for (int r = 0; r < n; ++r) {
|
||||
@@ -206,9 +250,17 @@ int VideoDriver::init(const Program& prog, PositionsFn positions,
|
||||
"video generator must", name_.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (max_tok_ < decl_.max_text) {
|
||||
RAD_ERR("video generator '%s': a pass carries %lld rows and a prompt may be %lld tokens",
|
||||
name_.c_str(), (long long)max_tok_, (long long)decl_.max_text);
|
||||
decoder_names_ = prog.vgen_str.decoders;
|
||||
decoder_area_ = prog.vgen_str.decoder_max_area;
|
||||
refine_rungs_ = prog.vgen_str.refine_rungs;
|
||||
decl_.refine_rungs = refine_rungs_.empty() ? nullptr : refine_rungs_.data();
|
||||
default_negative_ = prog.vgen_str.default_negative;
|
||||
decl_.default_negative = default_negative_.c_str();
|
||||
const int64_t prompts = decl_.guidance ? 2 : 1;
|
||||
if (max_tok_ < prompts * decl_.max_text) {
|
||||
RAD_ERR("video generator '%s': a pass carries %lld rows and %s may be %lld tokens",
|
||||
name_.c_str(), (long long)max_tok_, prompts == 2 ? "a prompt and its negative" :
|
||||
"a prompt", (long long)(prompts * decl_.max_text));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
int64_t b[R_N][2];
|
||||
@@ -222,7 +274,8 @@ int VideoDriver::init(const Program& prog, PositionsFn positions,
|
||||
host_ = static_cast<char*>(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED));
|
||||
frames_host_ = static_cast<uint8_t*>(rad_dev_alloc(frames_bytes_, RAD_MEM_HOST_PINNED));
|
||||
audio_host_ = static_cast<float*>(rad_dev_alloc(audio_bytes_, RAD_MEM_HOST_PINNED));
|
||||
if (!host_ || !frames_host_ || !audio_host_) {
|
||||
duration_host_ = static_cast<float*>(rad_dev_alloc(64, RAD_MEM_HOST_PINNED));
|
||||
if (!host_ || !frames_host_ || !audio_host_ || !duration_host_) {
|
||||
RAD_ERR("video generator: no pinned host memory for the pass staging and outputs (%lld + "
|
||||
"%lld + %lld bytes)", (long long)bytes_, (long long)frames_bytes_,
|
||||
(long long)audio_bytes_);
|
||||
@@ -258,12 +311,157 @@ void VideoDriver::fini() {
|
||||
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);
|
||||
if (duration_host_) rad_dev_free(duration_host_, RAD_MEM_HOST_PINNED);
|
||||
duration_host_ = nullptr;
|
||||
host_ = nullptr;
|
||||
frames_host_ = nullptr;
|
||||
audio_host_ = nullptr;
|
||||
}
|
||||
|
||||
/* ================================================================== requests */
|
||||
/* A length head's prediction (RadVideoGenDecl::duration_out) in chunks: diffusers'
|
||||
* LTX2DurationHead.predict_num_frames on the chunk grid -- the seconds clamped to the declared
|
||||
* bounds, rounded to frames, floored to the grid and lifted one chunk when that falls under the
|
||||
* minimum -- then held to min_chunks..max_chunks. `note` says what was clamped. */
|
||||
int32_t VideoDriver::predicted_chunks(double log_seconds, std::string* note) const {
|
||||
const RadVideoGenDecl& d = decl_;
|
||||
const double fps = (double)d.fps_num / (double)d.fps_den;
|
||||
float e = std::exp((float)log_seconds);
|
||||
if (d.duration_dtype == RAD_BF16) e = rad_bf16_to_f32(rad_f32_to_bf16(e));
|
||||
const double sec = e;
|
||||
auto round_even = [](double v) { return (int64_t)std::nearbyint(v); };
|
||||
const int64_t lo = std::max<int64_t>(1, round_even(d.duration_min * fps));
|
||||
const int64_t hi = round_even(d.duration_max * fps);
|
||||
const int64_t want = std::isfinite(sec) ? round_even(sec * fps) : hi;
|
||||
const int64_t frames = std::max(lo, std::min(want, hi));
|
||||
int64_t n = std::max<int64_t>(0, (frames - d.frames_tail) / d.frames_per_chunk);
|
||||
if (d.frames_per_chunk * n + d.frames_tail < lo &&
|
||||
d.frames_per_chunk * (n + 1) + d.frames_tail <= hi)
|
||||
++n;
|
||||
std::string what = fmt(": %.3f s predicted", sec);
|
||||
if (!(sec >= d.duration_min && sec <= d.duration_max))
|
||||
what += fmt(", held to %g..%g s", d.duration_min, d.duration_max);
|
||||
if (n < d.min_chunks || n > d.max_chunks) {
|
||||
n = std::max<int64_t>(d.min_chunks, std::min<int64_t>(n, d.max_chunks));
|
||||
what += fmt(", within the %lld..%lld frames this model makes",
|
||||
(long long)(d.frames_per_chunk * d.min_chunks + d.frames_tail),
|
||||
(long long)(d.frames_per_chunk * d.max_chunks + d.frames_tail));
|
||||
}
|
||||
if (note) *note = what;
|
||||
return (int32_t)n;
|
||||
}
|
||||
|
||||
/* The request's shape at `chunks` long: its geometry, rows and positions, its schedule, the
|
||||
* upscale's split and what its ticket says it makes. Run at submit, and again for a request whose
|
||||
* length the model predicts once its VCOND pass has written the prediction. */
|
||||
int VideoDriver::shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_t steps,
|
||||
std::string* why) {
|
||||
const RadVideoGenDecl& d = decl_;
|
||||
auto no = [&](const std::string& w) {
|
||||
if (why) *why = w;
|
||||
return RAD_E_INVAL;
|
||||
};
|
||||
const int64_t T = (int64_t)r.tokens.size();
|
||||
const VideoShape s = video_shape(d, r.width, r.height, chunks);
|
||||
j.geom.n_text = (int32_t)(d.step_text_rows > 0 ? d.step_text_rows : T);
|
||||
j.geom.frames = s.frames;
|
||||
j.geom.lat_frames = s.lat_frames;
|
||||
j.geom.lat_h = s.lat_h;
|
||||
j.geom.lat_w = s.lat_w;
|
||||
j.geom.n_audio = s.n_audio;
|
||||
j.rows = j.geom.n_text + s.audio_rows + s.video_rows;
|
||||
if (j.rows > max_tok_)
|
||||
return no("a step of this video is " + std::to_string(j.rows) + " rows and a pass "
|
||||
"carries " + std::to_string(max_tok_) + "; ask for a shorter or smaller video");
|
||||
const int64_t nr = positions_(RAD_VPOS_STEP, &j.geom, nullptr, 0);
|
||||
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");
|
||||
/* The schedule follows the upscale's split, which needs the small size first. */
|
||||
const bool upscaling = r.upscale > 1.0;
|
||||
const bool own_refine = upscaling && d.n_refine_rungs > 0;
|
||||
int64_t first_tokens = s.video_rows;
|
||||
if (upscaling) {
|
||||
int32_t sw = 0, sh = 0;
|
||||
video_small_size(d, r.width, r.height, r.upscale, &sw, &sh);
|
||||
first_tokens = video_shape(d, sw, sh, chunks).video_rows;
|
||||
}
|
||||
j.sched = video_schedule(d, steps, first_tokens, own_refine);
|
||||
if (j.sched.steps < 1) return no("the schedule has no steps");
|
||||
int32_t first_w = r.width, first_h = r.height;
|
||||
if (upscaling) {
|
||||
if (!(d.upscale_max > 1.0)) return no("this model has no latent upscaler");
|
||||
if (d.upscale_exact) {
|
||||
const int64_t m = (int64_t)std::llround(d.size_multiple * d.upscale_max);
|
||||
if (r.upscale != d.upscale_max || r.width % m || r.height % m)
|
||||
return no("this model's latent upscaler enlarges by exactly " +
|
||||
fmt("%g", d.upscale_max) + ": latent_upscale must be that, and both "
|
||||
"sides multiples of " + std::to_string(m));
|
||||
}
|
||||
if (r.upscale > d.upscale_max)
|
||||
return no("latent_upscale is at most " + fmt("%g", d.upscale_max) + " for this model");
|
||||
int32_t sw = 0, sh = 0;
|
||||
video_small_size(d, r.width, r.height, r.upscale, &sw, &sh);
|
||||
if (sw == r.width && sh == r.height)
|
||||
return no("latent_upscale " + fmt("%g", r.upscale) + " leaves " +
|
||||
std::to_string(r.width) + "x" + std::to_string(r.height) + " as it is: "
|
||||
"the small size is each side over the factor, rounded to a multiple of " +
|
||||
std::to_string(d.size_multiple));
|
||||
const int32_t evals = j.sched.steps;
|
||||
int32_t refine = r.refine;
|
||||
if (own_refine) {
|
||||
if (refine != 0 && refine != d.n_refine_rungs)
|
||||
return no("upscale_refine_steps must be " + std::to_string(d.n_refine_rungs) +
|
||||
": this model refines the upscaled video over the schedule it was "
|
||||
"trained on");
|
||||
refine = d.n_refine_rungs;
|
||||
}
|
||||
if (refine == 0) refine = std::min<int32_t>(d.upscale_refine, evals - 1);
|
||||
if (refine < 1 || refine >= evals)
|
||||
return no("upscale_refine_steps must be 1.." + std::to_string(evals - 1) + ": the "
|
||||
"schedule takes " + std::to_string(evals) + " evaluations and the small "
|
||||
"size at least one of them");
|
||||
const VideoShape ss = video_shape(d, sw, sh, chunks);
|
||||
j.geom_small = j.geom;
|
||||
j.geom_small.lat_h = ss.lat_h;
|
||||
j.geom_small.lat_w = ss.lat_w;
|
||||
j.rows_small = j.geom.n_text + ss.audio_rows + ss.video_rows;
|
||||
const int64_t ns = positions_(RAD_VPOS_STEP, &j.geom_small, nullptr, 0);
|
||||
if (ns != j.rows_small)
|
||||
return no("the model lays the small size " + std::to_string(sw) + "x" +
|
||||
std::to_string(sh) + " out in " + std::to_string(ns) + " step rows, which "
|
||||
"this server cannot run");
|
||||
j.pos_small.assign((size_t)(3 * ns), 0.0f);
|
||||
if (positions_(RAD_VPOS_STEP, &j.geom_small, j.pos_small.data(), ns) != ns)
|
||||
return no("the model could not lay the small size out");
|
||||
j.split = evals - refine;
|
||||
j.factor = (float)(((double)r.width / sw + (double)r.height / sh) / 2.0);
|
||||
r.ticket->small_width = sw;
|
||||
r.ticket->small_height = sh;
|
||||
r.ticket->refine = refine;
|
||||
first_w = sw;
|
||||
first_h = sh;
|
||||
}
|
||||
if (!r.image.empty()) {
|
||||
if (!d.image_cond) return no("this model cannot start from a picture");
|
||||
if (r.image.size() != (size_t)first_w * first_h * 3)
|
||||
return no("the first frame is not " + std::to_string(first_w) + "x" +
|
||||
std::to_string(first_h) + " RGB");
|
||||
}
|
||||
j.n_chunks = chunks;
|
||||
j.n_samples = (int64_t)s.n_audio * (d.sample_rate / d.audio_rate);
|
||||
VideoTicket& t = *r.ticket;
|
||||
t.frames = s.frames;
|
||||
t.steps = j.sched.steps;
|
||||
t.rows = j.rows;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
|
||||
if (!r || !r->ticket) return RAD_E_INVAL;
|
||||
const RadVideoGenDecl& d = decl_;
|
||||
@@ -275,7 +473,7 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
|
||||
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)
|
||||
if (r->chunks != 0 && (r->chunks < d.min_chunks || r->chunks > d.max_chunks))
|
||||
return no("the length must be " + std::to_string(d.min_chunks) + ".." +
|
||||
std::to_string(d.max_chunks) + " chunks");
|
||||
const int64_t W = r->width, H = r->height;
|
||||
@@ -287,87 +485,53 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
|
||||
" pixels, the long side at most " + std::to_string(d.max_aspect) +
|
||||
" times the short");
|
||||
const int32_t steps = r->steps > 0 ? r->steps : (int32_t)d.default_steps;
|
||||
if (d.n_rungs > 0 && steps != d.n_rungs + 1)
|
||||
return no("num_inference_steps must be " + std::to_string(d.n_rungs + 1) + ": this model "
|
||||
const bool evals = d.sched_kind == 1; /* form 1 counts evaluations, form 0 grid points */
|
||||
const int32_t rung_steps = evals ? d.n_rungs : d.n_rungs + 1;
|
||||
if (d.n_rungs > 0 && steps != rung_steps)
|
||||
return no("num_inference_steps must be " + std::to_string(rung_steps) + ": this model "
|
||||
"runs the schedule it was trained on, " + std::to_string(d.n_rungs) +
|
||||
" evaluations");
|
||||
if (steps < 2 || steps > d.max_steps)
|
||||
return no("num_inference_steps must be 2.." + std::to_string(d.max_steps) + " (sigma grid "
|
||||
"points, the last one 0)");
|
||||
if (steps < (evals ? 1 : 2) || steps > d.max_steps)
|
||||
return no("num_inference_steps must be " + std::to_string(evals ? 1 : 2) + ".." +
|
||||
std::to_string(d.max_steps) + (evals ? " (model evaluations)" :
|
||||
" (sigma grid points, the last one 0)"));
|
||||
|
||||
auto j = std::make_unique<Job>();
|
||||
const VideoShape s = video_shape(d, r->width, r->height, r->chunks);
|
||||
j->geom.n_text = (int32_t)T;
|
||||
j->geom.frames = s.frames;
|
||||
j->geom.lat_frames = s.lat_frames;
|
||||
j->geom.lat_h = s.lat_h;
|
||||
j->geom.lat_w = s.lat_w;
|
||||
j->geom.n_audio = s.n_audio;
|
||||
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");
|
||||
if (r->upscale > 1.0) {
|
||||
if (!(d.upscale_max > 1.0)) return no("this model has no latent upscaler");
|
||||
if (r->upscale > d.upscale_max)
|
||||
return no("latent_upscale is at most " + fmt("%g", d.upscale_max) + " for this model");
|
||||
int32_t sw = 0, sh = 0;
|
||||
video_small_size(d, r->width, r->height, r->upscale, &sw, &sh);
|
||||
if (sw == r->width && sh == r->height)
|
||||
return no("latent_upscale " + fmt("%g", r->upscale) + " leaves " +
|
||||
std::to_string(r->width) + "x" + std::to_string(r->height) + " as it is: "
|
||||
"the small size is each side over the factor, rounded to a multiple of " +
|
||||
std::to_string(d.size_multiple));
|
||||
const int32_t evals = j->sched.steps;
|
||||
int32_t refine = r->refine;
|
||||
if (refine == 0) refine = std::min<int32_t>(d.upscale_refine, evals - 1);
|
||||
if (refine < 1 || refine >= evals)
|
||||
return no("upscale_refine_steps must be 1.." + std::to_string(evals - 1) + ": the "
|
||||
"schedule takes " + std::to_string(evals) + " evaluations and the small "
|
||||
"size at least one of them");
|
||||
const VideoShape ss = video_shape(d, sw, sh, r->chunks);
|
||||
j->geom_small = j->geom;
|
||||
j->geom_small.lat_h = ss.lat_h;
|
||||
j->geom_small.lat_w = ss.lat_w;
|
||||
j->rows_small = T + ss.audio_rows + ss.video_rows;
|
||||
const int64_t ns = positions_(RAD_VPOS_STEP, &j->geom_small, nullptr, 0);
|
||||
if (ns != j->rows_small)
|
||||
return no("the model lays the small size " + std::to_string(sw) + "x" +
|
||||
std::to_string(sh) + " out in " + std::to_string(ns) + " step rows, which "
|
||||
"this server cannot run");
|
||||
j->pos_small.assign((size_t)(3 * ns), 0.0f);
|
||||
if (positions_(RAD_VPOS_STEP, &j->geom_small, j->pos_small.data(), ns) != ns)
|
||||
return no("the model could not lay the small size out");
|
||||
j->split = evals - refine;
|
||||
j->factor = (float)(((double)r->width / sw + (double)r->height / sh) / 2.0);
|
||||
r->ticket->small_width = sw;
|
||||
r->ticket->small_height = sh;
|
||||
r->ticket->refine = refine;
|
||||
/* Guidance: the request's terms over the model's defaults; a negative prompt only when a
|
||||
* scale asks for the unconditional branch. */
|
||||
bool named = r->has_neg;
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
named = named || !std::isnan(r->guidance[i]);
|
||||
j->guidance[i] = (float)(std::isnan(r->guidance[i]) ? d.guidance_default[i] : r->guidance[i]);
|
||||
if (!(j->guidance[i] >= 0.0f) || !std::isfinite(j->guidance[i]))
|
||||
return no("guidance terms must be finite and not negative");
|
||||
}
|
||||
j->n_chunks = r->chunks;
|
||||
j->n_samples = (int64_t)s.n_audio * (d.sample_rate / d.audio_rate);
|
||||
if (!d.guidance && named)
|
||||
return no("this model takes no guidance or negative prompt");
|
||||
j->n_neg = 0;
|
||||
if (d.guidance && (j->guidance[0] != 1.0f || j->guidance[4] != 1.0f)) {
|
||||
const int64_t N = (int64_t)r->neg_tokens.size();
|
||||
if (N < 1 || N > d.max_text)
|
||||
return no("the negative prompt is " + std::to_string(N) + " tokens; this model takes "
|
||||
"1.." + std::to_string(d.max_text));
|
||||
j->n_neg = (int32_t)N;
|
||||
}
|
||||
if (r->decoder < 0 || (r->decoder > 0 && (size_t)r->decoder >= decoder_area_.size()))
|
||||
return no("this model has no decoder " + std::to_string(r->decoder));
|
||||
if (r->decoder > 0 && W * H > decoder_area_[(size_t)r->decoder])
|
||||
return no("the " + decoder_names_[(size_t)r->decoder] + " decoder makes frames of " +
|
||||
std::to_string(decoder_area_[(size_t)r->decoder]) + " pixels at most");
|
||||
j->auto_len = r->chunks == 0 && d.duration_out != RAD_NULL_HANDLE;
|
||||
const int32_t chunks = r->chunks == 0 ? (int32_t)d.default_chunks : r->chunks;
|
||||
if (shape_job(*j, *r, chunks, steps, why) < 0) return RAD_E_INVAL;
|
||||
|
||||
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_) {
|
||||
@@ -472,8 +636,16 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows,
|
||||
b.lat_frames, b.lat_h / p, b.lat_w / p };
|
||||
std::memcpy(g + RAD_VGEOM_UP_SRC, up, sizeof up);
|
||||
}
|
||||
g[RAD_VGEOM_AUDIO_VOL] = g0.n_audio;
|
||||
g[RAD_VGEOM_AUDIO_VOL + 1] = 1;
|
||||
g[RAD_VGEOM_AUDIO_VOL + 2] = 1;
|
||||
const int32_t ppf = (int32_t)((g0.lat_h / decl_.patch) * (g0.lat_w / decl_.patch));
|
||||
g[RAD_VGEOM_FIRST_CU] = 0;
|
||||
g[RAD_VGEOM_FIRST_CU + 1] = ppf;
|
||||
g[RAD_VGEOM_FIRST_CU + 2] = ppf * g0.lat_frames;
|
||||
reg_[R_GEOM].used = RAD_VGEOM_N * 4;
|
||||
const int64_t audio_rows = decl_.audio_channels * (int64_t)g0.n_audio;
|
||||
const int64_t audio_rows =
|
||||
(decl_.audio_streams > 0 ? decl_.audio_streams : decl_.audio_channels) * (int64_t)g0.n_audio;
|
||||
const int64_t video_rows = rows - g0.n_text - audio_rows;
|
||||
*hptr<int32_t>(R_LANE) = j.lane;
|
||||
*hptr<int32_t>(R_FIRST) = j.step == 0;
|
||||
@@ -487,6 +659,8 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows,
|
||||
lat[1] = (int32_t)video_rows;
|
||||
lat[2] = 0;
|
||||
lat[3] = (int32_t)audio_rows;
|
||||
std::memcpy(hptr<float>(R_GUIDE), j.guidance, sizeof j.guidance);
|
||||
reg_[R_GUIDE].used = sizeof j.guidance;
|
||||
reg_[R_LANE].used = 4;
|
||||
reg_[R_FIRST].used = 4;
|
||||
reg_[R_SEG].used = 4 * 4;
|
||||
@@ -529,6 +703,10 @@ void VideoDriver::base_batches(const Job& j, const RadVideoGeom& g, int64_t n_to
|
||||
V.dec_rows = j.dec_rows;
|
||||
V.n_samples = j.n_samples;
|
||||
V.upscale = dptr<float>(ri, R_UP);
|
||||
V.guidance_h = j.guidance;
|
||||
V.guidance = dptr<float>(ri, R_GUIDE);
|
||||
V.has_image = !j.req->image.empty();
|
||||
V.decoder = j.req->decoder;
|
||||
B.vgen_b = &V;
|
||||
}
|
||||
}
|
||||
@@ -581,30 +759,54 @@ const RadBatch* VideoDriver::batch_for(int rank) const {
|
||||
|
||||
const RadBatch* VideoDriver::build_cond(Job& j, int step) {
|
||||
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
|
||||
const int64_t T = j.geom.n_text;
|
||||
/* The prompt, then the negative prompt when the request is guided against one, each its own
|
||||
* sequence from position 0. */
|
||||
const int64_t T = (int64_t)j.req->tokens.size(), N = j.n_neg;
|
||||
int32_t* tok = hptr<int32_t>(R_TOK);
|
||||
int32_t* pos = hptr<int32_t>(R_POS);
|
||||
std::memcpy(tok, j.req->tokens.data(), (size_t)T * 4);
|
||||
for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)i;
|
||||
if (N > 0) std::memcpy(tok + T, j.req->neg_tokens.data(), (size_t)N * 4);
|
||||
/* A left-padded encoder's prompt ends at text_left_pad - 1. */
|
||||
const int64_t lp = decl_.text_left_pad;
|
||||
for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)(lp > 0 ? lp - T + i : i);
|
||||
for (int64_t i = 0; i < N; ++i) pos[T + i] = (int32_t)(lp > 0 ? lp - N + i : i);
|
||||
int32_t* cu = hptr<int32_t>(R_CU);
|
||||
cu[0] = 0;
|
||||
cu[1] = (int32_t)T;
|
||||
cu[2] = (int32_t)(T + N);
|
||||
/* The first frame as the reference's image processor hands it to the VAE: x / 255 * 2 - 1 in
|
||||
* f32, then bf16. */
|
||||
const std::vector<uint8_t>& img = j.req->image;
|
||||
if (!img.empty()) {
|
||||
uint16_t* px = hptr<uint16_t>(R_IMG);
|
||||
for (size_t i = 0; i < img.size(); ++i)
|
||||
px[i] = rad_f32_to_bf16(2.0f * ((float)img[i] / 255.0f) - 1.0f);
|
||||
reg_[R_IMG].used = (int64_t)img.size() * 2;
|
||||
}
|
||||
float* tv = hptr<float>(R_TV);
|
||||
float* ta = hptr<float>(R_TA);
|
||||
for (int32_t i = 0; i < j.sched.steps; ++i) {
|
||||
tv[i] = 1.0f - j.sched.sig_v[(size_t)i];
|
||||
ta[i] = 1.0f - j.sched.sig_a[(size_t)i];
|
||||
}
|
||||
reg_[R_TOK].used = T * 4;
|
||||
reg_[R_POS].used = T * 4;
|
||||
reg_[R_CU].used = 2 * 4;
|
||||
reg_[R_TOK].used = (T + N) * 4;
|
||||
reg_[R_POS].used = (T + N) * 4;
|
||||
reg_[R_CU].used = (N > 0 ? 3 : 2) * 4;
|
||||
reg_[R_TV].used = j.sched.steps * 4;
|
||||
reg_[R_TA].used = j.sched.steps * 4;
|
||||
const RadVideoGeom& g = small_now(j) ? j.geom_small : j.geom;
|
||||
stage_geom(j, g, small_now(j) ? j.rows_small : j.rows, 0);
|
||||
if (upload() < 0) return nullptr;
|
||||
base_batches(j, g, T, step);
|
||||
for (auto& B : out_) B.gen = RAD_GEN_PASS_VCOND;
|
||||
base_batches(j, g, T + N, step);
|
||||
for (size_t r = 0; r < out_.size(); ++r) {
|
||||
RadBatch& B = out_[r];
|
||||
B.gen = RAD_GEN_PASS_VCOND;
|
||||
B.n_seq = N > 0 ? 2 : 1;
|
||||
B.max_q_len = B.max_q_len_prefill = (int32_t)std::max(T, N);
|
||||
vout_[r].n_neg = (int32_t)N;
|
||||
if (!img.empty()) vout_[r].image = dptr<uint16_t>((int)r, R_IMG);
|
||||
}
|
||||
if (j.auto_len) rb_.assign(1, Readback{ decl_.duration_out, 4, duration_host_ });
|
||||
pass_.kind = RAD_GEN_PASS_VCOND;
|
||||
pass_.job = j.id;
|
||||
return &out_[0];
|
||||
@@ -691,6 +893,7 @@ const RadBatch* VideoDriver::build_audio(Job& j, int step) {
|
||||
const RadBatch* VideoDriver::build_chunk(Job& j, int step) {
|
||||
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
|
||||
stage_geom(j, j.geom, j.rows, j.chunk);
|
||||
stage_seed(j); /* a decoder that denoises draws from the request's seed */
|
||||
if (upload() < 0) return nullptr;
|
||||
base_batches(j, j.geom, j.dec_rows, step);
|
||||
const bool last = j.chunk == j.n_chunks - 1;
|
||||
@@ -715,6 +918,26 @@ int VideoDriver::done() {
|
||||
case RAD_GEN_PASS_VCOND:
|
||||
j->cond_done = true;
|
||||
j->req->ticket->t_cond_ns = now;
|
||||
if (j->auto_len) {
|
||||
j->auto_len = false;
|
||||
std::string note, why;
|
||||
int32_t n = predicted_chunks((double)duration_host_[0], ¬e);
|
||||
/* Shaped as at submit, which passed at default_chunks; a longer video than a pass
|
||||
* can carry is shortened until it fits. */
|
||||
const int32_t steps = j->req->steps > 0 ? j->req->steps : (int32_t)decl_.default_steps;
|
||||
const int32_t at_submit = j->n_chunks;
|
||||
while (n > at_submit && shape_job(*j, *j->req, n, steps, &why) < 0) --n;
|
||||
if (n <= at_submit && shape_job(*j, *j->req, n, steps, &why) < 0) {
|
||||
fail_locked(*j, RAD_E_INVAL, why);
|
||||
break;
|
||||
}
|
||||
RAD_INFO("video: the model gives the prompt %d frames (%.2f s)%s", j->geom.frames,
|
||||
(double)j->geom.frames * decl_.fps_den / decl_.fps_num, note.c_str());
|
||||
VideoEvent e;
|
||||
e.kind = VideoEvent::LENGTH;
|
||||
e.n = j->geom.frames;
|
||||
j->req->ticket->push(std::move(e));
|
||||
}
|
||||
break;
|
||||
case RAD_GEN_PASS_VSTEP: {
|
||||
++j->step;
|
||||
|
||||
+17
-2
@@ -6,7 +6,8 @@
|
||||
* threads through `submit()` and leave through their VideoTicket.
|
||||
*
|
||||
* A request holds a lane from admission to its last chunk. Its geometry, schedule and rotary
|
||||
* positions are fixed at submit, so nothing is computed between passes but the staging.
|
||||
* positions are fixed at submit, so nothing is computed between passes but the staging; a request
|
||||
* whose length the model predicts is shaped again once, after its VCOND pass.
|
||||
*
|
||||
* Pass priority, one pass at a time:
|
||||
*
|
||||
@@ -76,6 +77,13 @@ private:
|
||||
std::vector<float> pos_small;
|
||||
float factor = 0.0f;
|
||||
bool upscaled = false;
|
||||
/* Guidance resolved against the model's defaults (RadVideoGenBatch::guidance_h) and the
|
||||
* negative prompt's tokens the VCOND pass carries (0: none). */
|
||||
float guidance[8] = {};
|
||||
int32_t n_neg = 0;
|
||||
/* The request named no length and the model predicts one (RadVideoGenDecl::duration_out):
|
||||
* shaped at default_chunks until its VCOND pass is done. */
|
||||
bool auto_len = false;
|
||||
int32_t lane = -1;
|
||||
bool admitted = false;
|
||||
bool cond_done = false;
|
||||
@@ -96,7 +104,7 @@ private:
|
||||
/* 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_UP, R_N };
|
||||
R_SEG, R_LAT, R_UP, R_IMG, R_GUIDE, R_N };
|
||||
|
||||
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
|
||||
template <class T> T* dptr(int rank, int r) const {
|
||||
@@ -105,6 +113,8 @@ private:
|
||||
int upload();
|
||||
/* The geometry and rows of the job's next step: the small ones before its upscale. */
|
||||
bool small_now(const Job& j) const { return j.split > 0 && !j.upscaled; }
|
||||
int shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_t steps, std::string* why);
|
||||
int32_t predicted_chunks(double log_seconds, std::string* note) const;
|
||||
void base_batches(const Job& j, const RadVideoGeom& g, int64_t n_tok, int step);
|
||||
void stage_geom(const Job& j, const RadVideoGeom& g, int64_t rows, int32_t chunk);
|
||||
void stage_sched(const Job& j, int32_t i, bool to_clean);
|
||||
@@ -123,6 +133,10 @@ private:
|
||||
|
||||
RadVideoGenDecl decl_{};
|
||||
std::vector<double> rungs_; /* decl_.rungs points here */
|
||||
std::vector<double> refine_rungs_; /* decl_.refine_rungs */
|
||||
std::string default_negative_;
|
||||
std::vector<std::string> decoder_names_; /* RadVideoGenDecl::decoders */
|
||||
std::vector<int64_t> decoder_area_; /* each one's largest frame */
|
||||
std::string name_;
|
||||
PositionsFn positions_ = nullptr;
|
||||
int64_t max_tok_ = 0;
|
||||
@@ -136,6 +150,7 @@ private:
|
||||
int64_t frames_bytes_ = 0;
|
||||
float* audio_host_ = nullptr;
|
||||
int64_t audio_bytes_ = 0;
|
||||
float* duration_host_ = nullptr; /* duration_out's readback, f32 [1] */
|
||||
std::vector<Readback> rb_;
|
||||
|
||||
std::vector<RadBatch> out_; /* one per rank */
|
||||
|
||||
+3
-4
@@ -774,10 +774,9 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
/* Evict the least recently used snapshot, where a use is its reservation or a lookup
|
||||
* resuming from it, and never one handed out or reserved this step (its admission
|
||||
* restores from the slot ahead of the step; the save lands in it after). A tip gets
|
||||
* no protection beyond its recency: sessions
|
||||
* are request ids, and a client that rewrites its last message leaves one tip per
|
||||
* turn that no later turn reaches, while the anchor every turn resumes from is used
|
||||
* each turn. */
|
||||
* no protection beyond its recency: sessions are request ids, and a client that
|
||||
* rewrites its last message leaves one tip per turn that no later turn reaches, while
|
||||
* the anchor every turn resumes from is used each turn. */
|
||||
const Ckpt* victim = nullptr;
|
||||
for (const auto& kvp : ck_by_prefix_) {
|
||||
if (handed(kvp.first) || reserved(kvp.first)) continue;
|
||||
|
||||
+21
-4
@@ -22,6 +22,12 @@ double sinc(double x) {
|
||||
|
||||
double lanczos(double x) { return (-3.0 <= x && x < 3.0) ? sinc(x) * sinc(x / 3.0) : 0.0; }
|
||||
|
||||
/* PIL's BILINEAR filter: a triangle of support 1. */
|
||||
double triangle(double x) {
|
||||
if (x < 0.0) x = -x;
|
||||
return x < 1.0 ? 1.0 - x : 0.0;
|
||||
}
|
||||
|
||||
/* One axis: for each output index its first input index, its tap count, and `ksize` fixed-point
|
||||
* coefficients. */
|
||||
struct Axis {
|
||||
@@ -30,11 +36,11 @@ struct Axis {
|
||||
std::vector<int> kk; /* [out, ksize] */
|
||||
};
|
||||
|
||||
Axis coeffs(int in_size, int out_size) {
|
||||
Axis coeffs(int in_size, int out_size, bool bilinear) {
|
||||
Axis a;
|
||||
const double scale = (double)in_size / (double)out_size;
|
||||
double filterscale = scale < 1.0 ? 1.0 : scale;
|
||||
const double support = 3.0 * filterscale;
|
||||
const double support = (bilinear ? 1.0 : 3.0) * filterscale;
|
||||
a.ksize = (int)std::ceil(support) * 2 + 1;
|
||||
a.bounds.assign((size_t)out_size * 2, 0);
|
||||
a.kk.assign((size_t)out_size * a.ksize, 0);
|
||||
@@ -50,7 +56,8 @@ Axis coeffs(int in_size, int out_size) {
|
||||
xmax -= xmin;
|
||||
int x = 0;
|
||||
for (; x < xmax; ++x) {
|
||||
const double w = lanczos((x + xmin - center + 0.5) * ss);
|
||||
const double t = (x + xmin - center + 0.5) * ss;
|
||||
const double w = bilinear ? triangle(t) : lanczos(t);
|
||||
k[(size_t)x] = w;
|
||||
ww += w;
|
||||
}
|
||||
@@ -80,7 +87,17 @@ inline unsigned muldiv255(unsigned a, unsigned b) {
|
||||
|
||||
} /* namespace */
|
||||
|
||||
static void resize_rgba(const FrameRGBA& src, int32_t w, int32_t h, bool bilinear, FrameRGBA* out);
|
||||
|
||||
void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out) {
|
||||
resize_rgba(src, w, h, false, out);
|
||||
}
|
||||
|
||||
void resize_bilinear_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out) {
|
||||
resize_rgba(src, w, h, true, out);
|
||||
}
|
||||
|
||||
static void resize_rgba(const FrameRGBA& src, int32_t w, int32_t h, bool bilinear, FrameRGBA* out) {
|
||||
const int iw = src.w, ih = src.h;
|
||||
/* Image.resize returns a copy at the same size. The premultiplied round trip below is not
|
||||
* lossless where alpha is below 255. */
|
||||
@@ -96,7 +113,7 @@ void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA*
|
||||
pre[i * 4 + 3] = (uint8_t)al;
|
||||
}
|
||||
const bool horiz = w != iw, vert = h != ih;
|
||||
const Axis ax = coeffs(iw, w), ay = coeffs(ih, h);
|
||||
const Axis ax = coeffs(iw, w, bilinear), ay = coeffs(ih, h, bilinear);
|
||||
/* the rows the vertical pass reads */
|
||||
const int y_first = ay.bounds[0];
|
||||
const int y_last = ay.bounds[(size_t)(h - 1) * 2] + ay.bounds[(size_t)(h - 1) * 2 + 1];
|
||||
|
||||
@@ -18,6 +18,8 @@ namespace mm {
|
||||
|
||||
/* `src` resized to w x h. */
|
||||
void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out);
|
||||
/* The same with PIL's BILINEAR filter (a triangle of support 1, widened when shrinking). */
|
||||
void resize_bilinear_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out);
|
||||
/* `src` over an opaque white ground. */
|
||||
void composite_white(const FrameRGBA& src, Frame* out);
|
||||
|
||||
|
||||
@@ -46,6 +46,8 @@ int decode_video(const uint8_t*, size_t, SampleFn, const void*, int64_t, Video*,
|
||||
std::string* why) {
|
||||
return no_decoder(why);
|
||||
}
|
||||
int h264_roundtrip(const Frame&, int32_t, Frame*, std::string* why) { return no_decoder(why); }
|
||||
bool h264_roundtrip_available() { return false; }
|
||||
int decode_audio(const uint8_t*, size_t, int32_t, int64_t, std::vector<float>*,
|
||||
std::string* why) {
|
||||
return no_decoder(why);
|
||||
@@ -677,6 +679,113 @@ int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_sample
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
bool h264_roundtrip_available() {
|
||||
return avcodec_find_encoder_by_name("libx264") && avcodec_find_decoder(AV_CODEC_ID_H264);
|
||||
}
|
||||
|
||||
/* PyAV's single-frame round trip: VideoFrame.from_ndarray(rgb24).reformat("yuv420p") (plain
|
||||
* SWS_BILINEAR, BT.601 coefficients, limited-range output), libx264 with the given crf, then the
|
||||
* decoded frame's to_ndarray("rgb24"), which to_rgb reproduces. */
|
||||
int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why) {
|
||||
std::string w;
|
||||
if (!why) why = &w;
|
||||
const int W = in.w & ~1, H = in.h & ~1;
|
||||
if (W <= 0 || H <= 0) { *why = "the picture is smaller than 2x2"; return RAD_E_INVAL; }
|
||||
const AVCodec* enc = avcodec_find_encoder_by_name("libx264");
|
||||
const AVCodec* dcd = avcodec_find_decoder(AV_CODEC_ID_H264);
|
||||
if (!enc || !dcd) { *why = "this libavcodec has no libx264 encoder or H.264 decoder"; return RAD_E_UNSUPPORTED; }
|
||||
AVCodecContext* ec = avcodec_alloc_context3(enc);
|
||||
AVCodecContext* dc = avcodec_alloc_context3(dcd);
|
||||
AVFrame* yuv = av_frame_alloc();
|
||||
AVFrame* dec = av_frame_alloc();
|
||||
AVPacket* pkt = av_packet_alloc();
|
||||
SwsContext* sws = nullptr;
|
||||
int st = RAD_OK;
|
||||
auto fail = [&](const char* what, int e) {
|
||||
*why = std::string(what) + (e < 0 ? " (" + averr(e) + ")" : std::string());
|
||||
st = e == AVERROR(ENOMEM) ? RAD_E_NOMEM : RAD_E_INVAL;
|
||||
};
|
||||
bool got = false;
|
||||
if (!ec || !dc || !yuv || !dec || !pkt) {
|
||||
*why = "out of memory";
|
||||
st = RAD_E_NOMEM;
|
||||
} else {
|
||||
ec->width = W;
|
||||
ec->height = H;
|
||||
ec->pix_fmt = AV_PIX_FMT_YUV420P;
|
||||
ec->time_base = AVRational{ 1, 1 };
|
||||
ec->framerate = AVRational{ 1, 1 };
|
||||
/* PyAV's codec defaults: as many threads as the machine has, splitting each frame into
|
||||
* that many slices, which shapes the bitstream. */
|
||||
ec->thread_count = 0;
|
||||
ec->thread_type = FF_THREAD_SLICE;
|
||||
av_opt_set(ec->priv_data, "preset", "veryfast", 0);
|
||||
av_opt_set(ec->priv_data, "crf", std::to_string(crf).c_str(), 0);
|
||||
int e = avcodec_open2(ec, enc, nullptr);
|
||||
if (e < 0) fail("opening libx264", e);
|
||||
if (st == RAD_OK && (e = avcodec_open2(dc, dcd, nullptr)) < 0) fail("opening the H.264 decoder", e);
|
||||
if (st == RAD_OK) {
|
||||
yuv->format = AV_PIX_FMT_YUV420P;
|
||||
yuv->width = W;
|
||||
yuv->height = H;
|
||||
if ((e = av_frame_get_buffer(yuv, 0)) < 0) fail("allocating a frame", e);
|
||||
}
|
||||
if (st == RAD_OK) {
|
||||
sws = sws_getContext(W, H, AV_PIX_FMT_RGB24, W, H, AV_PIX_FMT_YUV420P, SWS_BILINEAR,
|
||||
nullptr, nullptr, nullptr);
|
||||
if (!sws) fail("no RGB to yuv420p conversion", 0);
|
||||
}
|
||||
if (st == RAD_OK) {
|
||||
/* The source rows into a padded RGB frame: the scaler reads whole vectors past a tight
|
||||
* row's end. */
|
||||
AVFrame* rgb = av_frame_alloc();
|
||||
if (!rgb) fail("out of memory", AVERROR(ENOMEM));
|
||||
else {
|
||||
rgb->format = AV_PIX_FMT_RGB24;
|
||||
rgb->width = W;
|
||||
rgb->height = H;
|
||||
if ((e = av_frame_get_buffer(rgb, 0)) < 0) fail("allocating a frame", e);
|
||||
else {
|
||||
for (int y = 0; y < H; ++y)
|
||||
std::memcpy(rgb->data[0] + (ptrdiff_t)y * rgb->linesize[0],
|
||||
in.rgb.data() + (size_t)y * in.w * 3, (size_t)W * 3);
|
||||
if (sws_scale(sws, rgb->data, rgb->linesize, 0, H, yuv->data, yuv->linesize) != H)
|
||||
fail("colour conversion failed", 0);
|
||||
}
|
||||
av_frame_free(&rgb);
|
||||
}
|
||||
}
|
||||
/* Encode the frame and flush; every packet goes straight to the decoder. */
|
||||
for (int pass = 0; st == RAD_OK && pass < 2; ++pass) {
|
||||
yuv->pts = 0;
|
||||
if ((e = avcodec_send_frame(ec, pass == 0 ? yuv : nullptr)) < 0) { fail("encoding", e); break; }
|
||||
while (st == RAD_OK && (e = avcodec_receive_packet(ec, pkt)) >= 0) {
|
||||
if ((e = avcodec_send_packet(dc, pkt)) < 0) fail("decoding", e);
|
||||
av_packet_unref(pkt);
|
||||
}
|
||||
if (st == RAD_OK && e != AVERROR(EAGAIN) && e != AVERROR_EOF) fail("encoding", e);
|
||||
}
|
||||
if (st == RAD_OK) avcodec_send_packet(dc, nullptr);
|
||||
while (st == RAD_OK && (e = avcodec_receive_frame(dc, dec)) >= 0) {
|
||||
if (!got) {
|
||||
SwsContext* back = nullptr;
|
||||
st = to_rgb(dec, &back, out, why);
|
||||
sws_freeContext(back);
|
||||
got = st == RAD_OK;
|
||||
}
|
||||
av_frame_unref(dec);
|
||||
}
|
||||
if (st == RAD_OK && !got) fail("the round trip decoded to no frame", 0);
|
||||
}
|
||||
sws_freeContext(sws);
|
||||
av_packet_free(&pkt);
|
||||
av_frame_free(&yuv);
|
||||
av_frame_free(&dec);
|
||||
avcodec_free_context(&ec);
|
||||
avcodec_free_context(&dc);
|
||||
return st;
|
||||
}
|
||||
|
||||
#endif /* RAD_HAVE_FFMPEG */
|
||||
|
||||
} /* namespace mm */
|
||||
|
||||
@@ -77,5 +77,13 @@ int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* use
|
||||
int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_samples,
|
||||
std::vector<float>* out, std::string* why);
|
||||
|
||||
/* `in` encoded as a one-frame H.264 stream at constant quality `crf` (libx264, preset veryfast,
|
||||
* yuv420p) and decoded back, as a video model's reference pipeline does to a conditioning
|
||||
* picture so it carries the compression of the footage the model was trained on. An odd width
|
||||
* or height loses its last column or row first. Needs libx264. */
|
||||
int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why);
|
||||
/* Whether this build can run h264_roundtrip: its libavcodec has libx264. */
|
||||
bool h264_roundtrip_available();
|
||||
|
||||
} /* namespace mm */
|
||||
} /* namespace rad */
|
||||
+10
-3
@@ -376,7 +376,8 @@ public:
|
||||
RadGeneratorDecl generator{};
|
||||
struct GenStrings {
|
||||
std::string name, tmpl_text, tmpl_edit, tmpl_image, tmpl_image_sep, drop_prefix,
|
||||
tmpl_transparent;
|
||||
tmpl_transparent, default_negative;
|
||||
bool has_default_negative = false;
|
||||
std::vector<double> sigmas;
|
||||
} gen_str;
|
||||
bool is_generator() const { return generator.layout != 0; }
|
||||
@@ -392,6 +393,11 @@ public:
|
||||
struct VideoGenStrings {
|
||||
std::string name, tmpl;
|
||||
std::vector<double> rungs; /* RadVideoGenDecl::rungs; the declaration's pointer is null */
|
||||
std::vector<double> refine_rungs;
|
||||
std::string default_negative;
|
||||
/* RadVideoGenDecl::decoders, one name each, and their largest frames (0: max_area). */
|
||||
std::vector<std::string> decoders;
|
||||
std::vector<int64_t> decoder_max_area;
|
||||
} vgen_str;
|
||||
bool is_video_generator() const { return video_gen.max_lanes != 0; }
|
||||
/* Driven by passes, not token steps: any generator. */
|
||||
@@ -740,8 +746,9 @@ struct Config {
|
||||
/* --kv-cache-dtype bf16|fp8|fp8_v4|k6_v4. fp8 is an E4M3 cache with per-(sequence, head)
|
||||
* descales; it halves the per-token cost, most of the KV pool at production context. fp8_v4
|
||||
* keeps K as E4M3 and V as int4 in groups of 32, k6_v4 also K as int6 (RadBuildCtx::kv_quant),
|
||||
* served only where the plugin says so. Each changes the model's output slightly, so it is explicit and bf16 is the
|
||||
* default. No "auto": it would always resolve to bf16 and only add another name. */
|
||||
* served only where the plugin says so. Each changes the model's output slightly, so it is
|
||||
* explicit and bf16 is the default. No "auto": it would always resolve to bf16 and only add
|
||||
* another name. */
|
||||
std::string kv_cache_dtype = "bf16";
|
||||
int64_t host_pool_mib = 0;
|
||||
int64_t host_headroom_mib = 4096; /* --host-headroom-mib: RAM left free for the system at startup */
|
||||
|
||||
@@ -113,8 +113,15 @@ int Ctx::prepare() {
|
||||
RAD_TRY(bind_routing());
|
||||
RAD_TRY(bind_profiling());
|
||||
/* Recorded passes need a recording backend, and are off whenever every issue must be seen:
|
||||
* per-op profile, oracle. */
|
||||
tape_on_ = record_passes_ && tape_supported() && !profiling_ && !oracle_;
|
||||
* per-op profile, oracle, and a calibration tap. A `gram_accum` sums across passes while its
|
||||
* plugin counts the rows it has summed in step and writes the Grams once a token target is
|
||||
* reached; a played pass reissues the accumulation without calling step, so the files would
|
||||
* hold more rows than their header says and be written late. */
|
||||
const bool taps = std::any_of(program_->ops.begin(), program_->ops.end(),
|
||||
[](const OpInfo& o) { return o.op == "gram_accum"; });
|
||||
tape_on_ = record_passes_ && tape_supported() && !profiling_ && !oracle_ && !taps;
|
||||
if (taps && record_passes_ && tape_supported() && rank_ == 0)
|
||||
RAD_INFO("recorded passes: off, the program accumulates calibration Grams (gram_accum)");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
@@ -205,6 +205,8 @@ public:
|
||||
/* ---------------------------------------------------------- run-phase queries */
|
||||
const RadBatch* batch() const { return batch_; }
|
||||
int rank() const { return rank_; }
|
||||
/* Whether repeated passes are recorded and played back (prepare() says when they are not). */
|
||||
bool records_passes() const { return tape_on_; }
|
||||
int world_size() const { return world_size_; }
|
||||
RadStream stream() const { return stream_; }
|
||||
Program* program() const { return program_; }
|
||||
|
||||
+34
-72
@@ -51,19 +51,10 @@ struct SchedMetrics {
|
||||
int64_t step_ns = 0;
|
||||
int64_t step_ns_decode = 0;
|
||||
|
||||
/* The single-sequence decode floor, nanoseconds; 0 until a window of eligible steps fills.
|
||||
* A min over WINDOW MEANS of single-sequence decode steps (see DecodeFloor), not over raw
|
||||
* brackets -- a raw min latches a degenerate bracket forever. Single-sequence on purpose: a
|
||||
* decode step at eight sequences is a different measurement, so keying the floor to one row
|
||||
* keeps a batch arriving from being misread as drift. Scheduler::step_finished feeds DecodeFloor. */
|
||||
/* The single-sequence decode floor and the most recent window, nanoseconds: both window means
|
||||
* of single-sequence decode steps (DecodeFloor), 0 until a gated window completes. A decode
|
||||
* step at more sequences is a different measurement and does not count. */
|
||||
int64_t step_ns_decode_best = 0;
|
||||
|
||||
/* The most recent completed window mean of single-sequence decode steps, nanoseconds; 0 until
|
||||
* the first gated window completes. The advisory's OTHER side: best() is how fast the engine
|
||||
* has ever been, recent() is how fast it is now, and both are window means of the same stream
|
||||
* at the same size -- so they cannot disagree by order statistics the way the engine's floor
|
||||
* disagreed with the browser's per-poll min (7.7% phantom drift on a flat lane, 2026-10-18).
|
||||
* Scheduler::step_finished records it. */
|
||||
int64_t step_ns_decode_recent = 0;
|
||||
|
||||
/* Per KV group. `name` points into the Program, which outlives any scrape. */
|
||||
@@ -147,84 +138,55 @@ struct SchedMetrics {
|
||||
};
|
||||
|
||||
|
||||
/* Estimator for the single-sequence decode floor (SchedMetrics::step_ns_decode_best).
|
||||
*
|
||||
* A min over RAW step brackets is unbounded below: a decode step issued ahead behind a step with
|
||||
* long host work (a prefill chunk, or a decode step that saves a KV checkpoint) has its forward
|
||||
* pass finished before its own bracket opens, so the bracket holds only readback and commit --
|
||||
* about a millisecond, no GPU work. A min latches that degenerate on the first occurrence and
|
||||
* never recovers. Measured live 2026-10-18: floor 1.34 ms against a 15.70 ms mean, after which
|
||||
* the dashboard's restart advice read "heavily drifted, pays back fast" on a healthy engine --
|
||||
* a systematically wrong advisory, worse than none, because it recommends a restart that cannot
|
||||
* help.
|
||||
*
|
||||
* The fix mirrors the construction the dashboard already proves clean on this lane: a min over
|
||||
* WINDOW MEANS, not over raw samples. Each full window of single-sequence decode steps
|
||||
* contributes one mean; a degenerate is diluted by the honest steps sharing its window, so the
|
||||
* floor tracks the real floor. Two biases on that floor partially cancel: a window MEAN sits
|
||||
* above the true floor (it averages, so it cannot reach a lone fast step), while min-over-windows
|
||||
* picks the window with the most degenerates and pulls back down. A simulation of the live lane
|
||||
* (real ~15.9 ms, true floor ~14.4 ms, degenerate ~1.34 ms) puts the estimate at 14.3 ms median
|
||||
* at the observed ~1.4% degenerate rate, worst case ~13.6 ms -- within a few percent of the true
|
||||
* floor, and never the 12x latch of the raw min. The residual can sit slightly BELOW the true
|
||||
* floor (a degenerate-heavy window), which mildly OVER-reports drift; it is bounded and small,
|
||||
* not the unbounded latch. kWindow is a structural count of samples to average, not a magic
|
||||
* threshold a real step could fall below. Scheduler::step_finished feeds it one update per
|
||||
* single-sequence decode step. */
|
||||
/* Estimator for the single-sequence decode floor (SchedMetrics::step_ns_decode_best): a min over
|
||||
* window means, not over raw step brackets. A decode step issued ahead behind a step with long
|
||||
* host work (a prefill chunk, a KV checkpoint save) has its forward pass finished before its own
|
||||
* bracket opens, so the bracket holds only readback and commit, about a tenth of a real step; a
|
||||
* raw min would latch that forever. Such brackets are rejected before they enter a window, and the
|
||||
* window mean dilutes what remains. */
|
||||
struct DecodeFloor {
|
||||
/* Single-sequence decode steps averaged into one floor candidate. 32 approximates the number
|
||||
* of decode steps the dashboard's 500 ms poll spans at this lane's step time, so the engine
|
||||
* floor and the page's own c1 floor are computed over comparable windows. */
|
||||
/* Steps averaged into one floor candidate: about what the dashboard's 500 ms poll spans at a
|
||||
* single-sequence step, so the engine's floor and the page's are over comparable windows. */
|
||||
static constexpr int kWindow = 32;
|
||||
static constexpr int64_t kHorizon = 8 * kWindow;
|
||||
|
||||
void update(int64_t ns) {
|
||||
/* Reject degenerate brackets BEFORE they enter a window. A decode step issued ahead behind
|
||||
* a long host commit (a prefill chunk, or a KV checkpoint every 256 tokens) brackets at
|
||||
* ~9% of a real step; real single-sequence steps bracket at ~96%. The populations are ~10x
|
||||
* apart, so any threshold between them separates them -- 0.5 is the midpoint of that gap,
|
||||
* not a value tuned to one distribution. Filtering at the STEP level is essential: at the
|
||||
* observed ~1.4% rate a degenerate dilutes inside a 32-step window to a mean of ~0.91x,
|
||||
* which no window-level threshold would catch, and a min over hundreds of windows then
|
||||
* reliably lands on a degenerate-heavy window ~10% below the true floor.
|
||||
* No rejection until a window's worth of samples has been accepted, so the running mean is
|
||||
* never bootstrapped from a degenerate. */
|
||||
if (accepted_ >= kWindow && ns * 2 < mean_) return;
|
||||
++accepted_;
|
||||
mean_ += (ns - mean_) / (double)accepted_;
|
||||
/* A degenerate bracket is ~0.09 of a real step and a real one ~0.96 of the mean, so half
|
||||
* the reference separates them. The reference is a running mean over every step, the
|
||||
* rejected ones included, with a horizon of kHorizon steps: degenerates are rare enough to
|
||||
* barely move it, and when the real step gets faster (a slow warm-up, a shorter context)
|
||||
* it follows instead of rejecting every later step. No rejection until a window's worth
|
||||
* of samples has been seen. */
|
||||
++seen_;
|
||||
mean_ += (ns - mean_) / (double)(seen_ < kHorizon ? seen_ : kHorizon);
|
||||
if (seen_ > kWindow && ns * 2 < mean_) return;
|
||||
sum_ += ns;
|
||||
if (++count_ < kWindow) return;
|
||||
const int64_t mean = sum_ / count_;
|
||||
/* The FIRST window is recorded by neither side. The rejection gate needs a window's worth
|
||||
* of accepted samples before it can judge one, so the first window is by construction
|
||||
* un-gated and can carry degenerates; recording it would let the floor latch a value the
|
||||
* engine can no longer reach -- the same artifact the gate exists to remove, smuggled in
|
||||
* through bootstrap. Measured: at a 5% degenerate rate the un-gated first window put the
|
||||
* floor ~2% below the true floor and it stuck there forever. */
|
||||
/* The first window ran before the gate could judge and may carry degenerates, so it is
|
||||
* recorded by neither side. */
|
||||
if (warmed_) {
|
||||
if (best_ == 0 || mean < best_) best_ = mean;
|
||||
recent_ = mean; /* most recent completed window, same size as best_ */
|
||||
recent_ = mean;
|
||||
}
|
||||
warmed_ = true;
|
||||
sum_ = 0;
|
||||
count_ = 0;
|
||||
}
|
||||
/* The floor: the fastest window mean ever seen. A restart is priced against this. */
|
||||
/* The fastest window mean seen. */
|
||||
int64_t best() const { return best_; }
|
||||
/* The CURRENT speed: the most recent completed window mean, from the SAME stream and window
|
||||
* size as best(). The advisory compares best() against recent() -- both window means of one
|
||||
* population -- so the two sides cannot disagree by order statistics the way the engine's
|
||||
* floor disagreed with the browser's per-poll min (a 7.7% phantom gap on a flat lane,
|
||||
* 2026-10-18). 0 until the first window completes; the page must not divide by it. */
|
||||
/* The most recent completed window mean, from the same stream and window size as best();
|
||||
* 0 until the first gated window completes. */
|
||||
int64_t recent() const { return recent_; }
|
||||
|
||||
private:
|
||||
int64_t sum_ = 0;
|
||||
int count_ = 0; /* samples in the window being accumulated */
|
||||
int64_t best_ = 0;
|
||||
int64_t recent_ = 0;
|
||||
bool warmed_ = 0; /* false until one window has completed (the un-gated bootstrap) */
|
||||
int64_t accepted_ = 0; /* samples accepted across all windows (rejection gate's support) */
|
||||
double mean_ = 0.0; /* running mean of ACCEPTED steps -- the rejection reference */
|
||||
int64_t sum_ = 0;
|
||||
int count_ = 0; /* samples in the window being accumulated */
|
||||
int64_t best_ = 0;
|
||||
int64_t recent_ = 0;
|
||||
bool warmed_ = false; /* one window has completed */
|
||||
int64_t seen_ = 0; /* samples seen, rejected ones included */
|
||||
double mean_ = 0.0; /* the rejection reference */
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -1599,7 +1599,10 @@ const RadBatch* Scheduler::step() {
|
||||
/* ------------------------------------------------------------------ media */
|
||||
bool Scheduler::prefill_continues() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (stage_rows_ <= 0) return false;
|
||||
/* Only the step being released has a plan to read. Between a commit and the next step (an
|
||||
* encoder pass is prepared there) `plan_` is the committed step's, whose requests in_step() no
|
||||
* longer holds: a cancel and reap may have released one (#127). */
|
||||
if (stage_rows_ <= 0 || !step_open_) return false;
|
||||
/* The next step is held to decode rows (--prefill-interleave): experts staged for a chunk now
|
||||
* would be dropped by that step. */
|
||||
if (interleave_left_ > 0) return false;
|
||||
@@ -2010,13 +2013,8 @@ void Scheduler::step_finished() {
|
||||
m_.step_ns += ns;
|
||||
if (plan_.phase == RAD_PHASE_DECODE) {
|
||||
m_.step_ns_decode += ns;
|
||||
/* The single-sequence floor, keyed to the concurrency of THIS step (plan_.n_seq_decode is
|
||||
* the row count that was just timed, not a later snapshot). A mixed step is excluded by the
|
||||
* phase gate even when it carries one decode row: its lone row shares the step with a
|
||||
* prefill chunk and is not the mechanical floor. The estimator is a min over WINDOW MEANS,
|
||||
* not raw brackets: a decode step issued ahead behind a long host commit has no GPU work
|
||||
* in its bracket, and a raw min latches that degenerate forever; averaging a window of
|
||||
* single-row steps first dilutes it. See rad::DecodeFloor. */
|
||||
/* The single-sequence floor over the step just timed (rad::DecodeFloor). A mixed step
|
||||
* never counts: its decode row shares the step with a prefill chunk. */
|
||||
if (plan_.n_seq_decode == 1) {
|
||||
decode_floor_.update(ns);
|
||||
m_.step_ns_decode_best = decode_floor_.best();
|
||||
|
||||
@@ -604,9 +604,7 @@ private:
|
||||
* covered, both decayed with the same time constant, so their ratio is tokens over time. */
|
||||
double tps_win_prefill_ = 0.0, tps_win_decode_ = 0.0, tps_win_time_ = 0.0;
|
||||
bool step_open_ = false;
|
||||
/* Estimator for the single-sequence decode floor (see rad::DecodeFloor). Replaces a raw min
|
||||
* over step brackets, which latched a degenerate bracket forever (live defect 2026-10-18:
|
||||
* 1.16 ms against a 15.55 ms mean). step_finished feeds it each single-sequence decode step. */
|
||||
/* The single-sequence decode floor (rad::DecodeFloor), fed by step_finished. */
|
||||
DecodeFloor decode_floor_;
|
||||
|
||||
/* arrival; mu_ held */
|
||||
|
||||
+19
-68
@@ -125,10 +125,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
|
||||
o["model"] = opt_.model_id;
|
||||
o["version"] = opt_.version;
|
||||
o["uptime_s"] = unix_now() - started_at_;
|
||||
/* How long this process took to come up, measured on this machine. Raw figure: a restart's
|
||||
* real cost, for whoever is deciding whether one is worth it. 0 before the server listens.
|
||||
* The page no longer consumes it -- see the note on the decode-step detail line for why the
|
||||
* payback arithmetic that used to live there was removed. */
|
||||
/* Seconds this process took to come up, the cost of a restart; 0 before the server listens. */
|
||||
o["startup_s"] = startup_s_;
|
||||
o["in_flight"] = in_flight_.load(std::memory_order_relaxed);
|
||||
o["queue_cap"] = queue_depth_;
|
||||
@@ -1363,31 +1360,18 @@ for (const k of METRICS) {
|
||||
* is for is the variation, and the number above it already states the level -- scaled from zero
|
||||
* every steady state is a flat line on the floor. No variation draws down the middle.
|
||||
*
|
||||
* THE ENDS OF THAT RANGE ARE PERCENTILES, not the extremes. On a min/max axis one rare spike
|
||||
* owns the whole box and the typical variation is squeezed into a couple of pixels: measured over
|
||||
* real /stats samples, prefill sits at zero on a third of polls and spikes past 4,000 on the rest,
|
||||
* which leaves its middle band 0.1px of the 15px available -- a flat line for a metric that is
|
||||
* anything but. Taking the 5th and 95th percentiles and clamping to them gives the ordinary
|
||||
* movement the height it was being denied (the same samples' middle band rises 1.2x to 3.9x
|
||||
* depending on the metric). The cost is stated rather than hidden: a spike beyond the 95th now
|
||||
* draws pinned to the top of the box instead of towering over the line, so the box shows how the
|
||||
* metric has been behaving and not how bad its worst poll was. The number above still carries the
|
||||
* level, and the detail line still carries the extremes.
|
||||
*
|
||||
* THE INSET IS ONE UNIT, not two and three. The stroke is 1.25 units wide, so a half-unit of
|
||||
* clearance keeps it off the edge of the box; the extra it used to leave was a fifth of the
|
||||
* height spent on nothing, and on a 17px box that is the difference between a line that moves
|
||||
* and one that merely shifts. */
|
||||
* The ends of the range are the 5th and 95th percentiles, not the extremes: on a min/max axis one
|
||||
* rare spike owns the box and the typical variation is squeezed into a pixel. A spike past the
|
||||
* 95th draws pinned to the top; the number above carries the level and the detail line the
|
||||
* extremes. The stroke is 1.25 units wide, so a one-unit inset keeps it off the edge. */
|
||||
function spark(key, vals) {
|
||||
const s = M[key], w = 200, h = 22;
|
||||
if (vals.length < 3) { s.line.setAttribute("d", ""); return; }
|
||||
const q = (sorted, p) => sorted[Math.min(sorted.length - 1, Math.floor(p * (sorted.length - 1)))];
|
||||
const sorted = [...vals].sort((a, b) => a - b);
|
||||
let lo = q(sorted, 0.05), hi = q(sorted, 0.95);
|
||||
/* WHEN THE PERCENTILES COLLAPSE, fall back to the extremes. If nine tenths of the window holds
|
||||
* one value, the 5th and 95th land on it and carry nothing -- and a metric that is constant
|
||||
* apart from rare spikes has those spikes as its ONLY news, so pinning them outside the axis
|
||||
* would draw a flat line where the old axis at least showed them. */
|
||||
/* A window that is one value apart from rare spikes puts both percentiles on that value; the
|
||||
* extremes then serve, so the spikes still show. */
|
||||
if (!(hi > lo)) { lo = sorted[0]; hi = sorted[sorted.length - 1]; }
|
||||
const span = hi - lo;
|
||||
const dx = w / (vals.length - 1);
|
||||
@@ -1686,35 +1670,16 @@ function renderRequests(list, poolTokens) {
|
||||
let prev = null, prevAt = 0, bars = [], devs = [], layerBars = [];
|
||||
let lastStepMs = null, lastTps = null;
|
||||
|
||||
/* THE SINGLE-STREAM FLOOR and the engine's most recent window, shown as two numbers and
|
||||
* interpreted by nobody. The engine records the fastest single-sequence decode window it has
|
||||
* measured (step_ns_decode_best) and its most recent one (step_ns_decode_recent); the page states
|
||||
* both and draws no conclusion. Neither is asked of a human: a typed ruler goes stale and
|
||||
* mis-advises silently, and a browser meter sees only the steps taken while this tab is open. On
|
||||
* an engine too old to emit the floor, the page falls back to the fastest single-stream step this
|
||||
* tab has seen.
|
||||
*
|
||||
* THERE IS DELIBERATELY NO RESTART ADVICE HERE, and it was not never-built -- it was built,
|
||||
* deployed, measured, and removed the same day (2026-10-18). It compared the floor against the
|
||||
* recent window, called the gap drift, and priced a payback from startup_s. The gap is not drift.
|
||||
* On a HEALTHY shared lane the floor sat flat at 14.79 ms while the recent window moved between
|
||||
* 15.2 and 16.5 ms -- 3% to 11% -- tracking what else the lane was doing: it froze when the lane
|
||||
* went idle and ROSE on a fresh short request, so it was neither context length nor engine age.
|
||||
* The payback formula assumes a restart's improvement is permanent, so acting on it pays the 49 s
|
||||
* bringup and re-drifts within minutes; the line was telling the operator to restart every 12-19
|
||||
* minutes forever, for a gain that was never there. What best-vs-recent actually measures is the
|
||||
* distance between the lane's most favorable moment and its typical one.
|
||||
*
|
||||
* A verdict could go back here IF someone first observes the thing none of today's data shows:
|
||||
* step time rising with ENGINE AGE and STAYING up. Every excursion seen so far was load. The
|
||||
* full chain, including the estimator that survives this, is in patches/CHANGELOG-SOURCE.md. */
|
||||
/* The single-stream floor and the engine's most recent window, shown as two numbers with no
|
||||
* verdict. The engine records the fastest single-sequence decode window it has measured
|
||||
* (step_ns_decode_best) and its most recent one (step_ns_decode_recent). Their gap is not engine
|
||||
* drift: on a healthy lane the recent window moves 3-11% above a flat floor with whatever else the
|
||||
* lane is doing, so a restart priced against it would not pay back. Until the engine's first
|
||||
* window completes, the fastest single-stream step this tab has seen stands in. */
|
||||
let c1hist = [];
|
||||
const C1CAP = 7200; /* an hour at 2 polls/s of single-stream samples */
|
||||
let bestEver = 0; /* the best engine floor ever seen here, across restarts */
|
||||
try { bestEver = parseFloat(localStorage.getItem("radiance.c1best")) || 0; } catch (e) {}
|
||||
const bestAt = {}; /* fastest step seen at each concurrency, this process */
|
||||
|
||||
|
||||
function update(s, dt) {
|
||||
$("ver").textContent = s.version + " · up " + dur(s.uptime_s);
|
||||
|
||||
@@ -1734,35 +1699,21 @@ function update(s, dt) {
|
||||
M.step.u.textContent = st.u;
|
||||
setMetric("step", lastStepMs, st.n);
|
||||
|
||||
/* THE FLOOR, single-stream on both sides of the engine's own measurement. The floor is a
|
||||
* single-sequence window, so the engine keys it to one row deliberately: a decode step at eight
|
||||
* sequences is a different measurement, and reading it against a single-sequence floor would
|
||||
* report a batch arriving as a slowdown. */
|
||||
/* Single-stream steps only: the floor is a single-sequence window, and a batched step read
|
||||
* against it would report a batch arriving as a slowdown. */
|
||||
if (s.running === 1 && stepMs != null) { c1hist.push(stepMs); if (c1hist.length > C1CAP) c1hist.shift(); }
|
||||
const engBestMs = s.step_ns_decode_best > 0 ? s.step_ns_decode_best / 1e6 : 0;
|
||||
const engRecentMs = s.step_ns_decode_recent > 0 ? s.step_ns_decode_recent / 1e6 : 0;
|
||||
if (engBestMs > 0 && (bestEver === 0 || engBestMs < bestEver)) {
|
||||
bestEver = engBestMs;
|
||||
try { localStorage.setItem("radiance.c1best", String(bestEver)); } catch (e) {}
|
||||
}
|
||||
const floorMs = engBestMs > 0 ? engBestMs : (c1hist.length ? Math.min(...c1hist) : 0);
|
||||
/* The two engine figures, stated plainly. Painted every poll: without a verdict there is
|
||||
* nothing for a fast repaint to make unactionable, and `recent` only moves when a window of 32
|
||||
* single-sequence steps completes anyway. */
|
||||
let det = "";
|
||||
if (floorMs > 0) {
|
||||
det = "best " + floorMs.toFixed(2) + "ms";
|
||||
if (engRecentMs > 0) det += " · recent " + engRecentMs.toFixed(2) + "ms";
|
||||
}
|
||||
/* THE STEP AS A PERCENTAGE OF THE FASTEST THIS PROCESS HAS DONE AT THIS CONCURRENCY: ~99% is the fastest the lane has done, anything slower a percentage of it. Keyed by
|
||||
* concurrency on purpose: a c8 step read against the single-stream floor would report the batch
|
||||
* arriving as a slowdown -- the mistake that took the old drift line out. Raw ratio, no
|
||||
* threshold, no colour: the number is the statement. Capped at ~99 (shown with a tilde): `now` is a ~500 ms poll mean while
|
||||
* `best` is a 32-step window mean, so a fast stretch shorter than a window can read faster than the
|
||||
* recorded floor. That is "at your best", not a new record -- the engine only ratchets the floor on a
|
||||
* completed 32-step window, and a sub-window blip is not one. The cap is 99, not 100: a 500 ms window that briefly beats the
|
||||
* floor is not a sustained record, and 100% would claim a floor the window cannot confirm -- it
|
||||
* would read as a bug. ~99% says "at your best" without overclaiming. */
|
||||
/* The step as a percentage of the fastest at this concurrency (`@cN` above one). `now` is a
|
||||
* ~500 ms poll mean and `best` a 32-step window mean, so a short fast stretch can beat the
|
||||
* floor; the figure is capped at 99 and shown as ~99, "at the best", rather than claiming a
|
||||
* record the window cannot confirm. */
|
||||
if (s.running > 0 && lastStepMs != null) {
|
||||
const k = s.running;
|
||||
if (!(k in bestAt) || lastStepMs < bestAt[k]) bestAt[k] = lastStepMs;
|
||||
|
||||
+29
-4
@@ -127,11 +127,8 @@ struct SchedMetrics {
|
||||
* a decode step regardless of load. */
|
||||
int64_t step_ns = 0;
|
||||
int64_t step_ns_decode = 0;
|
||||
/* The fastest single-sequence decode step this process has measured, nanoseconds; 0 until one
|
||||
* runs. The dashboard reads this instead of asking a human to type a ruler (see the same field
|
||||
* on rad::SchedMetrics, where it is recorded). */
|
||||
/* The single-sequence decode floor and most recent window (rad::SchedMetrics). */
|
||||
int64_t step_ns_decode_best = 0;
|
||||
/* The most recent completed single-sequence decode window mean; see SchedMetrics. */
|
||||
int64_t step_ns_decode_recent = 0;
|
||||
};
|
||||
|
||||
@@ -589,7 +586,19 @@ struct ImageGenInfo {
|
||||
/* The model samples on a schedule of its own and takes no step count (a distilled model). */
|
||||
bool fixed_schedule = false;
|
||||
int64_t fixed_steps = 0;
|
||||
/* Guidance in the model card's terms: with `cfg_original` the scale s means cond + s (cond -
|
||||
* uncond), off at 0, and the core runs s + 1; otherwise uncond + s (cond - uncond), off at 1. */
|
||||
double default_cfg = 1.0;
|
||||
bool cfg_original = false;
|
||||
/* The negative prompt a guided request gets when it names none; without one it must. */
|
||||
bool has_default_negative = false;
|
||||
std::string default_negative;
|
||||
/* The pictures are not read by the conditioning network: they go to the generator's own
|
||||
* encoder only (RAD_GEN_LAYOUT_JOINT_STEP). */
|
||||
bool refs_encoder_only = false;
|
||||
/* A reference picture is shrunk to `ref_area` only when larger, then centre-cropped to the
|
||||
* size multiple; otherwise resized to `ref_area` at its aspect. */
|
||||
bool ref_shrink_only = false;
|
||||
};
|
||||
|
||||
class IImageGen {
|
||||
@@ -650,6 +659,22 @@ struct VideoGenInfo {
|
||||
/* A latent upscaler: the largest factor (0: none) and the full-size evaluations by default. */
|
||||
double upscale_max = 0.0;
|
||||
int64_t upscale_refine = 0;
|
||||
/* `steps` counts model evaluations rather than sigma grid points (RadVideoGenDecl form 1). */
|
||||
bool step_evals = false;
|
||||
/* Guidance (RadVideoGenDecl::guidance): the terms a request may name, their defaults and the
|
||||
* negative prompt a guided request gets when it names none. */
|
||||
bool guidance = false;
|
||||
double guidance_default[8] = {};
|
||||
std::string default_negative;
|
||||
/* Image to video: a first frame is taken, after an H.264 round trip at image_crf when > 0. */
|
||||
bool image_cond = false;
|
||||
int32_t image_crf = 0;
|
||||
/* A length head: a request that names no length gets the one the model predicts. */
|
||||
bool length_head = false;
|
||||
/* The decoders a request may name, the default first, and each one's largest frame in pixels
|
||||
* (RadVideoGenDecl::decoders); empty for a model with one. */
|
||||
std::vector<std::string> decoders;
|
||||
std::vector<int64_t> decoder_max_area;
|
||||
};
|
||||
|
||||
class IVideoGen {
|
||||
|
||||
+92
-31
@@ -9,8 +9,10 @@
|
||||
* repainted where the mask is transparent; the rest is restored exactly after decoding.
|
||||
*
|
||||
* Extensions, under vLLM-Omni's names: `seed`, `negative_prompt` with `true_cfg_scale`
|
||||
* (guidance), `num_inference_steps`, and `width` / `height` instead of `size`. A fixed-schedule
|
||||
* (distilled) model accepts only its own step count.
|
||||
* (guidance, in the model card's terms; `guidance_scale` is the same field under diffusers' name),
|
||||
* `num_inference_steps`, and `width` / `height` instead of `size`. A fixed-schedule (distilled)
|
||||
* model accepts only its own step count. A model whose card guides by default does so with its
|
||||
* own negative prompt unless the request names one or turns guidance off.
|
||||
*
|
||||
* Refused: `response_format: url`, since no image is stored to serve later; only b64_json.
|
||||
*
|
||||
@@ -77,7 +79,7 @@ json form_value(const std::string& key, const std::string& v) {
|
||||
if (e && *e == 0 && !v.empty()) return json(x);
|
||||
return json(v);
|
||||
}
|
||||
if (key == "true_cfg_scale") {
|
||||
if (key == "true_cfg_scale" || key == "guidance_scale") {
|
||||
char* e = nullptr;
|
||||
const double x = std::strtod(v.c_str(), &e);
|
||||
if (e && *e == 0 && !v.empty()) return json(x);
|
||||
@@ -107,18 +109,34 @@ std::string replace_all(std::string s, const std::string& what, const std::strin
|
||||
}
|
||||
|
||||
/* A picture as the generator's encoder reads it: each channel u -> 2 * (u / 255) - 1 in f32, then
|
||||
* bf16 (VaeImageProcessor's preprocess, cast to the VAE's dtype). */
|
||||
gen::Pixels to_pixels(const mm::FrameRGBA& f) {
|
||||
* bf16 (VaeImageProcessor's preprocess, cast to the VAE's dtype). An RGB model reads the colour
|
||||
* channels and not the alpha, as PIL's convert("RGB") drops it. */
|
||||
gen::Pixels to_pixels(const mm::FrameRGBA& f, int ch) {
|
||||
gen::Pixels p;
|
||||
p.w = f.w;
|
||||
p.h = f.h;
|
||||
p.ch = 4;
|
||||
p.bf16.resize(f.rgba.size());
|
||||
for (size_t i = 0; i < f.rgba.size(); ++i)
|
||||
p.bf16[i] = rad_f32_to_bf16(2.0f * ((float)f.rgba[i] / 255.0f) - 1.0f);
|
||||
p.ch = ch;
|
||||
p.bf16.resize((size_t)f.w * f.h * ch);
|
||||
for (size_t px = 0; px < (size_t)f.w * f.h; ++px)
|
||||
for (int c = 0; c < ch; ++c)
|
||||
p.bf16[px * ch + c] =
|
||||
rad_f32_to_bf16(2.0f * ((float)f.rgba[px * 4 + c] / 255.0f) - 1.0f);
|
||||
return p;
|
||||
}
|
||||
|
||||
/* The centred w x h window of a picture (diffusers' resize_mode "crop" after its resize). */
|
||||
mm::FrameRGBA crop_centre(const mm::FrameRGBA& f, int32_t w, int32_t h) {
|
||||
mm::FrameRGBA o;
|
||||
o.w = w;
|
||||
o.h = h;
|
||||
o.rgba.resize((size_t)w * h * 4);
|
||||
const int32_t x0 = (f.w - w) / 2, y0 = (f.h - h) / 2;
|
||||
for (int32_t y = 0; y < h; ++y)
|
||||
std::memcpy(&o.rgba[(size_t)y * w * 4], &f.rgba[((size_t)(y0 + y) * f.w + x0) * 4],
|
||||
(size_t)w * 4);
|
||||
return o;
|
||||
}
|
||||
|
||||
/* The decoded RGBA flattened on white (no alpha), for a jpeg or an opaque background. */
|
||||
std::vector<uint8_t> on_white(const std::vector<uint8_t>& rgba, int32_t w, int32_t h) {
|
||||
mm::FrameRGBA f;
|
||||
@@ -216,6 +234,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
"prompt", "model", "n", "size", "quality", "background", "output_format",
|
||||
"output_compression", "response_format", "stream", "partial_images", "moderation",
|
||||
"style", "user", "input_fidelity", "seed", "negative_prompt", "true_cfg_scale",
|
||||
"guidance_scale",
|
||||
"num_inference_steps", "width", "height",
|
||||
};
|
||||
for (auto it = body.begin(); it != body.end(); ++it) {
|
||||
@@ -274,6 +293,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
if (r.background == "transparent" && r.format == "jpeg")
|
||||
return error_response(err_bad("background", "jpeg has no transparency; ask for png or "
|
||||
"webp"), req.peer);
|
||||
if (r.background == "transparent" && info.pixel_channels < 4)
|
||||
return error_response(err_bad("background", "this model makes opaque images"), req.peer);
|
||||
if (num("output_compression", 0, 100, &v) < 0)
|
||||
return error_response(err_bad("output_compression", "expected an integer in 0..100"),
|
||||
req.peer);
|
||||
@@ -323,21 +344,35 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
}
|
||||
if (str("negative_prompt", &r.negative) < 0)
|
||||
return error_response(err_bad("negative_prompt", "expected a string"), req.peer);
|
||||
if (body.contains("true_cfg_scale") && !body["true_cfg_scale"].is_null()) {
|
||||
if (!body["true_cfg_scale"].is_number())
|
||||
return error_response(err_bad("true_cfg_scale", "expected a number"), req.peer);
|
||||
r.cfg = body["true_cfg_scale"].get<double>();
|
||||
if (!(r.cfg >= 1.0 && r.cfg <= 30.0))
|
||||
return error_response(err_bad("true_cfg_scale", "expected a number in 1..30"),
|
||||
req.peer);
|
||||
/* The scale in the model card's terms: off at 0 for a card that states it as
|
||||
* cond + s (cond - uncond), at 1 for uncond + s (cond - uncond). */
|
||||
const double cfg_off = info.cfg_original ? 0.0 : 1.0;
|
||||
const char* cfg_key = body.contains("guidance_scale") && !body["guidance_scale"].is_null()
|
||||
? "guidance_scale" : "true_cfg_scale";
|
||||
const bool cfg_given = body.contains(cfg_key) && !body[cfg_key].is_null();
|
||||
if (cfg_given && body.contains("true_cfg_scale") && body.contains("guidance_scale") &&
|
||||
!body["true_cfg_scale"].is_null())
|
||||
return error_response(err_bad("guidance_scale", "true_cfg_scale and guidance_scale are "
|
||||
"the same field; name one"), req.peer);
|
||||
r.cfg = info.default_cfg;
|
||||
if (cfg_given) {
|
||||
if (!body[cfg_key].is_number())
|
||||
return error_response(err_bad(cfg_key, "expected a number"), req.peer);
|
||||
r.cfg = body[cfg_key].get<double>();
|
||||
if (!(r.cfg >= cfg_off && r.cfg <= 30.0))
|
||||
return error_response(err_bad(cfg_key, "expected a number in " +
|
||||
std::string(cfg_off > 0 ? "1" : "0") +
|
||||
"..30"), req.peer);
|
||||
}
|
||||
/* Guidance needs a scale above one and a negative prompt (empty becomes " "), as in the
|
||||
* reference pipeline. */
|
||||
r.has_neg = r.cfg > 1.0 && body.contains("negative_prompt");
|
||||
if (r.has_neg && r.negative.empty()) r.negative = " ";
|
||||
if (r.cfg > 1.0 && !r.has_neg)
|
||||
return error_response(err_bad("true_cfg_scale", "guidance needs a negative_prompt"),
|
||||
req.peer);
|
||||
/* Guidance needs a scale past its off value and a negative prompt: the request's (empty
|
||||
* becomes " ", as in the reference pipeline), or the model's own. */
|
||||
const bool guided = r.cfg > cfg_off;
|
||||
const bool named_neg = body.contains("negative_prompt") && !body["negative_prompt"].is_null();
|
||||
r.has_neg = guided && (named_neg || info.has_default_negative);
|
||||
if (r.has_neg && !named_neg) r.negative = info.default_negative;
|
||||
else if (r.has_neg && r.negative.empty()) r.negative = " ";
|
||||
if (guided && !r.has_neg)
|
||||
return error_response(err_bad(cfg_key, "guidance needs a negative_prompt"), req.peer);
|
||||
|
||||
/* ---- the pictures */
|
||||
if (edit) {
|
||||
@@ -372,7 +407,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
* image generated without transparency has only decoder noise in its alpha. */
|
||||
if (r.background == "auto") {
|
||||
bool alpha = false;
|
||||
if (r.format != "jpeg")
|
||||
if (r.format != "jpeg" && info.pixel_channels >= 4)
|
||||
for (const mm::FrameRGBA& f : r.images)
|
||||
for (size_t i = 3; i < f.rgba.size() && !alpha; i += 4)
|
||||
alpha = f.rgba[i] < kTransparentBelow;
|
||||
@@ -437,17 +472,40 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
g->steps = r.steps;
|
||||
g->seed = r.seed;
|
||||
g->previews = r.previews;
|
||||
g->cfg = (float)r.cfg;
|
||||
/* The driver guides as uncond + cfg (cond - uncond); a card's cond + s (cond - uncond) is
|
||||
* that at s + 1. */
|
||||
g->cfg = (float)(info.cfg_original ? r.cfg + 1.0 : r.cfg);
|
||||
g->has_neg = r.has_neg;
|
||||
g->ticket = std::make_shared<gen::Ticket>();
|
||||
|
||||
std::vector<std::shared_ptr<mm::Item>> items;
|
||||
const int pch = (int)info.pixel_channels;
|
||||
for (const mm::FrameRGBA& f : r.images) {
|
||||
int32_t rw = 0, rh = 0;
|
||||
dims_for((double)info.ref_area, (double)f.w / (double)f.h, mult, &rw, &rh);
|
||||
mm::FrameRGBA rs;
|
||||
mm::resize_lanczos_rgba(f, rw, rh, &rs);
|
||||
g->refs.push_back(to_pixels(rs));
|
||||
if (info.ref_shrink_only) {
|
||||
/* Shrunk to the reference area only when larger, then cut to the size multiple. */
|
||||
const double area = (double)f.w * f.h;
|
||||
if (area > (double)info.ref_area) {
|
||||
const double k = std::sqrt((double)info.ref_area / area);
|
||||
rw = std::max<int32_t>(1, (int32_t)(f.w * k));
|
||||
rh = std::max<int32_t>(1, (int32_t)(f.h * k));
|
||||
mm::resize_lanczos_rgba(f, rw, rh, &rs);
|
||||
} else {
|
||||
rs = f;
|
||||
}
|
||||
const int32_t cw = rs.w / mult * mult, ch = rs.h / mult * mult;
|
||||
if (cw <= 0 || ch <= 0)
|
||||
return error_response(err_bad("image", "a picture must be at least " +
|
||||
std::to_string(mult) + " pixels a side"),
|
||||
req.peer);
|
||||
if (cw != rs.w || ch != rs.h) rs = crop_centre(rs, cw, ch);
|
||||
} else {
|
||||
dims_for((double)info.ref_area, (double)f.w / (double)f.h, mult, &rw, &rh);
|
||||
mm::resize_lanczos_rgba(f, rw, rh, &rs);
|
||||
}
|
||||
g->refs.push_back(to_pixels(rs, pch));
|
||||
if (info.refs_encoder_only) continue;
|
||||
mm::Frame rgb;
|
||||
mm::composite_white(rs, &rgb);
|
||||
std::shared_ptr<mm::Item> it;
|
||||
@@ -465,7 +523,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
mm::resize_lanczos_rgba(r.images[0], r.w, r.h, &src);
|
||||
mm::resize_lanczos_rgba(r.mask, r.w, r.h, &msk);
|
||||
g->inpaint = true;
|
||||
g->inp_src = to_pixels(src);
|
||||
g->inp_src = to_pixels(src, pch);
|
||||
const int32_t lw = r.w / (int32_t)ls, lh = r.h / (int32_t)ls;
|
||||
g->inp_mask.assign((size_t)lw * lh, 0.0f);
|
||||
keep_px.assign((size_t)r.w * r.h, 0);
|
||||
@@ -567,12 +625,15 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
auto encode = [fmt, comp, keep_px, src_px, flatten](gen::Image& im, std::string* b64,
|
||||
std::string* why) -> int {
|
||||
std::vector<uint8_t>& px = im.px;
|
||||
const size_t ch = (size_t)im.ch;
|
||||
if (!keep_px.empty() && !im.preview)
|
||||
for (size_t i = 0; i < keep_px.size(); ++i)
|
||||
if (keep_px[i]) std::memcpy(&px[i * 4], &src_px[i * 4], 4);
|
||||
if (keep_px[i]) std::memcpy(&px[i * ch], &src_px[i * 4], ch);
|
||||
std::vector<uint8_t> file;
|
||||
int s;
|
||||
if (flatten) {
|
||||
if (ch == 3) {
|
||||
s = mm::encode_image(px.data(), im.w, im.h, 3, fmt, comp, &file, why);
|
||||
} else if (flatten) {
|
||||
const std::vector<uint8_t> rgb = on_white(px, im.w, im.h);
|
||||
s = mm::encode_image(rgb.data(), im.w, im.h, 3, fmt, comp, &file, why);
|
||||
} else {
|
||||
|
||||
+77
-20
@@ -13,6 +13,7 @@
|
||||
#include <ctime>
|
||||
#include <limits>
|
||||
#include <random>
|
||||
#include <set>
|
||||
#include <type_traits>
|
||||
|
||||
namespace rad {
|
||||
@@ -3854,9 +3855,17 @@ json message_item(const std::string& id, const std::string& text, const char* st
|
||||
{ "content", text.empty() && std::strcmp(status, "in_progress") == 0
|
||||
? json::array() : json::array({ text_part(text) }) } };
|
||||
}
|
||||
json call_item(const ToolCall& tc, const char* status) {
|
||||
return json{ { "id", fc_id(tc.id) }, { "type", "function_call" }, { "call_id", tc.id },
|
||||
{ "name", tc.name }, { "arguments", tc.arguments }, { "status", status } };
|
||||
/* A call to a flattened namespace tool reports its namespace and its own name apart, as the
|
||||
* Responses API's function_call item does. */
|
||||
json call_item(const OaiRequest& r, const ToolCall& tc, const char* status) {
|
||||
json it = { { "id", fc_id(tc.id) }, { "type", "function_call" }, { "call_id", tc.id },
|
||||
{ "name", tc.name }, { "arguments", tc.arguments }, { "status", status } };
|
||||
auto ns = r.tool_namespace.find(tc.name);
|
||||
if (ns != r.tool_namespace.end()) {
|
||||
it["namespace"] = ns->second.first;
|
||||
it["name"] = ns->second.second;
|
||||
}
|
||||
return it;
|
||||
}
|
||||
|
||||
/* The response object, around its output items, with the request fields it echoes. */
|
||||
@@ -3880,7 +3889,8 @@ json response_object(const OaiRequest& r, const char* status, const json& output
|
||||
} /* namespace */
|
||||
|
||||
int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
|
||||
std::string* echo, ApiError* err) {
|
||||
std::string* echo, ApiError* err,
|
||||
std::map<std::string, std::pair<std::string, std::string>>* ns) {
|
||||
json b;
|
||||
RAD_TRY(parse_request_object(body, lim, &b, err));
|
||||
auto prev = b.find("previous_response_id");
|
||||
@@ -3983,11 +3993,14 @@ int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string
|
||||
}
|
||||
msgs.push_back(json{ { "role", role }, { "content", parts } });
|
||||
} else if (type == "function_call") {
|
||||
std::string id, name, args = "{}";
|
||||
std::string id, name, args = "{}", space;
|
||||
if (!member_str(item, "call_id", "input[].call_id", &id, err) ||
|
||||
!member_str(item, "name", "input[].name", &name, err) ||
|
||||
!member_str(item, "arguments", "input[].arguments", &args, err))
|
||||
!member_str(item, "arguments", "input[].arguments", &args, err) ||
|
||||
!member_str(item, "namespace", "input[].namespace", &space, err))
|
||||
return RAD_E_INVAL;
|
||||
/* A namespaced call, under the name its tool was flattened to below. */
|
||||
if (!space.empty()) name = space + "__" + name;
|
||||
json call = { { "id", id }, { "type", "function" },
|
||||
{ "function", { { "name", name }, { "arguments", args } } } };
|
||||
json* prev = last_assistant();
|
||||
@@ -4040,34 +4053,78 @@ int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string
|
||||
}
|
||||
o["messages"] = std::move(msgs);
|
||||
|
||||
/* Function tools only. Built-in tools (web search, file search, computer use) and freeform
|
||||
* custom tools have no chat-completions counterpart and are left out. */
|
||||
/* Function tools, and the function tools a namespace groups (Codex sends every MCP server's
|
||||
* tools that way), flattened to "<namespace>__<name>": the chat path has one flat list, and
|
||||
* the reply's function_call items report the two apart again (OaiRequest::tool_namespace).
|
||||
* Built-in tools (web search, file search, computer use) and freeform custom tools have no
|
||||
* chat-completions counterpart and are left out. */
|
||||
json echo_tools = json::array();
|
||||
auto tit = b.find("tools");
|
||||
if (tit != b.end() && tit->is_array()) {
|
||||
json tools = json::array();
|
||||
std::set<std::string> names;
|
||||
auto add = [&](const json& t, const std::string& space) -> int {
|
||||
std::string name;
|
||||
if (!member_str(t, "name", space.empty() ? "tools[].name" : "tools[].tools[].name",
|
||||
&name, err))
|
||||
return RAD_E_INVAL;
|
||||
const std::string flat = space.empty() ? name : space + "__" + name;
|
||||
if (!names.insert(flat).second) {
|
||||
*err = err_bad("tools", "two tools are named \"" + flat + "\" (a namespace's tools "
|
||||
"are offered to the model as <namespace>__<name>)");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
json fn = { { "name", flat },
|
||||
{ "parameters", t.contains("parameters") ? t.at("parameters") : json::object() } };
|
||||
if (t.contains("description")) fn["description"] = t.at("description");
|
||||
tools.push_back(json{ { "type", "function" }, { "function", fn } });
|
||||
if (!space.empty() && ns) (*ns)[flat] = { space, name };
|
||||
return RAD_OK;
|
||||
};
|
||||
for (const json& t : *tit) {
|
||||
if (str_or(t, "type") != "function") {
|
||||
const std::string type = str_or(t, "type");
|
||||
if (type == "namespace") {
|
||||
std::string space;
|
||||
if (!member_str(t, "name", "tools[].name", &space, err)) return RAD_E_INVAL;
|
||||
if (space.empty()) {
|
||||
*err = err_bad("tools[].name", "a namespace needs a name");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto inner = t.find("tools");
|
||||
if (inner == t.end() || !inner->is_array()) {
|
||||
*err = err_bad("tools[].tools", "a namespace holds an array of tools");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (const json& f : *inner) {
|
||||
if (str_or(f, "type") != "function") {
|
||||
RAD_DEBUG("responses: tool of type \"%s\" in namespace \"%s\" left out: "
|
||||
"no chat equivalent", str_or(f, "type", "?").c_str(),
|
||||
space.c_str());
|
||||
continue;
|
||||
}
|
||||
RAD_TRY(add(f, space));
|
||||
}
|
||||
echo_tools.push_back(t);
|
||||
continue;
|
||||
}
|
||||
if (type != "function") {
|
||||
RAD_DEBUG("responses: tool of type \"%s\" left out: no chat equivalent",
|
||||
str_or(t, "type", "?").c_str());
|
||||
continue;
|
||||
}
|
||||
std::string name;
|
||||
if (!member_str(t, "name", "tools[].name", &name, err)) return RAD_E_INVAL;
|
||||
json fn = { { "name", name },
|
||||
{ "parameters", t.contains("parameters") ? t.at("parameters") : json::object() } };
|
||||
if (t.contains("description")) fn["description"] = t.at("description");
|
||||
tools.push_back(json{ { "type", "function" }, { "function", fn } });
|
||||
RAD_TRY(add(t, ""));
|
||||
echo_tools.push_back(t);
|
||||
}
|
||||
if (!tools.empty()) o["tools"] = std::move(tools);
|
||||
}
|
||||
auto tc = b.find("tool_choice");
|
||||
if (tc != b.end() && !tc->is_null()) {
|
||||
std::string type = "auto", name;
|
||||
std::string type = "auto", name, space;
|
||||
if (tc->is_object() && (!member_str(*tc, "type", "tool_choice.type", &type, err) ||
|
||||
!member_str(*tc, "name", "tool_choice.name", &name, err)))
|
||||
!member_str(*tc, "name", "tool_choice.name", &name, err) ||
|
||||
!member_str(*tc, "namespace", "tool_choice.namespace", &space, err)))
|
||||
return RAD_E_INVAL;
|
||||
if (!space.empty()) name = space + "__" + name;
|
||||
if (!tc->is_object()) o["tool_choice"] = *tc;
|
||||
else if (type == "function")
|
||||
o["tool_choice"] = json{ { "type", "function" }, { "function", { { "name", name } } } };
|
||||
@@ -4119,7 +4176,7 @@ std::string responses_body(const OaiRequest& r, const ChoiceOut& c, const UsageO
|
||||
out.push_back(reasoning_item(random_id("rs_"), c.msg.reasoning, "completed"));
|
||||
if (!c.msg.content.empty())
|
||||
out.push_back(message_item(random_id("msg_"), c.msg.content, "completed"));
|
||||
for (const ToolCall& tc : c.msg.tool_calls) out.push_back(call_item(tc, "completed"));
|
||||
for (const ToolCall& tc : c.msg.tool_calls) out.push_back(call_item(r, tc, "completed"));
|
||||
const bool cut = c.finish == Finish::Length;
|
||||
return response_object(r, cut ? "incomplete" : "completed", out, &u,
|
||||
cut ? "max_output_tokens" : nullptr).dump();
|
||||
@@ -4175,7 +4232,7 @@ void ResponsesStream::open(std::string& out, Item k, size_t call) {
|
||||
const ToolCall& tc = last_.tool_calls[call];
|
||||
item_id_ = fc_id(tc.id);
|
||||
event(out, "response.output_item.added",
|
||||
json{ { "output_index", at }, { "item", call_item(tc, "in_progress") } });
|
||||
json{ { "output_index", at }, { "item", call_item(*r_, tc, "in_progress") } });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4207,7 +4264,7 @@ void ResponsesStream::close(std::string& out) {
|
||||
const bool cut = finished_ && last_.open_call && call_ + 1 == last_.tool_calls.size();
|
||||
event(out, "response.function_call_arguments.done",
|
||||
json{ { "item_id", item_id_ }, { "output_index", at }, { "arguments", tc.arguments } });
|
||||
item = call_item(tc, cut ? "incomplete" : "completed");
|
||||
item = call_item(*r_, tc, cut ? "incomplete" : "completed");
|
||||
}
|
||||
event(out, "response.output_item.done", json{ { "output_index", at }, { "item", item } });
|
||||
items_.push_back(std::move(item));
|
||||
|
||||
+8
-2
@@ -109,6 +109,10 @@ struct OaiRequest {
|
||||
/* The Responses API request fields its response object echoes (instructions, tools,
|
||||
* tool_choice, text, reasoning, ...), as a JSON object; "" for the other shapes. */
|
||||
std::string echo_json;
|
||||
/* The Responses API's namespaced function tools, flattened for the chat path: the flattened
|
||||
* name ("<namespace>__<name>") to its namespace and name, which a function_call item reports
|
||||
* apart. Empty for the other shapes. */
|
||||
std::map<std::string, std::pair<std::string, std::string>> tool_namespace;
|
||||
/* llama-server's native /completion: the generated token ids beside the text. */
|
||||
bool return_tokens = false;
|
||||
/* The reasoning block's closer when the reply starts inside the block, else "": the stop
|
||||
@@ -499,9 +503,11 @@ std::string anthropic_error_body(const ApiError& e);
|
||||
/* OpenAI's Responses API, translated into the equivalent chat request like Anthropic's. `*echo`
|
||||
* holds the request fields the response object repeats. previous_response_id needs server-side
|
||||
* storage and is refused; non-function tool types have no chat equivalent and are dropped, as
|
||||
* llama-server does. */
|
||||
* llama-server does. A namespace's function tools are flattened to "<namespace>__<name>", and
|
||||
* `*ns` (when given) maps each flattened name back for the reply's function_call items. */
|
||||
int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
|
||||
std::string* echo, ApiError* err);
|
||||
std::string* echo, ApiError* err,
|
||||
std::map<std::string, std::pair<std::string, std::string>>* ns = nullptr);
|
||||
std::string responses_body(const OaiRequest& r, const ChoiceOut& c, const UsageOut& u);
|
||||
|
||||
/* Anthropic's stop_reason for a finish and the stop string that caused it. */
|
||||
|
||||
+28
-11
@@ -170,7 +170,12 @@ void Server::register_routes() {
|
||||
router_.post("/v1/responses", [this](const HttpRequest& q) { return handle_responses(q); });
|
||||
router_.post("/responses", [this](const HttpRequest& q) { return handle_responses(q); });
|
||||
auto responses_tokens = [this](const HttpRequest& q) {
|
||||
return count_tokens(q, responses_to_chat, ApiShape::OpenAI, "response.input_tokens");
|
||||
return count_tokens(q,
|
||||
[](const std::string& b, const OaiLimits& l, std::string* c,
|
||||
std::string* ec, ApiError* e) {
|
||||
return responses_to_chat(b, l, c, ec, e);
|
||||
},
|
||||
ApiShape::OpenAI, "response.input_tokens");
|
||||
};
|
||||
router_.post("/v1/responses/input_tokens", responses_tokens);
|
||||
router_.post("/responses/input_tokens", responses_tokens);
|
||||
@@ -210,9 +215,7 @@ static const int64_t kSpareWorkers = 64;
|
||||
void Server::note_ready(uint64_t begin_ns) {
|
||||
if (begin_ns == 0) return;
|
||||
const uint64_t now = rad_mono_ns();
|
||||
/* Only a start in the past is a duration. A stamp that arrives out of order is ignored rather
|
||||
* than written as zero: a zero cost would price every restart as free in any payback formula
|
||||
* that divides by it. */
|
||||
/* A stamp that is not in the past leaves the figure unset rather than writing a zero. */
|
||||
if (now <= begin_ns) return;
|
||||
startup_s_ = (int64_t)((now - begin_ns) / 1000000000ull);
|
||||
}
|
||||
@@ -264,20 +267,32 @@ std::vector<std::string> Server::probe_reasoning_efforts() {
|
||||
l.default_reasoning_effort.clear();
|
||||
l.reasoning_effort_map.clear();
|
||||
l.probe = true;
|
||||
auto takes = [&](const std::string& effort) {
|
||||
template_default_effort_.clear();
|
||||
auto render = [&](const std::string& effort, std::string* text) {
|
||||
std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1)";
|
||||
if (!effort.empty()) body += R"(,"reasoning_effort":)" + json(effort).dump();
|
||||
body += "}";
|
||||
OaiRequest r;
|
||||
ApiError e;
|
||||
return parse_chat_request(body, odeps_, l, &r, &e) >= 0;
|
||||
if (parse_chat_request(body, odeps_, l, &r, &e) < 0) return false;
|
||||
if (text) *text = r.prompts.empty() ? std::string() : r.prompts[0].text;
|
||||
return true;
|
||||
};
|
||||
/* A render that fails without an effort says nothing about efforts; one that takes a
|
||||
* nonsense word takes every word. */
|
||||
if (!takes("") || takes("radiance-probe-not-a-level")) return {};
|
||||
std::vector<std::string> set;
|
||||
for (const char* w : { "low", "medium", "high", "xhigh", "max" })
|
||||
if (takes(w)) set.push_back(w);
|
||||
std::string plain;
|
||||
if (!render("", &plain) || render("radiance-probe-not-a-level", nullptr)) return {};
|
||||
std::vector<std::string> set, same;
|
||||
for (const char* w : { "low", "medium", "high", "xhigh", "max" }) {
|
||||
std::string text;
|
||||
if (!render(w, &text)) continue;
|
||||
set.push_back(w);
|
||||
if (text == plain) same.push_back(w);
|
||||
}
|
||||
/* The level a request naming none gets: the one level whose render is the same. A template may
|
||||
* spend it in a system prompt the client never sees (#113: Qwen3.8's is xhigh). Several, or
|
||||
* none, say nothing. */
|
||||
if (same.size() == 1) template_default_effort_ = same[0];
|
||||
lim_.reasoning_efforts = set;
|
||||
return set;
|
||||
}
|
||||
@@ -1548,10 +1563,12 @@ HttpResponse Server::handle_responses(const HttpRequest& req) {
|
||||
std::string chat, echo;
|
||||
ApiError err;
|
||||
OaiRequest r;
|
||||
if (responses_to_chat(req.body, lim_, &chat, &echo, &err) < 0 ||
|
||||
std::map<std::string, std::pair<std::string, std::string>> ns;
|
||||
if (responses_to_chat(req.body, lim_, &chat, &echo, &err, &ns) < 0 ||
|
||||
parse_chat_request(chat, odeps_, lim_, &r, &err) < 0)
|
||||
return error_response(err, req.peer);
|
||||
r.shape = ApiShape::Responses;
|
||||
r.tool_namespace = std::move(ns);
|
||||
r.id = random_id("resp_");
|
||||
r.echo_json = std::move(echo);
|
||||
return serve(req, r);
|
||||
|
||||
@@ -181,6 +181,9 @@ public:
|
||||
* also takes a nonsense word it takes any word, and the result is empty. Used to refuse words
|
||||
* outside the set and for /server_info; called once, before run(). */
|
||||
std::vector<std::string> probe_reasoning_efforts();
|
||||
/* The effort the template applies to a request that names none, found by the probe above as
|
||||
* the one whose render is the same; "" when none matches or the probe found no set. */
|
||||
const std::string& template_default_effort() const { return template_default_effort_; }
|
||||
/* Renders each --reasoning-effort-map target as a request's effort. Empty when the template
|
||||
* takes all of them; otherwise the first refusal, naming the target. */
|
||||
std::string check_reasoning_effort_map() const;
|
||||
@@ -198,6 +201,7 @@ public:
|
||||
void note_ready(uint64_t begin_ns);
|
||||
|
||||
private:
|
||||
std::string template_default_effort_;
|
||||
struct Generation;
|
||||
struct TranscriptionJob; /* speech.cpp */
|
||||
struct RealtimeSession; /* realtime.cpp */
|
||||
@@ -357,8 +361,8 @@ private:
|
||||
std::atomic<int64_t> speech_sessions_{0};
|
||||
std::atomic<bool> stopping_{false};
|
||||
int64_t started_at_ = 0;
|
||||
/* Seconds from the top of Engine::start() to the moment the server began listening -- the
|
||||
* cost of a restart, measured on this machine rather than guessed. 0 until note_ready(). */
|
||||
/* Seconds from the top of Engine::start() to the moment the server began listening; 0 until
|
||||
* note_ready(). */
|
||||
int64_t startup_s_ = 0;
|
||||
|
||||
/* Sinks whose HTTP side is gone but whose engine side may still be mid-step. Held until the
|
||||
|
||||
+212
-27
@@ -15,8 +15,19 @@
|
||||
* (`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.
|
||||
* A model with a length head (LTX-2.5's duration head) chooses the length of a request that names
|
||||
* none, or says `"seconds": "auto"`; the video object reports it once chosen. A model with more
|
||||
* than one decoder takes `decoder`, one of their names (LTX-2.5: `vae`, the default, or
|
||||
* `diffusion`).
|
||||
* A model that can start from a picture takes OpenAI's `input_reference`, a file in the form or a
|
||||
* data URL (a string or {image_url}) in JSON, as the video's first frame, prepared as the model's
|
||||
* pipeline prepares it: an H.264 round trip at the model's quality, then a bilinear resize to the
|
||||
* size the first steps run at. Non-empty `conditions` are refused.
|
||||
*
|
||||
* A guided model takes `negative_prompt` and its guidance terms, each the model's default when
|
||||
* absent: `guidance_scale`, `stg_scale`, `modality_scale` and `guidance_rescale` for the video,
|
||||
* the same with `audio_` in front for the soundtrack. A scale of 1 turns that modality's
|
||||
* unconditional branch off; the negative prompt is the model's own unless named.
|
||||
*
|
||||
* A model with a latent upscaler also takes `latent_upscale`, a factor from 1 to its largest: the
|
||||
* first steps run at `size` divided by it and the latent is enlarged to `size` for the last
|
||||
@@ -31,6 +42,7 @@
|
||||
#include "oai.h"
|
||||
|
||||
#include "gen/video.h"
|
||||
#include "mm/imaging.h"
|
||||
#include "mm/media.h"
|
||||
#include "mm/mp4.h"
|
||||
#include "rad_internal.h"
|
||||
@@ -40,6 +52,7 @@
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <random>
|
||||
#include <thread>
|
||||
@@ -66,12 +79,24 @@ struct Server::VideoJob {
|
||||
double upscale = 0.0;
|
||||
int32_t refine = 0;
|
||||
std::string upscale_from;
|
||||
/* A guided model's terms as resolved against its defaults, the negative prompt when a scale
|
||||
* used it, and whether the video started from a picture. */
|
||||
bool guided = false;
|
||||
double guidance[8] = {};
|
||||
std::string negative;
|
||||
bool has_negative = false;
|
||||
bool from_image = false;
|
||||
std::string decoder; /* a decoder the request named other than the default */
|
||||
int32_t w = 0, h = 0;
|
||||
bool worker_done = false; /* its thread has nothing left to do but return */
|
||||
};
|
||||
|
||||
namespace {
|
||||
|
||||
/* The largest picture `input_reference` may decode to, which bounds the memory a request can make
|
||||
* the server allocate before the resize. */
|
||||
constexpr int64_t kMaxRefPixels = (int64_t)1 << 26;
|
||||
|
||||
std::string new_video_id() {
|
||||
static const char* hex = "0123456789abcdef";
|
||||
std::random_device rd;
|
||||
@@ -130,11 +155,15 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
/* 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();
|
||||
std::vector<uint8_t> ref_bytes;
|
||||
bool has_ref = false;
|
||||
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.name == "input_reference" && !p.filename.empty()) {
|
||||
ref_bytes.assign(p.data.begin(), p.data.end());
|
||||
has_ref = true;
|
||||
continue;
|
||||
}
|
||||
if (!p.filename.empty())
|
||||
return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a file"),
|
||||
req.peer);
|
||||
@@ -154,6 +183,10 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
static const char* kKnown[] = {
|
||||
"model", "prompt", "seconds", "size", "input_reference", "seed", "num_inference_steps",
|
||||
"task", "target", "conditions", "user", "latent_upscale", "upscale_refine_steps",
|
||||
"negative_prompt", "decoder",
|
||||
/* RadVideoGenBatch::guidance_h's order */
|
||||
"guidance_scale", "stg_scale", "modality_scale", "guidance_rescale",
|
||||
"audio_guidance_scale", "audio_stg_scale", "audio_modality_scale", "audio_guidance_rescale",
|
||||
};
|
||||
for (auto it = body.begin(); it != body.end(); ++it) {
|
||||
bool known = false;
|
||||
@@ -178,12 +211,33 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
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 "
|
||||
if (has(body, "input_reference")) {
|
||||
/* JSON: a data URL, as a string or an image_url object. */
|
||||
const json& v = body["input_reference"];
|
||||
std::string u;
|
||||
if (v.is_string()) u = v.get<std::string>();
|
||||
else if (v.is_object() && v.contains("image_url") && v["image_url"].is_string())
|
||||
u = v["image_url"].get<std::string>();
|
||||
else if (v.is_object() && v.contains("image_url") && v["image_url"].is_object() &&
|
||||
v["image_url"].contains("url") && v["image_url"]["url"].is_string())
|
||||
u = v["image_url"]["url"].get<std::string>();
|
||||
else
|
||||
return bad("input_reference", "a picture is a file, a data: URL, or an object with an "
|
||||
"image_url");
|
||||
ApiError err;
|
||||
if (decode_media_url(u, "input_reference", &ref_bytes, &err) < 0)
|
||||
return error_response(err, req.peer);
|
||||
has_ref = true;
|
||||
}
|
||||
if (has_ref && !info.image_cond)
|
||||
return error_response(err_unsupported("input_reference", "this model 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" };
|
||||
const std::string task_want = has_ref ? "i2va" : "t2va";
|
||||
if (has(body, "task") && (!body["task"].is_string() ||
|
||||
body["task"].get<std::string>() != task_want)) {
|
||||
ApiError e = err_unsupported("task", has_ref ? "a video from a picture is i2va"
|
||||
: "this request makes video from text: t2va");
|
||||
e.supported = { task_want };
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
if (has(body, "conditions") && (!body["conditions"].is_array() || !body["conditions"].empty()))
|
||||
@@ -250,7 +304,13 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
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) {
|
||||
/* A model with a length head chooses the length of a request that names none, or `auto`. */
|
||||
const bool auto_len = info.length_head &&
|
||||
(!(has_sec || has_dur) ||
|
||||
(has_sec && body["seconds"].is_string() && body["seconds"].get<std::string>() == "auto"));
|
||||
if (auto_len) {
|
||||
chunks = 0;
|
||||
} else 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");
|
||||
@@ -263,26 +323,81 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
"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;
|
||||
/* The length the job reports until the model has chosen one. */
|
||||
const int64_t frames =
|
||||
info.frames_per_chunk * (chunks > 0 ? chunks : info.default_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;
|
||||
/* ---- the decoder, by name, the model's first when absent */
|
||||
std::string decoder;
|
||||
if (has(body, "decoder")) {
|
||||
if (!body["decoder"].is_string())
|
||||
return bad("decoder", "the decoder is a name");
|
||||
decoder = body["decoder"].get<std::string>();
|
||||
std::string names;
|
||||
int32_t idx = -1;
|
||||
for (size_t i = 0; i < info.decoders.size(); ++i) {
|
||||
names += (i ? ", " : "") + info.decoders[i];
|
||||
if (info.decoders[i] == decoder) idx = (int32_t)i;
|
||||
}
|
||||
if (idx < 0)
|
||||
return bad("decoder", info.decoders.empty()
|
||||
? std::string("this model has one decoder and takes no name")
|
||||
: "this model decodes with " + names);
|
||||
if (W * H > info.decoder_max_area[(size_t)idx])
|
||||
return bad("decoder", "the " + decoder + " decoder makes frames of " +
|
||||
std::to_string(info.decoder_max_area[(size_t)idx]) +
|
||||
" pixels at most");
|
||||
r->decoder = idx;
|
||||
if (idx == 0) decoder.clear();
|
||||
}
|
||||
if (has(body, "num_inference_steps")) {
|
||||
double v = 0;
|
||||
const char* unit = info.step_evals ? " model evaluations"
|
||||
: " sigma grid points, the last one 0";
|
||||
const int64_t lo = info.step_evals ? 1 : 2;
|
||||
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 ||
|
||||
std::to_string(info.max_steps) + unit);
|
||||
if (!number(body["num_inference_steps"], &v) || v != std::floor(v) || v < lo ||
|
||||
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)");
|
||||
return bad("num_inference_steps", "expected an integer in " + std::to_string(lo) +
|
||||
".." + std::to_string(info.max_steps) + " (" +
|
||||
(unit + 1) + ")");
|
||||
r->steps = (int32_t)v;
|
||||
}
|
||||
/* ---- guidance */
|
||||
static const char* kGuide[8] = {
|
||||
"guidance_scale", "stg_scale", "modality_scale", "guidance_rescale",
|
||||
"audio_guidance_scale", "audio_stg_scale", "audio_modality_scale", "audio_guidance_rescale",
|
||||
};
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
if (!has(body, kGuide[i])) continue;
|
||||
if (!info.guidance)
|
||||
return error_response(err_unsupported(kGuide[i], "this model takes no guidance"),
|
||||
req.peer);
|
||||
double v = 0;
|
||||
const bool rescale = i % 4 == 3;
|
||||
if (!number(body[kGuide[i]], &v) || !(v >= 0.0) || v > (rescale ? 1.0 : 100.0))
|
||||
return bad(kGuide[i], rescale ? "expected a number from 0 to 1"
|
||||
: "expected a number from 0 to 100");
|
||||
r->guidance[i] = v;
|
||||
}
|
||||
std::string negative = info.default_negative;
|
||||
if (has(body, "negative_prompt")) {
|
||||
if (!info.guidance)
|
||||
return error_response(err_unsupported("negative_prompt", "this model takes no "
|
||||
"guidance"), req.peer);
|
||||
if (!body["negative_prompt"].is_string())
|
||||
return bad("negative_prompt", "expected a string");
|
||||
negative = body["negative_prompt"].get<std::string>();
|
||||
r->has_neg = true;
|
||||
}
|
||||
if (has(body, "latent_upscale")) {
|
||||
double v = 0;
|
||||
if (!(info.upscale_max > 0.0))
|
||||
@@ -320,18 +435,65 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
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());
|
||||
auto render = [&](const std::string& text, std::vector<int32_t>* out) {
|
||||
auto put = [&](const std::string& s, bool special) {
|
||||
if (s.empty()) return;
|
||||
const auto ids = deps_.tok->encode(s, false, special);
|
||||
out->insert(out->end(), ids.begin(), ids.end());
|
||||
};
|
||||
put(t.substr(0, p), true);
|
||||
put(text, false);
|
||||
put(t.substr(p + kSlot.size()), true);
|
||||
};
|
||||
put(t.substr(0, p), true);
|
||||
put(prompt, false);
|
||||
put(t.substr(p + kSlot.size()), true);
|
||||
render(prompt, &r->tokens);
|
||||
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));
|
||||
if (info.guidance) {
|
||||
render(negative, &r->neg_tokens);
|
||||
if ((int64_t)r->neg_tokens.size() > info.max_text)
|
||||
return bad("negative_prompt", "the negative prompt is " +
|
||||
std::to_string(r->neg_tokens.size()) +
|
||||
" tokens; this model takes at most " +
|
||||
std::to_string(info.max_text));
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the first frame, at the size the first steps run at */
|
||||
if (has_ref) {
|
||||
int32_t fw = r->width, fh = r->height;
|
||||
if (r->upscale > 1.0) {
|
||||
RadVideoGenDecl geo{}; /* video_small_size reads the size multiple only */
|
||||
geo.size_multiple = info.size_multiple;
|
||||
gen::video_small_size(geo, r->width, r->height, r->upscale, &fw, &fh);
|
||||
}
|
||||
mm::Frame f;
|
||||
std::string why;
|
||||
if (mm::decode_image(ref_bytes.data(), ref_bytes.size(), kMaxRefPixels, &f, &why) < 0)
|
||||
return bad("input_reference", "the picture could not be read: " + why);
|
||||
if (info.image_crf > 0) {
|
||||
mm::Frame rt;
|
||||
const int e = mm::h264_roundtrip(f, info.image_crf, &rt, &why);
|
||||
if (e < 0) {
|
||||
ApiError err = err_bad("input_reference", "the picture could not be prepared: " + why);
|
||||
if (e != RAD_E_INVAL) { err.status = 503; err.type = "server_error"; }
|
||||
return error_response(err, req.peer);
|
||||
}
|
||||
f = std::move(rt);
|
||||
}
|
||||
mm::FrameRGBA a, sized;
|
||||
a.w = f.w;
|
||||
a.h = f.h;
|
||||
a.rgba.resize((size_t)f.w * f.h * 4);
|
||||
for (size_t i = 0, n = (size_t)f.w * f.h; i < n; ++i) {
|
||||
std::memcpy(&a.rgba[4 * i], &f.rgb[3 * i], 3);
|
||||
a.rgba[4 * i + 3] = 255;
|
||||
}
|
||||
mm::resize_bilinear_rgba(a, fw, fh, &sized);
|
||||
r->image.resize((size_t)fw * fh * 3);
|
||||
for (size_t i = 0, n = (size_t)fw * fh; i < n; ++i)
|
||||
std::memcpy(&r->image[3 * i], &sized.rgba[4 * i], 3);
|
||||
}
|
||||
|
||||
/* ---- admitted and queued: the job holds its place until its file is written */
|
||||
@@ -340,7 +502,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
j->id = new_video_id();
|
||||
j->model = opt_.model_id;
|
||||
j->prompt = prompt;
|
||||
j->seconds = rad::fmt("%.2f", (double)frames / fps);
|
||||
j->seconds = auto_len ? std::string("auto") : 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;
|
||||
@@ -348,6 +510,13 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
r->ticket = j->ticket;
|
||||
const int64_t n_tok = (int64_t)r->tokens.size();
|
||||
const int32_t steps = r->steps;
|
||||
j->guided = info.guidance;
|
||||
for (int i = 0; i < 8; ++i)
|
||||
j->guidance[i] = std::isnan(r->guidance[i]) ? info.guidance_default[i] : r->guidance[i];
|
||||
j->has_negative = info.guidance && (j->guidance[0] != 1.0 || j->guidance[4] != 1.0);
|
||||
if (j->has_negative) j->negative = negative;
|
||||
j->from_image = !r->image.empty();
|
||||
j->decoder = decoder;
|
||||
const double upscale = r->upscale;
|
||||
{
|
||||
std::string w;
|
||||
@@ -365,8 +534,10 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
j->refine = tk.refine;
|
||||
j->upscale_from = std::to_string(tk.small_width) + "x" + std::to_string(tk.small_height);
|
||||
}
|
||||
RAD_INFO("video %s: %s, %lld frames (%s s), %lld prompt tokens, %d steps%s, seed=%llu",
|
||||
j->id.c_str(), j->size.c_str(), (long long)frames, j->seconds.c_str(),
|
||||
RAD_INFO("video %s: %s, %s, %lld prompt tokens, %d steps%s, seed=%llu",
|
||||
j->id.c_str(), j->size.c_str(),
|
||||
auto_len ? "the length the model chooses"
|
||||
: rad::fmt("%lld frames (%s s)", (long long)frames, j->seconds.c_str()).c_str(),
|
||||
(long long)n_tok, steps > 0 ? steps : (int)tk.steps,
|
||||
tk.refine > 0 ? rad::fmt(" (the first %d at %dx%d, upscaled for the last %d)",
|
||||
(int)(tk.steps - tk.refine), (int)tk.small_width,
|
||||
@@ -406,6 +577,9 @@ void Server::video_work(std::shared_ptr<VideoJob> j) {
|
||||
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::LENGTH) {
|
||||
std::lock_guard<std::mutex> lk(videos_m_);
|
||||
j->seconds = rad::fmt("%.2f", (double)e.n * info.fps_den / info.fps_num);
|
||||
} 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);
|
||||
@@ -530,6 +704,17 @@ json Server::video_json(const VideoJob& j) {
|
||||
o["upscale_refine_steps"] = j.refine;
|
||||
o["upscale_from"] = j.upscale_from;
|
||||
}
|
||||
if (j.guided) {
|
||||
static const char* kGuide[8] = {
|
||||
"guidance_scale", "stg_scale", "modality_scale", "guidance_rescale",
|
||||
"audio_guidance_scale", "audio_stg_scale", "audio_modality_scale",
|
||||
"audio_guidance_rescale",
|
||||
};
|
||||
for (int i = 0; i < 8; ++i) o[kGuide[i]] = j.guidance[i];
|
||||
if (j.has_negative) o["negative_prompt"] = j.negative;
|
||||
}
|
||||
if (j.from_image) o["input_reference"] = true;
|
||||
if (!j.decoder.empty()) o["decoder"] = j.decoder;
|
||||
o["remixed_from_video_id"] = nullptr;
|
||||
if (j.failed) {
|
||||
json e;
|
||||
|
||||
+75
-3
@@ -10,6 +10,7 @@
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace rad {
|
||||
@@ -130,6 +131,54 @@ static size_t json_depth(const ojson& root) {
|
||||
return deepest;
|
||||
}
|
||||
|
||||
/* The conversation with every system message merged, in order, into one at its head, or false
|
||||
* when that is the conversation already (none, or one leading) or a system message carries more
|
||||
* than text. The Chat Completions API places no constraint on system messages, while many
|
||||
* templates raise unless there is exactly one, first (#137). */
|
||||
static bool lead_system(const ojson& messages, ojson* out) {
|
||||
if (!messages.is_array()) return false;
|
||||
std::string text;
|
||||
size_t n_sys = 0;
|
||||
bool first = false;
|
||||
for (size_t i = 0; i < messages.size(); ++i) {
|
||||
const ojson& m = messages[i];
|
||||
if (!m.is_object() || m.value("role", "") != "system") continue;
|
||||
if (i == 0) first = true;
|
||||
std::string t;
|
||||
const auto c = m.find("content");
|
||||
if (c != m.end() && c->is_string()) {
|
||||
t = c->get<std::string>();
|
||||
} else if (c != m.end() && c->is_array()) {
|
||||
for (const ojson& part : *c) {
|
||||
if (!part.is_object() || part.value("type", "") != "text" ||
|
||||
!part.contains("text") || !part.at("text").is_string())
|
||||
return false;
|
||||
t += part.at("text").get<std::string>();
|
||||
}
|
||||
} else if (c != m.end() && !c->is_null()) {
|
||||
return false;
|
||||
}
|
||||
if (n_sys++ && !text.empty() && !t.empty()) text += "\n\n";
|
||||
text += t;
|
||||
}
|
||||
if (n_sys == 0 || (n_sys == 1 && first)) return false;
|
||||
*out = ojson::array();
|
||||
out->push_back(ojson{ { "role", "system" }, { "content", text } });
|
||||
for (const ojson& m : messages)
|
||||
if (!m.is_object() || m.value("role", "") != "system") out->push_back(m);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The template's own words: the lifted autoparser wraps whatever the render threw in a sentence
|
||||
* about parser generation, which the render's failure is not. */
|
||||
static std::string template_words(const char* what) {
|
||||
static const char kWrap[] = "Unable to generate parser for this template. Automatic parser "
|
||||
"generation failed: ";
|
||||
std::string w = what ? what : "";
|
||||
if (w.compare(0, sizeof kWrap - 1, kWrap) == 0) w.erase(0, sizeof kWrap - 1);
|
||||
return w;
|
||||
}
|
||||
|
||||
int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOptions& opt,
|
||||
ChatPrompt* out) const {
|
||||
if (!ready()) {
|
||||
@@ -190,9 +239,32 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt
|
||||
try {
|
||||
p = common_chat_templates_apply(impl_->tmpls.get(), in);
|
||||
} catch (const std::exception& e) {
|
||||
if (!opt.quiet) RAD_ERR("chat: template refused the request: %s", e.what());
|
||||
out->error = e.what();
|
||||
return RAD_E_UNSUPPORTED;
|
||||
/* A template that takes one system message, first, refuses a conversation that has
|
||||
* another or has it later, which the API allows: it is rendered once more with them
|
||||
* merged into one at the head. Anything else the template refuses is the request's. */
|
||||
ojson merged;
|
||||
bool served = false;
|
||||
if (lead_system(messages, &merged)) {
|
||||
try {
|
||||
in.messages = common_chat_msgs_parse_oaicompat(merged);
|
||||
p = common_chat_templates_apply(impl_->tmpls.get(), in);
|
||||
served = true;
|
||||
static std::atomic<bool> said{ false };
|
||||
if (!opt.quiet && !said.exchange(true))
|
||||
RAD_WARN("chat: the model's chat template refuses system messages after the "
|
||||
"first (%s); such a conversation is rendered with its system "
|
||||
"messages merged, in order, into one at the head. Said once.",
|
||||
template_words(e.what()).c_str());
|
||||
} catch (const std::exception&) {
|
||||
}
|
||||
}
|
||||
if (!served) {
|
||||
const std::string w = template_words(e.what());
|
||||
if (!opt.quiet) RAD_WARN("chat: the model's chat template refused the request: %s",
|
||||
w.c_str());
|
||||
out->error = "the model's chat template refused this conversation: " + w;
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
out->prompt = std::move(p.prompt);
|
||||
|
||||
+14
-3
@@ -72,11 +72,22 @@ void log_emit(Log l, const char* file, int line, const char* fmt, ...) {
|
||||
const char* base = std::strrchr(file, '/');
|
||||
base = base ? base + 1 : file;
|
||||
|
||||
char msg[4096];
|
||||
va_list ap;
|
||||
/* A line longer than the stack buffer is formatted again in full: a trace row of many values
|
||||
* (RADIANCE_DUMP_HEAD) was cut at 4 KiB without a mark (#113). */
|
||||
char buf[4096];
|
||||
std::string big;
|
||||
va_list ap, ap2;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(msg, sizeof msg, fmt, ap);
|
||||
va_copy(ap2, ap);
|
||||
const int n = vsnprintf(buf, sizeof buf, fmt, ap);
|
||||
va_end(ap);
|
||||
if (n >= (int)sizeof buf) {
|
||||
big.resize((size_t)n + 1);
|
||||
vsnprintf(big.data(), big.size(), fmt, ap2);
|
||||
big.resize((size_t)n);
|
||||
}
|
||||
va_end(ap2);
|
||||
const char* msg = big.empty() ? buf : big.c_str();
|
||||
|
||||
const char* col = level_colour(l);
|
||||
const char* rst = col[0] ? "\033[0m" : "";
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# flux-3-klein-fp8.recipe -- FLUX.3 [klein] (or its base) with block-scaled fp8 linears.
|
||||
#
|
||||
# rad-convert <flux-3-image-klein pipeline directory> --recipe data/recipes/flux-3-klein-fp8.recipe \
|
||||
# -o flux-3-klein-fp8.rad
|
||||
#
|
||||
# Every linear of the text encoder's language model and of the DiT's early and joint blocks
|
||||
# becomes E4M3 codes with a bf16 scale a 128 x 128 block, read by the fp8a8 GEMMs over activations
|
||||
# quantised the same way. What stays bf16 is read once a pass or less: the embedding table, the
|
||||
# embedders, the timestep MLPs, the modulations, the output layer and the VAE. The language
|
||||
# model's layers past its last tap (32 of 36) are not carried.
|
||||
|
||||
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
|
||||
dit.mode.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dit.mode.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dit.mode.*.ffn_in.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dit.mode.*.ffn_out.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dit.single.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dit.single.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dit.single.*.ffn_in.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dit.single.*.ffn_out.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
vae.* cast dtype=bf16
|
||||
@@ -0,0 +1,23 @@
|
||||
# krea-2-bf16.recipe -- Krea 2 (Raw or Turbo) at bf16.
|
||||
#
|
||||
# rad-convert <Krea-2-Raw or -Turbo pipeline directory> --recipe data/recipes/krea-2-bf16.recipe \
|
||||
# -o krea-2-bf16.rad
|
||||
#
|
||||
# Every linear stays as the release holds it (bf16). The language model's layers past its last tap
|
||||
# (35 of 36) are not carried. The first matching rule decides.
|
||||
|
||||
# The release stores its norms, modulation tables, embedders, projector and output layer f32.
|
||||
# diffusers keeps every norm f32 and runs the rest bf16. Here the text fusion's norms, the q/k norms
|
||||
# and txt_in's norm stay f32; the DiT's norm1, norm2 and final norm are bf16, the fused modulation
|
||||
# kernel's operand, with the rest.
|
||||
fuse.*.norm1.weight cast dtype=f32
|
||||
fuse.*.norm2.weight cast dtype=f32
|
||||
fuse.*.q_norm.weight cast dtype=f32
|
||||
fuse.*.k_norm.weight cast dtype=f32
|
||||
dit.blk.*.q_norm.weight cast dtype=f32
|
||||
dit.blk.*.k_norm.weight cast dtype=f32
|
||||
txt.norm.weight cast dtype=f32
|
||||
fuse.* cast dtype=bf16
|
||||
txt.* cast dtype=bf16
|
||||
dit.* cast dtype=bf16
|
||||
vae.* cast dtype=bf16
|
||||
@@ -0,0 +1,41 @@
|
||||
# krea-2-fp8.recipe -- Krea 2 (Raw or Turbo) with block-scaled fp8 linears.
|
||||
#
|
||||
# rad-convert <Krea-2-Raw or -Turbo pipeline directory> --recipe data/recipes/krea-2-fp8.recipe \
|
||||
# -o krea-2-fp8.rad
|
||||
#
|
||||
# Every linear of the text encoder's language model, of the text fusion's blocks and of the DiT's
|
||||
# 28 blocks becomes E4M3 codes with a bf16 scale a 128 x 128 block, read by the fp8a8 GEMMs over
|
||||
# activations quantised the same way. What stays bf16 is read once a pass or less: the embedding
|
||||
# table, txt_in, img_in, the timestep MLP and modulation, the blocks' tables, the final layer and
|
||||
# the VAE. The language model's layers past its last tap (35 of 36) are not carried.
|
||||
|
||||
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
|
||||
fuse.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
fuse.*.attn_gate.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
fuse.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
fuse.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
fuse.*.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_gate.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
|
||||
|
||||
# The release stores its norms, modulation tables, embedders, projector and output layer f32.
|
||||
# diffusers keeps every norm f32 and runs the rest bf16. Here the text fusion's norms, the q/k norms
|
||||
# and txt_in's norm stay f32; the DiT's norm1, norm2 and final norm are bf16, the fused modulation
|
||||
# kernel's operand, with the rest.
|
||||
fuse.*.norm1.weight cast dtype=f32
|
||||
fuse.*.norm2.weight cast dtype=f32
|
||||
fuse.*.q_norm.weight cast dtype=f32
|
||||
fuse.*.k_norm.weight cast dtype=f32
|
||||
dit.blk.*.q_norm.weight cast dtype=f32
|
||||
dit.blk.*.k_norm.weight cast dtype=f32
|
||||
txt.norm.weight cast dtype=f32
|
||||
fuse.* cast dtype=bf16
|
||||
txt.* cast dtype=bf16
|
||||
dit.* cast dtype=bf16
|
||||
vae.* cast dtype=bf16
|
||||
@@ -0,0 +1,14 @@
|
||||
# ltx-2.5-bf16.recipe -- LTX-2.5 (the base or the distilled DiT) at the checkpoint's precision.
|
||||
#
|
||||
# rad-convert <LTX-2.5 diffusers pipeline directory> --recipe data/recipes/ltx-2.5-bf16.recipe \
|
||||
# -o ltx-2.5-bf16.rad
|
||||
#
|
||||
# The text encoder, the connectors, the DiT, both VAEs and the latent upsampler are kept bf16. The
|
||||
# vocoders run in f32 and a pipeline saved in bf16 holds them bf16, so they are cast here, once; the
|
||||
# spectrogram bases stay bf16.
|
||||
|
||||
voc.conv_* cast dtype=f32
|
||||
voc.upsamplers.* cast dtype=f32
|
||||
voc.resnets.* cast dtype=f32
|
||||
voc.act_out.* cast dtype=f32
|
||||
bwe.* cast dtype=f32
|
||||
@@ -0,0 +1,37 @@
|
||||
# ltx-2.5-fp8.recipe -- LTX-2.5 (the base or the distilled DiT) with block-scaled fp8 linears.
|
||||
#
|
||||
# rad-convert <LTX-2.5 diffusers pipeline directory> --recipe data/recipes/ltx-2.5-fp8.recipe \
|
||||
# -o ltx-2.5-fp8.rad
|
||||
#
|
||||
# Every linear of the text encoder (Gemma 4), of the two connectors and of the DiT's 48 blocks
|
||||
# becomes E4M3 codes with a bf16 scale a 128 x 128 block, read by the fp8a8 GEMMs over activations
|
||||
# quantised the same way; the biases stay bf16 and are added after. What stays bf16 is small or
|
||||
# read once a step: the attention gates' logits, the q and k norms, the patch projections, the
|
||||
# timestep MLPs and the tables, the connectors' registers, both VAEs and the latent upsampler.
|
||||
# The vocoders are cast to f32, which their convolutions and anti-aliased activations run in
|
||||
# (a pipeline saved in bf16 holds them bf16); the spectrogram bases stay bf16.
|
||||
|
||||
te.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
te.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
te.blk.*.attn_v.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
|
||||
conn.*.proj.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
conn.*.blk.*.qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
conn.*.blk.*.out.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
conn.*.blk.*.ff_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
conn.*.blk.*.ff_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dit.blk.*.qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dit.blk.*.q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dit.blk.*.kv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dit.blk.*.out.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dit.blk.*.ff_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dit.blk.*.ff_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dit.blk.*.audio_ff_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dit.blk.*.audio_ff_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
voc.conv_* cast dtype=f32
|
||||
voc.upsamplers.* cast dtype=f32
|
||||
voc.resnets.* cast dtype=f32
|
||||
voc.act_out.* cast dtype=f32
|
||||
bwe.* cast dtype=f32
|
||||
@@ -0,0 +1,15 @@
|
||||
# FLUX.3 [klein] (black-forest-labs/flux-3-image-klein) as block fp8: text to image and edits from up
|
||||
# to ten reference pictures on OpenAI's /v1/images/generations and /v1/images/edits, on one card,
|
||||
# RADIANCE_GPU in .env (default 0). For the base model, point --model at flux-3-klein-base-fp8.rad.
|
||||
# The FLUX Kommunity License (non-commercial use) applies.
|
||||
name: radiance-flux-3-klein
|
||||
services:
|
||||
radiance:
|
||||
extends: { file: common.yaml, service: radiance }
|
||||
container_name: radiance-flux-3-klein
|
||||
environment:
|
||||
ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}"
|
||||
command: >
|
||||
--model /models/flux-3-klein-fp8.rad
|
||||
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
|
||||
--tp 1
|
||||
@@ -0,0 +1,14 @@
|
||||
# Krea 2 Raw (krea/Krea-2-Raw) as block fp8: text to image on OpenAI's /v1/images/generations, on one
|
||||
# card, RADIANCE_GPU in .env (default 0). The Krea 2 Community License and Krea's acceptable use
|
||||
# policy apply.
|
||||
name: radiance-krea-2-raw
|
||||
services:
|
||||
radiance:
|
||||
extends: { file: common.yaml, service: radiance }
|
||||
container_name: radiance-krea-2-raw
|
||||
environment:
|
||||
ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}"
|
||||
command: >
|
||||
--model /models/krea-2-raw-fp8.rad
|
||||
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
|
||||
--tp 1
|
||||
@@ -0,0 +1,14 @@
|
||||
# Krea 2 Turbo (krea/Krea-2-Turbo) as block fp8: text to image on OpenAI's /v1/images/generations,
|
||||
# on one card, RADIANCE_GPU in .env (default 0).
|
||||
# The Krea 2 Community License and Krea's acceptable use policy apply.
|
||||
name: radiance-krea-2-turbo
|
||||
services:
|
||||
radiance:
|
||||
extends: { file: common.yaml, service: radiance }
|
||||
container_name: radiance-krea-2-turbo
|
||||
environment:
|
||||
ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}"
|
||||
command: >
|
||||
--model /models/krea-2-turbo-fp8.rad
|
||||
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
|
||||
--tp 1
|
||||
@@ -0,0 +1,15 @@
|
||||
# LTX-2.5 (Lightricks/LTX-2.5-Diffusers), distilled, as block fp8: video with its stereo soundtrack
|
||||
# from text or from text and a first frame, on OpenAI's /v1/videos, on one card, RADIANCE_GPU in
|
||||
# .env (default 0). The text encoder is read from pinned host memory (--vision-tower-placement ram).
|
||||
# For the base model, point --model at ltx-2.5-fp8.rad. The LTX-2.x Community License applies.
|
||||
name: radiance-ltx-2.5
|
||||
services:
|
||||
radiance:
|
||||
extends: { file: common.yaml, service: radiance }
|
||||
container_name: radiance-ltx-2.5
|
||||
environment:
|
||||
ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}"
|
||||
command: >
|
||||
--model /models/ltx-2.5-distilled-fp8.rad
|
||||
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
|
||||
--tp 1 --vision-tower-placement ram
|
||||
+205
-13
@@ -21,10 +21,14 @@ plugin claims.
|
||||
| `arch/gemma3` | `gemma3` | *(empty)* | Gemma 3 dense text (TranslateGemma 27B) from the bf16 checkpoint: sliding-window and global attention at one head geometry, GemmaRMSNorm, GELU ffn; linears bf16, or int8, MXFP4 or asymmetric int4 over an activation scaled per (row, 128), as the recipe stores them. Optional DFlash2 drafter (`rad-convert --draft-model`) |
|
||||
| `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/krea2` | `krea2` | *(empty)* | Krea 2 Raw and Turbo, an image generator: Qwen3-VL-4B's tapped layers through a text-fusion transformer, a 12.9B single-stream DiT and Wan 2.1's VAE, from the diffusers pipeline directory; bf16 or block fp8 |
|
||||
| `arch/flux3` | `flux3` | *(empty)* | FLUX.3 [klein] and its base, an image generator and editor: Qwen3-VL-4B's tapped layers, a 5.6B three-mode DiT over the text, up to ten reference pictures and the image, FLUX.2's VAE; bf16 or block fp8 |
|
||||
| `arch/flux3distilled` | `flux3distilled` | *(empty)* | the same plugin under the name FLUX.3 [klein]'s step-distilled release gives itself (`Flux3DistilledModularPipeline`; its base is a `Flux3ModularPipeline`) |
|
||||
| `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`) |
|
||||
| `arch/ltx2` | `ltx2` | *(empty)* | LTX-2.5 (base and distilled), a video with its stereo soundtrack from text or from text and a first frame: Gemma 4's language model and two text connectors, the duration head, a dual-stream audio-video DiT with four-way guidance, the causal video VAE (tiled past the default canvas) or the diffusion decoder, the audio VAE with a BigVGAN vocoder and bandwidth extension, the x2 latent upsampler; bf16 or block fp8, one card |
|
||||
|
||||
The traps below are readings that are wrong without any error: the model produces fluent output.
|
||||
|
||||
@@ -195,7 +199,7 @@ Three groups, which is why hybrid KV groups are first-class:
|
||||
|
||||
| group | kind | geometry |
|
||||
|---|---|---|
|
||||
| full attention | `RAD_KV_FULL` | 16 layers, head_dim 256, 4 KV heads; block size from the resolved kernel. `--kv-cache-dtype fp8_v4` / `k6_v4` (`qwen35_fp8` only) declare it at head_dim 200 / 176, the bytes of a token's quantised row over two (docs/OPS.md) |
|
||||
| full attention | `RAD_KV_FULL` | 16 layers, head_dim 256, 4 KV heads; block size from the resolved kernel. `--kv-cache-dtype fp8_v4` / `k6_v4` (`qwen35_fp8`; `qwen4exp_fp8` too) declare it at head_dim 200 / 176, the bytes of a token's quantised row over two (docs/OPS.md) |
|
||||
| GDN recurrent state | `RAD_KV_LINEAR` | 48 layers, 48 states of 128 x 128 |
|
||||
| GDN conv state | `RAD_KV_CONV` | 48 layers, 2*16 + 48 = 80 heads x 128 = 10240 channels, a rolling `conv_width - 1 + n_spec` window |
|
||||
|
||||
@@ -301,6 +305,11 @@ plugin reads each weight's encoding from the container and declares the op that
|
||||
- bf16: every norm gain, `A_log`, `dt_bias`, `conv1d`, `in_proj_a` and `in_proj_b` (48 rows is not
|
||||
a whole scale block), the router, `shared_expert_gate` and `embed_tokens`.
|
||||
|
||||
**The attention cache takes `--kv-cache-dtype fp8_v4` or `k6_v4`.** The QSA layers' cache (and the
|
||||
MTP head's layer, which shares it) is then declared at head_dim 200 or 176, a token's quantised row
|
||||
over two, and read by the gqa12 rows (gqa6 with 4-token pages at four ranks) of those layouts
|
||||
(docs/OPS.md). The indexer's key cache and tail keep their widths.
|
||||
|
||||
`data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe` is the served choice: four-bit codebook experts with
|
||||
ten protected experts left bf16, int8 block linears and lm_head, E4M3 mixing and MTP fc matrices,
|
||||
and the n-gram table at one fixed E4M3 scale.
|
||||
@@ -488,26 +497,25 @@ and 8.
|
||||
- The indexer is replicated whole.
|
||||
- The vocabulary is row-sharded, 19360 rows a rank at eight; the embedding's all-reduce is exact.
|
||||
- The f32 projections (the router's 288 x 4096, the index head gates' 32 x 4096, each
|
||||
connection's mHC projection of 24 x 16384) are replicated. From a pass of
|
||||
`RADIANCE_GLM_TP_SPLIT_ROWS` rows (default 256; 0 never), each rank computes a disjoint part
|
||||
connection's mHC projection of 24 x 16384) are replicated. From a pass of 256 rows
|
||||
(`kGlmTpSplitRows`, `arch/common/rad_tp_split.h`), each rank computes a disjoint part
|
||||
with the replicated kernel and an `all_gather` joins the parts, so every value is
|
||||
bit-identical: the router and the head gates split their output columns, the mHC projection
|
||||
its 16384-wide input into eight 2048-column chunks, whose partials `mhc_pre_finish` completes
|
||||
on every rank. Below the threshold, as in decode, the collective costs more than it saves.
|
||||
|
||||
**MoE decode fusions.** Three, each byte-identical to the launches it replaces, on unless its
|
||||
variable is `0`; any value but `0` or `1` refuses the start.
|
||||
**MoE decode fusions.** Three, each byte-identical to the launches it replaces, declared
|
||||
wherever a loaded library serves the fused op (the separate launches otherwise):
|
||||
|
||||
| variable | one launch for | where it applies |
|
||||
| fusion | one launch for | where it applies |
|
||||
|---|---|---|
|
||||
| `RADIANCE_GLM_ROUTER_FUSE` | `router_sigmoid_topk`, `moe_scatter` and the shared gate's `fill`: `router_sigmoid_topk_scatter` | passes of up to 128 rows (`M * top_k` <= 1024, one workgroup's sort); 84 launches fewer a trunk decode step, 2 a draft pass |
|
||||
| `RADIANCE_GLM_SWIGLU_QUANT` | `swiglu_clamped` and `quant_act_fp8`: `swiglu_clamped_quant_fp8` | the routed and shared arms and the three dense layers; 87 fewer a trunk step, 2 a draft pass |
|
||||
| `RADIANCE_GLM_GATHER_INVERSE` | none: the sort writes each slot's row (`moe_scatter_inv`) and the gather reads it (`moe_gather_inv`) instead of searching `sorted` | every MoE pass |
|
||||
| router | `router_sigmoid_topk`, `moe_scatter` and the shared gate's `fill`: `router_sigmoid_topk_scatter` | passes of up to 128 rows (`M * top_k` <= 1024, one workgroup's sort); 84 launches fewer a trunk decode step, 2 a draft pass |
|
||||
| SwiGLU | `swiglu_clamped` and `quant_act_fp8`: `swiglu_clamped_quant_fp8` | the routed and shared arms and the three dense layers; 87 fewer a trunk step, 2 a draft pass |
|
||||
| gather inverse | none: the sort writes each slot's row (`moe_scatter_inv`) and the gather reads it (`moe_gather_inv`) instead of searching `sorted` | every MoE pass |
|
||||
|
||||
With all three at `0` the graph and the launches are those
|
||||
`glm53_without_fusion_switches_is_the_pinned_graph_and_steps` pins. Paired on the eight R9700s
|
||||
below, greedy text at a fixed draft depth of 3 is identical with and without them, and eight
|
||||
agent streams decode 456 tok/s against 452, one 144 against 140.
|
||||
`glm53_moe_decode_fusions_replace_their_launches_where_they_fit` counts the launches. Paired on
|
||||
the eight R9700s below, greedy text at a fixed draft depth of 3 is identical with and without
|
||||
them, and eight agent streams decode 456 tok/s against 452, one 144 against 140.
|
||||
|
||||
**Measured** on eight R9700s (gfx1201, 32 GB; four on PCIe Gen5 x16, four on Gen5 x8) at TP8 with
|
||||
the flags of `deploy/compose/glm53-flash.yaml` (32768 tokens of context, eight sequences, MTP with
|
||||
@@ -870,6 +878,96 @@ its 8 steps.
|
||||
|
||||
---
|
||||
|
||||
# `krea2`: Krea 2 Raw and Turbo, an image generator
|
||||
|
||||
`arch/krea2` declares a generator in the core's JOINT_STEP layout: the conditioning pass leaves
|
||||
each lane's text rows (after the text fusion and `txt_in`) in its store, and every denoising step
|
||||
runs them with the image, since every row is modulated by the step's timestep and nothing can be
|
||||
cached as keys. Served on `/v1/images/generations` ([GUIDE §5.6](GUIDE.md)); it takes no reference
|
||||
pictures, so `/v1/images/edits` answers 501.
|
||||
|
||||
```
|
||||
text Qwen3-VL-4B's language model over the prompt in Qwen-Image's template, the template's
|
||||
system turn dropped; TWELVE taps, hidden_states[2, 5, .., 35] (the outputs of layers 1,
|
||||
4, .., 34) before any final norm; the layers past the last tap are not converted
|
||||
fusion two blocks attending across a token's twelve taps (twelve consecutive rows), a learned
|
||||
Linear(12, 1) over them (mix_rows), two blocks attending across the tokens, txt_in
|
||||
DiT 28 single-stream blocks over [text | image]; gqa 48 query heads to 12, a sigmoid output
|
||||
gate, q and k RMS-normed, three-axis rotary (text at the origin, an image token at
|
||||
(0, row, column)); six modulation rows a block = ONE timestep projection shared by all
|
||||
blocks + each block's learned table (table_add), gates without tanh
|
||||
norms every RMS norm zero-centred: the gain is 1 + w, in f32
|
||||
VAE Qwen-Image's (Wan 2.1's causal 3-D convolutions on one frame), 16 channels at 8x; a token
|
||||
is 2 x 2 latents (64 values), 16 pixels a side
|
||||
schedule Raw: 28 steps, the resolution-shifted schedule of its scheduler config, guidance 4.5 in
|
||||
the card's terms against an empty negative prompt; Turbo: 8 steps at a fixed shift
|
||||
(mu 1.15), no guidance. Raw or Turbo is read from the pipeline and scheduler config
|
||||
```
|
||||
|
||||
Traps:
|
||||
|
||||
- **Guidance is in the card's terms**: `cond + s (cond - uncond)`, which the core runs as
|
||||
`uncond + (s + 1)(cond - uncond)` (RadGenDecl::cfg_original). Read as diffusers' usual
|
||||
`uncond + s (...)` the picture is under-guided by one.
|
||||
- **The taps are layer outputs, not inputs.** `hidden_states[i]` is the output of layer i - 1;
|
||||
an off-by-one shifts all twelve and gives a plausible, wrong picture.
|
||||
- **The text rows are a token's twelve taps, then the tokens.** The first two fusion blocks attend
|
||||
within a token (twelve rows), the last two across tokens; swapping the order of the rows swaps
|
||||
which attention sees what.
|
||||
|
||||
Against diffusers' pipeline in bf16 on a tiny random-weight pipeline of the same layout (256x256,
|
||||
from the same latents, mean absolute difference in 8-bit levels): Turbo 0.6, Raw guided 2.2 in an
|
||||
all-bf16 container. Block fp8 moves the random model's Raw picture by 8.5 levels, which is the
|
||||
quantisation's: the container's codes decoded to bf16 on the host give the same picture.
|
||||
|
||||
---
|
||||
|
||||
# `flux3`: FLUX.3 [klein] and its base, an image generator and editor
|
||||
|
||||
`arch/flux3` declares a JOINT_STEP generator over three modes: the text, the reference pictures'
|
||||
latents and the image. The conditioning pass leaves each lane's text rows (after
|
||||
`context_embedder`) and reference rows (VAE-encoded by the generator's own encoder and embedded) in
|
||||
its store; every step runs the three modes' early blocks and then the joint blocks. Served on
|
||||
`/v1/images/generations` and `/v1/images/edits` with up to ten reference pictures.
|
||||
|
||||
```
|
||||
text Qwen3-VL-4B-Instruct's language model over the prompt in its chat template, right-padded
|
||||
to a multiple of 80 tokens; the padding takes part (each padding token at position 1,
|
||||
attending to the prompt alone: attn_cross with valid_cu); EIGHT taps hidden_states[4, 8,
|
||||
.., 32] side by side, 20480 values a token, through context_embedder
|
||||
DiT parallel blocks, h += gate (attn(n) + mlp(n)), n a LayerNorm without affine times
|
||||
(1 + scale) plus shift; 5 early blocks a mode, each mode on its own, then 28 joint blocks
|
||||
over [text | pictures | image] an entry; each mode its own modulation (text and pictures
|
||||
at t = 0, the image at the step's), separately for the early and the joint blocks
|
||||
rotary four axes (t, h, w, l): text along l, the image at (0, h/2, w/2, 0), reference k at
|
||||
l = -(1 + k)
|
||||
flow map the step-distilled release adds the embedding of the time the step goes TO to every
|
||||
mode's timestep embedding (transformer config flow_map)
|
||||
VAE FLUX.2's: 32 channels at 8x, GroupNorm(32) and a single-head mid-block attention; a token
|
||||
is 2 x 2 latents (128 values), normalised by the VAE's BatchNorm running statistics
|
||||
(chan_stats with var 1: sqrt(running_var + eps))
|
||||
schedule [klein]: 16 steps, no guidance; base: 50 steps, guidance 3.5 against an empty negative
|
||||
prompt; both a constant shift of 6.93
|
||||
refs at most ten, each shrunk (never enlarged) to 1024 x 1024 pixels of area
|
||||
```
|
||||
|
||||
Traps:
|
||||
|
||||
- **The padding is part of the prompt.** The pipeline pads to a multiple of 80 and the padding
|
||||
tokens' states reach the DiT; dropping them, or letting them attend to each other, changes every
|
||||
text row the image attends to.
|
||||
- **GroupNorm over 128 channels in 32 groups** is four channels a group, which group_norm runs at
|
||||
4-channel chunks; a kernel that needs 8 refuses the VAE.
|
||||
- **The prompt upsampler is not run.** diffusers' modular pipeline can rewrite the prompt with a
|
||||
separate LLM first; radiance reads the prompt as given, as the pipeline does with that block
|
||||
removed.
|
||||
|
||||
Against diffusers' modular pipeline in bf16 on a tiny random-weight pipeline of the same layout
|
||||
(256x256, from the same latents, mean absolute difference in 8-bit levels, GPU): [klein] 1.17, the
|
||||
base guided 2.30, an edit with one reference picture 1.16.
|
||||
|
||||
---
|
||||
|
||||
# `qwen3asr`: speech to text
|
||||
|
||||
`model_type: qwen3_asr` (`Qwen3ASRForConditionalGeneration`), served from the checkpoint as it
|
||||
@@ -1207,3 +1305,97 @@ output denormalised, folded back into patch rows (patch_fold), then the video
|
||||
|
||||
The node runs the network on whole clips here (its temporal chunking is off in the example
|
||||
workflows); every rank runs it whole, its weights in VRAM on each.
|
||||
|
||||
---
|
||||
|
||||
# `ltx2`: LTX-2.5, video with sound
|
||||
|
||||
`arch/ltx2` declares a video generator (`rad_declare_video_generator`, schedule form 1) on the
|
||||
passes of `core/gen/video_driver.h`: VCOND once per request (the text encoder over the prompt and
|
||||
the negative prompt, the connectors into the lane's text rows, the first frame encoded for image to
|
||||
video), VSTEP once per evaluation, VDECODE and ADECODE once per video, VUPSCALE between the two
|
||||
stages of the distilled recipe. Served on `/v1/videos` ([GUIDE §5.16](GUIDE.md)), one card, bf16 or
|
||||
block fp8. The checkpoint is the diffusers `LTX2Pipeline` directory, with `latent_upsampler/`,
|
||||
`duration_head/` and `diffusion_decoder/` read when they are there.
|
||||
|
||||
```
|
||||
text Gemma 4's language model over "<bos>{prompt}<eos>" (no template), LEFT-padded to 1024
|
||||
rows; every layer's output is kept (the embeddings, each layer's but the last, the final
|
||||
norm of the last), each RMS-normed per layer and flattened channel-major per token.
|
||||
Gemma 4 scores q.k at scale 1: the q and k norms' gains carry the 1/sqrt(head_dim)
|
||||
connector per modality a projection of that stack to its width (video 4096, audio 2048), the
|
||||
1024 rows past the prompt's tokens filled from 128 learnable registers, eight
|
||||
bidirectional blocks with a split rotary over the row index
|
||||
DiT 48 dual-stream blocks: video 4096 (32 x 128) over 1 x 1 patches of 128 channels (32
|
||||
pixels a latent, 8 frames a latent frame + the first), audio 2048 (32 x 64) over 25
|
||||
latents a second (8 channels x 16 mel bins); a block's video stream runs self-attention,
|
||||
cross-attention to its text, attention to the soundtrack and a feed-forward, the
|
||||
soundtrack's the same against the video; every attention gated per head
|
||||
(2 sigmoid(logit)), q and k RMS-normed across all heads; per-block tables + the step's
|
||||
timestep projection (table_add), the cross-modal ones shift-first
|
||||
rotary split over (t, y, x) at the patches' MIDPOINTS for the video, the time midpoint for the
|
||||
audio (rope_split, max 20 2048 2048 and 20)
|
||||
guidance up to four evaluations a step -- the prompt, the negative prompt, the prompt with block
|
||||
28's self-attentions bypassed (STG), the prompt without the cross-modal attentions --
|
||||
combined on the clean estimates with a rescale (ltx_guide); base defaults video
|
||||
(cfg 3, stg 1, modality 3, rescale 0.7), audio (7, 1, 3, 0.7); distilled: one, unguided
|
||||
VAE causal 3-D decoder, four up blocks of residual blocks with depth-to-space and
|
||||
PerChannelRMSNorm (pixel_norm div), 4 x 4 pixel patches out; a frame larger than
|
||||
960 x 544 in diffusers' tiles (16 latents every 14: tile_grid, tile_crop, a tile store,
|
||||
tile_stitch's blends to bytes), a smaller one whole; its encoder takes the first frame
|
||||
for image to video
|
||||
ddec the diffusion decoder, a request's `decoder` "diffusion": the latent with its last frame
|
||||
twice more (NATTEN's border needs them), stages of 4 6 4 2 neighbourhood-attention blocks
|
||||
(2048 1024 512 512 wide, windows 3x7x7 3x7x7 3x5x5 3x5x5, pre-norm, a 3-D gptj rotary
|
||||
over the voxel coordinates in 8 12 12 pairs, SwiGLU 4x) with pixel-shuffle upsamples
|
||||
(1x2x2, 2x1x1, 2x2x2, 2x2x2); the first three over the whole video, then per tile of the
|
||||
feature grid (_tile_intervals: 96 cells every 88, 40 every 28) the fourth and one x0 step
|
||||
at timestep 1 from the seed's noise (stream 2 + the tile) over 4 x 4 pixel patches: 8
|
||||
diffusion blocks of 256 (11x11x11 windows) conditioned on the fourth stage's output, the
|
||||
norms modulated by the timestep's shared table plus each block's own, each attending a
|
||||
head at a time (one head's q|k|v is a quarter of all four's); tile_stitch blends the
|
||||
tiles' overlaps into the frames
|
||||
audio a causal 2-D decoder to a stereo log-mel spectrogram at 16 kHz, a BigVGAN vocoder to 16
|
||||
kHz, a bandwidth extender (its own vocoder over the waveform's log-mel spectrogram plus a
|
||||
sinc-resampled skip, bwe_up) to 48 kHz; the vocoders in f32
|
||||
length the duration head (VCOND, when the container has it): each connector's prompt rows
|
||||
projected to 256 with a modality embedding, one learned query over all 2048 (four heads
|
||||
of 64, no mask), a tanh-GELU MLP to ln(seconds) -- read back by the core, which shapes a
|
||||
request that named no length from it (RadVideoGenDecl::duration_out)
|
||||
schedule base: 30 steps of FlowMatchEuler, exponential dynamic shift 0.95..2.05 over 1024..4096
|
||||
tokens, shift_terminal 0.1; distilled: its 8 trained sigmas (1.0 .. 0.421875), and with
|
||||
the upsampler the two-stage recipe -- the 8 at half size, the latent upsampler, both
|
||||
latents re-noised to 0.909375 with stream 1 of their seeds (flow_renoise), the stage-2
|
||||
sigmas 0.909375, 0.725, 0.421875 at the full size
|
||||
```
|
||||
|
||||
Traps:
|
||||
|
||||
- **The noise is radiance's.** The video's latent is stream 0 of the seed in packed (f, y, x)
|
||||
order; the soundtrack's the seed with its top bit flipped; the second stage's re-noise is stream
|
||||
1 of each. Parity against diffusers means handing it the same tensors: the latents, and for the
|
||||
first-frame pipeline and the re-noise its `randn_tensor` patched to return them.
|
||||
- **A distilled schedule is read as given.** diffusers stretches explicit sigmas to a scheduler
|
||||
config's `shift_terminal`; a distilled pipeline whose scheduler config kept the base model's 0.1
|
||||
would run different sigmas there, and the plugin runs the trained ones.
|
||||
- **The vocoder's dilations are nested lists** (`[[1, 3, 5], ...]`); the metadata reader flattens
|
||||
them row-major. Dropped, every resnet runs at dilation 1 and the soundtrack is noise.
|
||||
- **The first frame goes through H.264 at CRF 18 before the encoder**, as the pipeline does for
|
||||
LTX-2.5 (33 for the Gemma 3 generations). In the two-stage recipe the first frame of the
|
||||
UPSCALED latent is the one kept clean, as diffusers' image pipeline keeps it, not a re-encode
|
||||
at the full size.
|
||||
- **A tile's crop reads the latent after earlier tiles have decoded.** The buffer planner orders
|
||||
liveness by declaration, which has one crop before the decoder; the latent is a persistent buffer
|
||||
so the decoder's scratch cannot take its memory between tiles. Before that, every tile but the
|
||||
first decoded garbage and the first one partly.
|
||||
- **The MP4 is not a parity instrument.** H.264 at CRF 18 in yuv420p moves a random-weight
|
||||
model's frames by about 40 levels on its own; compare the frames before encoding (the op
|
||||
oracle's patch_pix8 output).
|
||||
|
||||
Against diffusers' pipelines in bf16 on a tiny random-weight pipeline of the same layout (256x256,
|
||||
17 frames, from the same latents), the first frame's row sums agree to within 0.2% at 2 unguided
|
||||
and 4 guided steps, for image to video, single-stage distilled and the distilled two-stage recipe
|
||||
with and without a first frame; diffusers on CUDA and on the CPU differ from each other by up to 0.1%.
|
||||
On an R9700 (libr4d) the same five renders land within 0.15% of diffusers' CUDA rows, every op
|
||||
agreeing with its host reference under the op oracle. Block fp8 moves the random model's rows by
|
||||
0.2 to 0.4% (the card's fp8a8 GEMMs, the CPU's fp8 codes widened to bf16).
|
||||
+9
-2
@@ -130,19 +130,26 @@ the cards the engine runs on.
|
||||
| `flashnext-tp1.yaml` | `qwen3.8-next-flash-fp8-iq4r-moe.rad` | The same on one card: a 42 GiB pinned host pool for the experts that do not fit, 4096-token prefill steps, 4 sequences |
|
||||
| `flashnext-bf16.yaml` | `qwen3.8-flash-next-bf16.rad` | Qwen3.8-Flash-Next in bf16, streamed from the disk tier. A reference, not a production server |
|
||||
| `qwen3.6-35b-a3b.yaml` | `qwen3.6-35b-a3b-fp8.rad` | Qwen3.6-35B-A3B, FP8 |
|
||||
| `ornith-1.5-35b-a3b.yaml` | `ornith-1.5-35b-a3b-fp8.rad` | Ornith-1.5-35B-A3B, FP8, MTP, vision |
|
||||
| `qwen3.8-27b-fp8.yaml` | `qwen3.8-27b-fp8.rad` | Qwen3.8-27B FP8 with its DFlash2 drafter and vision tower |
|
||||
| `qwen3.8-27b-mxfp4.yaml` | `qwen3.8-27b-mxfp4.rad` | Qwen3.8-27B with AMD's Quark AWQ-MXFP4 trunk, its DFlash2 drafter and vision tower |
|
||||
| `qwen3.8-27b-paro.yaml` | `qwen3.8-27b-paro-int4.rad` | Qwen3.8-27B ParoQuant int4 (learned rotations) with its DFlash2 drafter and vision tower, on one card; the int5 and MXFP4 containers serve from it too |
|
||||
| `qwen3.8-27b-bf16.yaml` | `qwen3.8-27b-bf16.rad` | Qwen3.8-27B in bf16 |
|
||||
| `gemma4-31b-w4a8.yaml` | `gemma4-31b-w4a8.rad` | Gemma 4 31B, int4 trunk with int8 activations, its assistant head as the MTP drafter, vision tower |
|
||||
| `gemma4-31b-heretic-ara-w4a8.yaml` | `gemma4-31b-heretic-ara-w4a8.rad` | The same for Gemma 4 31B heretic-ara (refusals removed) |
|
||||
| `translategemma-27b.yaml` | `translategemma-27b-mxfp4-gptq.rad` | TranslateGemma 27B MXFP4 with its chat template (`gemma3.jinja`) |
|
||||
| `glm53-flash.yaml` | `glm53-flash-mxfp4.rad` | GLM-5.3-Flash, MXFP4 experts and block-FP8 attention, on eight cards |
|
||||
| `minicpm5-2b.yaml` | `minicpm5-2b-fp8.rad` | MiniCPM5-2B FP8 with its DSpark drafter |
|
||||
| `minicpm5-2b-bf16.yaml` | `minicpm5-2b-bf16.rad` | MiniCPM5-2B in bf16 with its DSpark drafter |
|
||||
| `embeddinggemma2.yaml` | `embeddinggemma2-bf16.rad` | EmbeddingGemma 2 in bf16: text, image, video and audio embeddings on one card (`RADIANCE_GPU`) |
|
||||
| `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 |
|
||||
| `krea-2-turbo.yaml`, `krea-2-raw.yaml` | `krea-2-turbo-fp8.rad`, `krea-2-raw-fp8.rad` | Krea 2 Turbo and Raw as block fp8: text to image on one card (`RADIANCE_GPU`) |
|
||||
| `flux-3-klein.yaml` | `flux-3-klein-fp8.rad` | FLUX.3 [klein] as block fp8: generation and edits on one card (`RADIANCE_GPU`); the base container serves the same way |
|
||||
| `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 |
|
||||
| `ltx-2.5.yaml` | `ltx-2.5-distilled-fp8.rad` | LTX-2.5 distilled as block fp8: video with its stereo soundtrack on `/v1/videos`, one card (`RADIANCE_GPU`), the text encoder in pinned host memory; the base container serves the same way |
|
||||
| `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`) |
|
||||
|
||||
@@ -163,7 +170,7 @@ docker compose -f flashnext.yaml down # stop
|
||||
```
|
||||
|
||||
Every model listens on the same port and most take both cards (`flashnext-tp1.yaml`,
|
||||
`qwen3.8-27b-paro.yaml` and `embeddinggemma2.yaml` take one), so run one at a time: `down` one
|
||||
before `up` on another. The server runs as the host user given in `.env`. `/health`, `/ping` and
|
||||
`qwen3.8-27b-paro.yaml` and the files that read `RADIANCE_GPU` take one, `glm53-flash.yaml`
|
||||
eight), so run one at a time: `down` one before `up` on another. The server runs as the host user given in `.env`. `/health`, `/ping` and
|
||||
the dashboard page answer without the API key, and the health check fetches `/health` with
|
||||
busybox's `wget`.
|
||||
+114
-25
@@ -276,9 +276,13 @@ and runs.
|
||||
| `lfm2_bf16` | LiquidAI LFM2 and LFM2-VL in bf16, including d1 (§5.13) |
|
||||
| `embgemma2` | EmbeddingGemma 2, an embedding model (§5.6) |
|
||||
| `qwenimage21` | Qwen-Image 2.1 and 2.1-Turbo, an image model (§5.6) |
|
||||
| `krea2` | Krea 2 Raw and Turbo, an image model from text (§5.6) |
|
||||
| `flux3`, `flux3distilled` | FLUX.3 [klein] and its base, an image model that also edits (§5.6); one plugin under the two names the releases give themselves |
|
||||
| `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) |
|
||||
| `minimaxh3` | MiniMax-H3 and FastH3, video with its stereo soundtrack from text (§5.16) |
|
||||
| `ltx2` | LTX-2.5, video with its stereo soundtrack from text or a first frame (§5.16) |
|
||||
|
||||
**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
|
||||
@@ -393,6 +397,27 @@ rad-convert /srv/models/Qwen/Qwen-Image-2.1 -o qwen-image-2.1-fp8.rad \
|
||||
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
|
||||
|
||||
# Krea 2 Raw or Turbo, and FLUX.3 [klein] or its base, image models (§5.6): the diffusers pipeline
|
||||
# directory; fp8 blocks for the text encoder and the DiT. Krea 2 takes a recipe either way (or
|
||||
# krea-2-bf16.recipe), since the release stores its embedders and modulations f32
|
||||
rad-convert /srv/models/krea/Krea-2-Turbo -o krea-2-turbo-fp8.rad \
|
||||
--recipe data/recipes/krea-2-fp8.recipe
|
||||
rad-convert /srv/models/black-forest-labs/flux-3-image-klein -o flux-3-klein-fp8.rad \
|
||||
--recipe data/recipes/flux-3-klein-fp8.recipe
|
||||
|
||||
# LTX-2.5, video with sound (§5.16): the diffusers pipeline directory, latent_upsampler/ included
|
||||
# for the distilled release's two-stage recipe; fp8 blocks for the text encoder, the connectors and
|
||||
# the DiT, or bf16 (both recipes keep the vocoders f32, which they run in)
|
||||
rad-convert /srv/models/Lightricks/LTX-2.5-Diffusers -o ltx-2.5-fp8.rad \
|
||||
--recipe data/recipes/ltx-2.5-fp8.recipe
|
||||
# Its full (SFT) DiT, transformer_full/, is guided and takes the base schedule back: a folder whose
|
||||
# transformer/ links to it, and the scheduler's shifting turned on as the release's README does
|
||||
mkdir ltx-2.5-full && ln -s /srv/models/Lightricks/LTX-2.5-Diffusers/* ltx-2.5-full/
|
||||
rm ltx-2.5-full/transformer ltx-2.5-full/transformer_full
|
||||
ln -s /srv/models/Lightricks/LTX-2.5-Diffusers/transformer_full ltx-2.5-full/transformer
|
||||
rad-convert ltx-2.5-full -o ltx-2.5-full-fp8.rad --recipe data/recipes/ltx-2.5-fp8.recipe \
|
||||
--set scheduler.use_dynamic_shifting=1 --set scheduler.shift_terminal=0.1
|
||||
|
||||
# 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 \
|
||||
@@ -729,9 +754,10 @@ are first-seen, so steps wait on the drive. `ram` copies the table into host mem
|
||||
so a step has no host work. `vram` puts all of it on every card. `ram` needs the table's size free
|
||||
after the pinned host pools and the prefix cache's host tier, with `--host-headroom-mib` to spare
|
||||
(default 4 GiB), under every memory cgroup the process sits in, and refuses the start otherwise.
|
||||
`auto` takes the first of `vram`, `ram` and `disk` that holds the table. Without a device kernel for the gather (no libr4d) the table is
|
||||
read on the host: `vram` is refused, and `ram` is a copy in locked huge pages, which also needs a
|
||||
memlock limit that large (`--ulimit memlock=-1` in Docker, `LimitMEMLOCK=infinity` under systemd).
|
||||
`auto` takes the first of `vram`, `ram` and `disk` that holds the table. Without a device kernel
|
||||
for the gather (no libr4d) the table is read on the host: `vram` is refused, and `ram` is a copy in
|
||||
locked huge pages, which also needs a memlock limit that large (`--ulimit memlock=-1` in Docker,
|
||||
`LimitMEMLOCK=infinity` under systemd).
|
||||
|
||||
**`--weights-disk-tier`** serves a model larger than the card and the host pool together, with every
|
||||
step paced by the drive. A routed expert that fits neither lives only in the container. Before each
|
||||
@@ -792,8 +818,10 @@ widths.
|
||||
`fp8_v4` and `k6_v4` narrow the trunk's attention cache further, in groups of 32 dimensions with an
|
||||
f16 scale each: `fp8_v4` keeps K in E4M3 and stores V as int4, `k6_v4` stores K as int6 too. A token
|
||||
then costs 25/32 or 22/32 of what fp8 costs, and a drafter's cache stays fp8. libr4d has their
|
||||
kernels for Qwen3.8-27B's attention (head_dim 256, gqa 6), so the plugin offers them there and the
|
||||
server refuses them, naming the plugin, anywhere else. On two R9700s at the serve flags of
|
||||
kernels for Qwen3.8-27B's attention (head_dim 256, gqa 6) and Qwen3.8-Flash-Next's (head_dim 256,
|
||||
gqa 12 over 4-token pages, gqa 6 a rank at four ranks), so `qwen35_fp8` and `qwen4exp_fp8` offer
|
||||
them there and the server refuses them, naming the plugin, anywhere else. Flash-Next's QSA indexer
|
||||
keeps its own key cache, so its share of a token does not shrink. On two R9700s at the serve flags of
|
||||
`qwen3.8-27b-mxfp4.yaml` with `--max-num-batched-tokens 2048` and 12 GiB a card left to another
|
||||
engine, against the bf16 model on 17 long log-analysis documents (60 368 scored positions):
|
||||
|
||||
@@ -1229,6 +1257,13 @@ radiance --model m.rad --chat-template-kwargs @template-vars.json
|
||||
startup with the template's message.
|
||||
- `/tokenize` renders `messages` with the same variables.
|
||||
|
||||
**System messages.** Many templates raise unless a conversation has one system message, first; the
|
||||
Chat Completions API allows any number anywhere. A conversation the template refuses that has a
|
||||
system message after the first message, or more than one, is rendered again with its system
|
||||
messages merged, in order and separated by a blank line, into one at the head; the first such
|
||||
request logs a warning. Anything else a template refuses is a 400 on `messages` in the template's
|
||||
own words.
|
||||
|
||||
**`--reasoning-effort`** is the default for chat requests that set none, passed to the chat template
|
||||
verbatim, so the legal set is the template's. Qwen3.8 takes `xhigh|medium|low` and defaults to
|
||||
`xhigh`, which on a short task can spend the whole token budget inside `<think>` and return empty
|
||||
@@ -1345,7 +1380,7 @@ still verified by the adapter, so output is exact and only the acceptance rate c
|
||||
| flag | default | |
|
||||
|---|---|---|
|
||||
| `--gpu-headroom-mib N` | 96 | VRAM left unclaimed on every card |
|
||||
| `--kv-cache-dtype T` | bf16 | `bf16`, `fp8`, or on Qwen3.8-27B `fp8_v4` or `k6_v4` (§4.4) |
|
||||
| `--kv-cache-dtype T` | bf16 | `bf16`, `fp8`, or on Qwen3.8-27B and Qwen3.8-Flash-Next `fp8_v4` or `k6_v4` (§4.4) |
|
||||
| `--host-pool-mib N` | 0 | pinned host tier (weights) |
|
||||
| `--host-headroom-mib N` | 4096 | host RAM left free for the system when startup pins host memory — kept for the unpooled allocations, staging and page cache (§4.3) |
|
||||
| `--embedding-placement WHERE` | ram | `ram` or `vram`: the token embedding pinned in host memory beside `--host-pool-mib` and read in place, or on the card (§4.3) |
|
||||
@@ -1721,7 +1756,7 @@ becomes up to 280 tokens by default (`--image-tokens`, or a request's `image_tok
|
||||
`document`, `Retrieval-query`, `STS`, ...) and applies to text and content-part inputs; a model that
|
||||
states a default prompt applies it when the request names none.
|
||||
|
||||
**An image model** (Qwen-Image 2.1 or 2.1-Turbo) serves OpenAI's images API only; completions, chat
|
||||
**An image model** (Qwen-Image 2.1 or 2.1-Turbo, Krea 2, FLUX.3 [klein]) serves OpenAI's images API only; completions, chat
|
||||
and embeddings answer 501. OpenAI images clients (Open WebUI, the OpenAI SDKs) work unchanged; the
|
||||
picture always comes back in the response. The engine sizes the step, batch and context for an image
|
||||
model itself (`--max-num-batched-tokens` and `--max-model-len` from the model's largest pass,
|
||||
@@ -1785,6 +1820,15 @@ area (its latent rows replace its vision tokens). One card holds the fp8 contain
|
||||
container. A request the cache can never hold is a 400 naming the rows it needed. The models are
|
||||
under Qwen's research license, non-commercial.
|
||||
|
||||
**Krea 2 and FLUX.3 [klein]** take the same fields with their own defaults. Both make RGB pictures
|
||||
(`background: transparent` is a 400), 1024x1024 by default, sides rounded down to multiples of 16,
|
||||
up to 2048x2048 (16384 latent tokens). Krea 2 Raw runs 28 steps at guidance 4.5 against an empty
|
||||
negative prompt and Turbo 8 steps unguided; Krea 2 reads only text, so `/v1/images/edits` answers
|
||||
501. FLUX.3 [klein] runs 16 steps unguided and its base 50 at guidance 3.5; both edit from up to ten
|
||||
pictures, each shrunk to 1024x1024 of area when larger. The guidance scale is `guidance_scale` or
|
||||
`true_cfg_scale` (one of them), in the model card's terms. FLUX.3's pipeline can rewrite a prompt
|
||||
with a separate language model first; radiance reads the prompt as given.
|
||||
|
||||
### 5.7 Request fields
|
||||
|
||||
| field | notes |
|
||||
@@ -1912,8 +1956,12 @@ llama-server (`chat_template_kwargs`, `top_k`, ...). The answer is a response ob
|
||||
stream with every event's `output_index`, `content_index` and `sequence_number`, opening with
|
||||
`response.created` and `response.in_progress` at once, as OpenAI's and vLLM's do: they report the
|
||||
response object, not output. A reply cut at
|
||||
`max_output_tokens` is `incomplete`. Function tools are offered to the model; built-in tools (web
|
||||
search, file search, computer use) and freeform custom tools are left out, as in llama-server.
|
||||
`max_output_tokens` is `incomplete`. Function tools are offered to the model, and so are the
|
||||
function tools a `namespace` groups (Codex sends every MCP server's tools that way), named
|
||||
`<namespace>__<name>`: the reply's `function_call` item carries `namespace` and `name` apart, and a
|
||||
`function_call` input item or a `tool_choice` naming a namespace is joined back the same way. Two
|
||||
tools that would share a name are refused. Built-in tools (web search, file search, computer use)
|
||||
and freeform custom tools are left out, as in llama-server.
|
||||
Responses are not stored, so `previous_response_id` is refused: send the conversation as `input`.
|
||||
What a response object cannot carry is refused: `n` other than 1, and logprobs (`include` naming
|
||||
`message.output_text.logprobs`, `top_logprobs`, `logprobs`, `n_probs`), which
|
||||
@@ -2362,7 +2410,7 @@ 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
|
||||
A video generation model (MiniMax-H3, LTX-2.5) 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
|
||||
@@ -2427,6 +2475,54 @@ The MP4 holds H.264 video (yuv420p, BT.709) and AAC audio at 32 kHz stereo. A fi
|
||||
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.
|
||||
|
||||
**LTX-2.5** takes the same jobs with its own limits, and starts from a picture as well as from text:
|
||||
|
||||
```sh
|
||||
radiance --model ltx-2.5-fp8.rad --vision-tower-placement ram
|
||||
|
||||
# image to video: the picture is the first frame (a file in the form, or a data: URL in JSON)
|
||||
curl -s http://localhost:8000/v1/videos -F 'prompt=the fox turns and runs into the trees' \
|
||||
-F 'size=768x512' -F 'seconds=5' -F 'input_reference=@fox.png'
|
||||
```
|
||||
|
||||
- **`prompt`** is read as written (no template), at most 1024 tokens; **`negative_prompt`** is
|
||||
what guidance steers away from, empty by default.
|
||||
- **`seconds`** is rounded up to steps of 8 frames at 24 a second, from 17 frames (0.71 s) to 161
|
||||
(6.7 s). Left out (or `"auto"`), the release's duration head chooses the length the prompt
|
||||
implies, as diffusers does when `num_frames` is omitted: its prediction held to 1 to 20 seconds,
|
||||
rounded to frames and down to the 8-frame steps, then to the 161 frames this server makes. The
|
||||
video object says `"seconds": "auto"` until the prompt is read, then the length chosen. A
|
||||
container without the head makes 121 frames (5.04 s). **`size`**: both sides multiples of 32 from 256, at most
|
||||
1920 x 1088 pixels of area, at most 3:1; 960x544 by default, the release's own. A step carries at
|
||||
most 121 frames at 1920x1088 (a longer video at that size is refused). Up to 960 x 544 of area
|
||||
the VAE decodes each frame whole, as the pipeline does by default; a larger frame is decoded in
|
||||
diffusers' tiles (`vae.enable_tiling()`: 512 pixels every 448) and blended where they overlap,
|
||||
as the release's two-stage README does at 1920x1088.
|
||||
- **`input_reference`** is the first frame, resized and cropped to `size` and put through H.264
|
||||
at CRF 18 first, as the model was trained.
|
||||
- **`decoder`** picks how the latents become frames: `vae` (the default, the convolutional VAE that
|
||||
diffusers' LTX2Pipeline decodes with) or `diffusion`, the release's diffusion decoder (the
|
||||
README's "Decode with the diffusion decoder"): four stages of neighborhood-attention blocks, then
|
||||
one denoising step from noise over 4 x 4 pixel patches, run in its own tiles (768 pixels every
|
||||
704, 80 frames every 56) as diffusers' `enable_tiling()` runs it. It draws its noise from the
|
||||
request's seed, so a seed repeats its video. Frames of at most 960 x 544 of area.
|
||||
- The base model runs 30 steps (`num_inference_steps`, at most 64), each up to four evaluations:
|
||||
**`guidance_scale`** against the negative prompt, **`stg_scale`** against the model with block
|
||||
28's self-attentions bypassed, **`modality_scale`** against the model without its cross-modal
|
||||
attentions, and **`guidance_rescale`**, by default 3, 1, 3 and 0.7 for the video. The
|
||||
soundtrack's own four are the same fields prefixed `audio_` (7, 1, 3, 0.7). A scale of 1 (0 for
|
||||
`stg_scale`) drops its evaluation, so `{"guidance_scale": 1, "stg_scale": 0, "modality_scale":
|
||||
1, ...}` runs one evaluation a step.
|
||||
- The distilled release runs its 8 trained steps unguided, and only those; with its latent
|
||||
upsampler in the container, **`latent_upscale`** 2 (sides multiples of 64) runs them at half the
|
||||
size, enlarges the clean latent, re-noises it and refines at the full size in 3 more. `size` is
|
||||
the output's: the release's README recipe is `"size": "1920x1088", "latent_upscale": 2` (its first
|
||||
stage at 960x544).
|
||||
|
||||
The MP4's soundtrack is 48 kHz stereo. LTX-2.5 runs on one card; `--tp` above 1 is refused. Its
|
||||
Gemma 4 text encoder (13 GiB in fp8) does not fit a 32 GB card beside the DiT: serve it with
|
||||
`--vision-tower-placement ram`, which keeps it in pinned host memory and reads it once a prompt.
|
||||
|
||||
## 6. Operation
|
||||
|
||||
### 6.1 The dashboard
|
||||
@@ -2464,18 +2560,13 @@ take twice as long as its neighbour — so nothing is compared until 32 have bee
|
||||
averaged. A single slow step moves neither figure.
|
||||
|
||||
The percentage, `now X% of best`, is the page's own live window read against the
|
||||
floor. `now` is the mean of the steps that completed in the last poll (~500 ms);
|
||||
the figure is that mean as a fraction of `best`, so ~99% is the fastest the lane
|
||||
has done and anything slower reads a percentage of it (a step at 80% of the
|
||||
floor's speed reads "80% of best"). It is capped at ~99, shown with a tilde: `now` is a ~500 ms mean
|
||||
while `best` is a 32-step window mean, so a fast stretch shorter than a window can
|
||||
read faster than the recorded floor. That is "at your best", not a new record —
|
||||
the engine only lowers `best` on a completed 32-step window, and a sub-window blip
|
||||
is not one. The cap is 99 rather than 100 because a 500 ms window that briefly beats the floor is
|
||||
not a sustained record; 100% would claim a floor the window cannot confirm and would read as a
|
||||
bug, while ~99% says "at your best" without overclaiming. At higher concurrency the figure is keyed to that concurrency (`@c8`)
|
||||
and read against the fastest step seen at that concurrency, because a batched step
|
||||
is a different measurement and would report a batch arriving as a slowdown.
|
||||
floor: the mean of the steps that completed in the last poll (~500 ms) as a
|
||||
fraction of `best`, so a step at 80% of the floor's speed reads "80% of best". A
|
||||
fast stretch shorter than a window can beat the 32-step floor without being a new
|
||||
record, so the figure is capped and the fastest reads `~99%`. At higher
|
||||
concurrency it is keyed to that concurrency (`@c8`) and read against the fastest
|
||||
step seen there, because a batched step is a different measurement and would
|
||||
report a batch arriving as a slowdown.
|
||||
|
||||
The gap between them is normal, and it is not degradation. `best` is the most
|
||||
favorable moment the lane has hit; `recent` is what it is doing now. On a healthy
|
||||
@@ -2657,7 +2748,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.8.1
|
||||
I STARTUP REPORT -- radiance 1.9.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]
|
||||
@@ -2754,8 +2845,6 @@ reductions running on fewer blocks: Qwen3.8-27B's 41k-token prefill 9.5 s uncapp
|
||||
| `RADIANCE_CALIB_DIR` | where an engine run writes calibration data for a recipe's `gptq calib=DIR` |
|
||||
| `RADIANCE_CALIB_TOKENS` | with `RADIANCE_CALIB_DIR`, the tokens the calibration tap accumulates before it writes and switches itself off (default 65536) |
|
||||
| `RADIANCE_G3_CALIB_LAYERS` | `lo:hi`: `arch/gemma3`'s calibration tap over layers lo to hi - 1 only, to take a large model's Grams in passes (docs/ARCHITECTURES.md) |
|
||||
| `RADIANCE_GLM_TP_SPLIT_ROWS` | `arch/glm5next` under tensor parallelism: the pass height from which the router, the index head gates and the mHC projection split their f32 work over the ranks and gather it, bit-identical to the replicated form (default 256; `0` or a value that does not parse never splits) |
|
||||
| `RADIANCE_GLM_ROUTER_FUSE`, `RADIANCE_GLM_SWIGLU_QUANT`, `RADIANCE_GLM_GATHER_INVERSE` | `arch/glm5next`'s MoE decode fusions, each byte-identical to the launches it replaces: unset, empty or `1` on, `0` off, any other value refuses the start. For comparing, not for deployment (docs/ARCHITECTURES.md) |
|
||||
| `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) |
|
||||
| `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) |
|
||||
| `RADIANCE_AR8_SHARD_WEIGHTS`, `RADIANCE_AR8_PIECES` | the eight-rank two-shot's shard weights (`auto`, the default, reads the PCIe links; `off`; or eight integers) and piece count, with `RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS` and `RADIANCE_AR8_PIECES_MIN_ELEMS` for the message size each starts at (§4.7) |
|
||||
|
||||
+212
-30
@@ -373,7 +373,7 @@ kernels with its chunk-sum order, so the pair is byte-identical to `mhc_pre` (`r
|
||||
and two from 32, where the weight rows are 16-byte and the residual rows 8-byte aligned; the
|
||||
finish forms the 4x4 mixing on one wave and collapses the row over the workgroup; `mhc_post` at
|
||||
`hc` 4 writes eight columns of every stream a thread on 16-byte rows. Every form gives the bytes
|
||||
of the scalar kernels it replaces.
|
||||
of the scalar kernels that serve the rows it cannot read.
|
||||
|
||||
### Gemma 4's audio tower
|
||||
|
||||
@@ -518,7 +518,7 @@ form by `M`, `N` and `K`; on rows that are not 16-byte aligned it takes the 16x6
|
||||
are byte-identical (`tests/r4d_emu/test_fp8f32.cpp`). The grouped row takes equal-width parity
|
||||
tables (`N_odd = N`, `K_odd = K`), token or sorted activations, and stacked planes or pointer
|
||||
tables, and runs expert-major: a block per (column span, expert) takes every row of its expert,
|
||||
each element keeping the row-tile form's sequence.
|
||||
each element keeping the 16x64 tile's sequence.
|
||||
|
||||
**`group` has different meanings in this table.** A kernel that reads it the other way is wrong,
|
||||
not slow. `libref/ref_quant.cpp` is the definition.
|
||||
@@ -772,6 +772,8 @@ bytes).
|
||||
|---|---|---|
|
||||
| `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 `window_right`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` |
|
||||
| `attn_cross` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt | `q`, `k`, `v`, `cu_seqlens`, `cu_k` → `out` |
|
||||
| `attn_na3d` | `M`(range) `head_dim` `kt` `kh` `kw` `dtype` `scale`:f64/opt | `q`, `k`, `v`, `geom` → `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 `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/opt | `qkv`:inout, `positions` |
|
||||
@@ -801,6 +803,24 @@ with `window_right = r + 1` (non-causal only: key `j` visible when `i - j < wind
|
||||
`[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.
|
||||
|
||||
**`attn_cross`** is `attn_dense` with each entry's keys a run of their own: entry `s`'s queries
|
||||
are rows `[cu_seqlens[s], cu_seqlens[s+1])` of `q`, its keys and values rows `[cu_k[s], cu_k[s+1])`
|
||||
of `k` and `v`, and with `causal` a query sees key `j` of its run when `j <= i`, both counted from
|
||||
their run's start. A query that sees no key is zero. It is a video's rows reading their prompt
|
||||
(cross attention), and a padded prompt whose padding rows see only the prompt (`cu_k` the
|
||||
prompt's rows, `cu_seqlens` the prompt and its padding: every padding row sees every prompt row
|
||||
and none of the padding, as a masked padding token does in the reference).
|
||||
|
||||
**`attn_na3d`** is 3-D neighborhood attention, NATTEN's `na3d` (LTX-2.5's diffusion decoder). The
|
||||
rows of `q`, `k`, `v` and `out` are the voxels of the volume `geom` = `(T, H, W)` (i32 on the
|
||||
device), `(t, i, j)` row-major, each `[rows, heads head_dim]` at its own row pitch (column slices of
|
||||
a fused projection). A query sees the keys of a `kt x kh x kw` window, each extent at most its axis,
|
||||
centred on it and shifted inward at the border: along an axis of `L` and window `n` it starts at
|
||||
`clamp(c - n / 2, 0, L - n)`, so it always holds `n` keys. Per head, in f32: each score the dot over
|
||||
`d` ascending times `scale` (default `1 / sqrt(head_dim)`), the window's keys in raster order, the
|
||||
softmax as `attn_cross` takes it, the output rounded to its dtype. Rows past `T H W` are not
|
||||
written. libr4d serves `head_dim` 64.
|
||||
|
||||
**`attn_local_rel`** is Gemma 4's audio attention: local, with a relative-position term and a
|
||||
softcap. Query row `i` of a segment sees key rows `j` of the same segment with
|
||||
`0 <= i - j <= left` (`right` must be 0). Per head, `qf = q * (head_dim^-0.5 / ln 2) * softplus(pds)`
|
||||
@@ -918,8 +938,11 @@ The group is declared at `RAD_F8E4M3` with head_dim the row's bytes / 2, so the
|
||||
as it does for fp8, and the cache operand's last extent is the row. The ops take the model's
|
||||
head_dim. libr4d's rows are `kv_store_fp8v4` / `kv_store_k6v4`,
|
||||
`qk_norm_rope_gate_kv_store_fp8v4` / `_k6v4` (byte-identical to the prologue and the store, as at
|
||||
the other widths), and `attn_prefill_h256_gqa6_{fp8v4,k6v4}` and `attn_decode_h256_gqa6_{fp8v4,k6v4}`,
|
||||
which widen the codes to f16 in a tile's staging. `r4d_selftest` holds the stores to an exactly
|
||||
the other widths), `attn_prefill_h256_gqa6_{fp8v4,k6v4}` and `attn_decode_h256_gqa6_{fp8v4,k6v4}`,
|
||||
which widen the codes to f16 in a tile's staging, and the same kernels at Qwen3.8-Flash-Next's
|
||||
ratios over 4-token pages: `attn_{prefill,decode,decode_gq}_h256_gqa12_{fp8v4,k6v4}` and
|
||||
`attn_{prefill,decode,decode_gq}_h256_gqa6_bs4_{fp8v4,k6v4}`, the `decode_gq` rows with the output
|
||||
gate and quantiser in the split-KV merge. `r4d_selftest` holds the stores to an exactly
|
||||
representable set and the attention rows to its inline oracle.
|
||||
|
||||
### `qk_norm_rope_gate` (device-only)
|
||||
@@ -976,6 +999,9 @@ says which (`libref/ref_gen.cpp`).
|
||||
| `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` |
|
||||
| `table_add` | `M`(range) `n` `L` `dtype` | `x`, `t`w → `y` |
|
||||
| `mix_rows` | `M`(range) `n` `k` `dtype` | `x`, `w`w → `y` |
|
||||
| `chan_stats` | `M`(range) `n` `mode` `var`/opt `eps`:f64/opt `dtype` | `x`, `mean`w, `s`w → `y` |
|
||||
| `lane_gather` | `M`(range) `n` `stride` `dtype` | `src`, `lane`, `cu_seqlens` → `y` |
|
||||
| `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 |
|
||||
@@ -1007,8 +1033,20 @@ source into every listed lane (a repainted picture's latent into each of its ima
|
||||
store would round it, so the bytes are the three ops'.
|
||||
- `timestep_embed`: `[cos | sin]` of `t' * f_i`, `f_i = exp(-ln(max_period) * i / (n/2))` in f32,
|
||||
`t' = scale * t`; with `round` 1, `t' = scale * bf16(bf16(t * scale) / scale)`, the value
|
||||
diffusers' pipeline hands its transformer. `t` is f32 `[M]`.
|
||||
diffusers' pipeline hands its transformer; with `round` 2, `t' = scale * bf16(t)` (a pipeline
|
||||
that hands the transformer `t` in bf16 and scales it inside, Krea 2's); with `round` 3,
|
||||
`t' = bf16(scale * bf16(t))` (the scaling also in bf16, FLUX's). `t` is f32 `[M]`.
|
||||
- `gather_rows2`: `y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]]`, zeros past either source.
|
||||
- `table_add`: `y[r, l n + c] = x[r, c] + t[l, c]` for each of `L` rows of the weight `t` `[L, n]`,
|
||||
the sum f32 and rounded once: a modulation shared by every block plus each block's own learned
|
||||
table (Krea 2, LTX-2), every block's rows in one launch, read at `l n` of each `y` row.
|
||||
- `chan_stats`: a latent through per-channel statistics a VAE keeps as weights, `mean` and `s`
|
||||
`[n]`: `std` is `s`, or with `var` 1 `sqrt(s + eps)` (a BatchNorm's running variance, FLUX's VAE),
|
||||
each statistic rounded to `y`'s dtype as the reference casts it; `mode` `denorm` is
|
||||
`y = rd(rd(x std) + mean)` and `norm` is `y = rd(rd(x - mean) / std)`.
|
||||
- `mix_rows`: `y[r, c] = sum_i w[i] x[r k + i, c]` over `i < k`, f32 in ascending `i` and rounded
|
||||
once: a `Linear(k, 1)` across `k` consecutive rows (Krea 2's text fusion folds a token's twelve
|
||||
tapped encoder layers, laid out as consecutive rows, into one).
|
||||
- `randn_lanes`: for entries whose `flags` carry 1, the lane's rows become the entry's seed's
|
||||
standard-normal stream (`abi/rad_philox.h`), element `(k, c)` the stream's `k * n + c`. `seed` is
|
||||
`[n_seq, 2]` u32, low word first.
|
||||
@@ -1025,7 +1063,8 @@ shapes: an image's size belongs to a request, and a parameter is fixed at declar
|
||||
- `conv2d_nhwc`: `w` is PyTorch's `[cout, cin, k, k]` (a kernel may store it permuted through its
|
||||
layout hook), `b` `[cout]`; `up` 2 reads the input upsampled 2x nearest-neighbour; `pad` `same`
|
||||
is `k/2` zeros a side, `down` is none above and left and one below and right
|
||||
(`ZeroPad2d((0,1,0,1))` before a stride-2 conv). f32 accumulation, the bias added, one rounding.
|
||||
(`ZeroPad2d((0,1,0,1))` before a stride-2 conv), `causal` is `k - 1` rows above, none below and
|
||||
`k/2` columns a side (causal along the rows: LTX-2's audio VAE). f32 accumulation, the bias added, one rounding.
|
||||
- `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;
|
||||
@@ -1090,6 +1129,7 @@ libref function says which (`libref/ref_audio.cpp`).
|
||||
| `interleave2` | `M`(range) `dtype` | `a`, `b` → `y` |
|
||||
| `iota` | `M`(range) `start` `step` `period`/opt | → `y` |
|
||||
| `cu_repeat` | `M`(range) `mult` | `len` → `y` |
|
||||
| `int_affine` | `M`(range) `src` `mul` `add` | `x` → `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.
|
||||
@@ -1120,7 +1160,10 @@ conditional first, then the unconditional) are consecutive rows, `rep` of them a
|
||||
`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.
|
||||
sequences whose length lives on the device. `int_affine`:
|
||||
`y[j] = (src[j] < 0 ? 0 : x[src[j]]) mul[j] + add[j]` over three lists of integers of one length
|
||||
(`src` -1 a constant): the shapes and bounds a model derives from a pass's device geometry, such
|
||||
as a decoder's volume at each of its scales.
|
||||
|
||||
**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
|
||||
@@ -1194,8 +1237,8 @@ bf16 tensor and keeps f32 where it computes in f32; the libref function says whi
|
||||
|
||||
| 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`? |
|
||||
| `rms_mod` | `M`(range) `n` `eps`:f64 `gated`/opt `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `z` |
|
||||
| `rms_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `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` |
|
||||
@@ -1211,7 +1254,14 @@ reads its entry's rows of `s` and `g`.
|
||||
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.
|
||||
The residual rounds to `x`'s dtype and the norm chain to `z`'s. `wadd` is added to the gain in
|
||||
f32 (a zero-centred norm's `1 + w`), and with `norm_once` 1 the norm and its gain round together,
|
||||
`n2 = bf16(x rsqrt(mean(x^2) + eps) (w + wadd))`, as an f32 RMS norm with a gain stores its
|
||||
output (Krea 2's). `norm` `layer` (default `rms`) is a LayerNorm instead: `x` centred by its
|
||||
mean (an f32 sum in ascending order) and `rsqrt` of the centred values' biased variance plus
|
||||
`eps`. Without `w` the norm has no gain and rounds once, `n2 = bf16((x - mean) rsqrt(var +
|
||||
eps))` (FLUX.3's LayerNorm without an affine). `norm` `none` takes no norm and no gain,
|
||||
`n2 = x`, and refuses `w` (LTX-2's text keys and values, modulated as they are).
|
||||
- `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
|
||||
@@ -1376,7 +1426,7 @@ pass starts from. Each op rounds once into its output (`libref/ref_video.cpp`).
|
||||
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `conv3d_ndhwc` | `M`(range) `cin` `cout` `k` `kt` `dtype` | `x`, `w`w, `b`w, `geom`, `res`? → `y` |
|
||||
| `conv3d_ndhwc` | `M`(range) `cin` `cout` `k` `kt` `dtype` `tpad`/opt `tpre`/opt | `x`, `w`w, `b`w, `geom`, `res`? → `y` |
|
||||
| `group_norm` | `M`(range) `n` `groups` `eps`:f64 `act` `dtype` | `x`, `w`w, `b`w, `mod`?, `stats`:inout → `y` |
|
||||
| `tconv_dw` | `M`(range) `n` `k` `dtype` | `x`, `w`w, `b`w, `geom` → `y` |
|
||||
| `resize_bilinear` | `M`(range) `n` `dtype` | `x`, `geom` → `y` |
|
||||
@@ -1395,7 +1445,10 @@ Every op honours its activation operands' row pitches. `rd` is a rounding into t
|
||||
`y[(t,i,j), o] = rd(f32(sum over (dt, kh, kw, ci) of w[o, ci, dt, kh, kw]
|
||||
x[(t+dt-kt/2, i+kh-k/2, j+kw-k/2), ci]) + b[o])`, terms outside the volume zero, f32 accumulation
|
||||
in an order of the implementation's (libref: the taps in `(dt, kh, kw)` order, each tap's
|
||||
channels ascending). With `res`, `y = rd(rd(acc + b) + res)`: the convolution's output rounded,
|
||||
channels ascending). `tpad` (optional) pads the frames instead with `replicate` (the edge frame
|
||||
repeated, `kt/2` a side) or `causal` (the first frame repeated `kt - 1` times in front, nothing
|
||||
after; with `tpre` that many more copies in front, and y then has `T + tpre` frames): LTX-2's
|
||||
decoder and encoder. With `res`, `y = rd(rd(acc + b) + res)`: the convolution's output rounded,
|
||||
then the residual added and rounded, as a block's `skip(x) + h` in bf16. `res` may be the same
|
||||
memory as `y` (the residual added in place); `x` never aliases `y`. x, y, res and w bf16 (also
|
||||
f32), b bf16 or f32. MiniMax-H3: `k` = `kt` = 3, `(cin, cout)` `(24, 512)`, `(512, 512)`,
|
||||
@@ -1437,6 +1490,134 @@ Every op honours its activation operands' row pitches. `rd` is a rounding into t
|
||||
first, `stream` the parameter. `x` f32 `[M, n]` at its row pitch. MiniMax-H3: `n` 96 (the video's
|
||||
patch rows) and 32 (the soundtrack's), `stream` 1.
|
||||
|
||||
## LTX-2
|
||||
|
||||
The ops LTX-2's audio-video transformer adds (`libref/ref_ltx.cpp`): its rotary over fractional
|
||||
coordinates, the per-head gate on every attention's output, and the sampler step that combines a
|
||||
step's guidance passes in the clean-estimate space. Each rounds where the reference rounds
|
||||
(diffusers' `transformer_ltx2.py` and `pipeline_ltx2.py`): the transformer in bf16, the rotary,
|
||||
guidance and sampler in f32.
|
||||
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `rope_split` | `M`(range) `n_head` `head_dim` `dim` `n_dims` `theta`:f64 `max` `head0`/opt `dtype` | `x`:inout, `positions` |
|
||||
| `head_gate` | `M`(range) `n_head` `head_dim` `dtype` | `g`, `x`:inout |
|
||||
| `ltx_guide` | `M`(range) `n` `dtype` | `vc`, `vu`?, `vs`?, `vm`?, `scales`, `sched`, `stats`:inout, `x`:inout |
|
||||
| `pixel_norm` | `M`(range) `n` `eps`:f64 `form` `act`/opt `ileave`/opt `dtype` `mult`:f64/opt | `x` → `y` |
|
||||
| `d2s3d` | `M`(range) `C` `st` `sh` `sw` `drop`/opt `dtype` | `x`, `geom` → `y` |
|
||||
| `s2d3d` | `M`(range) `C` `st` `sh` `sw` `tpre`/opt `group`/opt `mode` `add`/opt `dtype` | `x`, `geom`, `y`:inout |
|
||||
| `pix_patch` | `M`(range) `p` `C` `order`/opt `dtype` | `x` → `y` |
|
||||
| `patch_pix8` | `M`(range) `p` `C` `order`/opt `dtype` | `x` → `y` |
|
||||
| `stft_logmel` | `M`(range) `hop` `nfft` `n_mel` `ch` `dtype` | `x`, `basis`w, `mel`w → `y` |
|
||||
| `bwe_up` | `M`(range) `ratio` `ch` `dtype` | `x`, `res` → `y` |
|
||||
| `vol_index` | `M`(range) | `geom` → `y` |
|
||||
| `tile_grid` | `M`(range) `tile` `stride` `rule`/opt `min`/opt `tile_t`/opt `stride_t`/opt `min_t`/opt `tail`/opt | `geom` → `y` |
|
||||
| `tile_crop` | `M`(range) `C` `dtype` | `x`, `geom`, `box` → `y` |
|
||||
| `tile_stitch` | `M`(range) `tile` `stride` `rule`/opt `min`/opt `tile_t`/opt `stride_t`/opt `min_t`/opt `scale` `scale_t`/opt `p` `C` `order`/opt `dtype` | `x`, `geom`, `first` → `y` |
|
||||
|
||||
- `rope_split` is LTX2AudioVideoRotaryPosEmbed's "split" rotary. Over the full width `dim` of all
|
||||
heads there are `P = dim / 2` pairs: the first `pad = P - steps n_dims` are not rotated, and the
|
||||
rest are a frequency ladder `freq[k] = f32(theta^linspace(0, 1, steps)[k] pi / 2)` (f64 before
|
||||
the cast, torch's linspace), `steps = P / n_dims`, its pairs interleaving the coordinates: pair
|
||||
`pad + k n_dims + d` turns by coordinate `d` at `freq[k]`. A coordinate `c` gives the angle
|
||||
`a = f32(f32(2 f32(c / max[d])) - 1) freq[k]`, `max` a list of `n_dims` values. Head `h` owns
|
||||
pairs `[h hd/2, (h+1) hd/2)` and turns its halves against each other,
|
||||
`o1 = f32(f32(x1 cos a) - f32(x2 sin a))`, `o2 = f32(f32(x2 cos a) + f32(x1 sin a))`, rounded to
|
||||
`x`'s dtype. `head0` is the first head the operand holds (a rank's share). `positions` is
|
||||
`[n_dims, M]`, f32 or integer, at its own strides. LTX-2.5: the video's self-attention `dim`
|
||||
4096, `n_dims` 3, `max` `20 2048 2048` (two padded pairs); the soundtrack's and both cross
|
||||
attentions' `dim` 2048, `n_dims` 1, `max` `20`; the text connectors' `max` 4096 over the row
|
||||
index.
|
||||
- `head_gate`: `x = rd(x rd(2 rd(sigmoid(g))))` for each head's `head_dim` values, `g`
|
||||
`[M, >= n_head]` the head's logit (the gated attention's `to_gate_logits`), each operand at its
|
||||
own row pitch.
|
||||
- `ltx_guide` is one sampler step over a modality's latent `x` (f32 `[M, n]`, all of it: the
|
||||
rescale's deviations are over every value) from its guidance passes' velocities (`[M, n]`, read
|
||||
as f32), all in f32:
|
||||
|
||||
x0_p = f32(x - f32(v_p sigma)) each pass p
|
||||
g = x0_c [+ f32(f32(gs - 1) f32(x0_c - x0_u))] [+ f32(stg f32(x0_c - x0_s))]
|
||||
[+ f32(f32(ms - 1) f32(x0_c - x0_m))] left to right
|
||||
r > 0: g = f32(f32(r f32(g f32(std(x0_c) / std(g)))) + f32(f32(1 - r) g))
|
||||
v = f32(f32(x - g) / sigma), x = f32(x + f32(f32(sigma_next - sigma) v))
|
||||
|
||||
A bracketed term is taken when its pass is bound and its coefficient is not zero. `std` is the
|
||||
unbiased deviation over all `M n` values, accumulated in f64. `scales` is f32 `[4]`
|
||||
`(gs, stg, ms, r)` and `sched` f32 `[2]` `(sigma, sigma_next)`, both read on the device; `stats`
|
||||
is f32 of at least 8200 values, the implementation's scratch.
|
||||
|
||||
Its VAE, audio VAE and vocoder run in bf16 tensors, and these ops round where those tensors are
|
||||
stored (`rd`, the output's dtype unless said).
|
||||
|
||||
- `pixel_norm` is an RMS norm over each row's `n` values: `m = rd(sum rd(x^2) / n)` (f32 sum in
|
||||
ascending order), then `form` `rsqrt` `z = rd(x rd(1 / sqrt(rd(m + eps))))` or `div`
|
||||
`z = rd(x / rd(sqrt(rd(m + eps))))`, with `act` silu `z = rd(z / (1 + exp(-z)))`, and with
|
||||
`mult` `z = rd(z mult)` (the connectors' scale to the DiT's width). The VAE's
|
||||
PerChannelRMSNorm and the audio VAE's PixelNorm are the div form (with the SiLU after them
|
||||
fused); the text connectors' per-layer norm is the rsqrt form, whose output `ileave` L
|
||||
interleaves: x's row `t L + l` goes to columns `c L + l` of y's row `t`, as the reference
|
||||
flattens `[C, layers]`.
|
||||
- `d2s3d` and `s2d3d` resample voxel rows (`geom` = x's `(T, H, W)`, i32 on the device), the
|
||||
packed channel of `(c, a, b, d)` being `((c st + a) sh + b) sw + d` (a the frame offset, b the
|
||||
row's, d the column's). `d2s3d` is the upsampler's depth to space,
|
||||
`y[(t st + a - drop, i sh + b, j sw + d), c] = x[(t, i, j), packed]`, the first `drop` frames
|
||||
dropped (by default `st - 1`, the causal mapping; 0 keeps them, as a decoder's tile that does not
|
||||
start the video does). `s2d3d` is the downsampler's space to depth over the volume with `tpre` leading
|
||||
frames prepended (frames `0 .. tpre - 1` again): `mode` copy writes the packed row, `mean`
|
||||
averages each run of `group` packed channels (f32 sum, divided, one rounding); with `add` 1
|
||||
`y = rd(y + v)`. `M` is x's rows.
|
||||
- `pix_patch` and `patch_pix8` are the patchifier both ways over dense 2-D operands whose shapes
|
||||
give the sizes: a `p x p` patch of `C` channels is one row of `C p p` values, channel `c`'s
|
||||
`(ph, pw)` at `c p p + pw p + ph` (`order` wh, LTX-2's) or `c p p + ph p + pw` (hw).
|
||||
`pix_patch` takes an image `[H, W C]` to `[H / p, (W / p) C p p]`; `patch_pix8` takes patch rows
|
||||
`[R, w C p p]` to RGB bytes `[R p, w p C]` by `to_rgba8`'s rule,
|
||||
`round(255 clamp(rd(rd(clamp(v, -1, 1) / 2) + 0.5), 0, 1))`, rd x's dtype.
|
||||
- `vol_index` writes a volume's voxel coordinates, the rotary positions of attention over it:
|
||||
`geom` = `(T, H, W)`, `y` i32 `[3, n]` component-major at its own row pitch, voxel
|
||||
`m = (t H + i) W + j`'s `(t, i, j)` at column `m`, for `m < min(n, T H W)`.
|
||||
- `tile_grid`, `tile_crop` and `tile_stitch` run a decoder in tiles as diffusers does: LTX-2's VAE
|
||||
(`tiled_decode`, `rule` `stride`, the default) and LTX-2.5's diffusion decoder
|
||||
(`_tile_intervals`, `rule` `intervals`). Along an axis of `L` cells a tile starts at every
|
||||
multiple of `stride` below `L`; under `intervals` an axis of `tile` cells or fewer is one tile, and
|
||||
while more than one start is left and the last leaves fewer than `min` cells (default 1) that
|
||||
start is dropped. A tile but the last is `min(tile, L - start)` long, the last runs to `L`. The
|
||||
same cut with `tile_t`, `stride_t` and `min_t` makes time bands (without `tile_t`, one band of
|
||||
every frame); tiles are raster-ordered over (time band, row band, column band). `tile_grid`
|
||||
writes the tiles of the grid `geom` = `(T, H, W)` to `y` i32 `[M, 8]`, row k
|
||||
`(t, h, w, t0, y0, x0, k, count)`, the last time band `tail` cells longer than its cut (frames a
|
||||
decoder carries past `T`); rows past the count are zero. A row's `(t, h, w)` is a decoder's volume
|
||||
operand and its first six entries `tile_crop`'s `box`: `tile_crop` copies the box
|
||||
`y[(a, i, j)] = x[(t0 + a, y0 + i, x0 + j)]` out of the volume `x` (`geom` its `(T, H, W)`).
|
||||
`tile_stitch` takes every tile's decoder output back to back in tile order: a cell is `scale`
|
||||
patches of `p x p` pixels a side and `scale_t` frames (default 1), the video's first cell one
|
||||
frame, so tile `(kt, i, j)` with cells `[t0, t1)` in time holds `scale_t (t1 - t0)` frames (less
|
||||
`scale_t - 1` when `t0` is 0) of `(h scale) x (w scale)` rows of patches (`pix_patch`'s columns).
|
||||
`geom` is the grid the tiles cut, `first` the first frame `y` holds, and `y` RGB bytes
|
||||
`[n (H scale p), (W scale p) C]`. A frame is the time band whose kept frames hold it (a band but
|
||||
the last keeps `stride_t scale_t`, the first `scale_t - 1` fewer), a pixel `(Y, X)` the tile
|
||||
`(Y / s, X / s)` of that band, `s = stride scale p`, the last band of an axis keeping the rest.
|
||||
With every product and sum rounded to `x`'s dtype and
|
||||
`mix(a, b, k, e) = rd(rd(a f32(1 - k / e)) + rd(b f32(k / e)))`, a band's picture is diffusers'
|
||||
in-place `blend_v` with the tile above and then `blend_h` with the tile to the left over
|
||||
`min(their extents, (tile - stride) scale p)` pixels, the neighbours read as their own blends
|
||||
left them (libref/ref_ltx.cpp writes the four-tile corner out), and a frame of a band within
|
||||
`min(their frames, (tile_t - stride_t) scale_t)` of its start is `blend_t` of the band before and
|
||||
this one; the byte is `patch_pix8`'s.
|
||||
- `stft_logmel` is each channel's causal log-mel spectrogram (the bandwidth extender's MelSTFT):
|
||||
`x [S, ch]`, `basis [2F, 1, nfft]` (the windowed DFT, real then imaginary rows,
|
||||
`F = nfft / 2 + 1`), `mel [n_mel, F]`; frame `t` reads samples `t hop + j - (nfft - hop)`, zero
|
||||
before the start; `s_k = rd(sum_j basis[k, j] x)`,
|
||||
`mag_k = rd(sqrt(rd(rd(re_k^2) + rd(im_k^2))))`,
|
||||
`y[t, h n_mel + m] = rd(log(max(rd(sum_k mel[m, k] mag_k), rd(1e-5))))`; y is `[S / hop, ch n_mel]`.
|
||||
- `bwe_up` is the extender's output: x `[S, ch]` raised `ratio` times by its Hann-windowed sinc
|
||||
resampler (width `w = ceil(6 / 0.99)`, `2 w ratio + 1` taps
|
||||
`rd(sinc(u) cos^2(clamp(u, -6, 6) pi / 12) 0.99 / ratio)` with `u = f32(n / ratio - w) 0.99`,
|
||||
the input's edges replicated), `up = rd(ratio rd(sum taps x))`, then
|
||||
`y = clamp(rd(res + up), -1, 1)`; rd is x's dtype, y f32 or x's dtype.
|
||||
|
||||
The VAEs' convolutions are `conv3d_ndhwc` with `tpad` and the audio VAE's `conv2d_nhwc` with
|
||||
`pad` causal.
|
||||
|
||||
## Mixture of experts
|
||||
|
||||
| op | params | operands |
|
||||
@@ -1582,9 +1763,9 @@ with `route_scale` 2.5.
|
||||
libr4d's `router_sigmoid_topk_f32` takes up to 512 experts and `top_k` up to 32, f32 logits, bias
|
||||
and weights, i32 ids, pitched rows, `M` up to 65535. It selects in one wave per row: each lane
|
||||
holds its experts as order-preserving keys (`-0` as `+0`, ties to the lower expert), and round `j`
|
||||
takes the largest key below round `j-1`'s winner. A row without NaN ranks gives the bytes of the
|
||||
serial scan. A NaN rank is never selected, and a row with fewer than `top_k` other ranks names
|
||||
expert 0 in its empty slots, weighted by expert 0's `p`.
|
||||
takes the largest key below round `j-1`'s winner. A row without NaN ranks gives the bytes of a
|
||||
serial scan with a strict `>`. A NaN rank is never selected, and a row with fewer than `top_k`
|
||||
other ranks names expert 0 in its empty slots, weighted by expert 0's `p`.
|
||||
|
||||
**`router_sigmoid_topk_scatter`** (device-only) is `router_sigmoid_topk` and `moe_scatter` over its
|
||||
`ids` in one launch, and with `gate` `[M, 1]` also the `fill` of an ungated shared arm's gate with
|
||||
@@ -1621,8 +1802,10 @@ at this dtype. The form follows the routed rows. The expert-major form, a block
|
||||
expert) that reads each expert slice once, takes up to 511 rows, and at GLM's TP8 slices (288
|
||||
experts, top 8) gate_up up to 768 and down up to 6143. At those slices the wide prefill form (P64:
|
||||
jobs of 32 or 64 rows of one expert) takes gate_up from 769 rows and down from 5760, ahead of the
|
||||
expert-major band. Elsewhere the row-group forms serve. Every form gives the bytes of the
|
||||
arithmetic-decode row-group form (`tests/r4d_emu/test_moemx.cpp`).
|
||||
expert-major band. At GLM's TP4 slices the GLM prefill form (jobs of 32 rows of one expert, its
|
||||
loads a stage ahead) takes from 512 rows; elsewhere the row groups (16 sorted rows a block) serve.
|
||||
Every form gives the bytes of one per-element sequence, restated on the host by
|
||||
`tests/r4d_emu/test_moemx.cpp`.
|
||||
|
||||
**`moe_gemm_q_mod4`** is the same GEMM over four classes by the expert's number mod 4. `w`/`w_scale`
|
||||
hold class 0 at `[N, K]` and `w_q`/`w_q_scale` class `q` at `[N_q, K_q]` (defaulting to `N`, `K`);
|
||||
@@ -1730,12 +1913,12 @@ at most 32 tokens. `mode=prefill` commits its final state and sets the count to
|
||||
scratch slot replays nothing.
|
||||
|
||||
libr4d's `kda_update_k128_v128_bf16` takes `head_k = head_v = 128`, 1 to 65535 heads, bf16
|
||||
activations, f32 `A_log`, `dt_bias` and state, both modes and both state forms. A wave holds one,
|
||||
two or four value rows of a head (four by default, the next token's operands loaded while the
|
||||
current one reduces) and runs the sequence's tokens in order; every form gives the bytes of the
|
||||
one-row kernel (`tests/r4d_emu/test_kda.cpp`). Under `anchor`, `verify` replays the accepted prefix
|
||||
in a separate dispatch before the window, so no value row overwrites factors another is still
|
||||
reading. A sequence whose window or slots are out of bounds is skipped on the device, not refused.
|
||||
activations, f32 `A_log`, `dt_bias` and state, both modes and both state forms. A wave holds four
|
||||
value rows of a head, loads the next token's operands while the current one reduces and runs the
|
||||
sequence's tokens in order (held to libref by `r4d_selftest` and `tests/r4d_emu/test_kda.cpp`).
|
||||
Under `anchor`, `verify` replays the accepted prefix in a separate dispatch before the window, so
|
||||
no value row overwrites factors another is still reading. A sequence whose window or slots are
|
||||
out of bounds is skipped on the device, not refused.
|
||||
|
||||
**Speculative rollback is part of the schema** (`spec.md` §10). The recurrent state and the conv
|
||||
window have already absorbed rejected tokens, so the state cache is a rolling window of
|
||||
@@ -2495,11 +2678,10 @@ it as bf16 high and low parts with f32 accumulation. At a multiple of 16 a tile
|
||||
one query; otherwise it pairs eight heads of two neighbouring queries, loading a key once where
|
||||
both tables name the page, so GLM-5.3's 8 heads a rank fill the tile. The pairing walks the union
|
||||
of the two tables, so each chunk runs once, for tables of up to 520 entries; past that it pairs
|
||||
by table position, with a second pass where the two differ.
|
||||
`RADIANCE_MLA_MATRIX_MAX_M` lowers the matrix row's `M` bound (65535 by default); past it the
|
||||
wave row, `mla_attn_bf16`, serves: a wave per head with an online softmax. Both split a short
|
||||
batch's history across workgroups and merge the f32 partials before narrowing, into the fixed
|
||||
scratch their hooks reserve; without scratch they compute unsplit.
|
||||
by table position, with a second pass where the two differ. Other head counts take the wave row,
|
||||
`mla_attn_bf16`: a wave per head with an online softmax. Both split a short batch's history across
|
||||
workgroups and merge the f32 partials before narrowing, into the fixed scratch their hooks
|
||||
reserve; without scratch they compute unsplit.
|
||||
|
||||
`mla_project` moves a query into the latent and a latent result out of it, through the bf16
|
||||
weight `b` `[heads*2*head_dim, latent_dim]` that stores each head's key rows, then its value rows.
|
||||
@@ -2512,8 +2694,8 @@ per-head width. Its rows are head-major, so a tensor-parallel slice of whole hea
|
||||
|
||||
libr4d's `mla_project_bf16` serves `head_dim` 256 and `latent_dim` 512, up to 64 heads, pitched
|
||||
tensors. It takes up to eight rows a thread (`absorb`) or a wave (`expand`), loading each weight
|
||||
element once for them, with every row's sum in the one-row kernels' order, so all forms give the
|
||||
same bytes.
|
||||
element once for them, with every row's sum in the same order whatever the group, so a row's bytes
|
||||
do not depend on the batch.
|
||||
|
||||
## Draft heads
|
||||
|
||||
|
||||
@@ -54,6 +54,7 @@ set(AVX_KERNEL_SRC
|
||||
avx_gen.cpp
|
||||
avx_gen_attn.cpp
|
||||
avx_video.cpp
|
||||
avx_ltx.cpp
|
||||
avx_vsa.cpp
|
||||
avx_audio.cpp
|
||||
)
|
||||
|
||||
@@ -1646,3 +1646,181 @@ AVX_KERNEL(qsa_block_key) {
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ attn_cross */
|
||||
/* attn_dense with each entry's keys a run of their own (`cu_k`), libref's attn_cross: causal
|
||||
* counts from each run's start, and a query that sees no key is zero. The same tiled online
|
||||
* softmax as attn_dense's portable path. */
|
||||
AVX_KERNEL(attn_cross) {
|
||||
if (!rad_args_have(a, 6)) return RAD_E_INVAL;
|
||||
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[3], *cuk = &a->t[4];
|
||||
const RadTensor *o = &a->t[5];
|
||||
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);
|
||||
if (head_dim <= 0 || gqa <= 0) return RAD_E_SHAPE;
|
||||
if (head_dim > AVX_HD_MAX) return RAD_E_UNSUPPORTED;
|
||||
const int64_t q_heads = q->rank >= 3 ? q->shape[q->rank - 2]
|
||||
: (q->rank == 2 ? q->shape[1] / head_dim : 1);
|
||||
const int64_t kv_heads = q_heads / gqa;
|
||||
if (kv_heads <= 0 || q_heads % gqa != 0) return RAD_E_SHAPE;
|
||||
const int64_t n_seq = numel(cu) - 1;
|
||||
if (n_seq <= 0 || numel(cuk) < n_seq + 1) return RAD_E_SHAPE;
|
||||
const int64_t total_q = numel(q) / (q_heads * head_dim);
|
||||
const int64_t total_k = numel(k) / (kv_heads * head_dim);
|
||||
if (total_q <= 0 || ldi(cu, offlin(cu, n_seq)) <= ldi(cu, offlin(cu, 0))) return RAD_E_SHAPE; /* zero rows */
|
||||
if (numel(o) < total_q * q_heads * head_dim) return RAD_E_SHAPE;
|
||||
for (int64_t s = 0; s < n_seq; ++s)
|
||||
if (ldi(cu, offlin(cu, s + 1)) < ldi(cu, offlin(cu, s)) ||
|
||||
ldi(cuk, offlin(cuk, s + 1)) < ldi(cuk, offlin(cuk, s)) ||
|
||||
ldi(cu, offlin(cu, s + 1)) > total_q || ldi(cuk, offlin(cuk, s + 1)) > total_k)
|
||||
return RAD_E_SHAPE;
|
||||
|
||||
const int64_t q_ds = q->rank >= 2 ? q->stride[q->rank - 1] : 1;
|
||||
const int64_t q_hs = q->rank >= 3 ? q->stride[q->rank - 2] : head_dim * q_ds;
|
||||
const int64_t q_rs = row_stride(q, q_heads * head_dim);
|
||||
const int64_t k_ds = k->rank >= 2 ? k->stride[k->rank - 1] : 1;
|
||||
const int64_t k_hs = k->rank >= 3 ? k->stride[k->rank - 2] : head_dim * k_ds;
|
||||
const int64_t k_rs = row_stride(k, kv_heads * head_dim);
|
||||
const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1;
|
||||
const int64_t v_hs = v->rank >= 3 ? v->stride[v->rank - 2] : head_dim * v_ds;
|
||||
const int64_t v_rs = row_stride(v, kv_heads * head_dim);
|
||||
const int64_t o_ds = o->rank >= 2 ? o->stride[o->rank - 1] : 1;
|
||||
const int64_t o_hs = o->rank >= 3 ? o->stride[o->rank - 2] : head_dim * o_ds;
|
||||
const int64_t o_rs = row_stride(o, q_heads * head_dim);
|
||||
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
|
||||
|
||||
AVX_PARALLEL_FOR_IF(n_seq * q_heads >= 2)
|
||||
for (int64_t sh = 0; sh < n_seq * q_heads; ++sh) {
|
||||
const int64_t s = sh / q_heads, h = sh % q_heads, kh = h / gqa;
|
||||
const int64_t b0 = ldi(cu, offlin(cu, s)), b1 = ldi(cu, offlin(cu, s + 1));
|
||||
const int64_t k0 = ldi(cuk, offlin(cuk, s)), k1 = ldi(cuk, offlin(cuk, s + 1));
|
||||
float* frame = (float*)scratch_f32((size_t)(4 * head_dim + AVX_KV_TILE) + 16);
|
||||
float* qbuf = frame;
|
||||
float* kbuf = frame + head_dim;
|
||||
float* vbuf = frame + 2 * head_dim;
|
||||
float* acc = frame + 3 * head_dim;
|
||||
float* sbuf = frame + 4 * head_dim;
|
||||
int64_t vbase[AVX_KV_TILE];
|
||||
for (int64_t i = b0; i < b1; ++i) {
|
||||
const int64_t qb = i * q_rs + h * q_hs, ob = i * o_rs + h * o_hs;
|
||||
const int64_t jend = causal ? std::min<int64_t>(k1, k0 + (i - b0) + 1) : k1;
|
||||
const float* qv = head_f32(q, qb, q_ds, head_dim, 1.0f, qbuf);
|
||||
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
|
||||
float m = -INFINITY, l = 0.0f;
|
||||
int ntile = 0;
|
||||
auto flush = [&]() {
|
||||
if (ntile == 0) return;
|
||||
float tmax = sbuf[0];
|
||||
for (int t = 1; t < ntile; ++t) if (sbuf[t] > tmax) tmax = sbuf[t];
|
||||
if (tmax > m) {
|
||||
const float r = (m == -INFINITY) ? 0.0f : sc_exp(m - tmax);
|
||||
if (r != 1.0f) {
|
||||
for (int64_t d = 0; d < head_dim; ++d) acc[d] *= r;
|
||||
l *= r;
|
||||
}
|
||||
m = tmax;
|
||||
}
|
||||
for (int t = 0; t < ntile; ++t) sbuf[t] = sc_exp(sbuf[t] - m);
|
||||
for (int t = 0; t < ntile; ++t) {
|
||||
const float w = sbuf[t];
|
||||
l += w;
|
||||
axpy(acc, head_f32(v, vbase[t], v_ds, head_dim, 1.0f, vbuf), w, head_dim);
|
||||
}
|
||||
ntile = 0;
|
||||
};
|
||||
for (int64_t j = k0; j < jend; ++j) {
|
||||
const float* kvr = head_f32(k, j * k_rs + kh * k_hs, k_ds, head_dim, 1.0f, kbuf);
|
||||
sbuf[ntile] = dotf(qv, kvr, head_dim) * scale;
|
||||
vbase[ntile] = j * v_rs + kh * v_hs;
|
||||
if (++ntile == AVX_KV_TILE) flush();
|
||||
}
|
||||
flush();
|
||||
if (m == -INFINITY) {
|
||||
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f);
|
||||
continue;
|
||||
}
|
||||
const float inv = l > 0.0f ? 1.0f / l : 0.0f;
|
||||
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* attn_na3d: libref's neighborhood attention (libref/ref_attn.cpp), the window's keys through
|
||||
* attn_cross's online softmax. */
|
||||
AVX_KERNEL(attn_na3d) {
|
||||
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *G = &a->t[3], *o = &a->t[4];
|
||||
const int64_t head_dim = p_int(a, "head_dim", 0);
|
||||
const int64_t kt = p_int(a, "kt", 0), kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0);
|
||||
if (head_dim <= 0 || kt <= 0 || kh <= 0 || kw <= 0 || numel(G) < 3 || q->rank != 2)
|
||||
return RAD_E_SHAPE;
|
||||
if (head_dim > AVX_HD_MAX) return RAD_E_UNSUPPORTED;
|
||||
const int64_t heads = q->shape[1] / head_dim;
|
||||
const int64_t T = ldi(G, offlin(G, 0)), H = ldi(G, offlin(G, 1)), W = ldi(G, offlin(G, 2));
|
||||
if (heads <= 0 || q->shape[1] % head_dim || T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE;
|
||||
const int64_t N = std::min(q->shape[0], T * H * W);
|
||||
if (N <= 0 || numel(k) < N * heads * head_dim || numel(v) < N * heads * head_dim ||
|
||||
numel(o) < N * heads * head_dim)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t nt = std::min(kt, T), nh = std::min(kh, H), nw = std::min(kw, W);
|
||||
const int64_t q_ds = q->stride[1], q_rs = row_stride(q, heads * head_dim);
|
||||
const int64_t k_ds = k->rank >= 2 ? k->stride[k->rank - 1] : 1, k_rs = row_stride(k, heads * head_dim);
|
||||
const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1, v_rs = row_stride(v, heads * head_dim);
|
||||
const int64_t o_ds = o->rank >= 2 ? o->stride[o->rank - 1] : 1, o_rs = row_stride(o, heads * head_dim);
|
||||
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
|
||||
auto start = [](int64_t c, int64_t n, int64_t L) {
|
||||
return std::min(std::max<int64_t>(c - n / 2, 0), L - n);
|
||||
};
|
||||
AVX_PARALLEL_FOR_IF(N * heads >= 2)
|
||||
for (int64_t rh = 0; rh < N * heads; ++rh) {
|
||||
const int64_t r = rh / heads, h = rh % heads;
|
||||
const int64_t t = r / (H * W), i = (r / W) % H, j = r % W;
|
||||
const int64_t t0 = start(t, nt, T), i0 = start(i, nh, H), j0 = start(j, nw, W);
|
||||
float* frame = (float*)scratch_f32((size_t)(4 * head_dim + AVX_KV_TILE) + 16);
|
||||
float* qbuf = frame;
|
||||
float* kbuf = frame + head_dim;
|
||||
float* vbuf = frame + 2 * head_dim;
|
||||
float* acc = frame + 3 * head_dim;
|
||||
float* sbuf = frame + 4 * head_dim;
|
||||
int64_t vbase[AVX_KV_TILE];
|
||||
const int64_t ob = r * o_rs + h * head_dim * o_ds;
|
||||
const float* qv = head_f32(q, r * q_rs + h * head_dim * q_ds, q_ds, head_dim, 1.0f, qbuf);
|
||||
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
|
||||
float m = -INFINITY, l = 0.0f;
|
||||
int ntile = 0;
|
||||
auto flush = [&]() {
|
||||
if (ntile == 0) return;
|
||||
float tmax = sbuf[0];
|
||||
for (int u = 1; u < ntile; ++u) if (sbuf[u] > tmax) tmax = sbuf[u];
|
||||
if (tmax > m) {
|
||||
const float rr = (m == -INFINITY) ? 0.0f : sc_exp(m - tmax);
|
||||
if (rr != 1.0f) {
|
||||
for (int64_t d = 0; d < head_dim; ++d) acc[d] *= rr;
|
||||
l *= rr;
|
||||
}
|
||||
m = tmax;
|
||||
}
|
||||
for (int u = 0; u < ntile; ++u) sbuf[u] = sc_exp(sbuf[u] - m);
|
||||
for (int u = 0; u < ntile; ++u) {
|
||||
l += sbuf[u];
|
||||
axpy(acc, head_f32(v, vbase[u], v_ds, head_dim, 1.0f, vbuf), sbuf[u], head_dim);
|
||||
}
|
||||
ntile = 0;
|
||||
};
|
||||
for (int64_t a1 = t0; a1 < t0 + nt; ++a1)
|
||||
for (int64_t b1 = i0; b1 < i0 + nh; ++b1)
|
||||
for (int64_t c1 = j0; c1 < j0 + nw; ++c1) {
|
||||
const int64_t key = (a1 * H + b1) * W + c1;
|
||||
const float* kr = head_f32(k, key * k_rs + h * head_dim * k_ds, k_ds, head_dim, 1.0f, kbuf);
|
||||
sbuf[ntile] = dotf(qv, kr, head_dim) * scale;
|
||||
vbase[ntile] = key * v_rs + h * head_dim * v_ds;
|
||||
if (++ntile == AVX_KV_TILE) flush();
|
||||
}
|
||||
flush();
|
||||
const float inv = l > 0.0f ? 1.0f / l : 0.0f;
|
||||
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -1094,6 +1094,37 @@ AVX_KERNEL(iota) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ int_affine */
|
||||
/* y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists. */
|
||||
static int avx_parse_ints(const char* s, int64_t* v, int cap) {
|
||||
int n = 0;
|
||||
while (s && *s) {
|
||||
char* e = nullptr;
|
||||
const long long x = std::strtoll(s, &e, 10);
|
||||
if (e == s) break;
|
||||
if (n == cap) return -1;
|
||||
v[n++] = x;
|
||||
s = e;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
AVX_KERNEL(int_affine) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *Y = &a->t[1];
|
||||
int64_t src[16], mul[16], add[16];
|
||||
const int n = avx_parse_ints(p_str(a, "src", ""), src, 16);
|
||||
if (n <= 0 || avx_parse_ints(p_str(a, "mul", ""), mul, 16) != n ||
|
||||
avx_parse_ints(p_str(a, "add", ""), add, 16) != n || numel(Y) < n)
|
||||
return RAD_E_SHAPE;
|
||||
for (int j = 0; j < n; ++j) {
|
||||
if (src[j] >= numel(X)) return RAD_E_SHAPE;
|
||||
const int64_t v = src[j] < 0 ? 0 : at(X, src[j]);
|
||||
st_int_dt(Y->dtype, Y->data, offlin(Y, j), v * mul[j] + add[j]);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ cu_repeat */
|
||||
/* y[j] = j * len[0] * mult over y's elements: the bounds of equal sequences. */
|
||||
AVX_KERNEL(cu_repeat) {
|
||||
|
||||
+64
-1
@@ -359,6 +359,17 @@ std::vector<Case> build_cases() {
|
||||
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 1), HI("causal", 0),
|
||||
HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24),
|
||||
HI("block", 7) });
|
||||
/* Cross attention: each entry's keys a run of their own, both sides of `causal`. */
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
for (int causal : { 0, 1 })
|
||||
add("attn_cross", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2),
|
||||
HI("causal", causal), HS("dtype", dt), HF("scale", 0.125) });
|
||||
/* Neighborhood attention: a 4 x 4 x 4 volume (the description's), windows narrower and as wide
|
||||
* as its axes. */
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
for (int kw : { 3, 4 })
|
||||
add("attn_na3d", { HI("M", 64), HI("head_dim", 64), HI("kt", 3), HI("kh", 3),
|
||||
HI("kw", kw), HS("dtype", dt) });
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
add("seg_sinusoid", { HI("M", 30), HI("n", 64), HI("period", 13), HS("dtype", dt) });
|
||||
/* Gemma 4's audio attention: left 12, over segments longer than the window. */
|
||||
@@ -698,10 +709,16 @@ std::vector<Case> build_cases() {
|
||||
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));
|
||||
add("table_add", { HI("M", 3), HI("n", 645), HI("L", 5), HS("dtype", dt) });
|
||||
add("mix_rows", { HI("M", 7), HI("n", 645), HI("k", 12), HS("dtype", dt) });
|
||||
for (const char* mode : { "denorm", "norm" })
|
||||
for (int var : { 0, 1 })
|
||||
add("chan_stats", { HI("M", 7), HI("n", 645), HS("mode", mode), HI("var", var),
|
||||
HF("eps", 1e-4), HS("dtype", dt) });
|
||||
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) });
|
||||
for (int round : { 1, 0 })
|
||||
for (int round : { 3, 2, 1, 0 })
|
||||
add("timestep_embed", { HI("M", 3), HI("n", 256), HF("scale", 1000.0),
|
||||
HF("max_period", 10000.0), HI("round", round),
|
||||
HS("dtype", dt) });
|
||||
@@ -776,6 +793,17 @@ std::vector<Case> build_cases() {
|
||||
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) });
|
||||
/* A zero-centred gain (1 + w), the norm and gain rounded once (Krea 2's). */
|
||||
add("rms_mod", { HI("M", 7), HI("n", 645), HF("eps", 1e-5), HI("gated", gated),
|
||||
HS("dtype", dt), HF("wadd", 1.0), HI("norm_once", 1) });
|
||||
add("rms_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-5), HI("group", 128),
|
||||
HI("gated", gated), HS("dtype", dt), HF("wadd", 1.0),
|
||||
HI("norm_once", 1) });
|
||||
/* A LayerNorm without a gain (FLUX's). */
|
||||
add("rms_mod", { HI("M", 7), HI("n", 645), HF("eps", 1e-6), HI("gated", gated),
|
||||
HS("dtype", dt), HS("norm", "layer") });
|
||||
add("rms_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-6), HI("group", 128),
|
||||
HI("gated", gated), HS("dtype", dt), HS("norm", "layer") });
|
||||
}
|
||||
add("flow_x0_step", { HI("M", 9), HI("n", 645), HS("dtype", dt) });
|
||||
for (int pt : { 1, 4 })
|
||||
@@ -833,6 +861,37 @@ std::vector<Case> build_cases() {
|
||||
add("flow_renoise", { HI("M", 9), HI("n", 96), HI("stream", 1), HS("dtype", "f32") });
|
||||
add("flow_renoise", { HI("M", 5), HI("n", 645), HI("stream", 7), HS("dtype", "f32") });
|
||||
|
||||
/* LTX-2: the video's 3-axis rotary (two padded pairs, a rank's second head), the cross
|
||||
* attentions' 1-axis one, the per-head gate and the guided step. */
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
add("rope_split", { HI("M", 7), HI("n_head", 3), HI("head_dim", 128), HI("dim", 4096),
|
||||
HI("n_dims", 3), HF("theta", 10000.0), HS("max", "20 2048 2048"),
|
||||
HI("head0", 1), HS("dtype", dt) });
|
||||
add("rope_split", { HI("M", 5), HI("n_head", 4), HI("head_dim", 64), HI("dim", 256),
|
||||
HI("n_dims", 1), HF("theta", 10000.0), HS("max", "20"),
|
||||
HS("dtype", dt) });
|
||||
add("head_gate", { HI("M", 7), HI("n_head", 5), HI("head_dim", 64), HS("dtype", dt) });
|
||||
add("ltx_guide", { HI("M", 9), HI("n", 128), HS("dtype", dt) });
|
||||
add("pixel_norm", { HI("M", 26), HI("n", 96), HF("eps", 1e-6), HS("form", "rsqrt"),
|
||||
HI("ileave", 13), HF("mult", 3.7), HS("dtype", dt) });
|
||||
add("pixel_norm", { HI("M", 7), HI("n", 256), HF("eps", 1e-8), HS("form", "div"),
|
||||
HS("act", "silu"), HS("dtype", dt) });
|
||||
add("d2s3d", { HI("M", 27), HI("C", 5), HI("st", 2), HI("sh", 2), HI("sw", 2),
|
||||
HS("dtype", dt) });
|
||||
add("s2d3d", { HI("M", 27), HI("C", 4), HI("st", 2), HI("sh", 1), HI("sw", 1),
|
||||
HI("tpre", 1), HS("mode", "copy"), HS("dtype", dt) });
|
||||
add("s2d3d", { HI("M", 64), HI("C", 6), HI("st", 2), HI("sh", 2), HI("sw", 2),
|
||||
HI("group", 4), HS("mode", "mean"), HI("add", 1), HS("dtype", dt) });
|
||||
add("pix_patch", { HI("M", 12), HI("p", 4), HI("C", 3), HS("dtype", dt) });
|
||||
add("patch_pix8", { HI("M", 12), HI("p", 4), HI("C", 3), HS("dtype", dt) });
|
||||
add("stft_logmel", { HI("M", 6), HI("hop", 80), HI("nfft", 512), HI("n_mel", 64),
|
||||
HI("ch", 2), HS("dtype", dt) });
|
||||
add("bwe_up", { HI("M", 600), HI("ratio", 3), HI("ch", 2), HS("dtype", dt) });
|
||||
add("tile_crop", { HI("M", 125), HI("C", 7), HS("dtype", dt) });
|
||||
add("tile_stitch", { HI("M", 4000), HI("tile", 4), HI("stride", 3), HI("scale", 2),
|
||||
HI("p", 4), HI("C", 3), HS("dtype", dt) });
|
||||
}
|
||||
|
||||
/* 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
|
||||
@@ -967,9 +1026,13 @@ std::vector<Case> build_cases() {
|
||||
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("tile_grid", { HI("M", 9), HI("tile", 16), HI("stride", 14) });
|
||||
add("vol_index", { HI("M", 125) });
|
||||
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) });
|
||||
add("int_affine", { HI("M", 4), HS("src", "0 -1 2 1"), HS("mul", "2 0 8 4"),
|
||||
HS("add", "-1 7 -7 -3") });
|
||||
|
||||
/* ================================================================== speed-only, at model size
|
||||
*
|
||||
|
||||
+123
-16
@@ -325,21 +325,27 @@ AVX_KERNEL(ln_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
|
||||
* libref's rule); `norm` none takes n2 = x. 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 *Yv = rad_arg_in(a, 0), *G = rad_arg_in(a, 1), *S = &a->t[2];
|
||||
const RadTensor* W = rad_arg_in(a, 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);
|
||||
const float wadd = p_f32(a, "wadd", 0.0f);
|
||||
const bool once = p_int(a, "norm_once", 0) != 0;
|
||||
const char* nk = p_str(a, "norm", "rms");
|
||||
const bool layer = std::strcmp(nk, "layer") == 0, none = std::strcmp(nk, "none") == 0;
|
||||
if ((!layer && !none && std::strcmp(nk, "rms") != 0) || (none && W)) return RAD_E_INVAL;
|
||||
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 ||
|
||||
if (rows <= 0 || n_seq <= 0 || rows_of(X, n) < rows || (W && 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;
|
||||
@@ -359,7 +365,8 @@ static int rms_mod_run(const RadArgs* a, bool quant) {
|
||||
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));
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
tabs[n_seq * tw + i] = W ? ldt(W, i * laststride(W)) + wadd : 1.0f;
|
||||
}
|
||||
const float* wrow = tabs + n_seq * tw;
|
||||
|
||||
@@ -380,13 +387,23 @@ static int rms_mod_run(const RadArgs* a, bool quant) {
|
||||
} else {
|
||||
std::memcpy(v, xv, (size_t)n * sizeof(float));
|
||||
}
|
||||
const float rs = 1.0f / std::sqrt(row_sumsq(v, n) / (float)n + eps);
|
||||
if (layer) {
|
||||
/* Centred first, the mean an f32 sum in ascending order (libref's). */
|
||||
float mu = 0.0f;
|
||||
for (int64_t k = 0; k < n; ++k) mu += v[k];
|
||||
mu /= (float)n;
|
||||
for (int64_t k = 0; k < n; ++k) v[k] -= mu;
|
||||
}
|
||||
/* `none`: no norm, the residual as it is (libref's n2 = x). */
|
||||
const float rs = none ? 1.0f : 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);
|
||||
if (W) {
|
||||
if (!once) 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);
|
||||
@@ -424,7 +441,9 @@ AVX_KERNEL(timestep_embed) {
|
||||
for (int64_t i = 0; i < h; ++i) f[i] = sc_exp(coef * (float)i / (float)h);
|
||||
for (int64_t m = 0; m < rows; ++m) {
|
||||
const float tv = ldt(T, offlin(T, m));
|
||||
const float tt = round ? scale * narrow1(RAD_BF16, narrow1(RAD_BF16, tv * scale) / scale)
|
||||
const float tt = round == 3 ? narrow1(RAD_BF16, scale * narrow1(RAD_BF16, tv))
|
||||
: round == 2 ? scale * narrow1(RAD_BF16, tv)
|
||||
: round ? scale * narrow1(RAD_BF16, narrow1(RAD_BF16, tv * scale) / scale)
|
||||
: scale * tv;
|
||||
for (int64_t i = 0; i < h; ++i) {
|
||||
const float arg = tt * f[i];
|
||||
@@ -553,14 +572,15 @@ AVX_KERNEL(randn_lanes) {
|
||||
* x' = bf16(x + bf16(bf16(sigma_next - sigma) * v'))
|
||||
*
|
||||
* flag 4 writes x - sigma v' to the lane's preview, and flag 2 restores the kept region,
|
||||
* x' = bf16(m x' + (1 - m)((1 - sigma_next) src + sigma_next noise)). libref requires every
|
||||
* operand, the optional three included. Every entry is checked before any lane is written. */
|
||||
* x' = bf16(m x' + (1 - m)((1 - sigma_next) src + sigma_next noise)). inp, mask and preview are
|
||||
* optional, as in libref: an entry whose flags need one that is absent is refused. Every entry is
|
||||
* checked before any lane is written. */
|
||||
AVX_KERNEL(flow_euler) {
|
||||
if (!rad_args_have(a, 13)) return RAD_E_INVAL;
|
||||
if (!rad_args_have(a, 9) || !rad_arg_in(a, 11)) return RAD_E_INVAL;
|
||||
const RadTensor *V = &a->t[0], *sg = &a->t[1], *sgn = &a->t[2], *cfg = &a->t[3];
|
||||
const RadTensor *pair = &a->t[4], *lane = &a->t[5], *fl = &a->t[6], *seed = &a->t[7];
|
||||
const RadTensor *cu = &a->t[8], *inp = &a->t[9], *mask = &a->t[10], *st = &a->t[11];
|
||||
const RadTensor* pv = &a->t[12];
|
||||
const RadTensor *cu = &a->t[8], *inp = rad_arg_in(a, 9), *mask = rad_arg_in(a, 10);
|
||||
const RadTensor *st = &a->t[11], *pv = rad_arg_in(a, 12);
|
||||
const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0);
|
||||
if (n <= 0 || stride <= 0) return RAD_E_SHAPE;
|
||||
const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n), v_rows = rows_of(V, n);
|
||||
@@ -576,6 +596,8 @@ AVX_KERNEL(flow_euler) {
|
||||
if (len > 0 && (b0 < 0 || b0 + len > v_rows)) return RAD_E_SHAPE;
|
||||
if (pr >= 0 && len > 0 && (cu_at(cu, pr) < 0 || cu_at(cu, pr) + len > v_rows))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t f = ldi(fl, offlin(fl, e));
|
||||
if (((f & kInpaint) && (!inp || !mask)) || ((f & kPreview) && !pv)) return RAD_E_INVAL;
|
||||
}
|
||||
const uint32_t dt = st->dtype;
|
||||
for (int64_t e = 0; e < n_seq; ++e) {
|
||||
@@ -776,8 +798,11 @@ AVX_KERNEL(conv2d_nhwc) {
|
||||
const int64_t Ho = Y->shape[0], Wo = Y->shape[1] / cout;
|
||||
if (Hin <= 0 || Win <= 0 || Ho <= 0 || Wo <= 0) return RAD_E_SHAPE;
|
||||
const int64_t Hv = Hin * up, Wv = Win * up;
|
||||
const int64_t pt = down ? 0 : k / 2, pb = down ? 1 : k / 2;
|
||||
if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pt + pb - k) / stride + 1 != Wo)
|
||||
/* `causal` pads k - 1 rows above and none below (libref's). */
|
||||
const bool causal = pad && !std::strcmp(pad, "causal");
|
||||
const int64_t pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2;
|
||||
const int64_t pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
|
||||
if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pl + pr - k) / stride + 1 != Wo)
|
||||
return RAD_E_SHAPE;
|
||||
if (numel(W) < cout * cin * k * k || numel(B) < cout) return RAD_E_SHAPE;
|
||||
const int64_t xr = X->stride[0], yr = Y->stride[0];
|
||||
@@ -855,7 +880,7 @@ AVX_KERNEL(conv2d_nhwc) {
|
||||
for (int64_t kh = 0; kh < k; ++kh) {
|
||||
const int64_t iy = oy * stride + kh - pt;
|
||||
for (int64_t kw = 0; kw < k; ++kw) {
|
||||
const int64_t ix = ox * stride + kw - pt;
|
||||
const int64_t ix = ox * stride + kw - pl;
|
||||
char* d = dst + (size_t)((kh * k + kw) * cin) * ael;
|
||||
if (iy < 0 || iy >= Hv || ix < 0 || ix >= Wv) {
|
||||
std::memset(d, 0, (size_t)cin * ael);
|
||||
@@ -1186,3 +1211,85 @@ AVX_KERNEL(scatter_add_rows) {
|
||||
for (int64_t m = 0; m < M; ++m) add_row(m);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ table_add */
|
||||
/* libref's table_add: y[r, l n + c] = x[r, c] + t[l, c], f32 sum rounded once to y's dtype. */
|
||||
AVX_KERNEL(table_add) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *T = &a->t[1], *Y = &a->t[2];
|
||||
const int64_t n = p_int(a, "n", 0), L = p_int(a, "L", 0);
|
||||
if (n <= 0 || L <= 0 || numel(T) < L * n) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(Y, L * n);
|
||||
if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE;
|
||||
AVX_PARALLEL_FOR_IF(rows * L * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* buf = scratch_f32((size_t)(3 * n + 64));
|
||||
float *xs = buf, *ts = buf + n + 16, *p = ts + n + 16;
|
||||
const float* xv = in_row(X, rowoff(X, r, n), n, xs);
|
||||
for (int64_t l = 0; l < L; ++l) {
|
||||
const float* tv = in_row(T, l * n * laststride(T), n, ts);
|
||||
for (int64_t c = 0; c < n; ++c) p[c] = xv[c] + tv[c];
|
||||
out_row(Y, rowoff(Y, r, L * n) + l * n * laststride(Y), n, p);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ mix_rows */
|
||||
/* libref's mix_rows: y[r, c] = sum_i w[i] x[r k + i, c], f32 in ascending i, rounded once. */
|
||||
AVX_KERNEL(mix_rows) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *W = &a->t[1], *Y = &a->t[2];
|
||||
const int64_t n = p_int(a, "n", 0), k = p_int(a, "k", 0);
|
||||
if (n <= 0 || k <= 0 || numel(W) < k) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(Y, n);
|
||||
if (rows <= 0 || rows_of(X, n) < rows * k) return RAD_E_SHAPE;
|
||||
std::vector<float> w((size_t)k);
|
||||
for (int64_t i = 0; i < k; ++i) w[(size_t)i] = ldt(W, i * laststride(W));
|
||||
AVX_PARALLEL_FOR_IF(rows * n * k >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* buf = scratch_f32((size_t)(2 * n + 64));
|
||||
float *xs = buf, *acc = buf + n + 16;
|
||||
for (int64_t c = 0; c < n; ++c) acc[c] = 0.0f;
|
||||
for (int64_t i = 0; i < k; ++i) {
|
||||
const float* xv = in_row(X, rowoff(X, r * k + i, n), n, xs);
|
||||
for (int64_t c = 0; c < n; ++c) acc[c] += w[(size_t)i] * xv[c];
|
||||
}
|
||||
out_row(Y, rowoff(Y, r, n), n, acc);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ chan_stats */
|
||||
/* libref's chan_stats: per-channel statistics held as weights, every step rounded as libref. */
|
||||
AVX_KERNEL(chan_stats) {
|
||||
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *Mn = &a->t[1], *Sd = &a->t[2], *Y = &a->t[3];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
const bool var = p_int(a, "var", 0) != 0;
|
||||
const float eps = p_f32(a, "eps", 0.0f);
|
||||
const char* mode = p_str(a, "mode", "denorm");
|
||||
const bool norm = std::strcmp(mode, "norm") == 0;
|
||||
if (!norm && std::strcmp(mode, "denorm") != 0) return RAD_E_INVAL;
|
||||
if (n <= 0 || numel(Mn) < n || numel(Sd) < n) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(Y, n);
|
||||
if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE;
|
||||
const uint32_t dt = Y->dtype;
|
||||
std::vector<float> mu((size_t)n), sd((size_t)n);
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
mu[(size_t)c] = narrow1(dt, ldt(Mn, c * laststride(Mn)));
|
||||
const float v = ldt(Sd, c * laststride(Sd));
|
||||
sd[(size_t)c] = narrow1(dt, var ? std::sqrt(v + eps) : v);
|
||||
}
|
||||
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* buf = scratch_f32((size_t)(2 * n + 32));
|
||||
float *xs = buf, *o = buf + n + 16;
|
||||
const float* xv = in_row(X, rowoff(X, r, n), n, xs);
|
||||
for (int64_t c = 0; c < n; ++c)
|
||||
o[c] = norm ? narrow1(dt, narrow1(dt, xv[c] - mu[(size_t)c]) / sd[(size_t)c])
|
||||
: narrow1(dt, narrow1(dt, xv[c] * sd[(size_t)c]) + mu[(size_t)c]);
|
||||
out_row(Y, rowoff(Y, r, n), n, o);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
+7
-2
@@ -100,7 +100,7 @@ int avx_par_force(int threads);
|
||||
X(gemm_nt_q_gated) X(embed_lookup) X(embed_lookup_q) X(logits_gemm) \
|
||||
X(lora_shrink) X(lora_expand) \
|
||||
/* ---- attention */ \
|
||||
X(attn_paged) X(attn_dense) X(kv_store) X(rope) \
|
||||
X(attn_paged) X(attn_dense) X(attn_cross) X(attn_na3d) X(table_add) X(mix_rows) X(chan_stats) X(kv_store) X(rope) \
|
||||
X(rope_table) X(qk_norm_rope) X(qsa_block_key) X(attn_local_rel) \
|
||||
X(qsa_score) X(qsa_select) X(qsa_tail_store) X(qsa_work) \
|
||||
/* ---- mixture of experts */ \
|
||||
@@ -123,12 +123,17 @@ int avx_par_force(int threads);
|
||||
X(vtile_gather) X(vtile_stitch) X(grid_pos3) X(vsa_select) \
|
||||
X(attn_vsa) X(conv3d_ndhwc) X(group_norm) X(tconv_dw) \
|
||||
X(resize_bilinear) X(patch_fold) X(flow_renoise) \
|
||||
/* ---- LTX-2 */ \
|
||||
X(rope_split) X(head_gate) X(ltx_guide) X(pixel_norm) \
|
||||
X(d2s3d) X(s2d3d) X(pix_patch) X(patch_pix8) \
|
||||
X(stft_logmel) X(bwe_up) X(tile_grid) X(tile_crop) \
|
||||
X(tile_stitch) X(vol_index) \
|
||||
/* ---- audio generation */ \
|
||||
X(conv1d) X(conv_t1d) X(snake) X(cfg_topk_sample) \
|
||||
X(rvq_embed) X(frame_mix_store) X(end_status) X(frame_store) \
|
||||
X(resample_nearest) X(fourier_embed) X(win_input) X(win_prep) \
|
||||
X(win_finish) X(chan_split) X(interleave2) X(iota) \
|
||||
X(cu_repeat) X(snake_aa) \
|
||||
X(cu_repeat) X(snake_aa) X(int_affine) \
|
||||
/* ---- sampling, and the drafter's token walk */ \
|
||||
X(sample_penalties) X(sample_dry) X(sample_temp) X(sample_topk) \
|
||||
X(sample_topp) X(sample_minp) X(sample_typical) X(sample_xtc) \
|
||||
|
||||
@@ -0,0 +1,604 @@
|
||||
/* avx_ltx.cpp -- LTX-2's ops (docs/OPS.md, "LTX-2"): its rotary over fractional coordinates, the
|
||||
* per-head attention gate, the guided sampler step, its VAE's norm, resampling and patches, and its
|
||||
* vocoder's spectrogram and resampler. libref's arithmetic, element by element
|
||||
* (libref/ref_ltx.cpp states the roundings): LTX-2 is a GPU model, and these run on the CPU only
|
||||
* where a whole model does, so they are written for agreement rather than speed.
|
||||
*/
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
using namespace avx;
|
||||
|
||||
namespace {
|
||||
|
||||
/* A product the compiler may not fuse into the add after it (libavx builds with
|
||||
* -ffp-contract=fast; libref rounds the product first). */
|
||||
inline float keep(float x) { __asm__("" : "+x"(x)); return x; }
|
||||
|
||||
double linspace01(int64_t i, int64_t steps) {
|
||||
if (steps <= 1) return 0.0;
|
||||
const double step = 1.0 / (double)(steps - 1);
|
||||
return i < steps / 2 ? step * (double)i : 1.0 - step * (double)(steps - 1 - i);
|
||||
}
|
||||
|
||||
int parse_floats(const char* s, std::vector<float>* out) {
|
||||
out->clear();
|
||||
while (s && *s) {
|
||||
char* end = nullptr;
|
||||
const double v = std::strtod(s, &end);
|
||||
if (end == s) break;
|
||||
out->push_back((float)v);
|
||||
s = end;
|
||||
}
|
||||
return (int)out->size();
|
||||
}
|
||||
|
||||
inline int64_t at_i(const RadTensor* t, int64_t i) {
|
||||
return (int64_t)ld_elem(t->data, t->dtype, i * laststride(t));
|
||||
}
|
||||
|
||||
float pos_at(const RadTensor* p, int64_t d, int64_t r) {
|
||||
const int64_t off = p->rank >= 2 ? d * p->stride[0] + r * p->stride[1] : r * laststride(p);
|
||||
return ldt(p, off);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ------------------------------------------------------------------ rope_split */
|
||||
AVX_KERNEL(rope_split) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *P = &a->t[1];
|
||||
const int64_t nh = p_int(a, "n_head", 0), hd = p_int(a, "head_dim", 0);
|
||||
const int64_t dim = p_int(a, "dim", 0), nd = p_int(a, "n_dims", 0), h0 = p_int(a, "head0", 0);
|
||||
const double theta = (double)p_f32(a, "theta", 10000.0f);
|
||||
std::vector<float> mx;
|
||||
if (nh <= 0 || hd <= 0 || (hd & 1) || nd <= 0 || dim < (h0 + nh) * hd ||
|
||||
parse_floats(p_str(a, "max", ""), &mx) != (int)nd)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t P2 = dim / 2, steps = P2 / nd, pad = P2 - steps * nd, half = hd / 2;
|
||||
const int64_t rows = rows_of(X, nh * hd);
|
||||
if (rows <= 0 || P->rank < 1) return RAD_E_SHAPE;
|
||||
std::vector<float> freq((size_t)steps);
|
||||
for (int64_t k = 0; k < steps; ++k)
|
||||
freq[(size_t)k] = (float)(std::pow(theta, linspace01(k, steps)) * M_PI / 2.0);
|
||||
const int64_t xs = laststride(X);
|
||||
AVX_PARALLEL_FOR_IF(rows * nh * hd >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t xb = rowoff(X, r, nh * hd);
|
||||
for (int64_t h = 0; h < nh; ++h)
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
const int64_t p = (h0 + h) * half + i;
|
||||
if (p < pad) continue;
|
||||
const int64_t j = p - pad, d = j % nd, k = j / nd;
|
||||
const float g = pos_at(P, d, r) / mx[(size_t)d];
|
||||
const float ang = (2.0f * g - 1.0f) * freq[(size_t)k];
|
||||
const float c = (float)std::cos((double)ang), s = (float)std::sin((double)ang);
|
||||
const int64_t o1 = xb + (h * hd + i) * xs, o2 = xb + (h * hd + half + i) * xs;
|
||||
const float x1 = ldt(X, o1), x2 = ldt(X, o2);
|
||||
st_elem(X->data, X->dtype, o1, keep(x1 * c) - keep(x2 * s));
|
||||
st_elem(X->data, X->dtype, o2, keep(x2 * c) + keep(x1 * s));
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ head_gate */
|
||||
AVX_KERNEL(head_gate) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *G = &a->t[0], *X = &a->t[1];
|
||||
const int64_t nh = p_int(a, "n_head", 0), hd = p_int(a, "head_dim", 0);
|
||||
if (nh <= 0 || hd <= 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(X, nh * hd);
|
||||
if (rows <= 0 || rows_of(G, nh) < rows) return RAD_E_SHAPE;
|
||||
const int64_t xs = laststride(X), gs = laststride(G);
|
||||
AVX_PARALLEL_FOR_IF(rows * nh * hd >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t xb = rowoff(X, r, nh * hd), gb = rowoff(G, r, nh);
|
||||
for (int64_t h = 0; h < nh; ++h) {
|
||||
const float lg = ldt(G, gb + h * gs);
|
||||
const float sg = narrow1(G->dtype, 1.0f / (1.0f + std::exp(-lg)));
|
||||
const float gate = narrow1(X->dtype, 2.0f * sg);
|
||||
for (int64_t i = 0; i < hd; ++i) {
|
||||
const int64_t o = xb + (h * hd + i) * xs;
|
||||
st_elem(X->data, X->dtype, o, ldt(X, o) * gate);
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ ltx_guide */
|
||||
AVX_KERNEL(ltx_guide) {
|
||||
if (a->n_t < 8) return RAD_E_INVAL;
|
||||
const RadTensor *Vc = &a->t[0], *Vu = rad_arg_in(a, 1), *Vs = rad_arg_in(a, 2);
|
||||
const RadTensor *Vm = rad_arg_in(a, 3), *Sc = &a->t[4], *Sh = &a->t[5], *X = &a->t[7];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
if (n <= 0 || numel(Sc) < 4 || numel(Sh) < 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(X, n);
|
||||
if (rows <= 0 || rows_of(Vc, n) < rows || (Vu && rows_of(Vu, n) < rows) ||
|
||||
(Vs && rows_of(Vs, n) < rows) || (Vm && rows_of(Vm, n) < rows))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t ss = laststride(Sc);
|
||||
const float gs = ldt(Sc, 0), stg = ldt(Sc, ss), ms = ldt(Sc, 2 * ss), rr = ldt(Sc, 3 * ss);
|
||||
const float sig = ldt(Sh, 0), sig_n = ldt(Sh, laststride(Sh));
|
||||
const bool use_u = Vu && gs != 1.0f, use_s = Vs && stg != 0.0f, use_m = Vm && ms != 1.0f;
|
||||
const float cu = gs - 1.0f, cm = ms - 1.0f;
|
||||
const int64_t N = rows * n;
|
||||
std::vector<float> x0c((size_t)N), g((size_t)N);
|
||||
auto x0 = [&](const RadTensor* V, int64_t r, int64_t c, float x) {
|
||||
return x - keep(ldt(V, rowoff(V, r, n) + c * laststride(V)) * sig);
|
||||
};
|
||||
AVX_PARALLEL_FOR_IF(N >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r)
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
const float x = ldt(X, rowoff(X, r, n) + c * laststride(X));
|
||||
const float xc = x0(Vc, r, c, x);
|
||||
float v = xc;
|
||||
if (use_u) v = v + keep(cu * (xc - x0(Vu, r, c, x)));
|
||||
if (use_s) v = v + keep(stg * (xc - x0(Vs, r, c, x)));
|
||||
if (use_m) v = v + keep(cm * (xc - x0(Vm, r, c, x)));
|
||||
x0c[(size_t)(r * n + c)] = xc;
|
||||
g[(size_t)(r * n + c)] = v;
|
||||
}
|
||||
float fac = 1.0f, kept = 1.0f;
|
||||
if (rr > 0.0f) {
|
||||
auto stdev = [&](const std::vector<float>& v) {
|
||||
double m = 0.0;
|
||||
for (float e : v) m += e;
|
||||
m /= (double)N;
|
||||
double sq = 0.0;
|
||||
for (float e : v) sq += ((double)e - m) * ((double)e - m);
|
||||
return (float)std::sqrt(sq / (double)(N > 1 ? N - 1 : 1));
|
||||
};
|
||||
fac = stdev(x0c) / stdev(g);
|
||||
kept = (float)(1.0 - (double)rr);
|
||||
}
|
||||
const float dt = sig_n - sig;
|
||||
AVX_PARALLEL_FOR_IF(N >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r)
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
float v = g[(size_t)(r * n + c)];
|
||||
if (rr > 0.0f) v = keep(rr * keep(v * fac)) + keep(kept * v);
|
||||
const int64_t o = rowoff(X, r, n) + c * laststride(X);
|
||||
const float x = ldt(X, o);
|
||||
const float vel = (x - v) / sig;
|
||||
st_elem(X->data, X->dtype, o, x + keep(dt * vel));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ pixel_norm */
|
||||
AVX_KERNEL(pixel_norm) {
|
||||
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), L = p_int(a, "ileave", 1);
|
||||
const float eps = p_f32(a, "eps", 1e-6f), mult = p_f32(a, "mult", 1.0f);
|
||||
const char* fs = p_str(a, "form", "rsqrt");
|
||||
const char* as = p_str(a, "act", "none");
|
||||
const int form = !std::strcmp(fs, "rsqrt") ? 0 : !std::strcmp(fs, "div") ? 1 : -1;
|
||||
const int act = !std::strcmp(as, "none") ? 0 : !std::strcmp(as, "silu") ? 1 : -1;
|
||||
if (form < 0 || act < 0 || n <= 0 || L <= 0) return RAD_E_INVAL;
|
||||
const int64_t rows = rows_of(Y, n * L) * L;
|
||||
if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE;
|
||||
const uint32_t dt = Y->dtype;
|
||||
const int64_t xs = laststride(X), ys = laststride(Y);
|
||||
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r / L, n * L), l = r % L;
|
||||
float ss = 0.0f;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float v = ldt(X, xb + i * xs);
|
||||
ss += narrow1(dt, v * v);
|
||||
}
|
||||
const float v = narrow1(dt, narrow1(dt, ss / (float)n) + eps);
|
||||
const float sc = form == 0 ? narrow1(dt, 1.0f / std::sqrt(v)) : narrow1(dt, std::sqrt(v));
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float x = ldt(X, xb + i * xs);
|
||||
float z = narrow1(dt, form == 0 ? x * sc : x / sc);
|
||||
if (act == 1) z = narrow1(dt, z / (1.0f + std::exp(-z)));
|
||||
if (mult != 1.0f) z = narrow1(dt, z * mult);
|
||||
st_elem(Y->data, dt, yb + (i * L + l) * ys, z);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ d2s3d */
|
||||
AVX_KERNEL(d2s3d) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2];
|
||||
const int64_t C = p_int(a, "C", 0), st = p_int(a, "st", 1), sh = p_int(a, "sh", 1);
|
||||
const int64_t sw = p_int(a, "sw", 1), drop = p_int(a, "drop", st - 1);
|
||||
if (C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || drop < 0 || drop >= st || numel(G) < 3)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2), P = st * sh * sw;
|
||||
const int64_t To = T * st - drop, Ho = H * sh, Wo = W * sw;
|
||||
if (T <= 0 || H <= 0 || W <= 0 || rows_of(X, C * P) < T * H * W ||
|
||||
rows_of(Y, C) < To * Ho * Wo)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t xs = laststride(X), ys = laststride(Y);
|
||||
AVX_PARALLEL_FOR_IF(To * Ho * Wo * C >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < To * Ho * Wo; ++r) {
|
||||
const int64_t tt = r / (Ho * Wo) + drop, ii = (r / Wo) % Ho, jj = r % Wo;
|
||||
const int64_t t = tt / st, aa = tt % st, i = ii / sh, b = ii % sh, j = jj / sw, d = jj % sw;
|
||||
const int64_t xb = rowoff(X, (t * H + i) * W + j, C * P), yb = rowoff(Y, r, C);
|
||||
for (int64_t c = 0; c < C; ++c)
|
||||
st_elem(Y->data, Y->dtype, yb + c * ys,
|
||||
ldt(X, xb + (((c * st + aa) * sh + b) * sw + d) * xs));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ s2d3d */
|
||||
AVX_KERNEL(s2d3d) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2];
|
||||
const int64_t C = p_int(a, "C", 0), st = p_int(a, "st", 1), sh = p_int(a, "sh", 1);
|
||||
const int64_t sw = p_int(a, "sw", 1), tpre = p_int(a, "tpre", 0), grp = p_int(a, "group", 1);
|
||||
const bool add = p_int(a, "add", 0) != 0;
|
||||
const char* ms = p_str(a, "mode", "copy");
|
||||
const int mode = !std::strcmp(ms, "copy") ? 0 : !std::strcmp(ms, "mean") ? 1 : -1;
|
||||
if (mode < 0) return RAD_E_INVAL;
|
||||
if (C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || tpre < 0 || grp <= 0 || numel(G) < 3)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2), P = C * st * sh * sw;
|
||||
const int64_t Tv = T + tpre;
|
||||
if (T <= 0 || Tv % st || H % sh || W % sw || (mode == 1 && P % grp)) return RAD_E_SHAPE;
|
||||
const int64_t To = Tv / st, Ho = H / sh, Wo = W / sw, Co = mode == 1 ? P / grp : P;
|
||||
if (rows_of(X, C) < T * H * W || rows_of(Y, Co) < To * Ho * Wo) return RAD_E_SHAPE;
|
||||
const int64_t xs = laststride(X), ys = laststride(Y);
|
||||
const uint32_t dt = Y->dtype;
|
||||
AVX_PARALLEL_FOR_IF(To * Ho * Wo * P >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < To * Ho * Wo; ++r) {
|
||||
const int64_t t = r / (Ho * Wo), i = (r / Wo) % Ho, j = r % Wo;
|
||||
const int64_t yb = rowoff(Y, r, Co);
|
||||
auto val = [&](int64_t q) {
|
||||
const int64_t d = q % sw, b = (q / sw) % sh, aa = (q / (sw * sh)) % st;
|
||||
const int64_t c = q / (sw * sh * st);
|
||||
const int64_t v = t * st + aa, tr = v < tpre ? v : v - tpre;
|
||||
return ldt(X, rowoff(X, (tr * H + i * sh + b) * W + j * sw + d, C) + c * xs);
|
||||
};
|
||||
for (int64_t o = 0; o < Co; ++o) {
|
||||
float v;
|
||||
if (mode == 0) {
|
||||
v = val(o);
|
||||
} else {
|
||||
float s = 0.0f;
|
||||
for (int64_t q = o * grp; q < (o + 1) * grp; ++q) s += val(q);
|
||||
v = narrow1(dt, s / (float)grp);
|
||||
}
|
||||
const int64_t oy = yb + o * ys;
|
||||
st_elem(Y->data, dt, oy, add ? narrow1(dt, ldt(Y, oy)) + narrow1(dt, v) : v);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ pix_patch / patch_pix8 */
|
||||
static inline int64_t patch_col(int64_t c, int64_t ph, int64_t pw, int64_t p, bool wh) {
|
||||
return c * p * p + (wh ? pw * p + ph : ph * p + pw);
|
||||
}
|
||||
|
||||
AVX_KERNEL(pix_patch) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *Y = &a->t[1];
|
||||
const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0);
|
||||
const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0;
|
||||
if (p <= 0 || C <= 0 || X->rank != 2 || Y->rank != 2 || X->shape[1] % C) return RAD_E_SHAPE;
|
||||
const int64_t H = X->shape[0], W = X->shape[1] / C;
|
||||
if (H <= 0 || W <= 0 || H % p || W % p || Y->shape[0] != H / p ||
|
||||
Y->shape[1] != (W / p) * C * p * p)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t xr = X->stride[0], yr = Y->stride[0];
|
||||
AVX_PARALLEL_FOR_IF(H * W * C >= AVX_PAR_MIN)
|
||||
for (int64_t y = 0; y < H; ++y)
|
||||
for (int64_t x = 0; x < W; ++x)
|
||||
for (int64_t c = 0; c < C; ++c)
|
||||
st_elem(Y->data, Y->dtype,
|
||||
(y / p) * yr + (x / p) * C * p * p + patch_col(c, y % p, x % p, p, wh),
|
||||
ldt(X, y * xr + x * C + c));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(patch_pix8) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *Y = &a->t[1];
|
||||
const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0);
|
||||
const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0;
|
||||
if (p <= 0 || C <= 0 || X->rank != 2 || Y->rank != 2 || Y->dtype != RAD_U8 ||
|
||||
X->shape[1] % (C * p * p))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t R = X->shape[0], w = X->shape[1] / (C * p * p);
|
||||
if (R <= 0 || w <= 0 || Y->shape[0] != R * p || Y->shape[1] != w * p * C) return RAD_E_SHAPE;
|
||||
const int64_t xr = X->stride[0], yr = Y->stride[0];
|
||||
const uint32_t dt = X->dtype;
|
||||
uint8_t* yb = (uint8_t*)Y->data;
|
||||
AVX_PARALLEL_FOR_IF(R * p * w * p * C >= AVX_PAR_MIN)
|
||||
for (int64_t y = 0; y < R * p; ++y)
|
||||
for (int64_t x = 0; x < w * p; ++x)
|
||||
for (int64_t c = 0; c < C; ++c) {
|
||||
const float v = ldt(X, (y / p) * xr + (x / p) * C * p * p +
|
||||
patch_col(c, y % p, x % p, p, wh));
|
||||
const float cl = std::min(std::max(v, -1.0f), 1.0f);
|
||||
float u = narrow1(dt, narrow1(dt, cl / 2.0f) + 0.5f);
|
||||
u = std::min(std::max(u, 0.0f), 1.0f);
|
||||
yb[y * yr + x * C + c] = (uint8_t)std::nearbyint(u * 255.0f);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ vol_index */
|
||||
AVX_KERNEL(vol_index) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *G = &a->t[0], *Y = &a->t[1];
|
||||
if (numel(G) < 3 || Y->rank != 2 || Y->shape[0] != 3) return RAD_E_SHAPE;
|
||||
const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2), n = Y->shape[1];
|
||||
if (T <= 0 || H <= 0 || W <= 0 || n <= 0) return RAD_E_SHAPE;
|
||||
const int64_t m1 = std::min(n, T * H * W);
|
||||
for (int64_t m = 0; m < m1; ++m) {
|
||||
const int64_t v[3] = { m / (H * W), (m / W) % H, m % W };
|
||||
for (int64_t c = 0; c < 3; ++c)
|
||||
st_int_dt(Y->dtype, Y->data, c * Y->stride[0] + m * Y->stride[1], v[c]);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ tile_grid / tile_crop / tile_stitch */
|
||||
/* diffusers' tiled decodes: libref/ref_ltx.cpp states the cuts and the blends. */
|
||||
namespace {
|
||||
struct TileCut {
|
||||
int64_t tile = 1, stride = 1, min = 1;
|
||||
bool intervals = false;
|
||||
int64_t count(int64_t L) const {
|
||||
if (intervals && L <= tile) return 1;
|
||||
int64_t n = (L + stride - 1) / stride;
|
||||
while (intervals && n > 1 && L - (n - 1) * stride < min) --n;
|
||||
return n;
|
||||
}
|
||||
int64_t len(int64_t L, int64_t k) const {
|
||||
return k == count(L) - 1 ? L - k * stride : std::min(tile, L - k * stride);
|
||||
}
|
||||
};
|
||||
|
||||
bool tile_cuts(const RadArgs* a, TileCut* s, TileCut* t) {
|
||||
static const char* const kRules[] = { "stride", "intervals" };
|
||||
const int rule = p_enum(a, "rule", kRules, 2, 0);
|
||||
s->tile = p_int(a, "tile", 0);
|
||||
s->stride = p_int(a, "stride", 0);
|
||||
s->min = p_int(a, "min", 1);
|
||||
s->intervals = rule == 1;
|
||||
t->tile = p_int(a, "tile_t", 1 << 30);
|
||||
t->stride = p_int(a, "stride_t", 1 << 30);
|
||||
t->min = p_int(a, "min_t", 1);
|
||||
t->intervals = rule == 1;
|
||||
return rule >= 0 && s->tile > 0 && s->stride > 0 && s->stride <= s->tile && s->min > 0 &&
|
||||
t->tile > 0 && t->stride > 0 && t->stride <= t->tile && t->min > 0;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
AVX_KERNEL(tile_grid) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *G = &a->t[0], *Y = &a->t[1];
|
||||
TileCut cs, ct;
|
||||
const int64_t n = numel(Y) / 8, tail = p_int(a, "tail", 0);
|
||||
if (!tile_cuts(a, &cs, &ct) || tail < 0 || n <= 0 || numel(G) < 3) return RAD_E_SHAPE;
|
||||
const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2);
|
||||
if (T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE;
|
||||
const int64_t nt = ct.count(T), ni = cs.count(H), nj = cs.count(W), count = nt * ni * nj;
|
||||
for (int64_t k = 0; k < n; ++k) {
|
||||
int64_t row[8] = {};
|
||||
if (k < count) {
|
||||
const int64_t kt = k / (ni * nj), i = (k / nj) % ni, j = k % nj;
|
||||
const int64_t v[8] = { ct.len(T, kt) + (kt == nt - 1 ? tail : 0), cs.len(H, i),
|
||||
cs.len(W, j), kt * ct.stride, i * cs.stride, j * cs.stride, k,
|
||||
count };
|
||||
std::memcpy(row, v, sizeof row);
|
||||
}
|
||||
for (int64_t e = 0; e < 8; ++e) st_int_dt(Y->dtype, Y->data, offlin(Y, k * 8 + e), row[e]);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(tile_crop) {
|
||||
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *G = &a->t[1], *B = &a->t[2], *Y = &a->t[3];
|
||||
const int64_t C = p_int(a, "C", 0);
|
||||
if (C <= 0 || numel(G) < 3 || numel(B) < 6) return RAD_E_SHAPE;
|
||||
const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2);
|
||||
const int64_t t = at_i(B, 0), h = at_i(B, 1), w = at_i(B, 2);
|
||||
const int64_t t0 = at_i(B, 3), y0 = at_i(B, 4), x0 = at_i(B, 5);
|
||||
if (t <= 0 || h <= 0 || w <= 0 || t0 < 0 || y0 < 0 || x0 < 0 || t0 + t > T || y0 + h > H ||
|
||||
x0 + w > W || rows_of(X, C) < T * H * W || rows_of(Y, C) < t * h * w)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t xs = laststride(X), ys = laststride(Y);
|
||||
AVX_PARALLEL_FOR_IF(t * h * w * C >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < t * h * w; ++r) {
|
||||
const int64_t f = r / (h * w), i = (r / w) % h, j = r % w;
|
||||
const int64_t xb = rowoff(X, ((t0 + f) * H + y0 + i) * W + x0 + j, C), yb = rowoff(Y, r, C);
|
||||
for (int64_t c = 0; c < C; ++c) st_elem(Y->data, Y->dtype, yb + c * ys, ldt(X, xb + c * xs));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
namespace {
|
||||
struct TileStore {
|
||||
TileCut cs, ct;
|
||||
int64_t T, H, W, sc, st, nt, ni, nj, hsum, wsum;
|
||||
TileStore(const TileCut& s, const TileCut& t, int64_t T_, int64_t H_, int64_t W_, int64_t sc_,
|
||||
int64_t st_)
|
||||
: cs(s), ct(t), T(T_), H(H_), W(W_), sc(sc_), st(st_), nt(t.count(T_)), ni(s.count(H_)),
|
||||
nj(s.count(W_)), hsum(0), wsum(0) {
|
||||
for (int64_t i = 0; i < ni; ++i) hsum += cs.len(H, i);
|
||||
for (int64_t j = 0; j < nj; ++j) wsum += cs.len(W, j);
|
||||
}
|
||||
int64_t frames(int64_t kt) const {
|
||||
return st * ct.len(T, kt) - (kt == 0 ? st - 1 : 0);
|
||||
}
|
||||
int64_t offset(int64_t kt, int64_t i, int64_t j) const {
|
||||
int64_t before = 0;
|
||||
for (int64_t q = 0; q < kt; ++q) before += frames(q);
|
||||
int64_t left = 0, above = 0;
|
||||
for (int64_t q = 0; q < j; ++q) left += cs.len(W, q);
|
||||
for (int64_t q = 0; q < i; ++q) above += cs.len(H, q);
|
||||
return sc * sc * (before * hsum * wsum + frames(kt) * (above * wsum + cs.len(H, i) * left));
|
||||
}
|
||||
int64_t rows() const { return offset(nt, 0, 0); }
|
||||
};
|
||||
} /* namespace */
|
||||
|
||||
AVX_KERNEL(tile_stitch) {
|
||||
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *G = &a->t[1], *Fst = &a->t[2], *Y = &a->t[3];
|
||||
TileCut cs, ct;
|
||||
const int64_t sc = p_int(a, "scale", 0), st = p_int(a, "scale_t", 1);
|
||||
const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0);
|
||||
const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0;
|
||||
if (!tile_cuts(a, &cs, &ct) || sc <= 0 || st <= 0 || p <= 0 || C <= 0 || numel(G) < 3 ||
|
||||
numel(Fst) < 1 || Y->dtype != RAD_U8 || Y->rank != 2)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2), f0 = at_i(Fst, 0);
|
||||
const int64_t Hpx = H * sc * p, Wpx = W * sc * p, P = C * p * p;
|
||||
if (T <= 0 || H <= 0 || W <= 0 || Y->shape[1] != Wpx * C || Y->shape[0] % Hpx) return RAD_E_SHAPE;
|
||||
const int64_t nf = Y->shape[0] / Hpx;
|
||||
const TileStore ts(cs, ct, T, H, W, sc, st);
|
||||
if (nf <= 0 || f0 < 0 || f0 + nf > st * T - (st - 1) || rows_of(X, P) < ts.rows())
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t s = cs.stride * sc * p, E = (cs.tile - cs.stride) * sc * p;
|
||||
const int64_t Et = (ct.tile - ct.stride) * st, xs = laststride(X);
|
||||
const uint32_t dt = X->dtype;
|
||||
auto R = [&](int64_t kt, int64_t i, int64_t j, int64_t f, int64_t yy, int64_t xx, int64_t c) {
|
||||
const int64_t wp = cs.len(W, j) * sc, hp = cs.len(H, i) * sc;
|
||||
const int64_t row = ts.offset(kt, i, j) + (f * hp + yy / p) * wp + xx / p;
|
||||
return ldt(X, rowoff(X, row, P) + patch_col(c, yy % p, xx % p, p, wh) * xs);
|
||||
};
|
||||
auto mix = [&](float va, float vb, int64_t k, int64_t e) {
|
||||
const float wa = (float)(1.0 - (double)k / (double)e), wb = (float)((double)k / (double)e);
|
||||
return narrow1(dt, narrow1(dt, keep(va * wa)) + narrow1(dt, keep(vb * wb)));
|
||||
};
|
||||
auto S = [&](int64_t kt, int64_t f, int64_t Yp, int64_t Xp, int64_t c) {
|
||||
const int64_t i = std::min(Yp / s, ts.ni - 1), ly = Yp - i * s;
|
||||
const int64_t j = std::min(Xp / s, ts.nj - 1), lx = Xp - j * s;
|
||||
const int64_t ha = i > 0 ? cs.len(H, i - 1) * sc * p : 0;
|
||||
const int64_t ev = i > 0 ? std::min(std::min(ha, cs.len(H, i) * sc * p), E) : 0;
|
||||
const int64_t wl = j > 0 ? cs.len(W, j - 1) * sc * p : 0;
|
||||
const int64_t eh = j > 0 ? std::min(std::min(wl, cs.len(W, j) * sc * p), E) : 0;
|
||||
const bool vb = i > 0 && ly < ev, hb = j > 0 && lx < eh;
|
||||
float V = R(kt, i, j, f, ly, lx, c);
|
||||
if (vb) {
|
||||
const int64_t ya = ha - ev + ly;
|
||||
float A = R(kt, i - 1, j, f, ya, lx, c);
|
||||
if (hb) A = mix(R(kt, i - 1, j - 1, f, ya, wl - eh + lx, c), A, lx, eh);
|
||||
V = mix(A, V, ly, ev);
|
||||
}
|
||||
if (hb) {
|
||||
float L = R(kt, i, j - 1, f, ly, wl - eh + lx, c);
|
||||
if (vb) L = mix(R(kt, i - 1, j - 1, f, ha - ev + ly, wl - eh + lx, c), L, ly, ev);
|
||||
V = mix(L, V, lx, eh);
|
||||
}
|
||||
return V;
|
||||
};
|
||||
uint8_t* yb = (uint8_t*)Y->data;
|
||||
const int64_t yr = Y->stride[0], band = ct.stride * st;
|
||||
AVX_PARALLEL_FOR_IF(nf * Hpx * Wpx * C >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < nf * Hpx; ++r) {
|
||||
const int64_t n = f0 + r / Hpx, Yp = r % Hpx;
|
||||
const int64_t kt = std::min((n + st - 1) / band, ts.nt - 1);
|
||||
const int64_t f = n - (kt == 0 ? 0 : kt * band - (st - 1));
|
||||
const int64_t et = kt > 0 ? std::min(std::min(ts.frames(kt - 1), ts.frames(kt)), Et) : 0;
|
||||
for (int64_t Xp = 0; Xp < Wpx; ++Xp)
|
||||
for (int64_t c = 0; c < C; ++c) {
|
||||
float v = S(kt, f, Yp, Xp, c);
|
||||
if (kt > 0 && f < et) v = mix(S(kt - 1, ts.frames(kt - 1) - et + f, Yp, Xp, c), v, f, et);
|
||||
const float cl = std::min(std::max(v, -1.0f), 1.0f);
|
||||
float u = narrow1(dt, narrow1(dt, cl / 2.0f) + 0.5f);
|
||||
u = std::min(std::max(u, 0.0f), 1.0f);
|
||||
yb[r * yr + Xp * C + c] = (uint8_t)std::nearbyint(u * 255.0f);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ stft_logmel */
|
||||
AVX_KERNEL(stft_logmel) {
|
||||
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *B = &a->t[1], *Mb = &a->t[2], *Y = &a->t[3];
|
||||
const int64_t hop = p_int(a, "hop", 0), nfft = p_int(a, "nfft", 0), nm = p_int(a, "n_mel", 0);
|
||||
const int64_t ch = p_int(a, "ch", 0);
|
||||
if (hop <= 0 || nfft < hop || nm <= 0 || ch <= 0) return RAD_E_SHAPE;
|
||||
const int64_t F = nfft / 2 + 1, S = rows_of(X, ch), frames = rows_of(Y, ch * nm);
|
||||
if (S <= 0 || frames <= 0 || frames * hop > S || numel(B) < 2 * F * nfft || numel(Mb) < nm * F)
|
||||
return RAD_E_SHAPE;
|
||||
const uint32_t dt = Y->dtype;
|
||||
const int64_t pad = nfft - hop, xs = laststride(X), ys = laststride(Y);
|
||||
const float floor_v = narrow1(dt, 1e-5f);
|
||||
AVX_PARALLEL_FOR_IF(frames * ch * F * nfft >= AVX_PAR_MIN)
|
||||
for (int64_t t = 0; t < frames; ++t)
|
||||
for (int64_t h = 0; h < ch; ++h) {
|
||||
std::vector<float> mag((size_t)F);
|
||||
for (int64_t k = 0; k < F; ++k) {
|
||||
float re = 0.0f, im = 0.0f;
|
||||
for (int64_t j = 0; j < nfft; ++j) {
|
||||
const int64_t s = t * hop + j - pad;
|
||||
if (s < 0) continue;
|
||||
const float v = ldt(X, rowoff(X, s, ch) + h * xs);
|
||||
re += keep(ldt(B, k * nfft + j) * v);
|
||||
im += keep(ldt(B, (F + k) * nfft + j) * v);
|
||||
}
|
||||
re = narrow1(dt, re);
|
||||
im = narrow1(dt, im);
|
||||
mag[(size_t)k] = narrow1(dt, std::sqrt(narrow1(dt, narrow1(dt, re * re) +
|
||||
narrow1(dt, im * im))));
|
||||
}
|
||||
const int64_t yb = rowoff(Y, t, ch * nm);
|
||||
for (int64_t m = 0; m < nm; ++m) {
|
||||
float s = 0.0f;
|
||||
for (int64_t k = 0; k < F; ++k) s += keep(ldt(Mb, m * F + k) * mag[(size_t)k]);
|
||||
const float mel = std::max(narrow1(dt, s), floor_v);
|
||||
st_elem(Y->data, dt, yb + (h * nm + m) * ys, std::log(mel));
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ bwe_up */
|
||||
AVX_KERNEL(bwe_up) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *Rz = &a->t[1], *Y = &a->t[2];
|
||||
const int64_t r = p_int(a, "ratio", 0), ch = p_int(a, "ch", 0);
|
||||
if (r <= 0 || ch <= 0) return RAD_E_SHAPE;
|
||||
const int64_t S = rows_of(X, ch), O = rows_of(Y, ch);
|
||||
if (S <= 0 || O <= 0 || O > S * r || rows_of(Rz, ch) < O) return RAD_E_SHAPE;
|
||||
const uint32_t dt = X->dtype;
|
||||
const int64_t w = (int64_t)std::ceil(6.0 / 0.99), K = 2 * w * r + 1, off = 2 * w * r;
|
||||
std::vector<float> f((size_t)K);
|
||||
for (int64_t n = 0; n < K; ++n) {
|
||||
const float u = keep(keep((float)n / (float)r - (float)w) * 0.99f);
|
||||
const float uc = std::min(std::max(u, -6.0f), 6.0f);
|
||||
const float cw = std::cos(keep(keep(uc * (float)M_PI) / 6.0f) / 2.0f);
|
||||
const float pu = keep((float)M_PI * u);
|
||||
const float sinc = u == 0.0f ? 1.0f : std::sin(pu) / pu;
|
||||
f[(size_t)n] = narrow1(dt, keep(keep(sinc * keep(cw * cw)) * 0.99f) / (float)r);
|
||||
}
|
||||
const int64_t xs = laststride(X), rs = laststride(Rz), ys = laststride(Y);
|
||||
AVX_PARALLEL_FOR_IF(O * ch * K >= AVX_PAR_MIN)
|
||||
for (int64_t o = 0; o < O; ++o)
|
||||
for (int64_t h = 0; h < ch; ++h) {
|
||||
const int64_t u = o + off;
|
||||
float acc = 0.0f;
|
||||
for (int64_t k = u % r; k < K; k += r) {
|
||||
const int64_t i = (u - k) / r;
|
||||
const int64_t s = std::min(std::max<int64_t>(i - w, 0), S - 1);
|
||||
acc += keep(f[(size_t)k] * ldt(X, rowoff(X, s, ch) + h * xs));
|
||||
}
|
||||
const float up = narrow1(dt, (float)r * narrow1(dt, acc));
|
||||
const float v = narrow1(dt, ldt(Rz, rowoff(Rz, o, ch) + h * rs) + up);
|
||||
st_elem(Y->data, Y->dtype, rowoff(Y, o, ch) + h * ys, std::min(std::max(v, -1.0f), 1.0f));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
+141
-5
@@ -297,6 +297,13 @@ static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_IN
|
||||
P_INTO("window_right") };
|
||||
static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"),
|
||||
OUT("out") };
|
||||
static const RadParamSpec pAttnCross[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"),
|
||||
P_INT("causal"), P_STR("dtype"), P_F64O("scale") };
|
||||
static const RadOperandSpec oAttnCross[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"),
|
||||
OPD("cu_k"), OUT("out") };
|
||||
static const RadParamSpec pAttnNa3d[] = { P_INT("M"), P_INT("head_dim"), P_INT("kt"), P_INT("kh"),
|
||||
P_INT("kw"), P_STR("dtype"), P_F64O("scale") };
|
||||
static const RadOperandSpec oAttnNa3d[] = { OPD("q"), OPD("k"), OPD("v"), OPD("geom"), OUT("out") };
|
||||
|
||||
static const RadParamSpec pKvStore[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head_kv"),
|
||||
P_INT("block_size"), P_STR("kv_dtype"),
|
||||
@@ -504,6 +511,13 @@ static const RadOperandSpec oAllGather[] = { OPD("x"), OUT("y") };
|
||||
/* ---- image generation --------------------------------------------------------------------- */
|
||||
static const RadParamSpec pLnMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype") };
|
||||
static const RadOperandSpec oLnMod[] = { OPD("x"), OPD("s"), OPD("cu_seqlens"), OUT("y") };
|
||||
static const RadParamSpec pTableAdd[] = { P_INT("M"), P_INT("n"), P_INT("L"), P_STR("dtype") };
|
||||
static const RadOperandSpec oTableAdd[] = { OPD("x"), WGT("t"), OUT("y") };
|
||||
static const RadParamSpec pMixRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_STR("dtype") };
|
||||
static const RadParamSpec pChanStats[] = { P_INT("M"), P_INT("n"), P_STR("mode"), P_INTO("var"),
|
||||
P_F64O("eps"), P_STR("dtype") };
|
||||
static const RadOperandSpec oChanStats[] = { OPD("x"), WGT("mean"), WGT("s"), OUT("y") };
|
||||
static const RadOperandSpec oMixRows[] = { OPD("x"), WGT("w"), OUT("y") };
|
||||
static const RadParamSpec pGateAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_STRO("act") };
|
||||
static const RadOperandSpec oGateAdd[] = { OPD("y"), OPD("g"), OPD("cu_seqlens"), INOUT("x") };
|
||||
static const RadParamSpec pLnModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"),
|
||||
@@ -511,12 +525,14 @@ static const RadParamSpec pLnModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P
|
||||
static const RadOperandSpec oLnModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), OPD("cu_seqlens"),
|
||||
INOUT("x"), OUT("q"), OUT("scale"), OUT_O("z") };
|
||||
static const RadParamSpec pRmsMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INTO("gated"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oRmsMod[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT("w"),
|
||||
P_STR("dtype"), P_F64O("wadd"),
|
||||
P_INTO("norm_once"), P_STRO("norm") };
|
||||
static const RadOperandSpec oRmsMod[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT_O("w"),
|
||||
OPD("cu_seqlens"), INOUT("x"), OUT("z") };
|
||||
static const RadParamSpec pRmsModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"),
|
||||
P_INT("gated"), P_STR("dtype") };
|
||||
static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT("w"),
|
||||
P_INT("gated"), P_STR("dtype"), P_F64O("wadd"),
|
||||
P_INTO("norm_once"), P_STRO("norm") };
|
||||
static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT_O("w"),
|
||||
OPD("cu_seqlens"), INOUT("x"), OUT("q"), OUT("scale"),
|
||||
OUT_O("z") };
|
||||
static const RadOperandSpec oFlowX0[] = { OPD("v"), OPD("t"), OPD("sigma"), OPD("sigma_next"),
|
||||
@@ -590,7 +606,8 @@ static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("se
|
||||
/* ---- the latent upscaler (avx_video.cpp), as libref declares it; patch_fold takes
|
||||
* patch_unfold's parameters and operands ------------------------------------------------------ */
|
||||
static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
|
||||
P_INT("kt"), P_STR("dtype") };
|
||||
P_INT("kt"), P_STR("dtype"), P_STRO("tpad"),
|
||||
P_INTO("tpre") };
|
||||
static const RadOperandSpec oConv3d[] = { OPD("x"), WGT("w"), WGT("b"), OPD("geom"),
|
||||
OPD_O("res"), OUT("y") };
|
||||
static const RadParamSpec pGroupNorm[] = { P_INT("M"), P_INT("n"), P_INT("groups"), P_F64("eps"),
|
||||
@@ -604,6 +621,52 @@ static const RadParamSpec pFlowRenoise[] = { P_INT("M"), P_INT("n"), P_INT("stre
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oFlowRenoise[] = { OPD("sigma"), OPD("seed"), INOUT("x") };
|
||||
|
||||
/* ---- LTX-2 (avx_ltx.cpp) */
|
||||
static const RadParamSpec pRopeSplit[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"),
|
||||
P_INT("dim"), P_INT("n_dims"), P_F64("theta"),
|
||||
P_STR("max"), P_INTO("head0"), P_STR("dtype") };
|
||||
static const RadOperandSpec oRopeSplit[] = { INOUT("x"), OPD("positions") };
|
||||
static const RadParamSpec pHeadGate[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oHeadGate[] = { OPD("g"), INOUT("x") };
|
||||
static const RadParamSpec pLtxGuide[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
|
||||
static const RadOperandSpec oLtxGuide[] = { OPD("vc"), OPD_O("vu"), OPD_O("vs"), OPD_O("vm"),
|
||||
OPD("scales"), OPD("sched"), INOUT("stats"),
|
||||
INOUT("x") };
|
||||
static const RadParamSpec pPixelNorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("form"),
|
||||
P_STRO("act"), P_INTO("ileave"), P_STR("dtype"),
|
||||
P_F64O("mult") };
|
||||
static const RadOperandSpec oPixelNorm[] = { OPD("x"), OUT("y") };
|
||||
static const RadParamSpec pD2s3d[] = { P_INT("M"), P_INT("C"), P_INT("st"), P_INT("sh"), P_INT("sw"),
|
||||
P_INTO("drop"), P_STR("dtype") };
|
||||
static const RadOperandSpec oD2s3d[] = { OPD("x"), OPD("geom"), OUT("y") };
|
||||
static const RadParamSpec pS2d3d[] = { P_INT("M"), P_INT("C"), P_INT("st"), P_INT("sh"), P_INT("sw"),
|
||||
P_INTO("tpre"), P_INTO("group"), P_STR("mode"),
|
||||
P_INTO("add"), P_STR("dtype") };
|
||||
static const RadOperandSpec oS2d3d[] = { OPD("x"), OPD("geom"), INOUT("y") };
|
||||
static const RadParamSpec pPixPatch[] = { P_INT("M"), P_INT("p"), P_INT("C"), P_STRO("order"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oPixPatch[] = { OPD("x"), OUT("y") };
|
||||
static const RadParamSpec pVolIndex[] = { P_INT("M") };
|
||||
static const RadOperandSpec oVolIndex[] = { OPD("geom"), OUT("y") };
|
||||
static const RadParamSpec pTileGrid[] = { P_INT("M"), P_INT("tile"), P_INT("stride"), P_STRO("rule"),
|
||||
P_INTO("min"), P_INTO("tile_t"), P_INTO("stride_t"),
|
||||
P_INTO("min_t"), P_INTO("tail") };
|
||||
static const RadOperandSpec oTileGrid[] = { OPD("geom"), OUT("y") };
|
||||
static const RadParamSpec pTileCrop[] = { P_INT("M"), P_INT("C"), P_STR("dtype") };
|
||||
static const RadOperandSpec oTileCrop[] = { OPD("x"), OPD("geom"), OPD("box"), OUT("y") };
|
||||
static const RadParamSpec pTileStitch[] = { P_INT("M"), P_INT("tile"), P_INT("stride"),
|
||||
P_STRO("rule"), P_INTO("min"), P_INTO("tile_t"),
|
||||
P_INTO("stride_t"), P_INTO("min_t"), P_INT("scale"),
|
||||
P_INTO("scale_t"), P_INT("p"), P_INT("C"),
|
||||
P_STRO("order"), P_STR("dtype") };
|
||||
static const RadOperandSpec oTileStitch[] = { OPD("x"), OPD("geom"), OPD("first"), OUT("y") };
|
||||
static const RadParamSpec pStftMel[] = { P_INT("M"), P_INT("hop"), P_INT("nfft"), P_INT("n_mel"),
|
||||
P_INT("ch"), P_STR("dtype") };
|
||||
static const RadOperandSpec oStftMel[] = { OPD("x"), WGT("basis"), WGT("mel"), OUT("y") };
|
||||
static const RadParamSpec pBweUp[] = { P_INT("M"), P_INT("ratio"), P_INT("ch"), P_STR("dtype") };
|
||||
static const RadOperandSpec oBweUp[] = { OPD("x"), OPD("res"), OUT("y") };
|
||||
|
||||
/* ---- audio generation (avx_audio.cpp), as libref declares it ------------------------------ */
|
||||
static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
|
||||
P_INT("dil"), P_STRO("act"), P_STR("dtype"),
|
||||
@@ -664,6 +727,8 @@ static const RadParamSpec pIota[] = { P_INT("M"), P_INT("start"), P_INT("step"),
|
||||
static const RadOperandSpec oIota[] = { OUT("y") };
|
||||
static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") };
|
||||
static const RadOperandSpec oCuRepeat[] = { OPD("len"), OUT("y") };
|
||||
static const RadParamSpec pIntAffine[] = { P_INT("M"), P_STR("src"), P_STR("mul"), P_STR("add") };
|
||||
static const RadOperandSpec oIntAffine[] = { OPD("x"), OUT("y") };
|
||||
|
||||
/* ---- vocabulary edges --------------------------------------------------------------------- */
|
||||
static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"),
|
||||
@@ -881,6 +946,11 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "attn_dense", ARR(pAttnDense), ARR(oAttnDense),
|
||||
"dense varlen attention over cu_seqlens; a non-causal window may reach further right "
|
||||
"(`window_right`)." },
|
||||
{ "attn_cross", ARR(pAttnCross), ARR(oAttnCross),
|
||||
"attn_dense with each entry's keys a run of their own (cu_k); causal counts from each run's "
|
||||
"start." },
|
||||
{ "attn_na3d", ARR(pAttnNa3d), ARR(oAttnNa3d),
|
||||
"3-D neighborhood attention over a volume, libref's window and arithmetic." },
|
||||
{ "kv_store", ARR(pKvStore), ARR(oKvStore), "scatter k and v into the paged cache." },
|
||||
{ "rope_table", ARR(pRopeTable), ARR(oRopeTable), "cos/sin at each position's own row." },
|
||||
{ "qsa_block_key", ARR(pQsaBlockKey), ARR(oQsaBlockKey),
|
||||
@@ -949,6 +1019,13 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "ln_mod", ARR(pLnMod), ARR(oLnMod),
|
||||
"y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a gainless layer norm and the row's entry's "
|
||||
"modulation row of `s` ([n_seq, >= n] at its own pitch)." },
|
||||
{ "table_add", ARR(pTableAdd), ARR(oTableAdd),
|
||||
"y[r, l n + c] = x[r, c] + t[l, c], f32 sum rounded once." },
|
||||
{ "chan_stats", ARR(pChanStats), ARR(oChanStats),
|
||||
"per-channel statistics held as weights: denorm rd(rd(x std) + mean), norm rd(rd(x - mean) / "
|
||||
"std)." },
|
||||
{ "mix_rows", ARR(pMixRows), ARR(oMixRows),
|
||||
"y[r, c] = sum_i w[i] x[r k + i, c], f32 in ascending i, rounded once." },
|
||||
{ "gate_add", ARR(pGateAdd), ARR(oGateAdd),
|
||||
"x = bf16(x + bf16(bf16(tanh(g[seq])) * y)), or with `act` none the gate g itself, bit for bit "
|
||||
"libref's." },
|
||||
@@ -1032,6 +1109,29 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "flow_renoise", ARR(pFlowRenoise), ARR(oFlowRenoise),
|
||||
"x = f32(f32(1 - s) x) + f32(s z), z the (seed, stream) normal stream at k n + c, bit for bit "
|
||||
"libref's." },
|
||||
{ "rope_split", ARR(pRopeSplit), ARR(oRopeSplit),
|
||||
"LTX-2's split rotary over fractional coordinates, libref's arithmetic element by element." },
|
||||
{ "head_gate", ARR(pHeadGate), ARR(oHeadGate),
|
||||
"x = rd(x rd(2 rd(sigmoid(g)))) per head, libref's." },
|
||||
{ "ltx_guide", ARR(pLtxGuide), ARR(oLtxGuide),
|
||||
"LTX-2's guided sampler step in f32, libref's arithmetic with the deviations in f64." },
|
||||
{ "pixel_norm", ARR(pPixelNorm), ARR(oPixelNorm),
|
||||
"an RMS norm over each row as bf16 tensors compute it, every step rounded; rsqrt or div form, "
|
||||
"optionally silu, `ileave` interleaving the output; libref's." },
|
||||
{ "d2s3d", ARR(pD2s3d), ARR(oD2s3d), "depth to space over voxel rows, libref's copy." },
|
||||
{ "s2d3d", ARR(pS2d3d), ARR(oS2d3d),
|
||||
"space to depth over voxel rows, a copy or the mean of each group, libref's." },
|
||||
{ "pix_patch", ARR(pPixPatch), ARR(oPixPatch), "an image to patch rows, libref's copy." },
|
||||
{ "patch_pix8", ARR(pPixPatch), ARR(oPixPatch), "patch rows to RGB bytes, libref's rule." },
|
||||
{ "vol_index", ARR(pVolIndex), ARR(oVolIndex), "a volume's voxel coordinates, libref's." },
|
||||
{ "tile_grid", ARR(pTileGrid), ARR(oTileGrid), "a tiled decode's boxes, libref's cut." },
|
||||
{ "tile_crop", ARR(pTileCrop), ARR(oTileCrop), "a tile out of a volume, libref's copy." },
|
||||
{ "tile_stitch", ARR(pTileStitch), ARR(oTileStitch),
|
||||
"decoded tiles blended to RGB bytes, libref's blends and rounding." },
|
||||
{ "stft_logmel", ARR(pStftMel), ARR(oStftMel),
|
||||
"each channel's causal log-mel spectrogram, libref's roundings." },
|
||||
{ "bwe_up", ARR(pBweUp), ARR(oBweUp),
|
||||
"a Hann-windowed sinc resampler plus a residual, clamped, libref's roundings." },
|
||||
{ "conv1d", ARR(pConv1d), ARR(oConv1d),
|
||||
"a 1-D convolution over the sequences `cu_seqlens` bounds, channels innermost, PyTorch's "
|
||||
"[cout, cin, k] weight, dilation `dil`, centred or (`causal`) all on the left, zeros outside "
|
||||
@@ -1073,6 +1173,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "interleave2", ARR(pInterleave), ARR(oInterleave2), "two streams interleaved, y [rows, 2]." },
|
||||
{ "iota", ARR(pIota), ARR(oIota), "y[i] = start + i * step." },
|
||||
{ "cu_repeat", ARR(pCuRepeat), ARR(oCuRepeat), "y[j] = j * len[0] * mult." },
|
||||
{ "int_affine", ARR(pIntAffine), ARR(oIntAffine),
|
||||
"y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists." },
|
||||
{ "embed_lookup", ARR(pEmbedM), ARR(oEmbed),
|
||||
"embedding gather, vocab-parallel with an offset; `mult` multiplies every row (rounded once)." },
|
||||
{ "embed_lookup_q", ARR(pEmbed), ARR(oEmbedQ),
|
||||
@@ -1382,6 +1484,11 @@ ROW("avx_attn_paged", "attn_paged", "attn",
|
||||
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(attn_paged)),
|
||||
SIMPLE("avx_attn_dense", "attn_dense", "attn", "dense varlen attention over cu_seqlens", DT_FLOAT,
|
||||
L(attn_dense)),
|
||||
SIMPLE("avx_attn_cross", "attn_cross", "attn",
|
||||
"dense varlen attention, keys bounded apart from the queries (cu_k)", DT_FLOAT,
|
||||
L(attn_cross)),
|
||||
SIMPLE("avx_attn_na3d", "attn_na3d", "attn", "3-D neighborhood attention over a volume", DT_FLOAT,
|
||||
L(attn_na3d)),
|
||||
ROW("avx_kv_store", "kv_store", "attn", "scatter k and v into the paged cache", DT_ANY,
|
||||
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(kv_store)),
|
||||
SIMPLE("avx_rope", "rope", "attn", "rotary embedding in place", DT_FLOAT, L(rope)),
|
||||
@@ -1458,6 +1565,12 @@ SIMPLE("avx_ln_mod", "ln_mod", "norm", "gainless layer norm times (1 + an entry'
|
||||
DT_FLOAT, L(ln_mod)),
|
||||
SIMPLE("avx_gate_add", "gate_add", "elem", "x += act(gate row) * y, act tanh or none", DT_FLOAT,
|
||||
L(gate_add)),
|
||||
SIMPLE("avx_table_add", "table_add", "elem", "a row plus each of L table rows", DT_FLOAT,
|
||||
L(table_add)),
|
||||
SIMPLE("avx_mix_rows", "mix_rows", "elem", "a weighted sum of k consecutive rows", DT_FLOAT,
|
||||
L(mix_rows)),
|
||||
SIMPLE("avx_chan_stats", "chan_stats", "elem", "per-channel statistics held as weights",
|
||||
DT_FLOAT, L(chan_stats)),
|
||||
SIMPLE("avx_ln_mod_quant_fp8", "ln_mod_quant_fp8", "norm",
|
||||
"gated residual, adaptive norm and the E4M3 quantiser in one pass",
|
||||
"float in, fp8_e4m3 out, f32 scale, bf16 z", L(ln_mod_quant_fp8)),
|
||||
@@ -1526,6 +1639,27 @@ SIMPLE("avx_patch_fold", "patch_fold", "elem", "voxel rows to normalised patch r
|
||||
L(patch_fold)),
|
||||
SIMPLE("avx_flow_renoise", "flow_renoise", "elem", "a clean latent re-noised to a sigma",
|
||||
DT_FLOAT, L(flow_renoise)),
|
||||
SIMPLE("avx_rope_split", "rope_split", "elem", "LTX-2's split rotary over coordinates", DT_FLOAT,
|
||||
L(rope_split)),
|
||||
SIMPLE("avx_head_gate", "head_gate", "elem", "each head times 2 sigmoid of its logit", DT_FLOAT,
|
||||
L(head_gate)),
|
||||
SIMPLE("avx_ltx_guide", "ltx_guide", "elem", "LTX-2's guided sampler step", DT_FLOAT,
|
||||
L(ltx_guide)),
|
||||
SIMPLE("avx_pixel_norm", "pixel_norm", "norm", "an RMS norm as bf16 tensors compute it", DT_FLOAT,
|
||||
L(pixel_norm)),
|
||||
SIMPLE("avx_d2s3d", "d2s3d", "elem", "depth to space over voxel rows", DT_FLOAT, L(d2s3d)),
|
||||
SIMPLE("avx_s2d3d", "s2d3d", "elem", "space to depth over voxel rows", DT_FLOAT, L(s2d3d)),
|
||||
SIMPLE("avx_pix_patch", "pix_patch", "elem", "an image to patch rows", DT_FLOAT, L(pix_patch)),
|
||||
SIMPLE("avx_patch_pix8", "patch_pix8", "elem", "patch rows to RGB bytes", DT_FLOAT, L(patch_pix8)),
|
||||
SIMPLE("avx_vol_index", "vol_index", "elem", "a volume's voxel coordinates", DT_ANY, L(vol_index)),
|
||||
SIMPLE("avx_tile_grid", "tile_grid", "elem", "a tiled decode's boxes", DT_ANY, L(tile_grid)),
|
||||
SIMPLE("avx_tile_crop", "tile_crop", "elem", "a tile out of a volume", DT_FLOAT, L(tile_crop)),
|
||||
SIMPLE("avx_tile_stitch", "tile_stitch", "elem", "decoded tiles blended to RGB bytes", DT_FLOAT,
|
||||
L(tile_stitch)),
|
||||
SIMPLE("avx_stft_logmel", "stft_logmel", "elem", "a causal log-mel spectrogram", DT_FLOAT,
|
||||
L(stft_logmel)),
|
||||
SIMPLE("avx_bwe_up", "bwe_up", "elem", "a sinc-resampled waveform plus a residual, clamped",
|
||||
DT_FLOAT, L(bwe_up)),
|
||||
|
||||
SIMPLE("avx_conv1d", "conv1d", "conv", "a 1-D convolution over sequences, as GEMMs over patch rows",
|
||||
DT_FLOAT, L(conv1d)),
|
||||
@@ -1560,6 +1694,8 @@ SIMPLE("avx_interleave2", "interleave2", "elem", "two streams interleaved", DT_A
|
||||
L(interleave2)),
|
||||
SIMPLE("avx_iota", "iota", "elem", "an arithmetic index sequence", DT_ANY, L(iota)),
|
||||
SIMPLE("avx_cu_repeat", "cu_repeat", "elem", "bounds of equal sequences", DT_ANY, L(cu_repeat)),
|
||||
SIMPLE("avx_int_affine", "int_affine", "elem", "integers derived from device geometry", DT_ANY,
|
||||
L(int_affine)),
|
||||
|
||||
SIMPLE("avx_embed_lookup", "embed_lookup", "vocab", "embedding gather", DT_FLOAT, L(embed_lookup)),
|
||||
/* Its layout hook only validates: the table is read as stored and other encodings are refused
|
||||
|
||||
+16
-6
@@ -458,14 +458,21 @@ AVX_KERNEL(conv3d_ndhwc) {
|
||||
const RadTensor *X = &a->t[0], *W = &a->t[1], *B = &a->t[2], *G = &a->t[3];
|
||||
const RadTensor *R = rad_arg_in(a, 4), *Y = &a->t[5];
|
||||
const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0);
|
||||
const int64_t k = p_int(a, "k", 0), kt = p_int(a, "kt", 0);
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1) || numel(G) < 3)
|
||||
const int64_t k = p_int(a, "k", 0), kt = p_int(a, "kt", 0), tpre = p_int(a, "tpre", 0);
|
||||
/* The frames' padding (libref's): zero, the edge frame repeated, or causal with `tpre` more
|
||||
* copies of the first frame in front (T + tpre frames out). */
|
||||
const char* tps = p_str(a, "tpad", "zero");
|
||||
const int tpad = !std::strcmp(tps, "zero") ? 0 : !std::strcmp(tps, "replicate") ? 1
|
||||
: !std::strcmp(tps, "causal") ? 2 : -1;
|
||||
if (tpad < 0 || (tpre && tpad != 2)) return RAD_E_INVAL;
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1) || tpre < 0 ||
|
||||
numel(G) < 3)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t T = at(G, 0), H = at(G, 1), Wd = at(G, 2);
|
||||
if (T <= 0 || H <= 0 || Wd <= 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = T * H * Wd, taps = kt * k * k, KK = taps * cin;
|
||||
if (rows_of(Y, cout) < rows || rows_of(X, cin) < rows || (R && rows_of(R, cout) < rows) ||
|
||||
numel(W) < cout * KK || numel(B) < cout)
|
||||
const int64_t rows = (T + tpre) * H * Wd, taps = kt * k * k, KK = taps * cin;
|
||||
if (rows_of(Y, cout) < rows || rows_of(X, cin) < T * H * Wd ||
|
||||
(R && rows_of(R, cout) < rows) || numel(W) < cout * KK || numel(B) < cout)
|
||||
return RAD_E_SHAPE;
|
||||
static thread_local std::vector<uint8_t> wbuf, pbuf;
|
||||
static thread_local std::vector<float> ybuf;
|
||||
@@ -505,7 +512,10 @@ AVX_KERNEL(conv3d_ndhwc) {
|
||||
for (int64_t dz = 0; dz < kt; ++dz)
|
||||
for (int64_t kh = 0; kh < k; ++kh)
|
||||
for (int64_t kw = 0; kw < k; ++kw, d += (size_t)cin * ael) {
|
||||
const int64_t tz = t + dz - pz, iy = i + kh - ps, ix = j + kw - ps;
|
||||
int64_t tz = t + dz - pz;
|
||||
if (tpad == 1) tz = std::min<int64_t>(std::max<int64_t>(tz, 0), T - 1);
|
||||
else if (tpad == 2) tz = std::max<int64_t>(t + dz - (kt - 1) - tpre, 0);
|
||||
const int64_t iy = i + kh - ps, ix = j + kw - ps;
|
||||
if (tz < 0 || tz >= T || iy < 0 || iy >= H || ix < 0 || ix >= Wd) {
|
||||
std::memset(d, 0, (size_t)cin * ael);
|
||||
continue;
|
||||
|
||||
@@ -136,16 +136,14 @@ bool chol_upper_loop(std::vector<double>& a, int64_t k) {
|
||||
return true;
|
||||
}
|
||||
|
||||
#ifdef RAD_LQ_LAPACK
|
||||
/* LAPACK where OpenBLAS was found; RAD_LQ_LAPACK=0 takes the loops instead, the reference the
|
||||
* LAPACK path is checked against (quant_algo_test). */
|
||||
bool use_lapack() {
|
||||
#ifdef RAD_LQ_LAPACK
|
||||
const char* e = std::getenv("RAD_LQ_LAPACK");
|
||||
return !(e && e[0] == '0');
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
bool chol_lower(std::vector<double>& a, int64_t k) {
|
||||
#ifdef RAD_LQ_LAPACK
|
||||
@@ -168,7 +166,7 @@ bool chol_upper(std::vector<double>& a, int64_t k) {
|
||||
return chol_upper_loop(a, k);
|
||||
}
|
||||
|
||||
/* Layer factors kept at once (RAD_LQ_FACTOR_CACHE_ALL: every one). */
|
||||
/* Layer factors kept at once. */
|
||||
constexpr size_t kFactors = 4;
|
||||
|
||||
struct Cache {
|
||||
@@ -222,10 +220,9 @@ Gram gptq_factor(const char* dir, const char* name, int64_t K, int64_t domain, d
|
||||
* once, and a 21504-wide factor is 1.85 GB in f32 (every one kept OOM-killed
|
||||
* TranslateGemma 27B's conversion at layer 25). A MoE layer's experts run in parallel
|
||||
* and alternate between its gate_up and down stems, so one kept factor would be
|
||||
* recomputed over and over. RAD_LQ_FACTOR_CACHE_ALL keeps every one. */
|
||||
static const bool all = std::getenv("RAD_LQ_FACTOR_CACHE_ALL") != nullptr;
|
||||
* recomputed over and over. */
|
||||
if (layer && !c.f.count(key)) {
|
||||
while (!all && c.order.size() >= kFactors) {
|
||||
while (c.order.size() >= kFactors) {
|
||||
c.f.erase(c.order.front());
|
||||
c.order.pop_front();
|
||||
}
|
||||
|
||||
@@ -81,6 +81,7 @@ set(R4D_UNITS
|
||||
# decoder's patch unfold, tiles, stitch and rotary positions, and the soundtrack decoder's
|
||||
# alias-free SnakeBeta.
|
||||
"r4d_video|"
|
||||
"r4d_ltx|"
|
||||
# A video latent upscaler: the 3x3x3 convolution as an implicit GEMM over voxel rows, the group
|
||||
# norm, the temporal depthwise convolution, the per-frame bilinear resize, the patch fold and the
|
||||
# re-noise.
|
||||
|
||||
@@ -869,6 +869,7 @@ int r4d_binary_bf16(long a, long b, long y, int M, int n, int op,
|
||||
int a_ld, int b_ld, int y_ld, long stream);
|
||||
int r4d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
|
||||
int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long stream);
|
||||
int r4d_fill_f32(long y, int M, int n, int y_ld, float value, long stream);
|
||||
// y[.., i] = silu(gu[.., i]) * gu[.., n + i]. The gate is the first half, the order rad-convert
|
||||
// fuses gate_proj and up_proj in.
|
||||
int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream);
|
||||
|
||||
@@ -362,9 +362,10 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
|
||||
* fill a card while their twins wait behind the other engine's kernel on the peer card, which
|
||||
* waits for a slot on the full card. Not capped: the hyper-connection gathers of the MoE paths
|
||||
* (r4d_ar_gather_hc_write without its inverse scratch, r4d_ar_hc_write_wht6), whose LDS table
|
||||
* needs a minimum block count, which may exceed the ceiling (dense models do not use them). Two TP2 engines on two R9700s (Qwen3.8-27B and Gemma 3 27B)
|
||||
* hung within a minute of concurrent prefill; MES then failed to evict the queues and the
|
||||
* failed reset froze the host. Capped in both engines so that their spinners together cannot
|
||||
* needs a minimum block count, which may exceed the ceiling (dense models do not use them).
|
||||
* Two TP2 engines on two R9700s (Qwen3.8-27B and Gemma 3 27B) hung within a minute of
|
||||
* concurrent prefill; MES then failed to evict the queues and the failed reset froze the
|
||||
* host. Capped in both engines so that their spinners together cannot
|
||||
* fill a card, the cycle cannot close. The flag and counter arrays keep their full size (maxb);
|
||||
* only the launch counts shrink, and each element's sum is the same. Unset, nothing changes. */
|
||||
if (const char* e = std::getenv("R4D_AR_MAX_BLOCKS")) {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// R4D dense attention, varlen over cu_seqlens segments, grouped-query: an encoder's, non-causal with
|
||||
// an optional two-sided window, i - j < window behind and j - i < wright ahead (wright is
|
||||
// `window_right`, or `window` for the symmetric |i - j| < window), or causal with an optional
|
||||
// window behind (a codec's sliding layers). bf16 in and out, f16 operands, f32 accumulate. Head
|
||||
// widths 64, 256 and 512 are compiled; each (head_dim, gqa) pair is a row.
|
||||
// window behind (a codec's sliding layers, a text encoder's prompt). bf16 in and out, f16
|
||||
// operands, f32 accumulate. Head widths 64, 256 and 512 are compiled; each (head_dim, gqa) pair
|
||||
// is a row.
|
||||
//
|
||||
// Core from the vision kernel (r4d_attn_vit_h72_bf16.hip): S^T = K.Q^T, so the wave32
|
||||
// column-distributed accumulator gives each lane one query row, softmax state is lane-private, and
|
||||
@@ -39,7 +40,8 @@ __global__ __launch_bounds__(NQB * GQA * DSPLIT * 32)
|
||||
void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
|
||||
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
|
||||
const int* __restrict__ cu, float scale, int window, int wright,
|
||||
int block, int cdiv, int causal, int q_ld, int k_ld, int v_ld, int o_ld)
|
||||
int block, int cdiv, int causal, int q_ld, int k_ld, int v_ld, int o_ld,
|
||||
int krep)
|
||||
{
|
||||
typedef DT16<1> D;
|
||||
typedef D::frag frag16;
|
||||
@@ -73,8 +75,9 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
|
||||
const int dp = warp % DSPLIT;
|
||||
const int g = (warp / DSPLIT) % GQA;
|
||||
const int qbi = warp / (DSPLIT * GQA);
|
||||
const int kvh = blockIdx.y, seq = blockIdx.z;
|
||||
const int hq = kvh * GQA + g;
|
||||
// blockIdx.y is a group of GQA query heads; krep groups read one KV head.
|
||||
const int kvh = blockIdx.y / krep, seq = blockIdx.z;
|
||||
const int hq = blockIdx.y * GQA + g;
|
||||
|
||||
const int s0 = cu[seq] / cdiv, slen = cu[seq + 1] / cdiv - s0;
|
||||
const int q0 = blockIdx.x * BQ;
|
||||
@@ -301,21 +304,25 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
|
||||
// ---- launch ----------------------------------------------------------------------------------
|
||||
// One instantiation per (head_dim, gqa), at a workgroup shape picked for it:
|
||||
// h64 gqa1: 8 query blocks of 16, K/V tiles of 64 keys (the vision towers' heads)
|
||||
// h256 gqa2: 8 query blocks x 2 heads, tiles of 32 (LDS: 37 KiB)
|
||||
// h256 gqa4: 4 query blocks x 4 heads, tiles of 32 (LDS: 37 KiB)
|
||||
// h512 gqa4: 2 query blocks x 4 heads x 2 head halves, tiles of 16 (LDS: 57 KiB)
|
||||
// h256 gqa2, 4, 8: 8, 4, 2 query blocks x the heads, tiles of 32 (LDS: 37 KiB)
|
||||
// h512 gqa2, 4, 8: 4, 2, 1 query blocks x the heads x 2 head halves, tiles of 16 (LDS: 57 KiB)
|
||||
// The LDS holds one K/V tile, so the query heads a workgroup carries change its waves, not it.
|
||||
// A wider group (16 query heads a KV head and up, any multiple of 8) runs as krep workgroups of
|
||||
// eight heads each over the same KV head: 16 heads in one would need 32 waves and, at h512, more
|
||||
// than 64 KiB of LDS.
|
||||
template<int HD, int GQA, int NQB, int DSPLIT, int TILE>
|
||||
static int r4d_attn_dense_launch(const void* q, const void* k, const void* v, void* o,
|
||||
const void* cu, int num_seqs, int max_seqlen, int n_head_kv,
|
||||
float scale, int window, int wright, int block, int cdiv,
|
||||
int causal, int q_ld, int k_ld, int v_ld, int o_ld, hipStream_t s)
|
||||
int causal, int q_ld, int k_ld, int v_ld, int o_ld, hipStream_t s,
|
||||
int krep = 1)
|
||||
{
|
||||
constexpr int BQ = NQB * 16;
|
||||
dim3 grid((max_seqlen + BQ - 1) / BQ, n_head_kv, num_seqs);
|
||||
dim3 grid((max_seqlen + BQ - 1) / BQ, n_head_kv * krep, num_seqs);
|
||||
hipLaunchKernelGGL((r4d_attn_dense_kernel<HD, GQA, NQB, DSPLIT, TILE>), grid,
|
||||
dim3(NQB * GQA * DSPLIT * 32), 0, s, (const uint16_t*)q, (const uint16_t*)k,
|
||||
(const uint16_t*)v, (uint16_t*)o, (const int*)cu, scale, window, wright,
|
||||
block, cdiv, causal, q_ld, k_ld, v_ld, o_ld);
|
||||
block, cdiv, causal, q_ld, k_ld, v_ld, o_ld, krep);
|
||||
const hipError_t e = hipGetLastError();
|
||||
return e == hipSuccess ? 0 : -100 - (int)e;
|
||||
}
|
||||
@@ -338,27 +345,34 @@ extern "C" int r4d_attn_dense_bf16(const void* q, const void* k, const void* v,
|
||||
return -4;
|
||||
if (num_seqs <= 0 || max_seqlen <= 0) return 0;
|
||||
if (wright == 0) wright = window;
|
||||
const int gqa = n_head / n_head_kv;
|
||||
int gqa = n_head / n_head_kv, krep = 1;
|
||||
if (gqa > 8 && gqa % 8 == 0) krep = gqa / 8, gqa = 8;
|
||||
hipStream_t s = (hipStream_t)stream;
|
||||
if (head_dim == 64 && gqa == 1)
|
||||
return r4d_attn_dense_launch<64, 1, 8, 1, 64>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen,
|
||||
n_head_kv, scale, window, wright, block,
|
||||
cdiv, causal, q_ld, k_ld, v_ld, o_ld, s);
|
||||
if (head_dim == 256 && gqa == 2)
|
||||
return r4d_attn_dense_launch<256, 2, 8, 1, 32>(q, k, v, o, cu_seqlens, num_seqs,
|
||||
max_seqlen, n_head_kv, scale, window,
|
||||
wright, block, cdiv, causal, q_ld, k_ld,
|
||||
v_ld, o_ld, s);
|
||||
if (head_dim == 256 && gqa == 4)
|
||||
return r4d_attn_dense_launch<256, 4, 4, 1, 32>(q, k, v, o, cu_seqlens, num_seqs,
|
||||
max_seqlen, n_head_kv, scale, window,
|
||||
wright, block, cdiv, causal, q_ld, k_ld,
|
||||
v_ld, o_ld, s);
|
||||
if (head_dim == 512 && gqa == 4)
|
||||
return r4d_attn_dense_launch<512, 4, 2, 2, 16>(q, k, v, o, cu_seqlens, num_seqs,
|
||||
max_seqlen, n_head_kv, scale, window,
|
||||
wright, block, cdiv, causal, q_ld, k_ld,
|
||||
v_ld, o_ld, s);
|
||||
#define R4D_DENSE(HD, G, NQB, DS, T) \
|
||||
return r4d_attn_dense_launch<HD, G, NQB, DS, T>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen, \
|
||||
n_head_kv, scale, window, wright, block, \
|
||||
cdiv, causal, q_ld, k_ld, v_ld, o_ld, s, krep)
|
||||
if (head_dim == 256) {
|
||||
switch (gqa) {
|
||||
case 2: R4D_DENSE(256, 2, 8, 1, 32);
|
||||
case 4: R4D_DENSE(256, 4, 4, 1, 32);
|
||||
case 8: R4D_DENSE(256, 8, 2, 1, 32);
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
if (head_dim == 512) {
|
||||
switch (gqa) {
|
||||
case 2: R4D_DENSE(512, 2, 4, 2, 16);
|
||||
case 4: R4D_DENSE(512, 4, 2, 2, 16);
|
||||
case 8: R4D_DENSE(512, 8, 1, 2, 16);
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
#undef R4D_DENSE
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
+81
-19
@@ -69,7 +69,8 @@ __global__ __launch_bounds__(NQB * GQA * 32)
|
||||
void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
|
||||
const int8_t* __restrict__ gk8, const float* __restrict__ gks,
|
||||
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
|
||||
const int* __restrict__ cu, int num_seqs, const int* __restrict__ used,
|
||||
const int* __restrict__ cu, const int* __restrict__ cuk, int num_seqs,
|
||||
const int* __restrict__ used,
|
||||
const int* __restrict__ bt, int bt_pitch,
|
||||
const uint16_t* __restrict__ kvc, int kv_heads,
|
||||
float scale, int causal, int q_ld, int k_ld, int k8_ld, int ks_ld,
|
||||
@@ -137,7 +138,10 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
if (slen <= 0 || q0 >= slen) return;
|
||||
const int qlast = min(q0 + BQ, slen) - 1;
|
||||
const int P = used ? used[seq] : 0;
|
||||
const int ke = causal ? qlast + 1 : slen; // own keys any query here can see
|
||||
// Own keys: beside the queries, or (`cuk`, attn_cross) a run of their own; a query sees key j
|
||||
// of its run, counted from the run's start, when j <= its own row with `causal`.
|
||||
const int ks0 = cuk ? cuk[seq] : s0, klen = cuk ? cuk[seq + 1] - ks0 : slen;
|
||||
const int ke = causal ? min(qlast + 1, klen) : klen; // own keys any query here can see
|
||||
|
||||
const float mul = scale * 1.44269504089f;
|
||||
const int qpos = q0 + qbi * 16 + c;
|
||||
@@ -193,12 +197,12 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
|
||||
// The K row of key `kk` of the current source; its V row is `vrow`.
|
||||
auto krow = [&](bool pre, int kk) -> const uint16_t* {
|
||||
if (!pre) return kbase + (long)(s0 + kk) * k_ld;
|
||||
if (!pre) return kbase + (long)(ks0 + kk) * k_ld;
|
||||
const int blk = btrow[kk / BS];
|
||||
return kvc + ((long)(blk * kv_heads + kvh) * BS + (kk % BS)) * (2 * HD);
|
||||
};
|
||||
auto vrow = [&](bool pre, int kk) -> const uint16_t* {
|
||||
if (!pre) return vbase + (long)(s0 + kk) * v_ld;
|
||||
if (!pre) return vbase + (long)(ks0 + kk) * v_ld;
|
||||
const int blk = btrow[kk / BS];
|
||||
return kvc + ((long)(blk * kv_heads + kvh) * BS + (kk % BS)) * (2 * HD) + HD;
|
||||
};
|
||||
@@ -222,12 +226,12 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
if ((TILE * K8G) % NTHR == 0 || i < TILE * K8G) {
|
||||
const int key = i / K8G, gg = i % K8G;
|
||||
const int kk = (k0 + key < klim) ? k0 + key : klim - 1;
|
||||
kr[p] = *(const uint4*)(gk8 + (long)(s0 + kk) * k8_ld + (long)kvh * HD + gg * 16);
|
||||
kr[p] = *(const uint4*)(gk8 + (long)(ks0 + kk) * k8_ld + (long)kvh * HD + gg * 16);
|
||||
}
|
||||
}
|
||||
if (tid < TILE) {
|
||||
const int kk = (k0 + tid < klim) ? k0 + tid : klim - 1;
|
||||
ksr = gks[(long)(s0 + kk) * ks_ld + kvh];
|
||||
ksr = gks[(long)(ks0 + kk) * ks_ld + kvh];
|
||||
}
|
||||
} else {
|
||||
#pragma unroll
|
||||
@@ -243,7 +247,7 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
if constexpr (PV8) {
|
||||
const int kk0 = k0 + (lgi / DG8) * 8 + vj;
|
||||
const int kk = (kk0 < klim) ? kk0 : klim - 1;
|
||||
const uint8_t* v8 = (const uint8_t*)gv + (long)(s0 + kk) * v_ld + (long)kvh * HD;
|
||||
const uint8_t* v8 = (const uint8_t*)gv + (long)(ks0 + kk) * v_ld + (long)kvh * HD;
|
||||
vr[0] = __builtin_bit_cast(uint4, load_tr_b128(v8 + (lgi % DG8) * 16));
|
||||
} else {
|
||||
#pragma unroll
|
||||
@@ -597,7 +601,7 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
|
||||
template<int HD, int GQA, int NQB, int TILE, bool I8, bool PV8>
|
||||
static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, const float* ks,
|
||||
const void* v, void* o, const int* cu,
|
||||
const void* v, void* o, const int* cu, const int* cuk,
|
||||
const int* used, const int* bt, int bt_pitch, const void* kvc,
|
||||
int num_seqs, int max_q, int n_head_kv, float scale, int causal,
|
||||
int q_ld, int k_ld, int k8_ld, int ks_ld, int v_ld, int o_ld,
|
||||
@@ -609,14 +613,15 @@ static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, cons
|
||||
hipLaunchKernelGGL((r4d_attn_ps_kernel<HD, GQA, NQB, TILE, I8, PV8>), grid,
|
||||
dim3(NQB * GQA * 32), 0, s,
|
||||
(const uint16_t*)q, (const uint16_t*)k, (const int8_t*)k8, ks,
|
||||
(const uint16_t*)v, (uint16_t*)o, cu, num_seqs, used, bt, bt_pitch,
|
||||
(const uint16_t*)v, (uint16_t*)o, cu, cuk, num_seqs, used, bt, bt_pitch,
|
||||
(const uint16_t*)kvc, n_head_kv, scale, causal, q_ld, k_ld, k8_ld, ks_ld,
|
||||
v_ld, o_ld, vs);
|
||||
const hipError_t e = hipGetLastError();
|
||||
return e == hipSuccess ? 0 : -100 - (int)e;
|
||||
}
|
||||
|
||||
/* head_dim 128 at gqa 1, 2, 4 and 8. Null `used`/`bt`/`kvc` means no prefix (the dense form).
|
||||
/* head_dim 128 at gqa 1, 2, 4 and 8, and 64 (an audio stream's heads) without a prefix or the
|
||||
* int8 and fp8 forms. Null `used`/`bt`/`kvc` means no prefix (the dense form).
|
||||
* `max_q` is the total query rows over all sequences and bounds the flat grid. Non-null `k8`
|
||||
* selects the int8 Q.K form (own-key codes, `k8_ld` bytes per row; a scale per (row, head) in
|
||||
* `ks`, `ks_ld` floats per row), gqa 1 only. Non-null `vs` selects the fp8 P.V form (`v` as E4M3
|
||||
@@ -626,16 +631,34 @@ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float
|
||||
const int* used, const int* bt, int bt_pitch, const void* kvc,
|
||||
int num_seqs, int max_q, int n_head, int n_head_kv, int head_dim,
|
||||
float scale, int causal, int q_ld, int k_ld, int k8_ld, int ks_ld,
|
||||
int v_ld, int o_ld, hipStream_t s, const float* vs = nullptr)
|
||||
int v_ld, int o_ld, hipStream_t s, const float* vs = nullptr,
|
||||
const int* cuk = nullptr)
|
||||
{
|
||||
if (n_head <= 0 || n_head_kv <= 0 || n_head % n_head_kv) return -2;
|
||||
if ((q_ld | k_ld | v_ld | o_ld) & 7) return -3;
|
||||
if (k8 && ((k8_ld & 15) || ((uintptr_t)k8 & 15) || !ks)) return -3;
|
||||
if (num_seqs <= 0 || max_q <= 0) return 0;
|
||||
const int gqa = n_head / n_head_kv;
|
||||
if (head_dim == 64) {
|
||||
if (k8 || vs || used || bt || kvc) return -1;
|
||||
#define R4D_PS64(G, NQB) \
|
||||
return r4d_attn_ps_launch<64, G, NQB, 64, false, false>(q, k, k8, ks, v, o, cu, cuk, used, \
|
||||
bt, bt_pitch, kvc, num_seqs, \
|
||||
max_q, n_head_kv, scale, causal, \
|
||||
q_ld, k_ld, k8_ld, ks_ld, v_ld, \
|
||||
o_ld, nullptr, s)
|
||||
switch (gqa) {
|
||||
case 1: R4D_PS64(1, 16);
|
||||
case 2: R4D_PS64(2, 4);
|
||||
case 4: R4D_PS64(4, 2);
|
||||
case 8: R4D_PS64(8, 1);
|
||||
default: return -1;
|
||||
}
|
||||
#undef R4D_PS64
|
||||
}
|
||||
if (head_dim != 128) return -1;
|
||||
#define R4D_PS(G, NQB, T, I8) \
|
||||
return r4d_attn_ps_launch<128, G, NQB, T, I8, false>(q, k, k8, ks, v, o, cu, used, bt, \
|
||||
return r4d_attn_ps_launch<128, G, NQB, T, I8, false>(q, k, k8, ks, v, o, cu, cuk, used, bt, \
|
||||
bt_pitch, kvc, num_seqs, max_q, \
|
||||
n_head_kv, scale, causal, q_ld, k_ld, \
|
||||
k8_ld, ks_ld, v_ld, o_ld, nullptr, s)
|
||||
@@ -646,10 +669,10 @@ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float
|
||||
if (gqa != 1 || used || bt || kvc || (v_ld & 15) || ((uintptr_t)v & 15)) return -1;
|
||||
if (k8)
|
||||
return r4d_attn_ps_launch<128, 1, 16, 64, true, true>(
|
||||
q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv,
|
||||
q, k, k8, ks, v, o, cu, cuk, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv,
|
||||
scale, causal, q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, vs, s);
|
||||
return r4d_attn_ps_launch<128, 1, 16, 64, false, true>(
|
||||
q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv, scale,
|
||||
q, k, k8, ks, v, o, cu, cuk, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv, scale,
|
||||
causal, q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, vs, s);
|
||||
}
|
||||
if (k8) {
|
||||
@@ -791,8 +814,44 @@ extern "C" int r4d_rad_attn_dense_h128(const RadArgs* a, RadStream s) {
|
||||
return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
// ============================================================== wide heads (attn_dense, h768 / h1152)
|
||||
// Image decoder mid-block attention: one head up to 1152 wide over every latent pixel (16384 rows
|
||||
/* attn_cross at head_dim 64 or 128: the dense kernel with each entry's keys a run of their own
|
||||
* (`cu_k`), causal counting from each run's start. */
|
||||
extern "C" int r4d_rad_attn_cross(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* q = r4d_opt(a, 0);
|
||||
const RadTensor* k = r4d_opt(a, 1);
|
||||
const RadTensor* v = r4d_opt(a, 2);
|
||||
const RadTensor* cu = r4d_opt(a, 3);
|
||||
const RadTensor* ck = r4d_opt(a, 4);
|
||||
const RadTensor* o = r4d_opt(a, 5);
|
||||
if (!q || !k || !v || !cu || !ck || !o) return R4D_NO(RAD_E_INVAL);
|
||||
if (!r4d_contig(cu) || cu->rank != 1 || cu->shape[0] < 2 || !r4d_contig(ck) ||
|
||||
r4d_numel(ck) < cu->shape[0])
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
const long long hd = r4d_geti_or(a, "head_dim", 0), gqa = r4d_geti_or(a, "gqa", 1);
|
||||
if ((hd != 64 && hd != 128) || gqa <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0;
|
||||
long long to = 0, ho = 0, o_ld = 0;
|
||||
if (!r4d_head_rows(q, hd, &total, &nh, &q_ld) ||
|
||||
!r4d_head_rows(k, hd, &tk, &hk, &k_ld) ||
|
||||
!r4d_head_rows(v, hd, &tv, &hv, &v_ld) ||
|
||||
!r4d_head_rows(o, hd, &to, &ho, &o_ld))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
if (hk != hv || ho != nh || hk * gqa != nh || tk != tv || to < total) return R4D_NO(RAD_E_SHAPE);
|
||||
const int num_seqs = (int)(cu->shape[0] - 1);
|
||||
const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)hd));
|
||||
const int e = r4d_attn_ps(q->data, k->data, nullptr, nullptr, v->data, o->data,
|
||||
(const int*)cu->data, nullptr, nullptr, 0, nullptr, num_seqs,
|
||||
(int)total, (int)nh, (int)hk, (int)hd, scale,
|
||||
(int)r4d_geti_or(a, "causal", 0), (int)q_ld, (int)k_ld, 0, 0,
|
||||
(int)v_ld, (int)o_ld, (hipStream_t)s, nullptr,
|
||||
(const int*)ck->data);
|
||||
if (e == -1 || e == -2) return R4D_NO(RAD_E_SHAPE);
|
||||
if (e == 0) return RAD_OK;
|
||||
return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
// ============================================================== wide heads (attn_dense, h384 .. h1152)
|
||||
// Image decoder mid-block attention: one head 384 to 1152 wide over every latent pixel (16384 rows
|
||||
// at 2048 x 2048). A lane cannot hold a 1152-wide output row (576 accumulator VGPRs), so the head
|
||||
// is split across the workgroup's eight waves: a wave owns HD/8 dims of the 16-query block.
|
||||
//
|
||||
@@ -945,7 +1004,8 @@ extern "C" int r4d_rad_attn_dense_wide(const RadArgs* a, RadStream s) {
|
||||
if (!q || !k || !v || !cu || !o) return R4D_NO(RAD_E_INVAL);
|
||||
if (!r4d_contig(cu) || cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE);
|
||||
const long long hd = r4d_geti_or(a, "head_dim", 0);
|
||||
if ((hd != 768 && hd != 1152) || r4d_geti_or(a, "gqa", 1) != 1 || r4d_geti_or(a, "causal", 0) != 0 ||
|
||||
if ((hd != 384 && hd != 512 && hd != 768 && hd != 1152) || r4d_geti_or(a, "gqa", 1) != 1 ||
|
||||
r4d_geti_or(a, "causal", 0) != 0 ||
|
||||
r4d_geti_or(a, "window", 0) != 0 || r4d_geti_or(a, "block", 0) != 0 ||
|
||||
r4d_geti_or(a, "cu_div", 1) != 1)
|
||||
return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
@@ -967,8 +1027,10 @@ extern "C" int r4d_rad_attn_dense_wide(const RadArgs* a, RadStream s) {
|
||||
(const uint16_t*)q->data, (const uint16_t*)k->data, \
|
||||
(const uint16_t*)v->data, (uint16_t*)o->data, (const int*)cu->data, \
|
||||
num_seqs, scale, (int)q_ld, (int)k_ld, (int)v_ld, (int)o_ld)
|
||||
if (hd == 768) R4D_WIDE(768);
|
||||
else R4D_WIDE(1152);
|
||||
if (hd == 384) R4D_WIDE(384);
|
||||
else if (hd == 512) R4D_WIDE(512);
|
||||
else if (hd == 768) R4D_WIDE(768);
|
||||
else R4D_WIDE(1152);
|
||||
#undef R4D_WIDE
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
|
||||
}
|
||||
@@ -54,6 +54,12 @@ using std::max;
|
||||
#ifndef R4D_ATTN_H256
|
||||
#define R4D_ATTN_H256 1
|
||||
#endif
|
||||
/* The fp8_v4 and k6_v4 caches at head_dim 256 (RadBuildCtx::kv_quant), off unless the including
|
||||
* unit serves a model whose plugin offers them: Qwen3.8-Flash-Next's QSA layers (gqa12, and gqa6
|
||||
* at four ranks). The kernels are the h256/gqa6 templates' O_V4 / O_K6 forms. */
|
||||
#ifndef R4D_ATTN_V4
|
||||
#define R4D_ATTN_V4 0
|
||||
#endif
|
||||
#define GQ_JOIN_(a, b, c) a##b##c
|
||||
#define GQ_JOIN(a, b, c) GQ_JOIN_(a, b, c)
|
||||
#define GQ_SYM(pre, suf) GQ_JOIN(pre, R4D_ATTN_GQA, suf)
|
||||
@@ -99,10 +105,11 @@ extern "C" long GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(const R4DArgs* a) {
|
||||
return r4d_decode_scratch(a, r4d_decode_splits(a, G8_D_TILE), G8_D_OPT);
|
||||
}
|
||||
|
||||
template <int HEAD_DIM, int KVP>
|
||||
template <int HEAD_DIM, int KVP, int XOPT = 0>
|
||||
/* Two dispatches: the attention kernel and the split-KV combine. R4DArgs is passed by value (168
|
||||
* bytes) like any other kernel argument. Non-null `gq` adds the output gate and quantiser to the
|
||||
* combine (attn_paged_gate_quant; R4DGateQuant in r4d_attn_decode_h256_gqa6.hip). */
|
||||
* combine (attn_paged_gate_quant; R4DGateQuant in r4d_attn_decode_h256_gqa6.hip). `XOPT` adds
|
||||
* option bits to the attention kernel's (O_V4, O_K6: the cache layout). */
|
||||
static int g8_decode_launch(const R4DArgs* a, RadStream stream,
|
||||
const R4DGateQuant* gq = nullptr) {
|
||||
int emit_rc = RAD_OK;
|
||||
@@ -115,12 +122,14 @@ static int g8_decode_launch(const R4DArgs* a, RadStream stream,
|
||||
|
||||
#define G8_LAUNCH(NW) \
|
||||
emit_rc = R4D_EMIT(stream, (r4d_attn_decode_kernel<NW, G8_D_TILE, HEAD_DIM, G8_GQA, \
|
||||
G8_BLOCK_SIZE, KVP, G8_D_OPT>), \
|
||||
G8_BLOCK_SIZE, KVP, G8_D_OPT | XOPT>), \
|
||||
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, *a, splits)
|
||||
/* One-wave workgroups stage V as codes (O_V8): same conversion count, half the LDS. */
|
||||
/* One-wave workgroups stage V as codes (O_V8): same conversion count, half the LDS. A v4
|
||||
* cache stages V widened (the kernel drops O_V8 under O_V4). */
|
||||
if (nw == 1)
|
||||
emit_rc = R4D_EMIT(stream, (r4d_attn_decode_kernel<1, G8_D_TILE, HEAD_DIM, G8_GQA,
|
||||
G8_BLOCK_SIZE, KVP, G8_D_OPT | O_V8>),
|
||||
G8_BLOCK_SIZE, KVP,
|
||||
G8_D_OPT | O_V8 | XOPT>),
|
||||
dim3(splits, a->kv_heads, a->num_seqs), dim3(32), 0, *a, splits);
|
||||
else if (nw == 2) G8_LAUNCH(2);
|
||||
else if (nw == 3) G8_LAUNCH(3);
|
||||
@@ -227,7 +236,9 @@ extern "C" int GQ_SYM(r4d_rad_attn_prefill_h64_gqa, _bf16)(const RadArgs* a, Rad
|
||||
* parameters and no tensors, so parameters come first and tensors are the fallback (see the
|
||||
* h256/gqa6 dispatch). The size is the maximum over every sequence count up to max_seqs, because
|
||||
* S * floor(128 / (kv_heads * S)) is not monotone in S. */
|
||||
static int64_t g8_decode_scratch(const RadArgs* a, int head_dim) {
|
||||
/* `row` is a token's bytes in a (block, head) page, 0 for the 16-bit and E4M3 caches' 2 * head_dim
|
||||
* (fill_paged_row). */
|
||||
static int64_t g8_decode_scratch(const RadArgs* a, int head_dim, long long row = 0) {
|
||||
const int sp = split_of(a);
|
||||
if (sp < 0) return R4D_NO(RAD_E_INVAL);
|
||||
|
||||
@@ -254,7 +265,7 @@ static int64_t g8_decode_scratch(const RadArgs* a, int head_dim) {
|
||||
}
|
||||
return worst;
|
||||
}
|
||||
const int rc = fill_paged(a, &r, head_dim);
|
||||
const int rc = fill_paged_row(a, &r, head_dim, row > 0 ? row : 2LL * head_dim);
|
||||
if (rc != RAD_OK) return rc;
|
||||
r.splits = sp;
|
||||
return GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(&r);
|
||||
@@ -271,10 +282,10 @@ extern "C" int64_t GQ_SYM(r4d_rad_attn_decode_h128_gqa, _scratch)(const RadArgs*
|
||||
}
|
||||
#endif
|
||||
|
||||
static int g8_decode_common(const RadArgs* a, R4DArgs* r, int head_dim) {
|
||||
static int g8_decode_common(const RadArgs* a, R4DArgs* r, int head_dim, long long row = 0) {
|
||||
const int sp = split_of(a);
|
||||
if (sp < 0) return R4D_NO(RAD_E_INVAL);
|
||||
const int rc = fill_paged(a, r, head_dim);
|
||||
const int rc = fill_paged_row(a, r, head_dim, row > 0 ? row : 2LL * head_dim);
|
||||
if (rc != RAD_OK) return rc;
|
||||
r->splits = sp;
|
||||
const int64_t need = GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(r);
|
||||
@@ -380,3 +391,39 @@ extern "C" int GQ_SYM(r4d_rad_attn_decode_h128_gqa, _bf16)(const RadArgs* a, Rad
|
||||
return g8_decode_launch<128, 1>(&r, s);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if R4D_ATTN_H256 && R4D_ATTN_V4
|
||||
/* ---- the fp8_v4 cache (a token's row 25 * 256 / 16 = 400 bytes: E4M3 K, int4 V, f16 scales) and
|
||||
* the k6_v4 cache (352 bytes: int6 K, int4 V), prefill, decode and decode with the gate and
|
||||
* quantiser in the merge. */
|
||||
#define G8_V4_ENTRIES(TAG, ROWB, XOPT) \
|
||||
extern "C" int GQ_SYM(r4d_rad_attn_prefill_h256_gqa, _##TAG)(const RadArgs* a, RadStream s) { \
|
||||
R4DArgs r; \
|
||||
const int rc = fill_paged_row(a, &r, 256, ROWB); \
|
||||
if (rc != RAD_OK) return rc; \
|
||||
return g8_prefill_launch<256, G8_P_OPT_256 | (XOPT), 0>(&r, (hipStream_t)s); \
|
||||
} \
|
||||
extern "C" int64_t GQ_SYM(r4d_rad_attn_decode_h256_gqa, _##TAG##_scratch)(const RadArgs* a) { \
|
||||
return g8_decode_scratch(a, 256, ROWB); \
|
||||
} \
|
||||
extern "C" int GQ_SYM(r4d_rad_attn_decode_h256_gqa, _##TAG)(const RadArgs* a, \
|
||||
RadStream stream) { \
|
||||
R4DArgs r; \
|
||||
const int rc = g8_decode_common(a, &r, 256, ROWB); \
|
||||
if (rc != RAD_OK) return rc; \
|
||||
return g8_decode_launch<256, 0, (XOPT)>(&r, stream); \
|
||||
} \
|
||||
extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _##TAG)(const RadArgs* a, \
|
||||
RadStream stream) { \
|
||||
R4DArgs r; \
|
||||
const int rc = g8_decode_common(a, &r, 256, ROWB); \
|
||||
if (rc != RAD_OK) return rc; \
|
||||
R4DGateQuant gq{}; \
|
||||
const int gc = g8_gate_quant_args(a, r, &gq); \
|
||||
if (gc != RAD_OK) return gc; \
|
||||
return g8_decode_launch<256, 0, (XOPT)>(&r, stream, &gq); \
|
||||
}
|
||||
G8_V4_ENTRIES(fp8v4, 400, O_V4)
|
||||
G8_V4_ENTRIES(k6v4, 352, O_V4 | O_K6)
|
||||
#undef G8_V4_ENTRIES
|
||||
#endif
|
||||
@@ -17,5 +17,7 @@
|
||||
// pages at 4 (RadKVGroupDecl takes the block size from the resolved kernel). A row saying 16 here
|
||||
// would refuse at issue rather than at declare.
|
||||
#define G8_BLOCK_SIZE 4
|
||||
// The fp8_v4 and k6_v4 caches (--kv-cache-dtype), which qwen4exp_fp8 offers for these layers.
|
||||
#define R4D_ATTN_V4 1
|
||||
|
||||
#include "r4d_attn_paged_gqa8.hip"
|
||||
@@ -19,5 +19,7 @@
|
||||
// the pages at 4 (RadKVGroupDecl takes the block size from the resolved kernel). A row saying 16
|
||||
// here would refuse at issue rather than at declare.
|
||||
#define G8_BLOCK_SIZE 4
|
||||
// The fp8_v4 and k6_v4 caches (--kv-cache-dtype), which qwen4exp_fp8 offers for these layers.
|
||||
#define R4D_ATTN_V4 1
|
||||
|
||||
#include "r4d_attn_paged_gqa8.hip"
|
||||
@@ -16,6 +16,7 @@
|
||||
#include "rad_philox.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
@@ -970,6 +971,17 @@ __global__ __launch_bounds__(kT) void iota_kernel(int* __restrict__ y, int n, in
|
||||
if (i < n) y[i] = start + (period > 0 ? i % period : i) * step;
|
||||
}
|
||||
|
||||
// y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j], the lists by value.
|
||||
constexpr int kAffMax = 16;
|
||||
struct IntAffine { int src[kAffMax], mul[kAffMax], add[kAffMax]; };
|
||||
|
||||
__global__ __launch_bounds__(kAffMax) void int_affine_kernel(const int* __restrict__ x,
|
||||
int* __restrict__ y, IntAffine p,
|
||||
int n) {
|
||||
const int j = threadIdx.x;
|
||||
if (j < n) y[j] = (p.src[j] < 0 ? 0 : x[p.src[j]]) * p.mul[j] + p.add[j];
|
||||
}
|
||||
|
||||
__global__ __launch_bounds__(kT) void cu_repeat_kernel(const int* __restrict__ len,
|
||||
int* __restrict__ y, int n, int mult) {
|
||||
const int j = blockIdx.x * kT + threadIdx.x;
|
||||
@@ -1597,6 +1609,38 @@ extern "C" int r4d_rad_iota(const RadArgs* a, RadStream s) {
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
namespace {
|
||||
int parse_ints(const char* s, int* v, int cap) {
|
||||
int n = 0;
|
||||
while (s && *s) {
|
||||
char* e = nullptr;
|
||||
const long x = std::strtol(s, &e, 10);
|
||||
if (e == s) break;
|
||||
if (n == cap) return -1;
|
||||
v[n++] = (int)x;
|
||||
s = e;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" int r4d_rad_int_affine(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1);
|
||||
if (!x || !y) return R4D_NO(RAD_E_INVAL);
|
||||
if (!is_i32(x) || !is_i32(y)) return R4D_NO(RAD_E_DTYPE);
|
||||
if (!r4d_contig(x) || !r4d_contig(y)) return R4D_NO(RAD_E_STRIDE);
|
||||
IntAffine p{};
|
||||
const int n = parse_ints(r4d_gets(a, "src"), p.src, kAffMax);
|
||||
if (n <= 0 || parse_ints(r4d_gets(a, "mul"), p.mul, kAffMax) != n ||
|
||||
parse_ints(r4d_gets(a, "add"), p.add, kAffMax) != n || r4d_numel(y) < n)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
for (int j = 0; j < n; ++j)
|
||||
if (p.src[j] >= r4d_numel(x)) return R4D_NO(RAD_E_SHAPE);
|
||||
hipLaunchKernelGGL(int_affine_kernel, dim3(1), dim3(kAffMax), 0, (hipStream_t)s,
|
||||
(const int*)x->data, (int*)y->data, p, n);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_cu_repeat(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *len = r4d_opt(a, 0), *y = r4d_opt(a, 1);
|
||||
if (!len || !y) return R4D_NO(RAD_E_INVAL);
|
||||
|
||||
+99
-205
@@ -1,6 +1,7 @@
|
||||
/* Canonical E4M3 weights with exact F32 block scales: native FP8 WMMA and F32 scale folding, no
|
||||
* checkpoint scale narrowing. The grouped form and the legacy dense form compute one 16x64 output
|
||||
* tile a block; the dense decode and prefill forms below them produce the same bytes faster. */
|
||||
* checkpoint scale narrowing. The legacy dense form computes one 16x64 output tile a block; the
|
||||
* dense decode and prefill forms below it produce the same bytes faster, and the grouped form runs
|
||||
* expert-major over the same per-element sequence. */
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_emit.h"
|
||||
@@ -8,108 +9,75 @@
|
||||
#include "r4d_fp8_wmma.h"
|
||||
#include "r4d_launch.h"
|
||||
#include <climits>
|
||||
#include <cstdio>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
struct Meta {
|
||||
long ar, asr, yr, wr, sr, wstep[2], sstep[2];
|
||||
int T, N, K, experts, topk, sorted_a, tile;
|
||||
int T, N, K, experts, topk, sorted_a;
|
||||
};
|
||||
__device__ const uint8_t* entry(const void* p, long step, int e) {
|
||||
return step ? (const uint8_t*)p + step * e : ((const uint8_t* const*)p)[e];
|
||||
}
|
||||
template <bool Grouped>
|
||||
__global__ void fp8_f32scale(const uint8_t* a, const float* as, const void* w0, const void* s0,
|
||||
const void* w1, const void* s1, const int* sorted, const int* offsets,
|
||||
/* The legacy dense form: a block per 16 rows by 64 columns, the operands staged through LDS a
|
||||
* dword at a time, so it serves any row pitch and alignment. */
|
||||
__global__ void fp8_f32scale(const uint8_t* a, const float* as, const uint8_t* w, const float* ws,
|
||||
uint16_t* y, Meta m) {
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, n0 = blockIdx.x * 64;
|
||||
__shared__ uint8_t qa[16 * 136], wb[64 * 136];
|
||||
__shared__ int source[16];
|
||||
int first = (int)blockIdx.y * (Grouped ? m.tile : 16);
|
||||
const int limit = min(first + (Grouped ? m.tile : 16), m.T);
|
||||
while (first < limit) {
|
||||
int expert = 0, end = limit;
|
||||
if constexpr (Grouped) {
|
||||
// Tile sorted rows rather than launching every expert, most of which are empty
|
||||
// during native MTP decode. Split a tile at each expert boundary.
|
||||
if (sorted[first] < 0 || offsets[m.experts] <= first) {
|
||||
for (int c = tid; c < 64; c += 128)
|
||||
if (n0 + c < m.N) y[(long)first * m.yr + n0 + c] = 0;
|
||||
++first;
|
||||
continue;
|
||||
const int first = (int)blockIdx.y * 16, end = min(first + 16, m.T);
|
||||
if (tid < 16) {
|
||||
const int r = first + tid;
|
||||
source[tid] = r < end ? r : -1;
|
||||
}
|
||||
__syncthreads();
|
||||
auto acc = r4d_fp8::acc_zero();
|
||||
for (int k0 = 0; k0 < m.K; k0 += 128) {
|
||||
for (int j = tid; j < 16 * 32; j += 128) {
|
||||
const int r = j / 32, c = (j % 32) * 4, src = source[r];
|
||||
uint32_t v = 0;
|
||||
if (src >= 0) {
|
||||
const auto* p = a + (long)src * m.ar + k0 + c;
|
||||
v = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) |
|
||||
((uint32_t)p[3] << 24);
|
||||
}
|
||||
int lo = 0, hi = m.experts;
|
||||
while (lo + 1 < hi) {
|
||||
const int mid = (lo + hi) / 2;
|
||||
if (offsets[mid] <= first)
|
||||
lo = mid;
|
||||
else
|
||||
hi = mid;
|
||||
}
|
||||
expert = lo;
|
||||
end = min(limit, offsets[expert + 1]);
|
||||
if (end <= first) return;
|
||||
*(uint32_t*)(qa + r * 136 + c) = v;
|
||||
}
|
||||
const int parity = Grouped ? expert & 1 : 0, e = Grouped ? expert / 2 : 0;
|
||||
const auto* w = entry(parity ? w1 : w0, m.wstep[parity], e);
|
||||
const auto* ws = (const float*)entry(parity ? s1 : s0, m.sstep[parity], e);
|
||||
if (tid < 16) {
|
||||
const int r = first + tid;
|
||||
const int flat = Grouped && r < end ? sorted[r] : r;
|
||||
source[tid] = r < end && flat >= 0 ? (Grouped && !m.sorted_a ? flat / m.topk : r) : -1;
|
||||
for (int j = tid; j < 64 * 32; j += 128) {
|
||||
const int r = j / 32, c = (j % 32) * 4;
|
||||
const auto* p = w + (long)(n0 + r) * m.wr + k0 + c;
|
||||
*(uint32_t*)(wb + r * 136 + c) = (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
|
||||
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
}
|
||||
__syncthreads();
|
||||
auto acc = r4d_fp8::acc_zero();
|
||||
for (int k0 = 0; k0 < m.K; k0 += 128) {
|
||||
for (int j = tid; j < 16 * 32; j += 128) {
|
||||
const int r = j / 32, c = (j % 32) * 4, src = source[r];
|
||||
uint32_t v = 0;
|
||||
if (src >= 0) {
|
||||
const auto* p = a + (long)src * m.ar + k0 + c;
|
||||
v = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) |
|
||||
((uint32_t)p[3] << 24);
|
||||
}
|
||||
*(uint32_t*)(qa + r * 136 + c) = v;
|
||||
}
|
||||
for (int j = tid; j < 64 * 32; j += 128) {
|
||||
const int r = j / 32, c = (j % 32) * 4;
|
||||
const auto* p = w + (long)(n0 + r) * m.wr + k0 + c;
|
||||
*(uint32_t*)(wb + r * 136 + c) = (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
|
||||
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
}
|
||||
__syncthreads();
|
||||
auto raw = r4d_fp8::acc_zero();
|
||||
auto raw = r4d_fp8::acc_zero();
|
||||
#pragma unroll
|
||||
for (int k = 0; k < 128; k += 16)
|
||||
raw = r4d_fp8::mma(r4d_fp8::frag<128>(qa, 0, k, lane),
|
||||
r4d_fp8::frag<128>(wb, wave * 16, k, lane), raw);
|
||||
const float weight_scale = ws[(long)(n0 / 128) * m.sr + k0 / 128];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const int src = source[(lane >> 4) * 8 + j];
|
||||
const float scale = src >= 0 ? as[(long)src * m.asr + k0 / 128] * weight_scale : 0;
|
||||
acc[j] += raw[j] * scale;
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
for (int k = 0; k < 128; k += 16)
|
||||
raw = r4d_fp8::mma(r4d_fp8::frag<128>(qa, 0, k, lane),
|
||||
r4d_fp8::frag<128>(wb, wave * 16, k, lane), raw);
|
||||
const float weight_scale = ws[(long)(n0 / 128) * m.sr + k0 / 128];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const int r = first + (lane >> 4) * 8 + j, c = n0 + wave * 16 + (lane & 15);
|
||||
if (r < end) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]);
|
||||
const int src = source[(lane >> 4) * 8 + j];
|
||||
const float scale = src >= 0 ? as[(long)src * m.asr + k0 / 128] * weight_scale : 0;
|
||||
acc[j] += raw[j] * scale;
|
||||
}
|
||||
__syncthreads();
|
||||
first = end;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const int r = first + (lane >> 4) * 8 + j, c = n0 + wave * 16 + (lane & 15);
|
||||
if (r < end) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]);
|
||||
}
|
||||
}
|
||||
/* The grouped form expert-major: a block per (column span, expert) takes every row of its
|
||||
* expert in 16-row tiles, so an expert slice is read from memory once however its rows fall in
|
||||
* the sorted order (the row tiles above re-read it once per tile its run spans). Each element
|
||||
* keeps the sequence above: per 128 of K in order a fresh chain of eight WMMAs, folded as raw *
|
||||
* (activation scale * weight scale). A block walks ColTiles column tiles of 64, each over K in
|
||||
* stages of StageK, as one stage sequence with the next stage loaded into registers while the
|
||||
* the sorted order (16-row tiles of the sorted order read it once per tile its run spans). Each
|
||||
* element keeps the sequence above: per 128 of K in order a fresh chain of eight WMMAs, folded as
|
||||
* raw * (activation scale * weight scale). A block walks ColTiles column tiles of 64, each over K
|
||||
* in stages of StageK, as one stage sequence with the next stage loaded into registers while the
|
||||
* current one computes from LDS. Block row `experts` zeroes the dropped rows past
|
||||
* offsets[experts]. */
|
||||
typedef unsigned f8_u4 __attribute__((ext_vector_type(4)));
|
||||
@@ -237,15 +205,15 @@ __global__ __launch_bounds__(128) void fp8_f32scale_experts(const uint8_t* a, co
|
||||
}
|
||||
// Both forms below keep fp8_f32scale's arithmetic for every output: per 128-K block the same
|
||||
// eight-mma chain from zero over the same fragments (the bytes at k + 8*(lane/16) of the block's
|
||||
// row segment, which the old kernel copied through LDS unchanged), then acc += raw * (a_scale *
|
||||
// row segment, which the legacy form copies through LDS unchanged), then acc += raw * (a_scale *
|
||||
// w_scale) in ascending block order. A WMMA output depends only on its own A row, B column and
|
||||
// C, so which rows and columns share a tile does not change it.
|
||||
|
||||
// Decode: one wave C adjacent 16-column tiles, S waves of a block on S consecutive K blocks at
|
||||
// once, the fragments loaded straight from global memory; R row tiles share each weight fragment
|
||||
// and C column tiles each activation fragment. Each wave scales its own partial products (the
|
||||
// a_scale x w_scale product and the multiply are the old fold's own two roundings) into LDS; then
|
||||
// every wave folds a share of the outputs, adding the round's products in block order to the
|
||||
// a_scale x w_scale product and the multiply are the legacy fold's own two roundings) into LDS;
|
||||
// then every wave folds a share of the outputs, adding the round's products in block order to the
|
||||
// output's running sum, which lives in LDS between rounds. The block's activation scales are
|
||||
// staged in LDS when they fit (`stage`).
|
||||
template <int R, int C>
|
||||
@@ -338,7 +306,7 @@ __global__ void fp8_f32scale_decode(const uint8_t* a, const float* as, const uin
|
||||
}
|
||||
}
|
||||
|
||||
// Prefill: the old kernel's 64-column block and LDS layout over R row tiles, so a staged weight
|
||||
// Prefill: the legacy form's 64-column block and LDS layout over R row tiles, so a staged weight
|
||||
// block serves R*16 rows instead of 16, staged with 16-byte loads and the next K block loaded
|
||||
// into registers while the current one is multiplied.
|
||||
template <int R>
|
||||
@@ -413,54 +381,18 @@ __global__ void __launch_bounds__(128)
|
||||
}
|
||||
}
|
||||
|
||||
// The dense form. RADIANCE_FP8F32_FORM names "legacy", "rows1"/"rows2"/"rows4" (row tiles a
|
||||
// block) or "decode", optionally "decodeRxS" or "decodeRxSxC" (R row tiles, S waves a block, C
|
||||
// column tiles a wave); otherwise the rule at the end of dense_form. The forms are byte-identical;
|
||||
// the choice is speed only.
|
||||
// The dense form: a decode form (`decode`, C column tiles a wave, S waves a block) or the row
|
||||
// tiles (R of 16 rows a block), by the rule at the end of dense_form. The forms are
|
||||
// byte-identical; the choice is speed only.
|
||||
struct Form {
|
||||
int kind = 0, r = 0, s = 0, c = 1;
|
||||
}; // kind 0 legacy, 1 decode, 2 rows
|
||||
bool decode = false;
|
||||
int r = 1, s = 1, c = 1;
|
||||
};
|
||||
constexpr int kLdsCap = 64 * 1024;
|
||||
long decode_lds(int R, int S, int C, long KB, bool stage) {
|
||||
return ((long)S * R * C * 8 * 32 + (long)R * C * 8 * 32 + (stage ? (long)R * 16 * KB : 0)) * 4;
|
||||
}
|
||||
// Row tiles a decode block shares a weight fragment over (at most three: four need 192 registers
|
||||
// and spill), then waves a block: doubled while the grid stays under 1024 waves, the K blocks last
|
||||
// and the exchange fits the LDS.
|
||||
Form decode_plan(long N, long K, long T) {
|
||||
Form f;
|
||||
f.kind = 1;
|
||||
const long tiles = (T + 15) / 16, kb = K / 128;
|
||||
f.r = (int)(tiles >= 3 ? 3 : tiles);
|
||||
const long blocks = (N / 16) * ((tiles + f.r - 1) / f.r);
|
||||
f.s = 1;
|
||||
while (f.s < 32 && f.s * 2 <= kb && blocks * f.s < 1024 &&
|
||||
decode_lds(f.r, f.s * 2, 1, kb, false) <= kLdsCap)
|
||||
f.s *= 2;
|
||||
return f;
|
||||
}
|
||||
Form dense_form(long N, long K, long T) {
|
||||
if (const char* e = std::getenv("RADIANCE_FP8F32_FORM")) {
|
||||
if (!std::strcmp(e, "legacy")) return Form{};
|
||||
if (!std::strncmp(e, "rows", 4)) {
|
||||
Form f;
|
||||
f.kind = 2;
|
||||
f.r = e[4] == '1' ? 1 : e[4] == '2' ? 2 : 4;
|
||||
return f;
|
||||
}
|
||||
if (!std::strncmp(e, "decode", 6)) {
|
||||
Form f = decode_plan(N, K, T);
|
||||
int r = 0, s = 0, c = 1;
|
||||
const int n = std::sscanf(e + 6, "%dx%dx%d", &r, &s, &c);
|
||||
if (n >= 2 && r >= 1 && r <= 3 && s >= 1 && s <= 32 && (s & (s - 1)) == 0 &&
|
||||
(c == 1 || c == 2 || c == 4) && !(r == 3 && c == 4)) {
|
||||
f.r = r;
|
||||
f.s = s;
|
||||
f.c = c;
|
||||
}
|
||||
return f;
|
||||
}
|
||||
}
|
||||
// Measured on gfx1201 (r4d_selftest --perfq, cold) at GLM's six shapes: decode1x8 up to 16
|
||||
// rows; from 17 to 64 two column tiles a wave (decode1x8x2) lead by 5 to 15 %, except at N 512
|
||||
// (too few column tiles, 1x8 stays) and N 4096 over K 1536, where the 16-row tile wins; from 65
|
||||
@@ -472,14 +404,12 @@ Form dense_form(long N, long K, long T) {
|
||||
const bool rows =
|
||||
T > 128 || (T > 64 && K <= 2048) || (T > 16 && T <= 64 && K <= 1536 && N >= 4096);
|
||||
if (!rows) {
|
||||
f.kind = 1;
|
||||
f.r = 1;
|
||||
f.decode = true;
|
||||
f.c = T > 16 && T <= 64 && N > 512 ? 2 : 1;
|
||||
f.s = 8;
|
||||
while (f.s > 1 && f.s > kb) f.s /= 2;
|
||||
return f;
|
||||
}
|
||||
f.kind = 2;
|
||||
f.r = T > 64 && N >= 4096 ? 2 : 1;
|
||||
return f;
|
||||
}
|
||||
@@ -494,35 +424,28 @@ int dense_fast(RadStream stream, const RadTensor& x, const RadTensor& xs, const
|
||||
const RadTensor& ws, const RadTensor& y, const Meta& m, bool* done) {
|
||||
*done = false;
|
||||
const Form f = dense_form(m.N, m.K, m.T);
|
||||
if (!f.kind || m.wr % 16 || m.ar % 16 ||
|
||||
if (m.wr % 16 || m.ar % 16 ||
|
||||
(reinterpret_cast<uintptr_t>(x.data) | reinterpret_cast<uintptr_t>(w.data)) % 16)
|
||||
return RAD_OK;
|
||||
const uint8_t *xa = (const uint8_t*)x.data, *wa = (const uint8_t*)w.data;
|
||||
const float *xsa = (const float*)xs.data, *wsa = (const float*)ws.data;
|
||||
uint16_t* ya = (uint16_t*)y.data;
|
||||
if (f.kind == 1) {
|
||||
if (f.decode) {
|
||||
const long kb = m.K / 128;
|
||||
const int stage = decode_lds(f.r, f.s, f.c, kb, true) <= kLdsCap;
|
||||
const long lds = decode_lds(f.r, f.s, f.c, kb, stage);
|
||||
const int stage = decode_lds(1, f.s, f.c, kb, true) <= kLdsCap;
|
||||
const long lds = decode_lds(1, f.s, f.c, kb, stage);
|
||||
if (lds > kLdsCap || m.N % (16 * f.c)) return RAD_OK;
|
||||
*done = true;
|
||||
const dim3 grid(m.N / (16 * f.c), (unsigned)(((m.T + 15) / 16 + f.r - 1) / f.r)),
|
||||
block(32 * f.s);
|
||||
#define F32S_DECODE(R_, C_) \
|
||||
if (f.r == R_ && f.c == C_) \
|
||||
return R4D_EMIT(stream, (fp8_f32scale_decode<R_, C_>), grid, block, (uint32_t)lds, xa, \
|
||||
xsa, wa, wsa, ya, m, stage);
|
||||
F32S_DECODE(1, 1)
|
||||
F32S_DECODE(2, 1) F32S_DECODE(3, 1) F32S_DECODE(1, 2) F32S_DECODE(2, 2) F32S_DECODE(3, 2)
|
||||
F32S_DECODE(1, 4) F32S_DECODE(2, 4)
|
||||
#undef F32S_DECODE
|
||||
* done = false;
|
||||
return RAD_OK;
|
||||
const dim3 grid(m.N / (16 * f.c), (unsigned)((m.T + 15) / 16)), block(32 * f.s);
|
||||
if (f.c == 2)
|
||||
return R4D_EMIT(stream, (fp8_f32scale_decode<1, 2>), grid, block, (uint32_t)lds, xa,
|
||||
xsa, wa, wsa, ya, m, stage);
|
||||
return R4D_EMIT(stream, (fp8_f32scale_decode<1, 1>), grid, block, (uint32_t)lds, xa, xsa,
|
||||
wa, wsa, ya, m, stage);
|
||||
}
|
||||
*done = true;
|
||||
if (f.r == 1) return emit_rows<1>(stream, xa, xsa, wa, wsa, ya, m);
|
||||
if (f.r == 2) return emit_rows<2>(stream, xa, xsa, wa, wsa, ya, m);
|
||||
return emit_rows<4>(stream, xa, xsa, wa, wsa, ya, m);
|
||||
return emit_rows<1>(stream, xa, xsa, wa, wsa, ya, m);
|
||||
}
|
||||
int body(const RadArgs* a, RadStream stream, bool grouped) {
|
||||
if (!a || !a->t || a->n_t < (grouped ? 9 : 5)) return RAD_E_INVAL;
|
||||
@@ -539,7 +462,7 @@ int body(const RadArgs* a, RadStream stream, bool grouped) {
|
||||
y.shape[1] != N || x.stride[1] != 1 || xs.stride[1] != 1 || y.stride[1] != 1 ||
|
||||
y.shape[0] < 1 || y.shape[0] > INT_MAX)
|
||||
return RAD_E_SHAPE;
|
||||
const int rank = grouped ? 3 : 2;
|
||||
const uint32_t rank = grouped ? 3 : 2;
|
||||
if (w.rank != rank || ws.rank != rank || w.shape[rank - 2] != N || w.shape[rank - 1] != K ||
|
||||
ws.shape[rank - 2] != N / 128 || ws.shape[rank - 1] != K / 128 || w.stride[rank - 1] != 1 ||
|
||||
ws.stride[rank - 1] != 1)
|
||||
@@ -553,75 +476,46 @@ int body(const RadArgs* a, RadStream stream, bool grouped) {
|
||||
m.T = (int)y.shape[0];
|
||||
m.N = N;
|
||||
m.K = K;
|
||||
const void *w1 = nullptr, *s1 = nullptr;
|
||||
const int *sorted = nullptr, *offsets = nullptr;
|
||||
if (grouped) {
|
||||
m.experts = r4d_geti_or(a, "n_expert", 0);
|
||||
m.topk = r4d_geti_or(a, "top_k", 0);
|
||||
const char* order = r4d_gets(a, "a_order");
|
||||
m.sorted_a = order && !std::strcmp(order, "sorted");
|
||||
const auto &wo = a->t[6], &so = a->t[7], &st = a->t[4], &off = a->t[5];
|
||||
if (m.experts < 2 || m.topk < 1 || r4d_geti_or(a, "N_odd", N) != N ||
|
||||
r4d_geti_or(a, "K_odd", K) != K || wo.dtype != RAD_F8E4M3 || so.dtype != RAD_F32 ||
|
||||
wo.rank != 3 || so.rank != 3 || wo.shape[1] != N || wo.shape[2] != K ||
|
||||
so.shape[1] != N / 128 || so.shape[2] != K / 128 || wo.stride[1] != m.wr ||
|
||||
so.stride[1] != m.sr || wo.stride[2] != 1 || so.stride[2] != 1 || st.dtype != RAD_I32 ||
|
||||
off.dtype != RAD_I32 || st.rank != 1 || off.rank != 1 || st.stride[0] != 1 ||
|
||||
off.stride[0] != 1 || st.shape[0] < m.T || off.shape[0] < m.experts + 1 || !wo.data ||
|
||||
!so.data || !st.data || !off.data)
|
||||
return RAD_E_SHAPE;
|
||||
m.wstep[0] = w.stride[0];
|
||||
m.wstep[1] = wo.stride[0];
|
||||
m.sstep[0] = ws.stride[0] * 4;
|
||||
m.sstep[1] = so.stride[0] * 4;
|
||||
if (w.shape[0] < (m.experts + 1) / 2 || wo.shape[0] < m.experts / 2) return RAD_E_SHAPE;
|
||||
w1 = wo.data;
|
||||
s1 = so.data;
|
||||
sorted = (const int*)st.data;
|
||||
offsets = (const int*)off.data;
|
||||
} else {
|
||||
if (!grouped) {
|
||||
if (x.shape[0] != m.T) return RAD_E_SHAPE;
|
||||
m.wstep[0] = N * m.wr;
|
||||
m.sstep[0] = (N / 128) * m.sr * 4;
|
||||
bool done = false;
|
||||
const int rc = dense_fast(stream, x, xs, w, ws, y, m, &done);
|
||||
if (done || rc < 0) return rc;
|
||||
return R4D_EMIT(stream, fp8_f32scale, dim3(N / 64, (m.T + 15) / 16), dim3(128), 0,
|
||||
(const uint8_t*)x.data, (const float*)xs.data, (const uint8_t*)w.data,
|
||||
(const float*)ws.data, (uint16_t*)y.data, m);
|
||||
}
|
||||
m.tile = m.T < 32 ? 1 : m.T < 128 ? 4 : 16;
|
||||
if (grouped) {
|
||||
/* The expert-major form at every routed-row count unless the environment bounds or
|
||||
* refuses it (RADIANCE_FP8F32_DECODE_EXPERTS 0 or 1, ..._MAX_T). Measured at GLM's TP8
|
||||
* slices: a long K (gate_up's 4096) wants the 256 stage, 25 to 40 % ahead of 128, and
|
||||
* under 128 routed rows four tiles a block on top; at down's K of 256 every variant
|
||||
* reads within a few percent of the bandwidth, so it keeps 128 over four tiles. Stage
|
||||
* and tiles can be pinned, for the microbenchmark. */
|
||||
auto env_long = [](const char* name, long dflt) {
|
||||
const char* v = std::getenv(name);
|
||||
return v && *v ? std::strtol(v, nullptr, 10) : dflt;
|
||||
};
|
||||
const char* force = std::getenv("RADIANCE_FP8F32_DECODE_EXPERTS");
|
||||
const long max_t = env_long("RADIANCE_FP8F32_DECODE_EXPERTS_MAX_T", -1);
|
||||
if (force ? force[0] == '1' : max_t < 0 || m.T <= max_t) {
|
||||
const long stage = env_long("RADIANCE_FP8F32_EXPERTS_STAGE_K", K <= 256 ? 128 : 256);
|
||||
const long tiles =
|
||||
env_long("RADIANCE_FP8F32_EXPERTS_COLTILES", K <= 256 || m.T < 128 ? 4 : 1);
|
||||
m.experts = r4d_geti_or(a, "n_expert", 0);
|
||||
m.topk = r4d_geti_or(a, "top_k", 0);
|
||||
const char* order = r4d_gets(a, "a_order");
|
||||
m.sorted_a = order && !std::strcmp(order, "sorted");
|
||||
const auto &wo = a->t[6], &so = a->t[7], &st = a->t[4], &off = a->t[5];
|
||||
if (m.experts < 2 || m.topk < 1 || r4d_geti_or(a, "N_odd", N) != N ||
|
||||
r4d_geti_or(a, "K_odd", K) != K || wo.dtype != RAD_F8E4M3 || so.dtype != RAD_F32 ||
|
||||
wo.rank != 3 || so.rank != 3 || wo.shape[1] != N || wo.shape[2] != K ||
|
||||
so.shape[1] != N / 128 || so.shape[2] != K / 128 || wo.stride[1] != m.wr ||
|
||||
so.stride[1] != m.sr || wo.stride[2] != 1 || so.stride[2] != 1 || st.dtype != RAD_I32 ||
|
||||
off.dtype != RAD_I32 || st.rank != 1 || off.rank != 1 || st.stride[0] != 1 ||
|
||||
off.stride[0] != 1 || st.shape[0] < m.T || off.shape[0] < m.experts + 1 || !wo.data ||
|
||||
!so.data || !st.data || !off.data)
|
||||
return RAD_E_SHAPE;
|
||||
m.wstep[0] = w.stride[0];
|
||||
m.wstep[1] = wo.stride[0];
|
||||
m.sstep[0] = ws.stride[0] * 4;
|
||||
m.sstep[1] = so.stride[0] * 4;
|
||||
if (w.shape[0] < (m.experts + 1) / 2 || wo.shape[0] < m.experts / 2) return RAD_E_SHAPE;
|
||||
/* The expert-major form at every routed-row count. Measured at GLM's TP8 slices: a long K
|
||||
* (gate_up's 4096) wants the 256 stage, 25 to 40 % ahead of 128, and under 128 routed rows
|
||||
* four tiles a block on top; at down's K of 256 every variant reads within a few percent of
|
||||
* the bandwidth, so it keeps 128 over four tiles. */
|
||||
#define F8_EXPERTS(SK, C) \
|
||||
R4D_EMIT(stream, (fp8_f32scale_experts<SK, C>), \
|
||||
dim3((N + 64 * C - 1) / (64 * C), m.experts + 1), dim3(128), 0, \
|
||||
(const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, w1, s1, sorted, \
|
||||
offsets, (uint16_t*)y.data, m)
|
||||
if (stage == 256) return tiles == 4 ? F8_EXPERTS(256, 4) : F8_EXPERTS(256, 1);
|
||||
return tiles == 4 ? F8_EXPERTS(128, 4) : F8_EXPERTS(128, 1);
|
||||
(const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, wo.data, so.data, \
|
||||
(const int*)st.data, (const int*)off.data, (uint16_t*)y.data, m)
|
||||
if (K > 256) return m.T < 128 ? F8_EXPERTS(256, 4) : F8_EXPERTS(256, 1);
|
||||
return F8_EXPERTS(128, 4);
|
||||
#undef F8_EXPERTS
|
||||
}
|
||||
}
|
||||
if (grouped)
|
||||
return R4D_EMIT(stream, fp8_f32scale<true>, dim3(N / 64, (m.T + m.tile - 1) / m.tile),
|
||||
dim3(128), 0, (const uint8_t*)x.data, (const float*)xs.data, w.data,
|
||||
ws.data, w1, s1, sorted, offsets, (uint16_t*)y.data, m);
|
||||
return R4D_EMIT(stream, fp8_f32scale<false>, dim3(N / 64, (m.T + 15) / 16), dim3(128), 0,
|
||||
(const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, w1, s1, sorted,
|
||||
offsets, (uint16_t*)y.data, m);
|
||||
}
|
||||
int dense(const RadArgs* a, RadStream stream) { return body(a, stream, false); }
|
||||
int grouped(const RadArgs* a, RadStream stream) { return body(a, stream, true); }
|
||||
|
||||
+177
-13
@@ -116,6 +116,62 @@ __global__ __launch_bounds__(kT) void gate_add_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- table_add
|
||||
// y[r, l n + c] = x[r, c] + t[l, c], f32 sum rounded once: one workgroup a (row, table row).
|
||||
__global__ __launch_bounds__(kT) void table_add_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ t, uint16_t* __restrict__ y,
|
||||
int n, int L, int x_ld, int y_ld) {
|
||||
const int r = blockIdx.x / L, l = blockIdx.x % L;
|
||||
for (int i = threadIdx.x * 8; i < n; i += kT * 8) {
|
||||
float a[8], b[8];
|
||||
ld8(x + (size_t)r * x_ld + i, a);
|
||||
ld8(t + (size_t)l * n + i, b);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) a[j] += b[j];
|
||||
st8(y + (size_t)r * y_ld + (size_t)l * n + i, a);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- mix_rows
|
||||
// y[r, c] = sum_i w[i] x[r k + i, c], f32 in ascending i, rounded once: one workgroup a row.
|
||||
__global__ __launch_bounds__(kT) void mix_rows_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, uint16_t* __restrict__ y,
|
||||
int n, int k, int x_ld, int y_ld) {
|
||||
const int r = blockIdx.x;
|
||||
for (int i = threadIdx.x * 8; i < n; i += kT * 8) {
|
||||
float acc[8] = {0, 0, 0, 0, 0, 0, 0, 0}, v[8];
|
||||
for (int q = 0; q < k; ++q) {
|
||||
const float wq = bf2f(w[q]);
|
||||
ld8(x + (size_t)(r * k + q) * x_ld + i, v);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) acc[j] += wq * v[j];
|
||||
}
|
||||
st8(y + (size_t)r * y_ld + i, acc);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- chan_stats
|
||||
// The statistics are rounded on the host side of each thread (cheap: n reads), every step as
|
||||
// libref rounds it.
|
||||
__global__ __launch_bounds__(kT) void chan_stats_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ mean,
|
||||
const uint16_t* __restrict__ sv, uint16_t* __restrict__ y, int n, int x_ld, int y_ld,
|
||||
int var, float eps, int norm) {
|
||||
const int r = blockIdx.x;
|
||||
for (int i = threadIdx.x * 8; i < n; i += kT * 8) {
|
||||
float a[8], mu[8], sd[8];
|
||||
ld8(x + (size_t)r * x_ld + i, a);
|
||||
ld8(mean + i, mu);
|
||||
ld8(sv + i, sd);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const float s = var ? bfr(sqrtf(sd[j] + eps)) : sd[j];
|
||||
a[j] = norm ? bfr(bfr(a[j] - mu[j]) / s) : bfr(bfr(a[j] * s) + mu[j]);
|
||||
}
|
||||
st8(y + (size_t)r * y_ld + i, a);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- ln_mod_quant_fp8
|
||||
// gate_add, ln_mod and quant_act_fp8 in one pass over the row: the DiT block's norm in front of
|
||||
// every quantised linear, with the previous branch's gated residual folded in. Three passes over a
|
||||
@@ -207,7 +263,8 @@ __global__ __launch_bounds__(kT) void timestep_kernel(
|
||||
int round, int y_ld) {
|
||||
const int m = blockIdx.x;
|
||||
const float tv = t[m];
|
||||
const float tt = round ? scale * bfr(bfr(tv * scale) / scale) : scale * tv;
|
||||
const float tt = round == 3 ? bfr(scale * bfr(tv)) : round == 2 ? scale * bfr(tv)
|
||||
: round ? scale * bfr(bfr(tv * scale) / scale) : scale * tv;
|
||||
for (int i = threadIdx.x; i < h; i += kT) {
|
||||
const float f = expf(coef * (float)i / (float)h);
|
||||
const float arg = tt * f;
|
||||
@@ -339,6 +396,25 @@ __device__ __forceinline__ float ca_rd(const float*, float v) { return v; }
|
||||
__device__ __forceinline__ void ca_st(uint16_t* p, int64_t i, float v) { p[i] = f32_to_bf16(v); }
|
||||
__device__ __forceinline__ void ca_st(float* p, int64_t i, float v) { p[i] = v; }
|
||||
|
||||
// The element-wise form, any of x, the statistics (TW) and y in bf16 or f32: a latent kept in
|
||||
// f32, or rows whose pitch the 8-wide kernel cannot take (an encoder's mean channels beside its
|
||||
// log-variance). Each step rounds to y's dtype as the reference stores it; the explicit _rn
|
||||
// intrinsics keep the compiler from contracting x s + mean into one fused multiply-add.
|
||||
template <typename TX, typename TW, typename TY>
|
||||
__global__ __launch_bounds__(kT) void chan_stats_any_kernel(
|
||||
const TX* __restrict__ x, const TW* __restrict__ mean, const TW* __restrict__ sv,
|
||||
TY* __restrict__ y, int n, int x_ld, int y_ld, int var, float eps, int norm) {
|
||||
const int r = blockIdx.x;
|
||||
for (int i = threadIdx.x; i < n; i += kT) {
|
||||
const float mu = ca_rd(y, ca_ld(mean, (size_t)i)), v = ca_ld(sv, (size_t)i);
|
||||
const float sd = ca_rd(y, var ? __fsqrt_rn(__fadd_rn(v, eps)) : v);
|
||||
const float a = ca_ld(x, (size_t)r * x_ld + i);
|
||||
ca_st(y, (int64_t)r * y_ld + i,
|
||||
norm ? ca_rd(y, __fdiv_rn(ca_rd(y, __fsub_rn(a, mu)), sd))
|
||||
: ca_rd(y, __fadd_rn(ca_rd(y, __fmul_rn(a, sd)), mu)));
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
__global__ __launch_bounds__(kT) void chan_affine_kernel(
|
||||
const T* __restrict__ x, T* __restrict__ y, int64_t total, int n, int x_ld, int inv, int rnd,
|
||||
@@ -467,7 +543,7 @@ template <int TP, int TC, int KS, int UP>
|
||||
__global__ __launch_bounds__(256) void conv_igemm_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
|
||||
const uint16_t* __restrict__ bias, uint16_t* __restrict__ y, int Hv, int Wv, int cin, int Wo,
|
||||
int cout, int k, int stride, int up, int pt, int x_ld, int y_ld, int Mpx, int K) {
|
||||
int cout, int k, int stride, int up, int pt, int pl, int x_ld, int y_ld, int Mpx, int K) {
|
||||
constexpr int BP = 2 * TP * 16, BC = 4 * TC * 16;
|
||||
constexpr int CPR = CV_BK / 8;
|
||||
constexpr int AL = BP * CPR / 256, WL = BC * CPR / 256;
|
||||
@@ -512,7 +588,7 @@ __global__ __launch_bounds__(256) void conv_igemm_kernel(
|
||||
auto loadA = [&](int i) -> r4d_u32x4 {
|
||||
if (!a_ok[i] || a_t[i] >= kk2) return zero;
|
||||
const int kh = a_t[i] / kq, kw = a_t[i] - kh * kq;
|
||||
const int iy = a_oy[i] * stride + kh - pt, ix = a_ox[i] * stride + kw - pt;
|
||||
const int iy = a_oy[i] * stride + kh - pt, ix = a_ox[i] * stride + kw - pl;
|
||||
if (iy < 0 || iy >= Hv || ix < 0 || ix >= Wv) return zero;
|
||||
/* Both are non-negative here, so a halving is a shift. */
|
||||
const int sy = UP == 1 ? iy : UP == 2 ? (iy >> 1) : iy / up;
|
||||
@@ -600,7 +676,7 @@ __global__ __launch_bounds__(256) void conv_igemm_kernel(
|
||||
__global__ __launch_bounds__(kT) void conv_direct_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
|
||||
const uint16_t* __restrict__ bias, uint16_t* __restrict__ y, int Hv, int Wv, int cin, int Wo,
|
||||
int cout, int k, int stride, int up, int pt, int x_ld, int y_ld, int64_t total) {
|
||||
int cout, int k, int stride, int up, int pt, int pl, int x_ld, int y_ld, int64_t total) {
|
||||
const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x;
|
||||
if (t >= total) return;
|
||||
const int co = (int)(t % cout);
|
||||
@@ -612,7 +688,7 @@ __global__ __launch_bounds__(kT) void conv_direct_kernel(
|
||||
const int iy = oy * stride + kh - pt;
|
||||
if (iy < 0 || iy >= Hv) continue;
|
||||
for (int kw = 0; kw < k; ++kw) {
|
||||
const int ix = ox * stride + kw - pt;
|
||||
const int ix = ox * stride + kw - pl;
|
||||
if (ix < 0 || ix >= Wv) continue;
|
||||
const uint16_t* xp = x + (size_t)(iy / up) * x_ld + (size_t)(ix / up) * cin;
|
||||
const uint16_t* wp = w + (size_t)co * K + (size_t)(kh * k + kw) * cin;
|
||||
@@ -637,9 +713,10 @@ inline bool rows8(const RadTensor* t, long long n, long long* rows, long long* l
|
||||
}
|
||||
|
||||
// A dense [H, W * c] image operand.
|
||||
inline bool image_of(const RadTensor* t, long long c, long long* H, long long* W) {
|
||||
inline bool image_of(const RadTensor* t, long long c, long long* H, long long* W,
|
||||
bool pitched = false) {
|
||||
if (!t || t->rank != 2 || c <= 0 || t->shape[1] % c || t->stride[1] != 1 ||
|
||||
t->stride[0] != t->shape[1])
|
||||
(pitched ? t->stride[0] < t->shape[1] : t->stride[0] != t->shape[1]))
|
||||
return false;
|
||||
*H = t->shape[0];
|
||||
*W = t->shape[1] / c;
|
||||
@@ -752,6 +829,87 @@ extern "C" int r4d_rad_gate_add(const RadArgs* a, RadStream s) {
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_table_add(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *x = r4d_opt(a, 0), *t = r4d_opt(a, 1), *y = r4d_opt(a, 2);
|
||||
if (!x || !t || !y) return R4D_NO(RAD_E_INVAL);
|
||||
if (!is_bf16(x) || !is_bf16(t) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE);
|
||||
const long long n = r4d_geti_or(a, "n", 0), L = r4d_geti_or(a, "L", 0);
|
||||
long long rx = 0, xl = 0, ry = 0, yl = 0;
|
||||
if (L <= 0 || !rows8(x, n, &rx, &xl) || !rows8(y, n * L, &ry, &yl) || !r4d_contig(t) ||
|
||||
((uintptr_t)t->data & 15))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
if (ry <= 0 || rx < ry || r4d_numel(t) < L * n) return R4D_NO(RAD_E_SHAPE);
|
||||
hipLaunchKernelGGL(table_add_kernel, dim3((unsigned)(ry * L)), dim3(kT), 0, (hipStream_t)s,
|
||||
(const uint16_t*)x->data, (const uint16_t*)t->data, (uint16_t*)y->data,
|
||||
(int)n, (int)L, (int)xl, (int)yl);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_mix_rows(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *x = r4d_opt(a, 0), *w = r4d_opt(a, 1), *y = r4d_opt(a, 2);
|
||||
if (!x || !w || !y) return R4D_NO(RAD_E_INVAL);
|
||||
if (!is_bf16(x) || !is_bf16(w) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE);
|
||||
const long long n = r4d_geti_or(a, "n", 0), k = r4d_geti_or(a, "k", 0);
|
||||
long long rx = 0, xl = 0, ry = 0, yl = 0;
|
||||
if (k <= 0 || !rows8(x, n, &rx, &xl) || !rows8(y, n, &ry, &yl) || !r4d_contig(w))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
if (ry <= 0 || rx < ry * k || r4d_numel(w) < k) return R4D_NO(RAD_E_SHAPE);
|
||||
hipLaunchKernelGGL(mix_rows_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s,
|
||||
(const uint16_t*)x->data, (const uint16_t*)w->data, (uint16_t*)y->data,
|
||||
(int)n, (int)k, (int)xl, (int)yl);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
template <typename TX, typename TW, typename TY>
|
||||
static int chan_stats_any(const RadTensor* x, const RadTensor* mn, const RadTensor* sv,
|
||||
const RadTensor* y, long long rows, long long n, long long xl,
|
||||
long long yl, int var, float eps, int norm, RadStream s) {
|
||||
hipLaunchKernelGGL((chan_stats_any_kernel<TX, TW, TY>), dim3((unsigned)rows), dim3(kT), 0,
|
||||
(hipStream_t)s, (const TX*)x->data, (const TW*)mn->data,
|
||||
(const TW*)sv->data, (TY*)y->data, (int)n, (int)xl, (int)yl, var, eps,
|
||||
norm);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
/* Both rows: bf16 (chan_stats_bf16, eight channels a thread when every row and statistic is
|
||||
* 16-byte aligned, element-wise otherwise) and f32 (chan_stats_f32: x and y f32 over bf16 or f32
|
||||
* statistics, a latent kept in f32 before a bf16 network reads it). */
|
||||
extern "C" int r4d_rad_chan_stats(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *x = r4d_opt(a, 0), *mn = r4d_opt(a, 1), *sv = r4d_opt(a, 2), *y = r4d_opt(a, 3);
|
||||
if (!x || !mn || !sv || !y) return R4D_NO(RAD_E_INVAL);
|
||||
const long long n = r4d_geti_or(a, "n", 0);
|
||||
const char* mode = r4d_gets(a, "mode");
|
||||
const int norm = mode && !std::strcmp(mode, "norm");
|
||||
if (!mode || (!norm && std::strcmp(mode, "denorm"))) return R4D_NO(RAD_E_INVAL);
|
||||
auto bf_f32 = [](const RadTensor* t) { return is_bf16(t) || t->dtype == RAD_F32; };
|
||||
if (!bf_f32(x) || !bf_f32(y) || !bf_f32(mn) || mn->dtype != sv->dtype || x->dtype != y->dtype)
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
const int var = (int)r4d_geti_or(a, "var", 0);
|
||||
const float eps = (float)r4d_getf(a, "eps", 0.0);
|
||||
long long rx = 0, xl = 0, ry = 0, yl = 0;
|
||||
if (is_bf16(x) && is_bf16(mn) && rows8(x, n, &rx, &xl) && rows8(y, n, &ry, &yl) &&
|
||||
r4d_contig(mn) && r4d_contig(sv) && !((uintptr_t)mn->data & 15) &&
|
||||
!((uintptr_t)sv->data & 15)) {
|
||||
if (ry <= 0 || rx < ry || r4d_numel(mn) < n || r4d_numel(sv) < n)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
hipLaunchKernelGGL(chan_stats_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s,
|
||||
(const uint16_t*)x->data, (const uint16_t*)mn->data,
|
||||
(const uint16_t*)sv->data, (uint16_t*)y->data, (int)n, (int)xl, (int)yl,
|
||||
var, eps, norm);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
xl = r4d_rows_pitch(x, n, &rx);
|
||||
yl = r4d_rows_pitch(y, n, &ry);
|
||||
if (xl < 0 || yl < 0 || !r4d_contig(mn) || !r4d_contig(sv)) return R4D_NO(RAD_E_STRIDE);
|
||||
if (ry <= 0 || rx < ry || r4d_numel(mn) < n || r4d_numel(sv) < n) return R4D_NO(RAD_E_SHAPE);
|
||||
const bool f = x->dtype == RAD_F32, wf = mn->dtype == RAD_F32;
|
||||
#define R4D_CS(TX, TW) chan_stats_any<TX, TW, TX>(x, mn, sv, y, ry, n, xl, yl, var, eps, norm, s)
|
||||
if (f) return wf ? R4D_CS(float, float) : R4D_CS(float, uint16_t);
|
||||
return wf ? R4D_CS(uint16_t, float) : R4D_CS(uint16_t, uint16_t);
|
||||
#undef R4D_CS
|
||||
}
|
||||
|
||||
/* Both rows: a bf16 embedding (timestep_embed_bf16) or an f32 one (timestep_embed_f32, a timestep
|
||||
* MLP kept in f32). */
|
||||
extern "C" int r4d_rad_timestep_embed(const RadArgs* a, RadStream s) {
|
||||
@@ -957,13 +1115,19 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) {
|
||||
const long long up = r4d_geti_or(a, "up", 1);
|
||||
const char* pad = r4d_gets(a, "pad");
|
||||
const bool down = pad && !std::strcmp(pad, "down");
|
||||
if (pad && !down && std::strcmp(pad, "same")) return R4D_NO(RAD_E_INVAL);
|
||||
const bool causal = pad && !std::strcmp(pad, "causal");
|
||||
if (pad && !down && !causal && std::strcmp(pad, "same")) return R4D_NO(RAD_E_INVAL);
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || stride <= 0 || up <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
long long Hin = 0, Win = 0, Ho = 0, Wo = 0;
|
||||
if (!image_of(x, cin, &Hin, &Win) || !image_of(y, cout, &Ho, &Wo)) return R4D_NO(RAD_E_SHAPE);
|
||||
/* y may be a column slice of wider rows (a channel written into its own columns): both kernels
|
||||
* store at its row pitch. */
|
||||
if (!image_of(x, cin, &Hin, &Win) || !image_of(y, cout, &Ho, &Wo, true))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
const long long Hv = Hin * up, Wv = Win * up;
|
||||
const long long pt = down ? 0 : k / 2, pb = down ? 1 : k / 2;
|
||||
if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pt + pb - k) / stride + 1 != Wo)
|
||||
/* Rows padded above `pt` and below `pb`, columns `pl` left and `pr` right. */
|
||||
const long long pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2;
|
||||
const long long pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
|
||||
if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pl + pr - k) / stride + 1 != Wo)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
const long long K = k * k * cin;
|
||||
if (r4d_numel(w) < cout * K || r4d_numel(b) < cout) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -977,7 +1141,7 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) {
|
||||
(const uint16_t*)x->data, (const uint16_t*)w->data,
|
||||
(const uint16_t*)b->data, (uint16_t*)y->data, (int)Hv, (int)Wv,
|
||||
(int)cin, (int)Wo, (int)cout, (int)k, (int)stride, (int)up, (int)pt,
|
||||
(int)x->stride[0], (int)y->stride[0], (int64_t)total);
|
||||
(int)pl, (int)x->stride[0], (int)y->stride[0], (int64_t)total);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
// 128 pixels a block, and the widest channel tile (192, 128, then 64) that leaves under a third
|
||||
@@ -995,7 +1159,7 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) {
|
||||
(unsigned)((cout + 4 * TC * 16 - 1) / (4 * TC * 16))), \
|
||||
dim3(256), 0, st, (const uint16_t*)x->data, (const uint16_t*)w->data, \
|
||||
(const uint16_t*)b->data, (uint16_t*)y->data, (int)Hv, (int)Wv, (int)cin, \
|
||||
(int)Wo, (int)cout, (int)k, (int)stride, (int)up, (int)pt, \
|
||||
(int)Wo, (int)cout, (int)k, (int)stride, (int)up, (int)pt, (int)pl, \
|
||||
(int)x->stride[0], (int)y->stride[0], (int)Mpx, (int)K)
|
||||
/* The decoder's two kernel sizes at its two sampling rates, and the generic form for the rest. */
|
||||
#define R4D_CONV_K(TP, TC) \
|
||||
|
||||
+21
-79
@@ -5,9 +5,6 @@
|
||||
#include "r4d_moe_sort.h"
|
||||
#include <climits>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
__global__ void gemm_nt_f32_kernel(const uint16_t* x, const float* w, float* y, long xp, long wp,
|
||||
@@ -71,31 +68,6 @@ __global__ void __launch_bounds__(128)
|
||||
if (c0 + c < n) y[(long)(r0 + q) * yp + c0 + c] = sum[q][c];
|
||||
}
|
||||
|
||||
// The tile forms, by rows x columns per wave. RADIANCE_F32_GEMM_TILE names one ("8x4") or
|
||||
// "legacy"; unset or unknown picks by M. All forms are byte-identical, so the choice is speed only.
|
||||
struct F32Tile {
|
||||
int r, c;
|
||||
};
|
||||
constexpr F32Tile kF32Tiles[] = { { 1, 1 }, { 2, 1 }, { 4, 1 }, { 8, 1 }, { 4, 2 },
|
||||
{ 8, 2 }, { 4, 4 }, { 8, 4 }, { 16, 2 }, { 16, 4 } };
|
||||
F32Tile f32_tile(long rows, long n) {
|
||||
if (const char* e = std::getenv("RADIANCE_F32_GEMM_TILE")) {
|
||||
if (!std::strcmp(e, "legacy")) return { 0, 0 };
|
||||
int r = 0, c = 0;
|
||||
if (std::sscanf(e, "%dx%d", &r, &c) == 2)
|
||||
for (const F32Tile& t : kF32Tiles)
|
||||
if (t.r == r && t.c == c) return t;
|
||||
}
|
||||
// Measured on gfx1201 (r4d_selftest --perff32, cold) at N 4/32/36/288, K 4096. 16x4 gains
|
||||
// 3-5 % at N 288/32 above 64 rows but loses 16 % at N 36; 8x4 holds at every width. A
|
||||
// projection of a few columns has too few waves for wide tiles at any M.
|
||||
if (n <= 8) return { 4, 1 };
|
||||
if (rows <= 1) return { 0, 0 };
|
||||
if (rows <= 2) return { 2, 1 };
|
||||
if (rows < 16) return { 4, 1 };
|
||||
if (rows < 64) return { 4, 4 };
|
||||
return { 8, 4 };
|
||||
}
|
||||
template <int R, int C>
|
||||
int gemm_f32_tile(RadStream stream, const RadTensor& x, const RadTensor& w, const RadTensor& y,
|
||||
long n, long k) {
|
||||
@@ -117,52 +89,28 @@ int gemm_f32_body(const RadArgs* a, RadStream stream) {
|
||||
w.stride[1] != 1 || y.stride[1] != 1 || x.stride[0] < k || w.stride[0] < k ||
|
||||
y.stride[0] < n)
|
||||
return RAD_E_SHAPE;
|
||||
const F32Tile t = f32_tile(x.shape[0], n);
|
||||
#define R4D_F32_TILE(R, C) \
|
||||
if (t.r == R && t.c == C) return gemm_f32_tile<R, C>(stream, x, w, y, n, k);
|
||||
R4D_F32_TILE(1, 1)
|
||||
R4D_F32_TILE(2, 1) R4D_F32_TILE(4, 1) R4D_F32_TILE(8, 1) R4D_F32_TILE(4, 2) R4D_F32_TILE(8, 2)
|
||||
R4D_F32_TILE(4, 4) R4D_F32_TILE(8, 4) R4D_F32_TILE(16, 2) R4D_F32_TILE(16, 4)
|
||||
#undef R4D_F32_TILE
|
||||
return R4D_EMIT(stream, gemm_nt_f32_kernel, dim3((n + 3) / 4, x.shape[0]), dim3(128), 0,
|
||||
(const uint16_t*)x.data, (const float*)w.data, (float*)y.data,
|
||||
x.stride[0], w.stride[0], y.stride[0], (int)n, (int)k);
|
||||
/* The tile form, rows x columns per wave, by M; all forms are byte-identical, so the choice is
|
||||
* speed only. Measured on gfx1201 (r4d_selftest --perff32, cold) at N 4/32/36/288, K 4096.
|
||||
* 16x4 gains 3-5 % at N 288/32 above 64 rows but loses 16 % at N 36; 8x4 holds at every
|
||||
* width. A projection of a few columns has too few waves for wide tiles at any M. */
|
||||
const long rows = x.shape[0];
|
||||
if (n <= 8) return gemm_f32_tile<4, 1>(stream, x, w, y, n, k);
|
||||
if (rows <= 1)
|
||||
return R4D_EMIT(stream, gemm_nt_f32_kernel, dim3((n + 3) / 4, x.shape[0]), dim3(128), 0,
|
||||
(const uint16_t*)x.data, (const float*)w.data, (float*)y.data,
|
||||
x.stride[0], w.stride[0], y.stride[0], (int)n, (int)k);
|
||||
if (rows <= 2) return gemm_f32_tile<2, 1>(stream, x, w, y, n, k);
|
||||
if (rows < 16) return gemm_f32_tile<4, 1>(stream, x, w, y, n, k);
|
||||
if (rows < 64) return gemm_f32_tile<4, 4>(stream, x, w, y, n, k);
|
||||
return gemm_f32_tile<8, 4>(stream, x, w, y, n, k);
|
||||
}
|
||||
__global__ void router_sigmoid_kernel(const float* logits, const float* bias, int* ids,
|
||||
float* weights, long lp, long bp, long ip, long wp, int ne,
|
||||
int k, int norm, float factor) {
|
||||
__shared__ float probabilities[512], ranking[512];
|
||||
const int r = blockIdx.x;
|
||||
for (int e = threadIdx.x; e < ne; e += 256) {
|
||||
const float p = 1.0f / (1.0f + expf(-logits[(long)r * lp + e]));
|
||||
probabilities[e] = p;
|
||||
ranking[e] = p + bias[(long)e * bp];
|
||||
}
|
||||
__syncthreads();
|
||||
if (threadIdx.x) return;
|
||||
int index[32];
|
||||
float chosen[32], total = 0;
|
||||
for (int j = 0; j < k; ++j) {
|
||||
int best = 0;
|
||||
for (int e = 1; e < ne; ++e)
|
||||
if (ranking[e] > ranking[best]) best = e;
|
||||
index[j] = best;
|
||||
chosen[j] = probabilities[best];
|
||||
total += chosen[j];
|
||||
ranking[best] = -INFINITY;
|
||||
}
|
||||
const float mult = norm ? factor / (total + 1e-20f) : factor;
|
||||
for (int j = 0; j < k; ++j) {
|
||||
ids[(long)r * ip + j] = index[j];
|
||||
weights[(long)r * wp + j] = chosen[j] * mult;
|
||||
}
|
||||
}
|
||||
// The scan above in one wave per row. Lane l holds experts l, l+32, ... as 64-bit keys: the
|
||||
// rank's order-preserving bits (-0 folded to +0) over ~e, so equal ranks order as the scan's strict
|
||||
// `>` does, to the lower expert. Round j takes the largest key below round j-1's winner and parks
|
||||
// it on lane j (top_k <= 32). Probabilities, `total` in round order, `mult` and the weights are
|
||||
// the scan's expressions, so a finite row gives the same bytes. A NaN rank is never selected here,
|
||||
// while the scan takes expert 0 first when its rank is NaN.
|
||||
// router_sigmoid_topk in one wave per row: p = sigmoid(logit), the top_k largest ranks p + bias
|
||||
// in descending order, equal ranks to the lower expert, as a serial scan with a strict `>` takes
|
||||
// them. Lane l holds experts l, l+32, ... as 64-bit keys: the rank's order-preserving bits (-0
|
||||
// folded to +0) over ~e, so equal ranks order to the lower expert. Round j takes the largest key
|
||||
// below round j-1's winner and parks it on lane j (top_k <= 32). `total` sums the selected p in
|
||||
// round order, mult = norm ? factor / (total + 1e-20) : factor, and a weight is p * mult. A NaN
|
||||
// rank is never selected.
|
||||
// OWN is a template bound because the keys are registers; a lane-derived trip count would index
|
||||
// them divergently, which gfx12 lowers to a v_movrels loop.
|
||||
__device__ __forceinline__ unsigned long long router_rank_key(float rank, int e) {
|
||||
@@ -283,12 +231,6 @@ int router_body(const RadArgs* a, RadStream stream) {
|
||||
bias.stride[0] < 1)
|
||||
return RAD_E_SHAPE;
|
||||
const int norm = (int)(r4d_geti_or(a, "norm", 0) != 0);
|
||||
const char* select = std::getenv("RADIANCE_ROUTER_SELECT");
|
||||
if (select && !std::strcmp(select, "old"))
|
||||
return R4D_EMIT(stream, router_sigmoid_kernel, dim3(lg.shape[0]), dim3(256), 0,
|
||||
(const float*)lg.data, (const float*)bias.data, (int*)ids.data,
|
||||
(float*)w.data, lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0],
|
||||
(int)ne, (int)k, norm, factor);
|
||||
const dim3 grid((unsigned)((lg.shape[0] + 3) / 4));
|
||||
if (ne <= 9 * 32)
|
||||
return R4D_EMIT(stream, router_sigmoid_wave_kernel<9>, grid, dim3(128), 0,
|
||||
|
||||
+20
-169
@@ -1,6 +1,5 @@
|
||||
/* Exact recurrent baseline for GLM KDA, including speculative candidate snapshots.
|
||||
* One wave owns one, two or four value rows and keeps each row's 128-wide state in four
|
||||
* registers per lane.
|
||||
* One wave owns four value rows and keeps each row's 128-wide state in four registers per lane.
|
||||
* Prefill uses the same recurrence and commits only its final state. */
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "r4d_args.h"
|
||||
@@ -26,29 +25,16 @@ struct KdaJob : KdaMeta {
|
||||
const int *idx, *cu, *accepted, *init;
|
||||
};
|
||||
|
||||
__device__ float sum(float v) {
|
||||
for (int d = 16; d; d >>= 1) v += __shfl_down(v, d, 32);
|
||||
return __shfl(v, 0, 32);
|
||||
}
|
||||
/* r4d_wave_sum adds the same partners in the same order as sum() does for lane 0, and every
|
||||
* other lane forms the same additions with the operands swapped, so all lanes hold lane 0's bits
|
||||
* without the broadcast. */
|
||||
template <bool Dpp>
|
||||
__device__ __forceinline__ float wave_total(float v) {
|
||||
if constexpr (Dpp)
|
||||
return r4d_wave_sum(v);
|
||||
else
|
||||
return sum(v);
|
||||
}
|
||||
__device__ long factor_offset(long base, int logical, long pitch) {
|
||||
return base + (logical / 128) * pitch + (logical % 128);
|
||||
}
|
||||
/* Separate dispatch: all old factor reads finish before the next window overwrites them. */
|
||||
template <bool Dpp>
|
||||
__global__ void kda_replay_kernel(float* state, const int* idx, const int* cu, const int* accepted,
|
||||
const int* init, KdaMeta m) {
|
||||
const int lane = threadIdx.x & 31, e = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y,
|
||||
seq = blockIdx.z;
|
||||
/* A sequence without tokens this step leaves its slots as they are. */
|
||||
if (cu[(long)seq * m.cs0] == cu[(long)(seq + 1) * m.cs0]) return;
|
||||
const int anchor = idx[(long)seq * m.is0],
|
||||
scratch = idx[(long)seq * m.is0 + (m.width / 2) * m.is1];
|
||||
if (anchor < 0 || anchor >= m.slots || scratch < 0 || scratch >= m.slots || anchor == scratch)
|
||||
@@ -80,123 +66,17 @@ __global__ void kda_replay_kernel(float* state, const int* idx, const int* cu, c
|
||||
}
|
||||
const float delta =
|
||||
state[factor_offset(fb, f + 384, m.ss2)] *
|
||||
(state[factor_offset(fb, f + 128 + e, m.ss2)] - wave_total<Dpp>(prediction));
|
||||
(state[factor_offset(fb, f + 128 + e, m.ss2)] - r4d_wave_sum(prediction));
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) s[d] += delta * k[d];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = s[d];
|
||||
}
|
||||
__global__ void kda_update_kernel(const uint16_t* q, const uint16_t* k, const uint16_t* v,
|
||||
const uint16_t* g, const uint16_t* beta, const float* alog,
|
||||
const float* bias, float* state_ptr, uint16_t* out,
|
||||
const int* idx, const int* cu, const int* accepted_ptr,
|
||||
const int* init, KdaMeta meta) {
|
||||
KdaJob j{};
|
||||
static_cast<KdaMeta&>(j) = meta;
|
||||
j.input[0] = q;
|
||||
j.input[1] = k;
|
||||
j.input[2] = v;
|
||||
j.input[3] = g;
|
||||
j.input[4] = beta;
|
||||
j.alog = alog;
|
||||
j.bias = bias;
|
||||
j.state = state_ptr;
|
||||
j.out = out;
|
||||
j.idx = idx;
|
||||
j.cu = cu;
|
||||
j.accepted = accepted_ptr;
|
||||
j.init = init;
|
||||
const int lane = threadIdx.x & 31, e = blockIdx.x * 4 + (threadIdx.x >> 5);
|
||||
const int head = blockIdx.y, seq = blockIdx.z;
|
||||
const int begin = j.cu[(long)seq * j.cs0], end = j.cu[(long)(seq + 1) * j.cs0];
|
||||
const int accepted = j.accepted ? j.accepted[(long)seq * j.as0] : 1;
|
||||
if (begin < 0 || end < begin || end > j.tokens || accepted < 1 ||
|
||||
accepted > (j.anchor ? 32 : j.width) ||
|
||||
(j.verify && end - begin > (j.anchor ? 32 : j.width)))
|
||||
return;
|
||||
const int read = j.idx[(long)seq * j.is0 + (j.verify && !j.anchor ? accepted - 1 : 0) * j.is1];
|
||||
if (read >= j.slots) return;
|
||||
if (read < 0) {
|
||||
if (!lane)
|
||||
for (int t = begin; t < end; ++t) j.out[(long)t * j.os0 + (long)head * j.os1 + e] = 0;
|
||||
return;
|
||||
}
|
||||
const bool initialized = !j.init || j.init[(long)seq * j.hs0] != 0;
|
||||
const int scratch = j.anchor ? j.idx[(long)seq * j.is0 + (j.width / 2) * j.is1] : 0;
|
||||
if (j.anchor && (scratch < 0 || scratch >= j.slots || scratch == read)) return;
|
||||
const long fb = (long)scratch * j.ss0 + (long)head * j.ss1;
|
||||
const long initial = (long)read * j.ss0 + (long)head * j.ss1 + (long)e * j.ss2;
|
||||
float state[4];
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) state[d] = initialized ? j.state[initial + lane + 32 * d] : 0;
|
||||
const float gain = expf(j.alog[head]);
|
||||
for (int t = begin; t < end; ++t) {
|
||||
float q[4], k[4], decay[4], sq = 0, sk = 0;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
const int channel = lane + d * 32;
|
||||
q[d] = bf16_to_f32(j.input[0][(long)t * j.row[0] + (long)head * j.head[0] + channel]);
|
||||
k[d] = bf16_to_f32(j.input[1][(long)t * j.row[1] + (long)head * j.head[1] + channel]);
|
||||
sq += q[d] * q[d];
|
||||
sk += k[d] * k[d];
|
||||
const float raw =
|
||||
bf16_to_f32(j.input[3][(long)t * j.row[3] + (long)head * j.head[3] + channel]);
|
||||
decay[d] = expf(j.lower / (1.0f + expf(-gain * (raw + j.bias[head * 128 + channel]))));
|
||||
}
|
||||
const float qi = j.scale * rsqrtf(sum(sq) + j.eps), ki = rsqrtf(sum(sk) + j.eps);
|
||||
const float beta =
|
||||
1.0f /
|
||||
(1.0f + expf(-bf16_to_f32(j.input[4][(long)t * j.row[4] + (long)head * j.head[4]])));
|
||||
float predicted = 0;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
q[d] *= qi;
|
||||
k[d] *= ki;
|
||||
state[d] *= decay[d];
|
||||
predicted += state[d] * k[d];
|
||||
}
|
||||
predicted = sum(predicted);
|
||||
const float value =
|
||||
bf16_to_f32(j.input[2][(long)t * j.row[2] + (long)head * j.head[2] + e]);
|
||||
if (j.anchor && j.verify) {
|
||||
const int f = 1 + (t - begin) * 385;
|
||||
if (e == 0) {
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
const int c = lane + 32 * d;
|
||||
j.state[factor_offset(fb, f + c, j.ss2)] = k[d];
|
||||
j.state[factor_offset(fb, f + 256 + c, j.ss2)] = decay[d];
|
||||
}
|
||||
if (!lane) j.state[factor_offset(fb, f + 384, j.ss2)] = beta;
|
||||
}
|
||||
if (!lane) j.state[factor_offset(fb, f + 128 + e, j.ss2)] = value;
|
||||
}
|
||||
const float delta = beta * (value - predicted);
|
||||
float result = 0;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
state[d] += delta * k[d];
|
||||
result += state[d] * q[d];
|
||||
}
|
||||
result = sum(result);
|
||||
if (!lane) j.out[(long)t * j.os0 + (long)head * j.os1 + e] = f32_to_bf16(result);
|
||||
if ((!j.anchor && j.verify) || (!j.verify && t + 1 == end)) {
|
||||
const int write = j.idx[(long)seq * j.is0 + (j.verify ? t - begin : 0) * j.is1];
|
||||
if (write >= 0 && write < j.slots) {
|
||||
const long target = (long)write * j.ss0 + (long)head * j.ss1 + (long)e * j.ss2;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) j.state[target + lane + 32 * d] = state[d];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (j.anchor && e == 0 && !lane) j.state[fb] = j.verify ? (float)(end - begin) : 0.0f;
|
||||
}
|
||||
/* kda_update_kernel with R value rows a wave: the loads, norms and decay exponentials, which do
|
||||
* not depend on the state, are formed once for R rows, and the rows' reductions interleave. Each
|
||||
* row's arithmetic is kda_update_kernel's in its order, so the bytes match (selftest --perfkda).
|
||||
* With Prefetch the next token's operands are loaded while this one is reduced. */
|
||||
template <int R, bool Prefetch>
|
||||
/* R value rows a wave: the loads, norms and decay exponentials, which do not depend on the state,
|
||||
* are formed once for R rows, and the rows' reductions interleave. The next token's operands are
|
||||
* loaded while this one is reduced. */
|
||||
template <int R>
|
||||
__global__ void kda_rows_kernel(const uint16_t* q, const uint16_t* k, const uint16_t* v,
|
||||
const uint16_t* g, const uint16_t* beta, const float* alog,
|
||||
const float* bias, float* state_ptr, uint16_t* out, const int* idx,
|
||||
@@ -222,7 +102,7 @@ __global__ void kda_rows_kernel(const uint16_t* q, const uint16_t* k, const uint
|
||||
const int head = blockIdx.y, seq = blockIdx.z;
|
||||
const int begin = j.cu[(long)seq * j.cs0], end = j.cu[(long)(seq + 1) * j.cs0];
|
||||
const int accepted = j.accepted ? j.accepted[(long)seq * j.as0] : 1;
|
||||
if (begin < 0 || end < begin || end > j.tokens || accepted < 1 ||
|
||||
if (begin < 0 || end <= begin || end > j.tokens || accepted < 1 ||
|
||||
accepted > (j.anchor ? 32 : j.width) ||
|
||||
(j.verify && end - begin > (j.anchor ? 32 : j.width)))
|
||||
return;
|
||||
@@ -269,14 +149,11 @@ __global__ void kda_rows_kernel(const uint16_t* q, const uint16_t* k, const uint
|
||||
for (int r = 0; r < R; ++r) o.value[r] = ldg_u16(vb + (long)t * j.row[2] + r);
|
||||
};
|
||||
Token cur;
|
||||
if (Prefetch && begin < end) fetch(begin, cur);
|
||||
if (begin < end) fetch(begin, cur);
|
||||
for (int t = begin; t < end; ++t) {
|
||||
[[maybe_unused]] Token next;
|
||||
Token next;
|
||||
/* The last token loads itself again rather than a row past `end`. */
|
||||
if constexpr (Prefetch)
|
||||
fetch(t + 1 < end ? t + 1 : t, next);
|
||||
else
|
||||
fetch(t, cur);
|
||||
fetch(t + 1 < end ? t + 1 : t, next);
|
||||
float qv[4], kv[4], decay[4], sq = 0, sk = 0;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
@@ -355,7 +232,7 @@ __global__ void kda_rows_kernel(const uint16_t* q, const uint16_t* k, const uint
|
||||
j.state[target + r * j.ss2 + lane + 32 * d] = state[r][d];
|
||||
}
|
||||
}
|
||||
if constexpr (Prefetch) cur = next;
|
||||
cur = next;
|
||||
}
|
||||
if (j.anchor && e0 == 0 && !lane) j.state[fb] = j.verify ? (float)(end - begin) : 0.0f;
|
||||
}
|
||||
@@ -448,44 +325,18 @@ int body(const RadArgs* a, RadStream stream) {
|
||||
j.init = (const int*)init->data;
|
||||
j.hs0 = init->stride[0];
|
||||
}
|
||||
/* RADIANCE_KDA_FORM=old is the one-row kernel on shuffle sums, the reference the selftest
|
||||
* holds every form to byte for byte; RADIANCE_KDA_ROWS (1, 2 or 4 value rows a wave) and
|
||||
* RADIANCE_KDA_PREFETCH=0 pin the other form's variants for the microbenchmark. */
|
||||
const char* kform = std::getenv("RADIANCE_KDA_FORM");
|
||||
const bool old = kform && !std::strcmp(kform, "old");
|
||||
const unsigned seqs = (unsigned)(cu.shape[0] - 1);
|
||||
if (j.anchor && j.verify) {
|
||||
const int rc =
|
||||
old ? R4D_EMIT(stream, kda_replay_kernel<false>, dim3(32, (unsigned)H, seqs), dim3(128),
|
||||
0, j.state, j.idx, j.cu, j.accepted, j.init, static_cast<KdaMeta>(j))
|
||||
: R4D_EMIT(stream, kda_replay_kernel<true>, dim3(32, (unsigned)H, seqs), dim3(128),
|
||||
0, j.state, j.idx, j.cu, j.accepted, j.init, static_cast<KdaMeta>(j));
|
||||
R4D_EMIT(stream, kda_replay_kernel, dim3(32, (unsigned)H, seqs), dim3(128), 0, j.state,
|
||||
j.idx, j.cu, j.accepted, j.init, static_cast<KdaMeta>(j));
|
||||
if (rc != RAD_OK) return rc;
|
||||
}
|
||||
if (old)
|
||||
return R4D_EMIT(stream, kda_update_kernel, dim3(32, (unsigned)H, seqs), dim3(128), 0,
|
||||
j.input[0], j.input[1], j.input[2], j.input[3], j.input[4], j.alog, j.bias,
|
||||
j.state, j.out, j.idx, j.cu, j.accepted, j.init, static_cast<KdaMeta>(j));
|
||||
const char* rows_env = std::getenv("RADIANCE_KDA_ROWS");
|
||||
const long rows = rows_env && *rows_env ? std::strtol(rows_env, nullptr, 10) : 4;
|
||||
const char* prefetch_env = std::getenv("RADIANCE_KDA_PREFETCH");
|
||||
const bool prefetch = !prefetch_env || prefetch_env[0] != '0';
|
||||
#define KDA_ROWS(RR, PF) \
|
||||
return R4D_EMIT(stream, (kda_rows_kernel<RR, PF>), dim3(32 / RR, (unsigned)H, seqs), \
|
||||
dim3(128), 0, j.input[0], j.input[1], j.input[2], j.input[3], j.input[4], \
|
||||
j.alog, j.bias, j.state, j.out, j.idx, j.cu, j.accepted, j.init, \
|
||||
static_cast<KdaMeta>(j))
|
||||
if (rows == 1) {
|
||||
if (prefetch) KDA_ROWS(1, true);
|
||||
KDA_ROWS(1, false);
|
||||
}
|
||||
if (rows == 2) {
|
||||
if (prefetch) KDA_ROWS(2, true);
|
||||
KDA_ROWS(2, false);
|
||||
}
|
||||
if (prefetch) KDA_ROWS(4, true);
|
||||
KDA_ROWS(4, false);
|
||||
#undef KDA_ROWS
|
||||
constexpr int kRows = 4;
|
||||
return R4D_EMIT(stream, (kda_rows_kernel<kRows>), dim3(32 / kRows, (unsigned)H, seqs),
|
||||
dim3(128), 0, j.input[0], j.input[1], j.input[2], j.input[3], j.input[4],
|
||||
j.alog, j.bias, j.state, j.out, j.idx, j.cu, j.accepted, j.init,
|
||||
static_cast<KdaMeta>(j));
|
||||
}
|
||||
}
|
||||
extern "C" int r4d_rad_kda_update(const RadArgs* a, RadStream stream) { return body(a, stream); }
|
||||
+1091
File diff suppressed because it is too large.
Load diff
+31
-127
@@ -67,41 +67,8 @@ __global__ void mhc_partial_kernel(const uint16_t* h, const float* fn, Out out,
|
||||
}
|
||||
}
|
||||
|
||||
// Prefill reuses each F32 mixing weight across four BF16 token rows.
|
||||
// Each row keeps the same accumulation and reduction order as the scalar-row path.
|
||||
template <class Out>
|
||||
__global__ void mhc_partial_rows4_kernel(const uint16_t* h, const float* fn, Out out, int width,
|
||||
int mix, int chunk0, long hp, long fp, long rows) {
|
||||
__shared__ float sums[4][4];
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const int j = blockIdx.y, chunk = chunk0 + blockIdx.x;
|
||||
const long first = (long)blockIdx.z * 4;
|
||||
float sum[4] = { 0, 0, 0, 0 };
|
||||
for (int i = chunk * 2048 + tid; i < min(width, (chunk + 1) * 2048); i += 128) {
|
||||
const float weight = j == mix ? 0 : fn[(long)j * fp + i];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < 4; ++r)
|
||||
if (first + r < rows) {
|
||||
const float v = bf16_to_f32(h[(first + r) * hp + i]);
|
||||
sum[r] += v * (j == mix ? v : weight);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int r = 0; r < 4; ++r) {
|
||||
sum[r] = warp_sum(sum[r]);
|
||||
if (!lane) sums[r][wave] = sum[r];
|
||||
}
|
||||
__syncthreads();
|
||||
if (!tid)
|
||||
for (int r = 0; r < 4; ++r)
|
||||
if (first + r < rows) {
|
||||
*out.at(first + r, j, chunk) = sums[r][0] + sums[r][1] + sums[r][2] + sums[r][3];
|
||||
if (j == mix) out.pad(first + r, mix, chunk);
|
||||
}
|
||||
}
|
||||
|
||||
// Reuse each input across four coefficients and each weight across four rows.
|
||||
// All per-output K accumulation and reduction orders match the rows4 path.
|
||||
// Prefill reuses each input across four coefficients and each F32 mixing weight across four BF16
|
||||
// token rows. Every output keeps mhc_partial_kernel's accumulation and reduction order.
|
||||
template <class Out>
|
||||
__global__ void mhc_partial_rows4_coeff4_kernel(const uint16_t* h, const float* fn, Out out,
|
||||
int width, int mix, int chunk0, long hp, long fp,
|
||||
@@ -246,17 +213,18 @@ __global__ __launch_bounds__(128) void mhc_partial_vec_kernel(const uint16_t* h,
|
||||
}
|
||||
}
|
||||
|
||||
template <class In, bool VecX>
|
||||
// The geometries without the chunk split: one workgroup a row projects the residual itself from
|
||||
// `fn`, then mixes and collapses it.
|
||||
__global__ void mhc_pre_kernel(const uint16_t* h, const float* fn, const float* scale,
|
||||
const float* base, uint16_t* x, float* post, float* comb, int n,
|
||||
int hc, int iterations, float eps, float heps, long hp, long fp,
|
||||
long xp, long pp, long cp, int chunks, In in) {
|
||||
long xp, long pp, long cp) {
|
||||
__shared__ float sums[8], inverse, coefficients[80], pre[8], c[64];
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const long r = blockIdx.x;
|
||||
const int width = hc * n, mix = hc * (hc + 2);
|
||||
float ss = 0;
|
||||
for (int i = tid; !chunks && i < width; i += 256) {
|
||||
for (int i = tid; i < width; i += 256) {
|
||||
const float v = bf16_to_f32(h[r * hp + i]);
|
||||
ss += v * v;
|
||||
}
|
||||
@@ -265,20 +233,14 @@ __global__ void mhc_pre_kernel(const uint16_t* h, const float* fn, const float*
|
||||
__syncthreads();
|
||||
if (!tid) {
|
||||
float s = 0;
|
||||
if (chunks)
|
||||
for (int i = 0; i < chunks; ++i) s += *in.at(r, mix, i);
|
||||
else
|
||||
for (int i = 0; i < 8; ++i) s += sums[i];
|
||||
for (int i = 0; i < 8; ++i) s += sums[i];
|
||||
inverse = rsqrtf(s / (float)width + eps);
|
||||
}
|
||||
__syncthreads();
|
||||
for (int j = wave; j < mix; j += 8) {
|
||||
float dot = 0;
|
||||
if (chunks)
|
||||
for (int i = lane; i < chunks; i += 32) dot += *in.at(r, j, i);
|
||||
else
|
||||
for (int i = lane; i < width; i += 32)
|
||||
dot += bf16_to_f32(h[r * hp + i]) * fn[(long)j * fp + i];
|
||||
for (int i = lane; i < width; i += 32)
|
||||
dot += bf16_to_f32(h[r * hp + i]) * fn[(long)j * fp + i];
|
||||
dot = warp_sum(dot);
|
||||
if (!lane) coefficients[j] = dot * inverse;
|
||||
}
|
||||
@@ -319,7 +281,7 @@ __global__ void mhc_pre_kernel(const uint16_t* h, const float* fn, const float*
|
||||
for (int j = 0; j < hc * hc; ++j) comb[r * cp + j] = c[j];
|
||||
}
|
||||
__syncthreads();
|
||||
if (VecX && mix_rows_vec(h + r * hp, x + r * xp, pre, n, hc, tid, 256)) return;
|
||||
if (mix_rows_vec(h + r * hp, x + r * xp, pre, n, hc, tid, 256)) return;
|
||||
for (int i = tid; i < n; i += 256) {
|
||||
float v = 0;
|
||||
for (int j = 0; j < hc; ++j) v += pre[j] * bf16_to_f32(h[r * hp + j * n + i]);
|
||||
@@ -383,29 +345,8 @@ __device__ __forceinline__ float glm_warp_mix(int lane, long row, const float* s
|
||||
if (lane < 16) comb[row * cp + lane] = value;
|
||||
return pre;
|
||||
}
|
||||
template <class In>
|
||||
__global__ void mhc_pre_glm_warp_kernel(const uint16_t* h, const float* scale, const float* base,
|
||||
uint16_t* x, float* post, float* comb, int iterations,
|
||||
float eps, float heps, long hp, long xp, long pp, long cp,
|
||||
In in) {
|
||||
const int lane = threadIdx.x;
|
||||
const long row = blockIdx.x;
|
||||
const float pre =
|
||||
glm_warp_mix(lane, row, scale, base, post, comb, iterations, eps, heps, pp, cp, in);
|
||||
const float p0 = __shfl(pre, 0, 32), p1 = __shfl(pre, 1, 32), p2 = __shfl(pre, 2, 32),
|
||||
p3 = __shfl(pre, 3, 32);
|
||||
for (int i = lane; i < 4096; i += 32) {
|
||||
float v = 0;
|
||||
v += p0 * bf16_to_f32(h[row * hp + i]);
|
||||
v += p1 * bf16_to_f32(h[row * hp + 4096 + i]);
|
||||
v += p2 * bf16_to_f32(h[row * hp + 8192 + i]);
|
||||
v += p3 * bf16_to_f32(h[row * hp + 12288 + i]);
|
||||
x[row * xp + i] = f32_to_bf16(v);
|
||||
}
|
||||
}
|
||||
|
||||
// The warp kernel's mix on wave 0, then the collapsed read over the whole block: one wave writing
|
||||
// 4096 columns a row was most of a decode step's mhc_pre.
|
||||
// glm_warp_mix on wave 0, then the collapsed read over the whole block: one wave writing 4096
|
||||
// columns a row would be most of a decode step's mhc_pre.
|
||||
template <class In>
|
||||
__global__ __launch_bounds__(256) void mhc_pre_glm_wide_kernel(
|
||||
const uint16_t* h, const float* scale, const float* base, uint16_t* x, float* post, float* comb,
|
||||
@@ -516,23 +457,15 @@ constexpr int kChunkCols = 2048, kPartStride = 28;
|
||||
template <class Out>
|
||||
int emit_partials(RadStream stream, const RadTensor& h, const RadTensor& fn, Out out, int n, int hc,
|
||||
int chunk0, int count, long rows) {
|
||||
const char* rows4 = std::getenv("RADIANCE_MHC_PREFILL_ROWS4");
|
||||
const char* coeff4 = std::getenv("RADIANCE_MHC_PREFILL_COEFF4");
|
||||
/* From 2 rows the four-slot form (RADIANCE_MHC_PARTIAL_VEC 0 off, 1 at every row count;
|
||||
* RADIANCE_MHC_PARTIAL_ROWS 1, 2 or 4 pins its rows a wave), on 16-byte weight and 8-byte
|
||||
* residual rows; GLM's 2048-column chunks only. Measured cold on gfx1201 at GLM's shape:
|
||||
* one row a wave leads up to 16 rows (13 us against the old 20 to 36), two rows from 48
|
||||
* (20 against 22 us, at 128 rows 34 against 39, at 2048 391 against 500); four rows a wave
|
||||
* trail two at every count. */
|
||||
const char* vec = std::getenv("RADIANCE_MHC_PARTIAL_VEC");
|
||||
/* From 2 rows the four-slot form, on 16-byte weight and 8-byte residual rows; GLM's
|
||||
* 2048-column chunks only. Measured cold on gfx1201 at GLM's shape: one row a wave leads up
|
||||
* to 16 rows (13 us against 20 to 36 for the one-slot kernels), two rows from 48 (20 against
|
||||
* 22 us, at 128 rows 34 against 39, at 2048 391 against 500); four rows a wave trail two at
|
||||
* every count. */
|
||||
const bool vec_aligned = ((uintptr_t)fn.data & 15) == 0 && fn.stride[0] % 4 == 0 &&
|
||||
((uintptr_t)h.data & 7) == 0 && h.stride[0] % 4 == 0 &&
|
||||
hc * n % kChunkCols == 0;
|
||||
if (vec_aligned && (vec ? vec[0] == '1' : rows >= 2)) {
|
||||
const char* pin_rows = std::getenv("RADIANCE_MHC_PARTIAL_ROWS");
|
||||
const long R = pin_rows && *pin_rows ? std::strtol(pin_rows, nullptr, 10)
|
||||
: rows >= 32 ? 2
|
||||
: 1;
|
||||
if (vec_aligned && rows >= 2) {
|
||||
const int mix = hc * (hc + 2), groups = (mix + 4) / 4;
|
||||
#define MHC_VEC(RR) \
|
||||
do { \
|
||||
@@ -542,25 +475,18 @@ int emit_partials(RadStream stream, const RadTensor& h, const RadTensor& fn, Out
|
||||
(const float*)fn.data, out, mix, chunk0, count, (long)h.stride[0], \
|
||||
(long)fn.stride[0], rows, items); \
|
||||
} while (0)
|
||||
if (R == 4) MHC_VEC(4);
|
||||
if (R == 2) MHC_VEC(2);
|
||||
if (rows >= 32) MHC_VEC(2);
|
||||
MHC_VEC(1);
|
||||
#undef MHC_VEC
|
||||
}
|
||||
const char* rows4_min = std::getenv("RADIANCE_MHC_ROWS4_MIN");
|
||||
const bool use_rows4 =
|
||||
(!rows4 || rows4[0] == '1') &&
|
||||
rows >= (rows4_min && *rows4_min ? std::strtol(rows4_min, nullptr, 10) : 32);
|
||||
if (use_rows4 && (!coeff4 || coeff4[0] == '1'))
|
||||
/* Otherwise four rows and four coefficients a block from 32 rows, one row and one coefficient
|
||||
* below. */
|
||||
constexpr long kRows4Min = 32;
|
||||
if (rows >= kRows4Min)
|
||||
return R4D_EMIT(stream, (mhc_partial_rows4_coeff4_kernel<Out>),
|
||||
dim3(count, (hc * (hc + 2) + 4) / 4, (unsigned)((rows + 3) / 4)), dim3(128),
|
||||
0, (const uint16_t*)h.data, (const float*)fn.data, out, hc * n,
|
||||
hc * (hc + 2), chunk0, (long)h.stride[0], (long)fn.stride[0], rows);
|
||||
if (use_rows4)
|
||||
return R4D_EMIT(stream, (mhc_partial_rows4_kernel<Out>),
|
||||
dim3(count, hc * (hc + 2) + 1, (unsigned)((rows + 3) / 4)), dim3(128), 0,
|
||||
(const uint16_t*)h.data, (const float*)fn.data, out, hc * n, hc * (hc + 2),
|
||||
chunk0, (long)h.stride[0], (long)fn.stride[0], rows);
|
||||
return R4D_EMIT(stream, (mhc_partial_kernel<Out>),
|
||||
dim3(count, hc * (hc + 2) + 1, (unsigned)rows), dim3(128), 0,
|
||||
(const uint16_t*)h.data, (const float*)fn.data, out, hc * n, hc * (hc + 2),
|
||||
@@ -571,39 +497,19 @@ int emit_partials(RadStream stream, const RadTensor& h, const RadTensor& fn, Out
|
||||
template <class In>
|
||||
int emit_finish(RadStream stream, const RadTensor& h, const float* fn, long fp, const RadTensor& s,
|
||||
const RadTensor& b, const RadTensor& x, const RadTensor& p, const RadTensor& c,
|
||||
int n, int hc, int iters, float eps, float heps, long rows, int chunks, bool split,
|
||||
In in) {
|
||||
const char* warp = std::getenv("RADIANCE_MHC_PREFILL_WARP");
|
||||
int n, int hc, int iters, float eps, float heps, long rows, bool split, In in) {
|
||||
/* The warp mix at every row count: byte-identical to the scalar one and a quarter of its time
|
||||
* at one to six rows. RADIANCE_MHC_FINISH, for the microbenchmark: `old` the one-wave finish
|
||||
* from 32 rows and the scalar mix and read below, `scalar` that mix with the wide read. */
|
||||
const char* form = std::getenv("RADIANCE_MHC_FINISH");
|
||||
const bool old = form && !std::strcmp(form, "old");
|
||||
const bool warp_mix = split && (warp ? warp[0] == '1' : true) &&
|
||||
(old ? rows >= 32 : !(form && !std::strcmp(form, "scalar")));
|
||||
if (warp_mix && old)
|
||||
return R4D_EMIT(stream, (mhc_pre_glm_warp_kernel<In>), dim3((unsigned)rows), dim3(32), 0,
|
||||
(const uint16_t*)h.data, (const float*)s.data, (const float*)b.data,
|
||||
(uint16_t*)x.data, (float*)p.data, (float*)c.data, iters, eps, heps,
|
||||
(long)h.stride[0], (long)x.stride[0], (long)p.stride[0], (long)c.stride[0],
|
||||
in);
|
||||
if (warp_mix)
|
||||
* at one to six rows. */
|
||||
if (split)
|
||||
return R4D_EMIT(stream, (mhc_pre_glm_wide_kernel<In>), dim3((unsigned)rows), dim3(256), 0,
|
||||
(const uint16_t*)h.data, (const float*)s.data, (const float*)b.data,
|
||||
(uint16_t*)x.data, (float*)p.data, (float*)c.data, iters, eps, heps,
|
||||
(long)h.stride[0], (long)x.stride[0], (long)p.stride[0], (long)c.stride[0],
|
||||
in);
|
||||
if (old)
|
||||
return R4D_EMIT(stream, (mhc_pre_kernel<In, false>), dim3((unsigned)rows), dim3(256), 0,
|
||||
(const uint16_t*)h.data, fn, (const float*)s.data, (const float*)b.data,
|
||||
(uint16_t*)x.data, (float*)p.data, (float*)c.data, n, hc, iters, eps, heps,
|
||||
(long)h.stride[0], fp, (long)x.stride[0], (long)p.stride[0],
|
||||
(long)c.stride[0], split ? chunks : 0, in);
|
||||
return R4D_EMIT(stream, (mhc_pre_kernel<In, true>), dim3((unsigned)rows), dim3(256), 0,
|
||||
return R4D_EMIT(stream, mhc_pre_kernel, dim3((unsigned)rows), dim3(256), 0,
|
||||
(const uint16_t*)h.data, fn, (const float*)s.data, (const float*)b.data,
|
||||
(uint16_t*)x.data, (float*)p.data, (float*)c.data, n, hc, iters, eps, heps,
|
||||
(long)h.stride[0], fp, (long)x.stride[0], (long)p.stride[0], (long)c.stride[0],
|
||||
split ? chunks : 0, in);
|
||||
(long)h.stride[0], fp, (long)x.stride[0], (long)p.stride[0], (long)c.stride[0]);
|
||||
}
|
||||
bool coefficients(const RadArgs* a, long* iters, float* eps, float* heps) {
|
||||
*iters = r4d_geti_or(a, "iterations", 0);
|
||||
@@ -640,7 +546,7 @@ int pre_body(const RadArgs* a, RadStream stream) {
|
||||
if (rc < 0) return rc;
|
||||
}
|
||||
return emit_finish(stream, h, (const float*)fn.data, (long)fn.stride[0], s, b, x, p, c, n, hc,
|
||||
(int)iters, eps, heps, rows, chunks, split, in);
|
||||
(int)iters, eps, heps, rows, split, in);
|
||||
}
|
||||
int partial_body(const RadArgs* a, RadStream stream) {
|
||||
if (!a || a->n_t < 3) return RAD_E_INVAL;
|
||||
@@ -676,7 +582,7 @@ int finish_body(const RadArgs* a, RadStream stream) {
|
||||
return RAD_E_SHAPE;
|
||||
const Dense in{ (float*)part.data, (long)part.stride[0], kPartStride, 0 };
|
||||
return emit_finish(stream, h, nullptr, 0, s, b, x, p, c, n, hc, (int)iters, eps, heps, rows,
|
||||
chunks, true, in);
|
||||
true, in);
|
||||
}
|
||||
int post_body(const RadArgs* a, RadStream stream) {
|
||||
if (!a || a->n_t < 5) return RAD_E_INVAL;
|
||||
@@ -689,12 +595,10 @@ int post_body(const RadArgs* a, RadStream stream) {
|
||||
!matrix(p, RAD_F32, rows, hc) || !matrix(c, RAD_F32, rows, hc * hc) ||
|
||||
!matrix(o, RAD_BF16, rows, hc * n) || o.data == h.data)
|
||||
return RAD_E_SHAPE;
|
||||
/* RADIANCE_MHC_POST_VEC=0 keeps the per-output kernel, for the microbenchmark. */
|
||||
const char* vec = std::getenv("RADIANCE_MHC_POST_VEC");
|
||||
const auto aligned = [](const RadTensor& t) {
|
||||
return ((uintptr_t)t.data & 15) == 0 && t.stride[0] % 8 == 0;
|
||||
};
|
||||
if ((!vec || vec[0] == '1') && hc == 4 && n % 8 == 0 && aligned(x) && aligned(h) && aligned(o))
|
||||
if (hc == 4 && n % 8 == 0 && aligned(x) && aligned(h) && aligned(o))
|
||||
return R4D_EMIT(stream, mhc_post_vec_kernel, dim3((n / 8 + 255) / 256, (unsigned)rows),
|
||||
dim3(256), 0, (const uint16_t*)x.data, (const uint16_t*)h.data,
|
||||
(const float*)p.data, (const float*)c.data, (uint16_t*)o.data, n,
|
||||
|
||||
+10
-44
@@ -19,31 +19,11 @@ struct ProjectMeta {
|
||||
long xr, xh, wp, yr, yh;
|
||||
int rows, heads;
|
||||
};
|
||||
/* Absorption streams adjacent latent columns; expansion reduces a contiguous weight row. */
|
||||
__global__ void project_absorb(const uint16_t* x, const uint16_t* w, uint16_t* y, ProjectMeta m) {
|
||||
const int col = blockIdx.x * 128 + threadIdx.x, head = blockIdx.y, r = blockIdx.z;
|
||||
if (col >= 512) return;
|
||||
float sum = 0;
|
||||
for (int j = 0; j < 256; ++j)
|
||||
sum = fmaf(bf16_to_f32(x[(long)r * m.xr + head * m.xh + j]),
|
||||
bf16_to_f32(w[((long)head * 512 + j) * m.wp + col]), sum);
|
||||
y[(long)r * m.yr + head * m.yh + col] = f32_to_bf16(sum);
|
||||
}
|
||||
__global__ void project_expand(const uint16_t* x, const uint16_t* w, uint16_t* y, ProjectMeta m) {
|
||||
const int lane = threadIdx.x & 31, col = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y,
|
||||
r = blockIdx.z;
|
||||
float sum = 0;
|
||||
for (int j = lane; j < 512; j += 32)
|
||||
sum = fmaf(bf16_to_f32(x[(long)r * m.xr + head * m.xh + j]),
|
||||
bf16_to_f32(w[((long)head * 512 + 256 + col) * m.wp + j]), sum);
|
||||
#pragma unroll
|
||||
for (int mask = 16; mask; mask >>= 1) sum += __shfl_xor(sum, mask, 32);
|
||||
if (!lane) y[(long)r * m.yr + head * m.yh + col] = f32_to_bf16(sum);
|
||||
}
|
||||
/* project_absorb and project_expand with R rows a thread (absorb) or a wave (expand): each weight
|
||||
* element is loaded once for R rows. Every row's sum runs over j in the same order, and
|
||||
* r4d_xor_sum<32> exchanges as the shuffle loop does, so the bytes match the one-row kernels.
|
||||
* A tail group past the last row reads that row again and stores nothing for it. */
|
||||
/* Absorption streams adjacent latent columns; expansion reduces a contiguous weight row. R rows
|
||||
* a thread (absorb) or a wave (expand): each weight element is loaded once for R rows. Every row's
|
||||
* sum runs over j in the same order whatever R is (expand: each lane's share in ascending j, then
|
||||
* r4d_xor_sum<32>), so a row's bytes do not depend on the batch it is in. A tail group past the
|
||||
* last row reads that row again and stores nothing for it. */
|
||||
template <int R>
|
||||
__global__ void project_absorb_rows(const uint16_t* x, const uint16_t* w, uint16_t* y,
|
||||
ProjectMeta m) {
|
||||
@@ -122,24 +102,11 @@ int project_body(const RadArgs* a, RadStream stream) {
|
||||
return RAD_E_SHAPE;
|
||||
const ProjectMeta m{ x.stride[0], x.stride[1], w.stride[0], y.stride[0],
|
||||
y.stride[1], (int)x.shape[0], (int)h };
|
||||
/* RADIANCE_MLA_PROJECT: `old` the one-row kernels on shuffle sums, the reference the selftest
|
||||
* holds the row forms to byte for byte; 1, 2, 4 or 8 pins the rows a thread (absorb) or a
|
||||
* wave (expand). */
|
||||
const char* form = std::getenv("RADIANCE_MLA_PROJECT");
|
||||
const auto* xp = (const uint16_t*)x.data;
|
||||
const auto* wp = (const uint16_t*)w.data;
|
||||
auto* yp = (uint16_t*)y.data;
|
||||
if (form && !std::strcmp(form, "old")) {
|
||||
if (absorb)
|
||||
return R4D_EMIT(stream, project_absorb, dim3(4, h, m.rows), dim3(128), 0, xp, wp, yp,
|
||||
m);
|
||||
return R4D_EMIT(stream, project_expand, dim3(64, h, m.rows), dim3(128), 0, xp, wp, yp, m);
|
||||
}
|
||||
const long R = form && *form ? std::strtol(form, nullptr, 10)
|
||||
: m.rows >= 8 ? 8
|
||||
: m.rows >= 4 ? 4
|
||||
: m.rows >= 2 ? 2
|
||||
: 1;
|
||||
/* The largest of 8, 4, 2 and 1 rows a group that the batch fills. */
|
||||
const int R = m.rows >= 8 ? 8 : m.rows >= 4 ? 4 : m.rows >= 2 ? 2 : 1;
|
||||
#define MLA_PROJECT_ROWS(RR) \
|
||||
do { \
|
||||
const unsigned groups = (unsigned)((m.rows + RR - 1) / RR); \
|
||||
@@ -639,10 +606,9 @@ int body(const RadArgs* a, RadStream stream) {
|
||||
// Vectors need every cache row on a sixteen-byte boundary.
|
||||
const bool wide = g_mla_matrix_form != 1 && !((uintptr_t)kv.data & 15) && !(kv.stride[0] % 8) &&
|
||||
!(kv.stride[2] % 8);
|
||||
/* RADIANCE_MLA_PAIR=pos keeps the positional pairing, for comparison; the union's LDS lists
|
||||
* hold a table of at most kUnionBlocks entries. */
|
||||
const char* pairing = std::getenv("RADIANCE_MLA_PAIR");
|
||||
const bool by_page = !(pairing && !std::strcmp(pairing, "pos")) && bt.shape[1] <= kUnionBlocks;
|
||||
/* The union's LDS lists hold a table of at most kUnionBlocks entries; a wider table takes the
|
||||
* positional pairing. */
|
||||
const bool by_page = bt.shape[1] <= kUnionBlocks;
|
||||
const bool stats = MATRIX && env_on("RADIANCE_MLA_CONFLICT_STATS");
|
||||
Meta m{ q.stride[0], q.stride[1], kv.stride[0], kv.stride[2],
|
||||
bt.stride[0], bt.stride[1], len.stride[0], o.stride[0],
|
||||
|
||||
+28
-11
@@ -837,9 +837,11 @@ extern "C" int r4d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld
|
||||
// y[m, i] = v over an [M, n] extent with a row pitch, for a rank with nothing to compute whose
|
||||
// downstream reader (an all-reduce, a residual) still needs a defined buffer. A memset cannot
|
||||
// handle the pitch or a two-byte value.
|
||||
__global__ __launch_bounds__(kThreads) void fill_kernel(uint16_t* __restrict__ y, uint32_t n,
|
||||
uint32_t y_ld, uint16_t v) {
|
||||
uint16_t* __restrict__ yr = y + (size_t)blockIdx.x * y_ld;
|
||||
// T is the element's bits: uint16_t for bf16, uint32_t for f32.
|
||||
template<typename T>
|
||||
__global__ __launch_bounds__(kThreads) void fill_kernel(T* __restrict__ y, uint32_t n,
|
||||
uint32_t y_ld, T v) {
|
||||
T* __restrict__ yr = y + (size_t)blockIdx.x * y_ld;
|
||||
for (uint32_t i = threadIdx.x; i < n; i += kThreads) yr[i] = v;
|
||||
}
|
||||
|
||||
@@ -854,8 +856,20 @@ extern "C" int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long s
|
||||
if (!y) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (!y_ld) y_ld = n;
|
||||
hipLaunchKernelGGL(fill_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
|
||||
(uint16_t*)y, (uint32_t)n, (uint32_t)y_ld, f32_to_bf16_host(value));
|
||||
hipLaunchKernelGGL(fill_kernel<uint16_t>, dim3((uint32_t)M), dim3(kThreads), 0,
|
||||
(hipStream_t)stream, (uint16_t*)y, (uint32_t)n, (uint32_t)y_ld,
|
||||
f32_to_bf16_host(value));
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r4d_fill_f32(long y, int M, int n, int y_ld, float value, long stream) {
|
||||
if (!y) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (!y_ld) y_ld = n;
|
||||
uint32_t bits;
|
||||
std::memcpy(&bits, &value, sizeof bits);
|
||||
hipLaunchKernelGGL(fill_kernel<uint32_t>, dim3((uint32_t)M), dim3(kThreads), 0,
|
||||
(hipStream_t)stream, (uint32_t*)y, (uint32_t)n, (uint32_t)y_ld, bits);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
@@ -1306,8 +1320,10 @@ extern "C" int r4d_rad_cast(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* x = r4d_opt(a, CS_X);
|
||||
const RadTensor* y = r4d_opt(a, CS_Y);
|
||||
if (!x || !y) return R4D_NO(RAD_E_INVAL);
|
||||
R4D_NEED(dt_bf16(x));
|
||||
R4D_NEED(dt_bf16(y));
|
||||
/* A copy at the dtype both sides share: bf16, or f32 (a latent kept aside and put back). */
|
||||
if (x->dtype != y->dtype || (x->dtype != RAD_BF16 && x->dtype != RAD_F32))
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
const long long es = x->dtype == RAD_F32 ? 4 : 2;
|
||||
|
||||
const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1));
|
||||
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -1319,7 +1335,7 @@ extern "C" int r4d_rad_cast(const RadArgs* a, RadStream s) {
|
||||
* while the source holds the live rows, so the source need only have at least as many. */
|
||||
if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
return r4d_p2p_copy2d(r4d_addr(y), r4d_addr(x), y_ld * 2, x_ld * 2, n * 2, M,
|
||||
return r4d_p2p_copy2d(r4d_addr(y), r4d_addr(x), y_ld * es, x_ld * es, n * es, M,
|
||||
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
@@ -1566,7 +1582,7 @@ extern "C" int r4d_rad_sigmoid(const RadArgs* a, RadStream s) {
|
||||
extern "C" int r4d_rad_fill(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* y = r4d_opt(a, 0);
|
||||
if (!y) return R4D_NO(RAD_E_INVAL);
|
||||
R4D_NEED(dt_bf16(y));
|
||||
if (y->dtype != RAD_BF16 && y->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
|
||||
const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1));
|
||||
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
long long M = 0;
|
||||
@@ -1574,8 +1590,9 @@ extern "C" int r4d_rad_fill(const RadArgs* a, RadStream s) {
|
||||
if (y_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (M <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
const double v = r4d_getf(a, "value", 0.0);
|
||||
return r4d_fill_bf16(r4d_addr(y), (int)M, (int)n, (int)y_ld, (float)v,
|
||||
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
const int e = (y->dtype == RAD_F32 ? r4d_fill_f32 : r4d_fill_bf16)(
|
||||
r4d_addr(y), (int)M, (int)n, (int)y_ld, (float)v, (long)(uintptr_t)s);
|
||||
return e == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ logit_softcap */
|
||||
|
||||
+121
-308
@@ -10,14 +10,14 @@
|
||||
#include "r4d_mxfp4.h"
|
||||
#include <climits>
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
struct MxMeta {
|
||||
long wstep[2], sstep[2];
|
||||
int wrow[2], srow[2], n[2], k[2];
|
||||
long ar, asr, yr;
|
||||
int T, Arows, N, K, experts, topk, sorted_a, tile, parts, aligned_jobs;
|
||||
int T, Arows, N, K, experts, topk, sorted_a, parts;
|
||||
int stage_out, out16;
|
||||
};
|
||||
__device__ const uint8_t* entry(const void* base, long step, int e) {
|
||||
@@ -26,96 +26,43 @@ __device__ const uint8_t* entry(const void* base, long step, int e) {
|
||||
/* E2M1 values are exactly representable in E4M3. Stage those codes directly,
|
||||
* use FP8 WMMA, and fold each 32-wide E8M0 scale into the F32 accumulator.
|
||||
* No persistent expansion or checkpoint relayout is needed. */
|
||||
// Four independent bytes: magnitudes >=2 map to (m+12)*4; 0/1 map to 0/48.
|
||||
// Expand each magnitude-test bit into a byte mask without cross-byte carries.
|
||||
__device__ __forceinline__ uint32_t fp4x4(uint32_t n) {
|
||||
const uint32_t mag = n & 0x07070707u, flag = (mag + 0x06060606u) & 0x08080808u;
|
||||
const uint32_t mask = (flag << 5) - (flag >> 3);
|
||||
return ((((mag + 0x0c0c0c0cu) << 2) & mask) | (((mag & 0x01010101u) * 0x30u) & ~mask) |
|
||||
((n & 0x08080808u) << 4));
|
||||
}
|
||||
/* Eight codes of a packed word to their E4M3 bytes in k order. The table form (r4d_mxfp4.h, v_perm
|
||||
* on the magnitude) gives the same bytes in about a third of the instructions; the arithmetic form
|
||||
* stays reachable (RADIANCE_MXFP4_LUT=0) as the bytewise reference. */
|
||||
template <bool Lut>
|
||||
/* Eight codes of a packed word to their E4M3 bytes in k order, by table (r4d_mxfp4.h, v_perm on
|
||||
* the magnitude): the bytes of the bytewise arithmetic decode in about a third of the
|
||||
* instructions. */
|
||||
__device__ __forceinline__ uint2 mx_codes8(uint32_t packed) {
|
||||
if constexpr (Lut) {
|
||||
uint32_t lo, hi;
|
||||
r4d_mxfp4_unpack8_exact(packed, &lo, &hi);
|
||||
return uint2{ lo, hi };
|
||||
} else {
|
||||
const uint32_t low = fp4x4(packed & 0x0f0f0f0fu), high = fp4x4((packed >> 4) & 0x0f0f0f0fu);
|
||||
return uint2{ __byte_perm(low, high, 0x5140), __byte_perm(low, high, 0x7362) };
|
||||
}
|
||||
uint32_t lo, hi;
|
||||
r4d_mxfp4_unpack8_exact(packed, &lo, &hi);
|
||||
return uint2{ lo, hi };
|
||||
}
|
||||
template <int ColTiles, int RowTiles, bool CachedRows, bool Lut>
|
||||
/* The row-group form: a one-wave block per (16 columns, 16 sorted rows), the rows split at each
|
||||
* expert boundary. */
|
||||
__global__ void moe_mxfp4_fp8_kernel(const uint8_t* a, const float* as, const void* w0,
|
||||
const void* s0, const void* w1, const void* s1,
|
||||
const int* sorted, const int* offset, uint16_t* y, MxMeta m) {
|
||||
__shared__ __align__(16) uint8_t aa[16 * RowTiles * 136], bb[16 * ColTiles * 136];
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5,
|
||||
col0 = blockIdx.x * (16 * ColTiles);
|
||||
constexpr int JobRows = 16 * RowTiles, Threads = 32 * ColTiles * RowTiles;
|
||||
const int wave_col = ColTiles == 1 ? 0 : wave % ColTiles,
|
||||
wave_row = RowTiles == 1 ? 0 : wave / ColTiles;
|
||||
int first = blockIdx.y * m.tile;
|
||||
int group_end = min((int)(blockIdx.y + 1) * m.tile, m.T), job_expert = 0;
|
||||
if (m.aligned_jobs) {
|
||||
// Expert e begins at job floor(offset[e]/JobRows)+e. The extra job per expert
|
||||
// bounds padding without a prefix-sum pass; every live job owns one row tile
|
||||
// of one expert, so hot experts still spread across independent CTAs.
|
||||
const int job = blockIdx.y, tail = offset[m.experts] / JobRows + m.experts;
|
||||
if (job >= tail) {
|
||||
const int r0 = offset[m.experts] + (job - tail) * JobRows;
|
||||
for (int r = r0; r < min(r0 + JobRows, m.T); ++r)
|
||||
if (tid < 16 * ColTiles && col0 + tid < m.N) y[(long)r * m.yr + col0 + tid] = 0;
|
||||
return;
|
||||
__shared__ __align__(16) uint8_t aa[16 * 136], bb[16 * 136];
|
||||
const int tid = threadIdx.x, lane = tid & 31, col0 = blockIdx.x * 16;
|
||||
const int first = blockIdx.y * 16, group_end = min((int)(blockIdx.y + 1) * 16, m.T);
|
||||
for (int start = first; start < group_end;) {
|
||||
if (sorted[start] < 0 || offset[m.experts] <= start) {
|
||||
if (tid < 16 && col0 + tid < m.N) y[(long)start * m.yr + col0 + tid] = 0;
|
||||
++start;
|
||||
continue;
|
||||
}
|
||||
int lo = 0, hi = m.experts;
|
||||
while (lo + 1 < hi) {
|
||||
const int mid = (lo + hi) / 2;
|
||||
if (offset[mid] / JobRows + mid <= job)
|
||||
if (offset[mid] <= start)
|
||||
lo = mid;
|
||||
else
|
||||
hi = mid;
|
||||
}
|
||||
job_expert = lo;
|
||||
first = offset[lo] + (job - (offset[lo] / JobRows + lo)) * JobRows;
|
||||
group_end = min(first + JobRows, offset[lo + 1]);
|
||||
}
|
||||
for (int start = first; start < group_end;) {
|
||||
if (sorted[start] < 0 || offset[m.experts] <= start) {
|
||||
if (tid < 16 * ColTiles && col0 + tid < m.N) y[(long)start * m.yr + col0 + tid] = 0;
|
||||
++start;
|
||||
continue;
|
||||
}
|
||||
int lo = m.aligned_jobs ? job_expert : 0, hi = m.experts;
|
||||
if (!m.aligned_jobs)
|
||||
while (lo + 1 < hi) {
|
||||
const int mid = (lo + hi) / 2;
|
||||
if (offset[mid] <= start)
|
||||
lo = mid;
|
||||
else
|
||||
hi = mid;
|
||||
}
|
||||
const int cls = lo & 1, end = min(group_end, offset[lo + 1]);
|
||||
if (end <= start) return;
|
||||
const auto* w = entry(cls ? w1 : w0, m.wstep[cls], lo / 2);
|
||||
const auto* ws = entry(cls ? s1 : s0, m.sstep[cls], lo / 2);
|
||||
auto total = r4d_fp8::acc_zero();
|
||||
// Routing is invariant across K; each activation scale covers all four groups.
|
||||
int sources[8];
|
||||
if constexpr (CachedRows) {
|
||||
#pragma unroll
|
||||
for (int row = 0; row < 8; ++row) {
|
||||
const int r = start + wave_row * 16 + (lane >> 4) * 8 + row;
|
||||
const int flat = r < end ? sorted[r] : -1;
|
||||
const int ar = flat < 0 ? -1 : m.sorted_a ? r : flat / m.topk;
|
||||
sources[row] = ar >= 0 && ar < m.Arows ? ar : -1;
|
||||
}
|
||||
}
|
||||
for (int kb = 0; kb < m.k[cls]; kb += 128) {
|
||||
for (int j = tid; j < 16 * RowTiles * 16; j += Threads) {
|
||||
for (int j = tid; j < 16 * 16; j += 32) {
|
||||
const int r = j / 16, d = (j % 16) * 8;
|
||||
const int ar = start + r < end && sorted[start + r] >= 0
|
||||
? (m.sorted_a ? start + r : sorted[start + r] / m.topk)
|
||||
@@ -124,56 +71,40 @@ __global__ void moe_mxfp4_fp8_kernel(const uint8_t* a, const float* as, const vo
|
||||
if (ar >= 0 && ar < m.Arows) __builtin_memcpy(&av, a + (long)ar * m.ar + kb + d, 8);
|
||||
*reinterpret_cast<uint2*>(aa + r * 136 + d) = av;
|
||||
}
|
||||
for (int j = tid; j < 16 * ColTiles * 16; j += Threads) {
|
||||
for (int j = tid; j < 16 * 16; j += 32) {
|
||||
const int r = j / 16, d = (j % 16) * 8;
|
||||
const int n = col0 + r, part = n / (m.N / m.parts), within = n % (m.N / m.parts);
|
||||
const int wn = part * (m.n[cls] / m.parts) + within;
|
||||
uint32_t packed = 0;
|
||||
if (n < m.N && within < m.n[cls] / m.parts)
|
||||
__builtin_memcpy(&packed, w + (long)wn * m.wrow[cls] + (kb + d) / 2, 4);
|
||||
*reinterpret_cast<uint2*>(bb + r * 136 + d) = mx_codes8<Lut>(packed);
|
||||
*reinterpret_cast<uint2*>(bb + r * 136 + d) = mx_codes8(packed);
|
||||
}
|
||||
__syncthreads();
|
||||
if (start + wave_row * 16 < end) {
|
||||
const int n = col0 + wave_col * 16 + (lane & 15), part = n / (m.N / m.parts),
|
||||
within = n % (m.N / m.parts);
|
||||
const int wn = part * (m.n[cls] / m.parts) + within;
|
||||
const bool valid = n < m.N && within < m.n[cls] / m.parts;
|
||||
float activation[8];
|
||||
if constexpr (CachedRows) {
|
||||
const int n = col0 + (lane & 15), part = n / (m.N / m.parts),
|
||||
within = n % (m.N / m.parts);
|
||||
const int wn = part * (m.n[cls] / m.parts) + within;
|
||||
const bool valid = n < m.N && within < m.n[cls] / m.parts;
|
||||
#pragma unroll
|
||||
for (int row = 0; row < 8; ++row)
|
||||
activation[row] =
|
||||
sources[row] >= 0 ? as[(long)sources[row] * m.asr + kb / 128] : 0;
|
||||
}
|
||||
for (int group = 0; group < 4; ++group) {
|
||||
const int exp = valid ? ws[(long)wn * m.srow[cls] + kb / 32 + group] : 127;
|
||||
auto raw = r4d_fp8::acc_zero();
|
||||
#pragma unroll
|
||||
for (int group = 0; group < 4; ++group) {
|
||||
const int exp = valid ? ws[(long)wn * m.srow[cls] + kb / 32 + group] : 127;
|
||||
auto raw = r4d_fp8::acc_zero();
|
||||
for (int k = group * 32; k < (group + 1) * 32; k += 16)
|
||||
raw = r4d_fp8::mma(r4d_fp8::frag<128>(aa, 0, k, lane),
|
||||
r4d_fp8::frag<128>(bb, 0, k, lane), raw);
|
||||
// E8M0 maps directly to the F32 exponent field; code zero is 2^-127,
|
||||
// a representable subnormal, and code 255 is NaN.
|
||||
const float scale = __uint_as_float(exp == 255 ? 0x7fc00000u
|
||||
: exp ? ((uint32_t)exp << 23)
|
||||
: 0x00400000u);
|
||||
#pragma unroll
|
||||
for (int k = group * 32; k < (group + 1) * 32; k += 16)
|
||||
raw = r4d_fp8::mma(r4d_fp8::frag<128>(aa, wave_row * 16, k, lane),
|
||||
r4d_fp8::frag<128>(bb, wave_col * 16, k, lane), raw);
|
||||
// E8M0 maps directly to the F32 exponent field; code zero is 2^-127,
|
||||
// a representable subnormal, and code 255 is NaN.
|
||||
const float scale = __uint_as_float(exp == 255 ? 0x7fc00000u
|
||||
: exp ? ((uint32_t)exp << 23)
|
||||
: 0x00400000u);
|
||||
#pragma unroll
|
||||
for (int row = 0; row < 8; ++row) {
|
||||
if constexpr (CachedRows) {
|
||||
if (sources[row] >= 0) total[row] += raw[row] * activation[row] * scale;
|
||||
} else {
|
||||
const int r = start + wave_row * 16 + (lane >> 4) * 8 + row;
|
||||
if (r < end) {
|
||||
const int ar = sorted[r] < 0 ? -1
|
||||
: m.sorted_a ? r
|
||||
: sorted[r] / m.topk;
|
||||
if (ar >= 0 && ar < m.Arows)
|
||||
total[row] +=
|
||||
raw[row] * as[(long)ar * m.asr + kb / 128] * scale;
|
||||
}
|
||||
}
|
||||
for (int row = 0; row < 8; ++row) {
|
||||
const int r = start + (lane >> 4) * 8 + row;
|
||||
if (r < end) {
|
||||
const int ar = sorted[r] < 0 ? -1 : m.sorted_a ? r : sorted[r] / m.topk;
|
||||
if (ar >= 0 && ar < m.Arows)
|
||||
total[row] += raw[row] * as[(long)ar * m.asr + kb / 128] * scale;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -181,8 +112,7 @@ __global__ void moe_mxfp4_fp8_kernel(const uint8_t* a, const float* as, const vo
|
||||
}
|
||||
#pragma unroll
|
||||
for (int row = 0; row < 8; ++row) {
|
||||
const int r = start + wave_row * 16 + (lane >> 4) * 8 + row,
|
||||
n = col0 + wave_col * 16 + (lane & 15);
|
||||
const int r = start + (lane >> 4) * 8 + row, n = col0 + (lane & 15);
|
||||
if (r < end && n < m.N) y[(long)r * m.yr + n] = f32_to_bf16(total[row]);
|
||||
}
|
||||
start = end;
|
||||
@@ -201,18 +131,20 @@ __device__ __forceinline__ r4d_u32x4 mx_ldg16(const uint8_t* p) {
|
||||
__device__ __forceinline__ uint32_t mx_ldg4(const uint8_t* p) {
|
||||
return *(const __attribute__((address_space(1))) mx_g4*)p;
|
||||
}
|
||||
/* The TP8 prefill form (M32N64, aligned jobs, cached rows) with its loads a stage ahead. A job's
|
||||
* row table resolves into LDS once; the next 128 of K (activation bytes, weight codes, an exponent
|
||||
* dword a column, the activation scales) is loaded into registers while the current stage computes
|
||||
* from LDS. The form above waits on three dependent latencies a stage: the routing entry, the
|
||||
* activation row it names, and the exponent bytes it reads after the barrier. A job begins at its
|
||||
* first row even when that slot is dropped; rows are independent, so the bytes are the same.
|
||||
/* The GLM prefill form: jobs of 32 rows of one expert by 64 columns, eight waves, with its loads a
|
||||
* stage ahead. Expert e begins at job floor(offset[e]/32)+e: the extra job per expert bounds the
|
||||
* padding without a prefix-sum pass, and every live job owns one row tile of one expert, so hot
|
||||
* experts still spread across independent blocks. A job's row table resolves into LDS once; the
|
||||
* next 128 of K (activation bytes, weight codes, an exponent dword a column, the activation
|
||||
* scales) is loaded into registers while the current stage computes from LDS, where a form that
|
||||
* loads after the barrier waits on three dependent latencies a stage: the routing entry, the
|
||||
* activation row it names, and the exponent bytes. A job begins at its first row even when that
|
||||
* slot is dropped; rows are independent, so the bytes are the same.
|
||||
* The exponents are decoded once, at staging; the fold carries no row predicate, the epilogue
|
||||
* writes a dropped row's zero instead.
|
||||
* One stage ahead only: a deeper prefetch measured slower on the expert-major forms. The barriers
|
||||
* order LDS only (lds_barrier), so the prefetch stays in flight across them and L0 keeps the
|
||||
* activation rows the next column block reads. */
|
||||
template <bool Lut>
|
||||
__global__ __launch_bounds__(256)
|
||||
R4D_WAVES(16) void moe_mxfp4_prefill_kernel(const uint8_t* a, const float* as, const void* w0,
|
||||
const void* s0, const void* w1, const void* s1,
|
||||
@@ -285,7 +217,7 @@ __global__ __launch_bounds__(256)
|
||||
*reinterpret_cast<r4d_u32x4*>(aa + arow * P + ad) = ra;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 4; ++t)
|
||||
*reinterpret_cast<uint2*>(bb + wcol * P + 2 * wd + 8 * t) = mx_codes8<Lut>(rw[t]);
|
||||
*reinterpret_cast<uint2*>(bb + wcol * P + 2 * wd + 8 * t) = mx_codes8(rw[t]);
|
||||
if (tid < BN) {
|
||||
// E8M0 maps directly to the F32 exponent field; code zero is 2^-127, a representable
|
||||
// subnormal, and code 255 is NaN.
|
||||
@@ -351,13 +283,8 @@ __global__ __launch_bounds__(256)
|
||||
* fresh WMMA pair from zero, folded as (raw * activation scale) * E8M0 scale and added, two
|
||||
* roundings and an add (the unit is built -ffp-contract=off). The tiles of a wave are separate
|
||||
* accumulators, so no element sees another order. `stage_out` writes the output through LDS in
|
||||
* 16-byte rows instead of a lane's 2-byte column stores.
|
||||
*
|
||||
* DB (streamed A only): two LDS stages, one barrier a stage. The next stage is stored into the
|
||||
* other buffer after the current one computes, which every wave last read before the previous
|
||||
* barrier; the single-buffer order needs a second barrier before it may overwrite the stage it
|
||||
* computes from. Same bytes in LDS, same per-element sequence. */
|
||||
template <int BM, int BN, int StageK, int CT, bool Resident, bool DB = false>
|
||||
* 16-byte rows instead of a lane's 2-byte column stores. */
|
||||
template <int BM, int BN, int StageK, int CT, bool Resident>
|
||||
struct MxP64 {
|
||||
static constexpr int Threads = 256, WR = BM / 16, WC = 8 / WR, TC = BN / (16 * WC),
|
||||
KB = StageK / 128;
|
||||
@@ -366,28 +293,27 @@ struct MxP64 {
|
||||
static constexpr int TPA = Threads / BM, ACh = StageK / 16 / TPA, RCh = KR / 16 / TPA;
|
||||
static constexpr int TPW = Threads / BN, WCh = StageK / 32 / TPW,
|
||||
SAK = Resident ? KR / 128 : KB;
|
||||
static constexpr int NB = DB ? 2 : 1, BB = NB * BN * PB > BM *PO ? NB * BN * PB : BM * PO;
|
||||
static constexpr int Lds = NB * (BM * PA + 16 * KB * BN + 4 * SAK * BM) + BB + 4 * BM;
|
||||
static constexpr int BB = BN * PB > BM * PO ? BN * PB : BM * PO;
|
||||
static constexpr int Lds = BM * PA + 16 * KB * BN + 4 * SAK * BM + BB + 4 * BM;
|
||||
// The waves a SIMD the LDS admits (128 KiB a WGP, a block's eight waves over four SIMDs):
|
||||
// stating it keeps the compiler from trading the stage registers for waves it cannot get.
|
||||
static constexpr int Waves = 2 * (131072 / Lds > 8 ? 8 : 131072 / Lds);
|
||||
};
|
||||
template <int BM, int BN, int StageK, int CT, bool Resident, bool DB = false>
|
||||
template <int BM, int BN, int StageK, int CT, bool Resident>
|
||||
__global__ __launch_bounds__(256)
|
||||
R4D_WAVES((MxP64<BM, BN, StageK, CT, Resident, DB>::Waves)) void moe_mxfp4_p64_kernel(
|
||||
R4D_WAVES((MxP64<BM, BN, StageK, CT, Resident>::Waves)) void moe_mxfp4_p64_kernel(
|
||||
const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1,
|
||||
const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) {
|
||||
using G = MxP64<BM, BN, StageK, CT, Resident, DB>;
|
||||
using G = MxP64<BM, BN, StageK, CT, Resident>;
|
||||
constexpr int Threads = G::Threads, WC = G::WC, TC = G::TC, KB = G::KB, AK = G::AK, PA = G::PA,
|
||||
PB = G::PB;
|
||||
constexpr int PO = G::PO, TPA = G::TPA, TPW = G::TPW, SAK = G::SAK;
|
||||
static_assert(BM % 16 == 0 && 8 % G::WR == 0 && TC >= 1 && TC * 16 * WC == BN &&
|
||||
(Resident || CT == 1) && G::ACh >= 1 && G::WCh >= 1 && BN * KB <= Threads &&
|
||||
BM * SAK <= Threads && !(DB && Resident) && G::Lds <= 65536,
|
||||
BM * SAK <= Threads && G::Lds <= 65536,
|
||||
"stage chunks must divide evenly over the block, in 64 KiB of LDS");
|
||||
constexpr int NB = G::NB;
|
||||
__shared__ __align__(16) uint8_t aa[NB * BM * PA], bb[G::BB];
|
||||
__shared__ __align__(16) float ss[NB * 4 * KB * BN], sa[NB * SAK * BM];
|
||||
__shared__ __align__(16) uint8_t aa[BM * PA], bb[G::BB];
|
||||
__shared__ __align__(16) float ss[4 * KB * BN], sa[SAK * BM];
|
||||
__shared__ int src[BM];
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, wave_row = wave / WC,
|
||||
wave_col = wave % WC;
|
||||
@@ -479,20 +405,19 @@ __global__ __launch_bounds__(256)
|
||||
re = 0x7f7f7f7fu;
|
||||
if (evalid && k0 + ekb * 128 < kc) re = mx_ldg4(ep + (k0 + ekb * 128) / 32);
|
||||
};
|
||||
auto store = [&](int b) {
|
||||
auto store = [&]() {
|
||||
if constexpr (!Resident) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < G::ACh; ++i)
|
||||
*reinterpret_cast<r4d_u32x4*>(aa + b * BM * PA + arow * PA + (a0 + i * TPA) * 16) =
|
||||
ra[i];
|
||||
if (tid < BM * KB) sa[b * SAK * BM + tid] = rsa;
|
||||
*reinterpret_cast<r4d_u32x4*>(aa + arow * PA + (a0 + i * TPA) * 16) = ra[i];
|
||||
if (tid < BM * KB) sa[tid] = rsa;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < G::WCh; ++i) {
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 4; ++t)
|
||||
*reinterpret_cast<uint2*>(bb + b * BN * PB + wcol * PB + (w0c + i * TPW) * 32 +
|
||||
8 * t) = mx_codes8<true>(rw[i][t]);
|
||||
*reinterpret_cast<uint2*>(bb + wcol * PB + (w0c + i * TPW) * 32 + 8 * t) =
|
||||
mx_codes8(rw[i][t]);
|
||||
}
|
||||
if (tid < BN * KB) {
|
||||
// E8M0 maps directly to the F32 exponent field; code zero is 2^-127, a representable
|
||||
@@ -500,7 +425,7 @@ __global__ __launch_bounds__(256)
|
||||
#pragma unroll
|
||||
for (int g = 0; g < 4; ++g) {
|
||||
const uint32_t exp = (re >> (8 * g)) & 0xffu;
|
||||
ss[b * 4 * KB * BN + (ekb * 4 + g) * BN + ecol] =
|
||||
ss[(ekb * 4 + g) * BN + ecol] =
|
||||
__uint_as_float(exp == 255 ? 0x7fc00000u
|
||||
: exp ? (exp << 23)
|
||||
: 0x00400000u);
|
||||
@@ -510,32 +435,30 @@ __global__ __launch_bounds__(256)
|
||||
r4d_fp8::f8v total[TC];
|
||||
#pragma unroll
|
||||
for (int t = 0; t < TC; ++t) total[t] = r4d_fp8::acc_zero();
|
||||
auto compute = [&](int s, int b) {
|
||||
auto compute = [&](int s) {
|
||||
const int k0 = (s % ksn) * StageK;
|
||||
const uint8_t *ab = aa + b * BM * PA, *bp = bb + b * BN * PB;
|
||||
const float* sp = ss + b * 4 * KB * BN;
|
||||
#pragma unroll
|
||||
for (int kb = 0; kb < KB; ++kb) {
|
||||
if (k0 + kb * 128 >= kc) break;
|
||||
const float* sar = sa + b * SAK * BM + (Resident ? k0 / 128 + kb : kb) * BM + rowbase;
|
||||
const float* sar = sa + (Resident ? k0 / 128 + kb : kb) * BM + rowbase;
|
||||
float activation[8];
|
||||
#pragma unroll
|
||||
for (int row = 0; row < 8; ++row) activation[row] = sar[row];
|
||||
const int ka = (Resident ? k0 : 0) + kb * 128;
|
||||
#pragma unroll
|
||||
for (int group = 0; group < 4; ++group) {
|
||||
const auto fa0 = r4d_fp8::frag<AK>(ab, wave_row * 16, ka + group * 32, lane);
|
||||
const auto fa1 = r4d_fp8::frag<AK>(ab, wave_row * 16, ka + group * 32 + 16, lane);
|
||||
const auto fa0 = r4d_fp8::frag<AK>(aa, wave_row * 16, ka + group * 32, lane);
|
||||
const auto fa1 = r4d_fp8::frag<AK>(aa, wave_row * 16, ka + group * 32 + 16, lane);
|
||||
#pragma unroll
|
||||
for (int t = 0; t < TC; ++t) {
|
||||
auto raw = r4d_fp8::mma(
|
||||
fa0, r4d_fp8::frag<StageK>(bp, colw + t * 16, kb * 128 + group * 32, lane),
|
||||
fa0, r4d_fp8::frag<StageK>(bb, colw + t * 16, kb * 128 + group * 32, lane),
|
||||
r4d_fp8::acc_zero());
|
||||
raw = r4d_fp8::mma(
|
||||
fa1,
|
||||
r4d_fp8::frag<StageK>(bp, colw + t * 16, kb * 128 + group * 32 + 16, lane),
|
||||
r4d_fp8::frag<StageK>(bb, colw + t * 16, kb * 128 + group * 32 + 16, lane),
|
||||
raw);
|
||||
const float scale = sp[(kb * 4 + group) * BN + colw + t * 16 + (lane & 15)];
|
||||
const float scale = ss[(kb * 4 + group) * BN + colw + t * 16 + (lane & 15)];
|
||||
// A dropped row folds zeros (or NaN under a code-255 scale) and is written as 0.
|
||||
#pragma unroll
|
||||
for (int row = 0; row < 8; ++row)
|
||||
@@ -586,21 +509,11 @@ __global__ __launch_bounds__(256)
|
||||
}
|
||||
};
|
||||
load(0);
|
||||
if constexpr (DB) {
|
||||
store(0);
|
||||
lds_barrier();
|
||||
}
|
||||
for (int s = 0; s < S; ++s) {
|
||||
if constexpr (DB) {
|
||||
if (s + 1 < S) load(s + 1);
|
||||
if (live) compute(s, s & 1);
|
||||
if (s + 1 < S) store((s + 1) & 1);
|
||||
} else {
|
||||
store(0);
|
||||
lds_barrier();
|
||||
if (s + 1 < S) load(s + 1);
|
||||
if (live) compute(s, 0);
|
||||
}
|
||||
store();
|
||||
lds_barrier();
|
||||
if (s + 1 < S) load(s + 1);
|
||||
if (live) compute(s);
|
||||
lds_barrier();
|
||||
if (s % ksn == ksn - 1) {
|
||||
epilogue(colb + (s / ksn) * BN);
|
||||
@@ -620,7 +533,7 @@ __global__ __launch_bounds__(256)
|
||||
* A stage of StageK of K is loaded into registers while the previous one computes from LDS; at
|
||||
* gate_up's K of 4096 the 256 stage measured fastest. Block row `experts` zeroes the dropped rows
|
||||
* past offset[experts]. */
|
||||
template <int Waves, int StageK, bool Lut>
|
||||
template <int Waves, int StageK>
|
||||
__global__ __launch_bounds__(32 * Waves) void moe_mxfp4_expert_kernel(
|
||||
const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1,
|
||||
const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) {
|
||||
@@ -715,7 +628,7 @@ __global__ __launch_bounds__(32 * Waves) void moe_mxfp4_expert_kernel(
|
||||
const uint32_t q[4] = { rw[i].x, rw[i].y, rw[i].z, rw[i].w };
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 4; ++t)
|
||||
*reinterpret_cast<uint2*>(bb + c * P + 2 * d + 8 * t) = mx_codes8<Lut>(q[t]);
|
||||
*reinterpret_cast<uint2*>(bb + c * P + 2 * d + 8 * t) = mx_codes8(q[t]);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < SChunks; ++i) {
|
||||
@@ -777,7 +690,7 @@ struct MxStage {
|
||||
uint32_t s[SChunks];
|
||||
float sa;
|
||||
};
|
||||
template <int StageK, int ColTiles, bool Lut>
|
||||
template <int StageK, int ColTiles>
|
||||
__global__ __launch_bounds__(128) void moe_mxfp4_expert_staged_kernel(
|
||||
const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1,
|
||||
const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) {
|
||||
@@ -870,8 +783,7 @@ __global__ __launch_bounds__(128) void moe_mxfp4_expert_staged_kernel(
|
||||
d = (j % (StageK / 32)) * 16;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 4; ++t)
|
||||
*reinterpret_cast<uint2*>(bb + c * P + 2 * d + 8 * t) =
|
||||
mx_codes8<Lut>(R.w[i][t]);
|
||||
*reinterpret_cast<uint2*>(bb + c * P + 2 * d + 8 * t) = mx_codes8(R.w[i][t]);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < St::SChunks; ++i) {
|
||||
@@ -993,78 +905,24 @@ int body(const RadArgs* a, RadStream stream) {
|
||||
m.ar = aq->stride[0];
|
||||
m.asr = as->stride[0];
|
||||
m.yr = y->stride[0];
|
||||
m.tile = m.T < 32 ? 1 : m.T < 128 ? 4 : 16;
|
||||
// Validated GLM projections at TP4 and TP8: retain the small/decode path and other models.
|
||||
const bool glm_prefill = ne == 288 && top == 8 && nn[0] == nn[1] && kk[0] == kk[1] &&
|
||||
((parts == 2 && (nn[0] == 1024 || nn[0] == 512) && kk[0] == 4096) ||
|
||||
(parts == 1 && nn[0] == 4096 && (kk[0] == 512 || kk[0] == 256)));
|
||||
auto enabled = [&](const char* name) {
|
||||
const char* v = std::getenv(name);
|
||||
return v ? v[0] == '1' : glm_prefill;
|
||||
};
|
||||
/* The expert-major form up to a routed-row bound per projection (token rows: gate_up, sorted
|
||||
* rows: down), measured at GLM's TP8 slices: gate_up up to 768 rows, where the prefill form
|
||||
* overtakes it, down up to 6143 rows (at 8192 the pipelined prefill form reads the slice
|
||||
* 2.2 times less often and wins by a quarter). Other shapes keep the decode band. The environment
|
||||
* moves the bounds, forces either side (RADIANCE_MXFP4_DECODE_EXPERTS 0 or 1) and pins stage
|
||||
* and tiles, for the microbenchmark. */
|
||||
const char* lut_env = std::getenv("RADIANCE_MXFP4_LUT");
|
||||
const bool lut = lut_env ? lut_env[0] == '1' : true;
|
||||
auto env_long = [](const char* name, long dflt) {
|
||||
const char* v = std::getenv(name);
|
||||
return v && *v ? std::strtol(v, nullptr, 10) : dflt;
|
||||
};
|
||||
const long max_t =
|
||||
env_long(m.sorted_a ? "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_DOWN"
|
||||
: "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_GATE_UP",
|
||||
glm_prefill && (nn[0] == 512 || kk[0] == 256) ? (m.sorted_a ? 6143 : 768) : 511);
|
||||
const char* experts_env = std::getenv("RADIANCE_MXFP4_DECODE_EXPERTS");
|
||||
const bool tp8 = glm_prefill && (nn[0] == 512 || kk[0] == 256);
|
||||
/* The P64 form from a routed-row bound per projection, ahead of the expert-major band (its
|
||||
* down bound overlaps it): gate_up from 769 rows, where the prefill forms begin, down from
|
||||
* 20 rows an expert at GLM's 288. Default at GLM's TP8 slices only, the measured ones
|
||||
* (RADIANCE_MXFP4_PREFILL_P64=0 keeps the TP8 prefill form of stage 1, which also takes a grid
|
||||
* P64 cannot address). The
|
||||
* tile follows the rows an expert, measured at the TP8 slices (perfmx, cold): down BM32 BN64
|
||||
* K128 over four column tiles up to 3072 tokens (2048: 647 against 831 us), above BM64 BN128
|
||||
* K128 x4 with the LDS output (4096: 1101 against 1607); gate_up BM32 BN64 K256 up to 1536
|
||||
* tokens (768: 563 against 660), BM64 BN64 K256 up to 3072 (2048: 941 against 995), above
|
||||
* BM64 BN128 K128 with the LDS output (4096: 1715 against 1915). BM, BN, stage, column tiles,
|
||||
* the LDS output, the double buffer and the three row bounds move with the environment, and a
|
||||
* forced expert-major form (DECODE_EXPERTS=1) keeps precedence. */
|
||||
const char* p64_env = std::getenv("RADIANCE_MXFP4_PREFILL_P64");
|
||||
const bool resident = m.K <= 256;
|
||||
long dbm = 32, dbn = 64, dsk = 128, dout = 0;
|
||||
if (resident) {
|
||||
if (m.T >= env_long("RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", 24576)) {
|
||||
dbm = 64;
|
||||
dbn = 128;
|
||||
dout = 1;
|
||||
}
|
||||
} else if (m.T < env_long("RADIANCE_MXFP4_PREFILL_P64_T_BM64", 12288))
|
||||
dsk = 256;
|
||||
else if (m.T < env_long("RADIANCE_MXFP4_PREFILL_P64_T_BN128", 24576)) {
|
||||
dbm = 64;
|
||||
dsk = 256;
|
||||
} else {
|
||||
dbm = 64;
|
||||
dbn = 128;
|
||||
dout = 1;
|
||||
}
|
||||
const long bm = env_long("RADIANCE_MXFP4_PREFILL_P64_BM", dbm) == 32 ? 32 : 64;
|
||||
const bool tp8 = glm_prefill && (nn[0] == 512 || kk[0] == 256);
|
||||
if ((p64_env ? p64_env[0] == '1' : tp8) && !(experts_env && experts_env[0] == '1') &&
|
||||
m.T >= env_long(m.sorted_a ? "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN"
|
||||
: "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP",
|
||||
m.sorted_a ? 5760 : 769) &&
|
||||
(m.T + bm - 1) / bm + m.experts <= 65535) {
|
||||
const long bn = env_long("RADIANCE_MXFP4_PREFILL_P64_BN", dbn) == 64 ? 64 : 128;
|
||||
const long sk = env_long("RADIANCE_MXFP4_PREFILL_P64_STAGE_K", dsk) == 256 ? 256 : 128;
|
||||
const long ct = resident && env_long("RADIANCE_MXFP4_PREFILL_P64_COLTILES", 4) != 1 ? 4 : 1;
|
||||
m.stage_out = env_long("RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", dout) == 1;
|
||||
// The double buffer exists where two stages fit in 64 KiB of LDS: every 128 stage, and
|
||||
// the 256 stage at BM32 BN64.
|
||||
const bool db = !resident && env_long("RADIANCE_MXFP4_PREFILL_P64_DB", 0) == 1 &&
|
||||
(sk == 128 || (bm == 32 && bn == 64));
|
||||
* 20 rows an expert at GLM's 288. At GLM's TP8 slices only, the measured ones; a grid P64
|
||||
* cannot address takes the forms below. The tile follows the rows an expert, measured at the
|
||||
* TP8 slices (perfmx, cold): down BM32 BN64 K128 over four column tiles up to 3072 tokens
|
||||
* (2048: 647 against 831 us), above BM64 BN128 K128 x4 with the LDS output (4096: 1101
|
||||
* against 1607); gate_up BM32 BN64 K256 up to 1536 tokens (768: 563 against 660), BM64 BN64
|
||||
* K256 up to 3072 (2048: 941 against 995), above BM64 BN128 K128 with the LDS output (4096:
|
||||
* 1715 against 1915). */
|
||||
const bool resident = m.K <= 256, wide = m.T >= 24576;
|
||||
const long bm = wide || (!resident && m.T >= 12288) ? 64 : 32;
|
||||
if (tp8 && m.T >= (m.sorted_a ? 5760 : 769) && (m.T + bm - 1) / bm + m.experts <= 65535) {
|
||||
m.stage_out = wide;
|
||||
m.out16 = (reinterpret_cast<uintptr_t>(y->data) & 15) == 0 && m.yr % 8 == 0;
|
||||
const long jobs = (m.T + bm - 1) / bm + m.experts;
|
||||
#define MX_P64(BM, BN, SK, CT, R) \
|
||||
@@ -1072,85 +930,40 @@ int body(const RadArgs* a, RadStream stream) {
|
||||
dim3(((long)m.N + BN * CT - 1) / (BN * CT), jobs), dim3(256), 0, \
|
||||
(const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, w[1]->data, \
|
||||
s[1]->data, (const int*)sorted->data, (const int*)off->data, (uint16_t*)y->data, m)
|
||||
#define MX_P64D(BM, BN, SK) \
|
||||
R4D_EMIT(stream, (moe_mxfp4_p64_kernel<BM, BN, SK, 1, false, true>), \
|
||||
dim3(((long)m.N + BN - 1) / BN, jobs), dim3(256), 0, (const uint8_t*)aq->data, \
|
||||
(const float*)as->data, w[0]->data, s[0]->data, w[1]->data, s[1]->data, \
|
||||
(const int*)sorted->data, (const int*)off->data, (uint16_t*)y->data, m)
|
||||
if (db) {
|
||||
if (sk == 256) return MX_P64D(32, 64, 256);
|
||||
if (bm == 32) return bn == 64 ? MX_P64D(32, 64, 128) : MX_P64D(32, 128, 128);
|
||||
return bn == 64 ? MX_P64D(64, 64, 128) : MX_P64D(64, 128, 128);
|
||||
}
|
||||
#undef MX_P64D
|
||||
#define MX_P64_SK(BM, BN, CT, R) \
|
||||
return sk == 256 ? MX_P64(BM, BN, 256, CT, R) : MX_P64(BM, BN, 128, CT, R);
|
||||
#define MX_P64_BN(BM, CT, R) \
|
||||
if (bn == 64) { MX_P64_SK(BM, 64, CT, R) } \
|
||||
MX_P64_SK(BM, 128, CT, R)
|
||||
#define MX_P64_BM(CT, R) \
|
||||
if (bm == 32) { MX_P64_BN(32, CT, R) } \
|
||||
MX_P64_BN(64, CT, R)
|
||||
if (!resident) { MX_P64_BM(1, false) }
|
||||
if (ct == 1) { MX_P64_BM(1, true) }
|
||||
MX_P64_BM(4, true)
|
||||
#undef MX_P64_BM
|
||||
#undef MX_P64_BN
|
||||
#undef MX_P64_SK
|
||||
if (resident) return wide ? MX_P64(64, 128, 128, 4, true) : MX_P64(32, 64, 128, 4, true);
|
||||
if (wide) return MX_P64(64, 128, 128, 1, false);
|
||||
return bm == 64 ? MX_P64(64, 64, 256, 1, false) : MX_P64(32, 64, 256, 1, false);
|
||||
#undef MX_P64
|
||||
}
|
||||
if (experts_env ? experts_env[0] == '1' : max_t < 0 || m.T <= max_t) {
|
||||
const long stage = env_long("RADIANCE_MXFP4_EXPERTS_STAGE_K", m.K <= 256 ? 128 : 256);
|
||||
const long tiles = env_long("RADIANCE_MXFP4_EXPERTS_COLTILES", m.K <= 256 ? 4 : 1);
|
||||
/* The expert-major form up to a routed-row bound per projection (token rows: gate_up, sorted
|
||||
* rows: down), measured at GLM's TP8 slices: gate_up up to 768 rows, where the prefill form
|
||||
* overtakes it, down up to 6143 rows (at 8192 the pipelined prefill form reads the slice
|
||||
* 2.2 times less often and wins by a quarter). Other shapes keep the decode band. A K of 256
|
||||
* takes 128 stages over four column tiles, a longer K the 256 stage over one. */
|
||||
if (m.T <= (tp8 ? (m.sorted_a ? 6143 : 768) : 511)) {
|
||||
#define MX_EXPERTS(KERNEL, C) \
|
||||
R4D_EMIT(stream, KERNEL, dim3(((long)m.N + 64 * C - 1) / (64 * C), m.experts + 1), dim3(128), \
|
||||
0, (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, \
|
||||
w[1]->data, s[1]->data, (const int*)sorted->data, (const int*)off->data, \
|
||||
(uint16_t*)y->data, m)
|
||||
#define MX_EXPERTS_LUT(L) \
|
||||
if (stage == 128) \
|
||||
return tiles == 4 ? MX_EXPERTS((moe_mxfp4_expert_staged_kernel<128, 4, L>), 4) \
|
||||
: MX_EXPERTS((moe_mxfp4_expert_staged_kernel<128, 1, L>), 1); \
|
||||
return tiles == 4 ? MX_EXPERTS((moe_mxfp4_expert_staged_kernel<256, 4, L>), 4) \
|
||||
: MX_EXPERTS((moe_mxfp4_expert_kernel<4, 256, L>), 1);
|
||||
if (lut) { MX_EXPERTS_LUT(true) }
|
||||
MX_EXPERTS_LUT(false)
|
||||
#undef MX_EXPERTS_LUT
|
||||
if (m.K <= 256) return MX_EXPERTS((moe_mxfp4_expert_staged_kernel<128, 4>), 4);
|
||||
return MX_EXPERTS((moe_mxfp4_expert_kernel<4, 256>), 1);
|
||||
#undef MX_EXPERTS
|
||||
}
|
||||
m.aligned_jobs = enabled("RADIANCE_MXFP4_ALIGNED_JOBS") && m.T >= 512;
|
||||
const bool wide = enabled("RADIANCE_MXFP4_PREFILL_N32") && m.T >= 512;
|
||||
const bool tall = wide && m.aligned_jobs && enabled("RADIANCE_MXFP4_PREFILL_M32");
|
||||
const int job_rows = tall ? 32 : 16;
|
||||
const int jobs =
|
||||
m.aligned_jobs ? (m.T + job_rows - 1) / job_rows + m.experts : (m.T + m.tile - 1) / m.tile;
|
||||
/* From 512 routed rows (past the expert-major band) the GLM prefill form at GLM's slices, in
|
||||
* jobs of 32 rows of one expert; elsewhere the row groups, 16 sorted rows a block. */
|
||||
const bool pipe = glm_prefill && m.T >= 512;
|
||||
const int jobs = pipe ? (m.T + 31) / 32 + m.experts : (m.T + 15) / 16;
|
||||
if (jobs > 65535) return RAD_E_SHAPE;
|
||||
#define MX_EMIT(CT, RT, CACHE, L) \
|
||||
R4D_EMIT(stream, (moe_mxfp4_fp8_kernel<CT, RT, CACHE, L>), \
|
||||
dim3(((long)m.N + 16 * CT - 1) / (16 * CT), jobs), dim3(32 * CT * RT), 0, \
|
||||
(const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, w[1]->data, \
|
||||
s[1]->data, (const int*)sorted->data, (const int*)off->data, (uint16_t*)y->data, m)
|
||||
#define MX_PIPE(L) \
|
||||
R4D_EMIT(stream, (moe_mxfp4_prefill_kernel<L>), dim3(((long)m.N + 63) / 64, jobs), dim3(256), \
|
||||
0, (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, \
|
||||
w[1]->data, s[1]->data, (const int*)sorted->data, (const int*)off->data, \
|
||||
(uint16_t*)y->data, m)
|
||||
const char* cached = std::getenv("RADIANCE_MXFP4_PREFILL_CACHE_ROWS");
|
||||
const bool pipe = enabled("RADIANCE_MXFP4_PREFILL_PIPE");
|
||||
#define MX_EMIT_LUT(L) \
|
||||
if (tall && enabled("RADIANCE_MXFP4_PREFILL_N64")) { \
|
||||
if (cached ? cached[0] == '1' : glm_prefill) \
|
||||
return pipe ? MX_PIPE(L) : MX_EMIT(4, 2, true, L); \
|
||||
return MX_EMIT(4, 2, false, L); \
|
||||
} \
|
||||
if (tall) return MX_EMIT(2, 2, false, L); \
|
||||
if (wide) return MX_EMIT(2, 1, false, L); \
|
||||
return MX_EMIT(1, 1, false, L);
|
||||
if (lut) { MX_EMIT_LUT(true) }
|
||||
MX_EMIT_LUT(false)
|
||||
#undef MX_EMIT_LUT
|
||||
#undef MX_PIPE
|
||||
#undef MX_EMIT
|
||||
if (pipe)
|
||||
return R4D_EMIT(stream, moe_mxfp4_prefill_kernel, dim3(((long)m.N + 63) / 64, jobs),
|
||||
dim3(256), 0, (const uint8_t*)aq->data, (const float*)as->data,
|
||||
w[0]->data, s[0]->data, w[1]->data, s[1]->data, (const int*)sorted->data,
|
||||
(const int*)off->data, (uint16_t*)y->data, m);
|
||||
return R4D_EMIT(stream, moe_mxfp4_fp8_kernel, dim3(((long)m.N + 15) / 16, jobs), dim3(32), 0,
|
||||
(const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data,
|
||||
w[1]->data, s[1]->data, (const int*)sorted->data, (const int*)off->data,
|
||||
(uint16_t*)y->data, m);
|
||||
}
|
||||
}
|
||||
extern "C" int r4d_rad_moe_mxfp4(const RadArgs* a, RadStream stream) { return body(a, stream); }
|
||||
@@ -164,6 +164,10 @@ int r4d_rad_seg_sinusoid (const RadArgs*, RadStream);
|
||||
* (an image decoder's mid block). */
|
||||
int r4d_rad_attn_prefix_self (const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_dense_h128 (const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_cross (const RadArgs*, RadStream);
|
||||
int r4d_rad_table_add (const RadArgs*, RadStream);
|
||||
int r4d_rad_mix_rows (const RadArgs*, RadStream);
|
||||
int r4d_rad_chan_stats (const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_dense_wide (const RadArgs*, RadStream);
|
||||
/* The image generator's other ops (r4d_gen.hip). */
|
||||
int r4d_rad_ln_mod (const RadArgs*, RadStream);
|
||||
@@ -204,6 +208,7 @@ int r4d_rad_interleave2 (const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_dense_small_h256 (const RadArgs*, RadStream);
|
||||
int r4d_rad_iota (const RadArgs*, RadStream);
|
||||
int r4d_rad_cu_repeat (const RadArgs*, RadStream);
|
||||
int r4d_rad_int_affine (const RadArgs*, RadStream);
|
||||
/* r4d_video.hip */
|
||||
int r4d_rad_rms_mod (const RadArgs*, RadStream);
|
||||
int r4d_rad_rms_mod_quant_fp8 (const RadArgs*, RadStream);
|
||||
@@ -221,6 +226,21 @@ int r4d_rad_tconv_dw (const RadArgs*, RadStream);
|
||||
int r4d_rad_resize_bilinear (const RadArgs*, RadStream);
|
||||
int r4d_rad_patch_fold (const RadArgs*, RadStream);
|
||||
int r4d_rad_flow_renoise (const RadArgs*, RadStream);
|
||||
int r4d_rad_rope_split (const RadArgs*, RadStream);
|
||||
int r4d_rad_head_gate (const RadArgs*, RadStream);
|
||||
int r4d_rad_ltx_guide (const RadArgs*, RadStream);
|
||||
int r4d_rad_pixel_norm (const RadArgs*, RadStream);
|
||||
int r4d_rad_d2s3d (const RadArgs*, RadStream);
|
||||
int r4d_rad_s2d3d (const RadArgs*, RadStream);
|
||||
int r4d_rad_pix_patch (const RadArgs*, RadStream);
|
||||
int r4d_rad_patch_pix8 (const RadArgs*, RadStream);
|
||||
int r4d_rad_vol_index (const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_na3d (const RadArgs*, RadStream);
|
||||
int r4d_rad_tile_grid (const RadArgs*, RadStream);
|
||||
int r4d_rad_tile_crop (const RadArgs*, RadStream);
|
||||
int r4d_rad_tile_stitch (const RadArgs*, RadStream);
|
||||
int r4d_rad_stft_logmel (const RadArgs*, RadStream);
|
||||
int r4d_rad_bwe_up (const RadArgs*, RadStream);
|
||||
/* r4d_vsa.hip: video sparse attention's selection (scratch for the tile means) and attention. */
|
||||
int r4d_rad_vsa_select (const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_vsa_select_scratch (const RadArgs*);
|
||||
@@ -280,6 +300,24 @@ int64_t r4d_rad_attn_decode_h256_gqa6_scratch(const RadArgs*);
|
||||
* kernel; see attn_decode_gq_h256_gqa6_fp8kv. */
|
||||
int r4d_rad_attn_decode_gq_h256_gqa6_fp8(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_gq_h256_gqa6_bf16(const RadArgs*, RadStream);
|
||||
/* The fp8_v4 and k6_v4 caches on both: prefill, decode, and decode with the gate and quantiser in
|
||||
* the merge (R4D_ATTN_V4 in r4d_attn_paged_gqa8.hip). */
|
||||
int r4d_rad_attn_prefill_h256_gqa12_fp8v4(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_h256_gqa12_fp8v4(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_gq_h256_gqa12_fp8v4(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_attn_decode_h256_gqa12_fp8v4_scratch(const RadArgs*);
|
||||
int r4d_rad_attn_prefill_h256_gqa12_k6v4(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_h256_gqa12_k6v4(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_gq_h256_gqa12_k6v4(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_attn_decode_h256_gqa12_k6v4_scratch(const RadArgs*);
|
||||
int r4d_rad_attn_prefill_h256_gqa6_fp8v4(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_h256_gqa6_fp8v4(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_gq_h256_gqa6_fp8v4(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_attn_decode_h256_gqa6_fp8v4_scratch(const RadArgs*);
|
||||
int r4d_rad_attn_prefill_h256_gqa6_k6v4(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_h256_gqa6_k6v4(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_gq_h256_gqa6_k6v4(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_attn_decode_h256_gqa6_k6v4_scratch(const RadArgs*);
|
||||
|
||||
/* -- gated delta net (r4d_gdn_*.hip) -- */
|
||||
int r4d_rad_gdn_chunk_scan (const RadArgs*, RadStream);
|
||||
|
||||
+589
-22
@@ -188,6 +188,23 @@ static const RadOperandSpec oAttnDense[] = {
|
||||
{ "cu_seqlens", RAD_OPD_IN, 0 },
|
||||
{ "out", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pAttnCross[] = {
|
||||
P_INT("M"), P_INT("head_dim"), P_INT("gqa"), P_INT("causal"), P_STR("dtype"),
|
||||
P_F64O("scale"),
|
||||
};
|
||||
static const RadOperandSpec oAttnCross[] = {
|
||||
{ "q", RAD_OPD_IN, 0 },
|
||||
{ "k", RAD_OPD_IN, 0 },
|
||||
{ "v", RAD_OPD_IN, 0 },
|
||||
{ "cu_seqlens", RAD_OPD_IN, 0 },
|
||||
{ "cu_k", RAD_OPD_IN, 0 },
|
||||
{ "out", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pAttnNa3d[] = { P_INT("M"), P_INT("head_dim"), P_INT("kt"), P_INT("kh"),
|
||||
P_INT("kw"), P_STR("dtype"), P_F64O("scale") };
|
||||
static const RadOperandSpec oAttnNa3d[] = { { "q", RAD_OPD_IN, 0 }, { "k", RAD_OPD_IN, 0 },
|
||||
{ "v", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 },
|
||||
{ "out", RAD_OPD_OUT, 0 } };
|
||||
|
||||
/* Not docs/OPS.md's `qk_norm_rope` (qkv in place, `theta`): this kernel splits a packed [q|gate]
|
||||
* projection per head, writes q, k and the gate to three destinations, and takes a precomputed
|
||||
@@ -2257,6 +2274,20 @@ static const RadOperandSpec oLnModQ[] = {
|
||||
{ "scale", RAD_OPD_OUT, 0 }, { "z", RAD_OPD_OUT, 1 },
|
||||
};
|
||||
/* `act` is the gate's activation, "tanh" (the default) or "none". */
|
||||
static const RadParamSpec pTableAdd[] = { P_INT("M"), P_INT("n"), P_INT("L"), P_STR("dtype") };
|
||||
static const RadOperandSpec oTableAdd[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "t", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pMixRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_STR("dtype") };
|
||||
static const RadParamSpec pChanStats[] = { P_INT("M"), P_INT("n"), P_STR("mode"), P_INTO("var"),
|
||||
P_F64O("eps"), P_STR("dtype") };
|
||||
static const RadOperandSpec oChanStats[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "mean", RAD_OPD_WEIGHT, 0 }, { "s", RAD_OPD_WEIGHT, 0 },
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadOperandSpec oMixRows[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pGateAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_STRO("act") };
|
||||
static const RadOperandSpec oGateAdd[] = {
|
||||
{ "y", RAD_OPD_IN, 0 }, { "g", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 },
|
||||
@@ -2408,6 +2439,8 @@ static const RadParamSpec pIota[] = { P_INT("M"), P_INT("start"), P_INT("step"),
|
||||
static const RadOperandSpec oIota[] = { { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") };
|
||||
static const RadOperandSpec oCuRepeat[] = { { "len", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pIntAffine[] = { P_INT("M"), P_STR("src"), P_STR("mul"), P_STR("add") };
|
||||
static const RadOperandSpec oIntAffine[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pSnakeAa[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("k"),
|
||||
P_INTO("log"), P_STR("dtype") };
|
||||
static const RadOperandSpec oSnakeAa[] = {
|
||||
@@ -2419,17 +2452,19 @@ static const RadOperandSpec oSnakeAa[] = {
|
||||
/* ---- video generation (r4d_video.hip); the same specs as libref's (ref_registry.cpp). `geom` is
|
||||
* the request's latent geometry, i32 on the device. */
|
||||
static const RadParamSpec pRmsMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INTO("gated"),
|
||||
P_STR("dtype") };
|
||||
P_STR("dtype"), P_F64O("wadd"),
|
||||
P_INTO("norm_once"), P_STRO("norm") };
|
||||
static const RadOperandSpec oRmsMod[] = {
|
||||
{ "y", RAD_OPD_IN, 1 }, { "g", RAD_OPD_IN, 1 }, { "s", RAD_OPD_IN, 0 },
|
||||
{ "w", RAD_OPD_WEIGHT, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
{ "w", RAD_OPD_WEIGHT, 1 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
{ "z", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pRmsModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"),
|
||||
P_INT("gated"), P_STR("dtype") };
|
||||
P_INT("gated"), P_STR("dtype"), P_F64O("wadd"),
|
||||
P_INTO("norm_once"), P_STRO("norm") };
|
||||
static const RadOperandSpec oRmsModQ[] = {
|
||||
{ "y", RAD_OPD_IN, 1 }, { "g", RAD_OPD_IN, 1 }, { "s", RAD_OPD_IN, 0 },
|
||||
{ "w", RAD_OPD_WEIGHT, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
{ "w", RAD_OPD_WEIGHT, 1 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
{ "q", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 }, { "z", RAD_OPD_OUT, 1 },
|
||||
};
|
||||
static const RadOperandSpec oFlowX0[] = {
|
||||
@@ -2464,7 +2499,8 @@ static const RadOperandSpec oGridPos3[] = { { "y", RAD_OPD_OUT, 0 } };
|
||||
/* ---- a video latent upscaler (r4d_upscaler.hip); the same specs as libref's. `geom` is the
|
||||
* request's volume, i32 on the device; patch_fold takes patch_unfold's specs. */
|
||||
static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
|
||||
P_INT("kt"), P_STR("dtype") };
|
||||
P_INT("kt"), P_STR("dtype"), P_STRO("tpad"),
|
||||
P_INTO("tpre") };
|
||||
static const RadOperandSpec oConv3d[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 },
|
||||
{ "geom", RAD_OPD_IN, 0 }, { "res", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 },
|
||||
@@ -2489,6 +2525,64 @@ static const RadOperandSpec oFlowRenoise[] = {
|
||||
{ "sigma", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
};
|
||||
|
||||
/* ---- LTX-2 (r4d_ltx.hip); the same specs as libref's. */
|
||||
static const RadParamSpec pRopeSplit[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"),
|
||||
P_INT("dim"), P_INT("n_dims"), P_F64("theta"),
|
||||
P_STR("max"), P_INTO("head0"), P_STR("dtype") };
|
||||
static const RadOperandSpec oRopeSplit[] = {
|
||||
{ "x", RAD_OPD_INOUT, 0 }, { "positions", RAD_OPD_IN, 0 },
|
||||
};
|
||||
static const RadParamSpec pHeadGate[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oHeadGate[] = { { "g", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 } };
|
||||
static const RadParamSpec pLtxGuide[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
|
||||
static const RadOperandSpec oLtxGuide[] = {
|
||||
{ "vc", RAD_OPD_IN, 0 }, { "vu", RAD_OPD_IN, 1 }, { "vs", RAD_OPD_IN, 1 },
|
||||
{ "vm", RAD_OPD_IN, 1 }, { "scales", RAD_OPD_IN, 0 }, { "sched", RAD_OPD_IN, 0 },
|
||||
{ "stats", RAD_OPD_INOUT, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
};
|
||||
/* LTX-2's VAE, audio VAE and vocoder (r4d_ltx.hip); `geom` is x's volume, i32 on the device. */
|
||||
static const RadParamSpec pPixelNorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("form"),
|
||||
P_STRO("act"), P_INTO("ileave"), P_STR("dtype"),
|
||||
P_F64O("mult") };
|
||||
static const RadOperandSpec oPixelNorm[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pD2s3d[] = { P_INT("M"), P_INT("C"), P_INT("st"), P_INT("sh"),
|
||||
P_INT("sw"), P_INTO("drop"), P_STR("dtype") };
|
||||
static const RadOperandSpec oD2s3d[] = { { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 },
|
||||
{ "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pS2d3d[] = { P_INT("M"), P_INT("C"), P_INT("st"), P_INT("sh"),
|
||||
P_INT("sw"), P_INTO("tpre"), P_INTO("group"),
|
||||
P_STR("mode"), P_INTO("add"), P_STR("dtype") };
|
||||
static const RadOperandSpec oS2d3d[] = { { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 },
|
||||
{ "y", RAD_OPD_INOUT, 0 } };
|
||||
static const RadParamSpec pPixPatch[] = { P_INT("M"), P_INT("p"), P_INT("C"), P_STRO("order"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oPixPatch[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pVolIndex[] = { P_INT("M") };
|
||||
static const RadOperandSpec oVolIndex[] = { { "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pTileGrid[] = { P_INT("M"), P_INT("tile"), P_INT("stride"), P_STRO("rule"),
|
||||
P_INTO("min"), P_INTO("tile_t"), P_INTO("stride_t"),
|
||||
P_INTO("min_t"), P_INTO("tail") };
|
||||
static const RadOperandSpec oTileGrid[] = { { "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pTileCrop[] = { P_INT("M"), P_INT("C"), P_STR("dtype") };
|
||||
static const RadOperandSpec oTileCrop[] = { { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 },
|
||||
{ "box", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pTileStitch[] = { P_INT("M"), P_INT("tile"), P_INT("stride"),
|
||||
P_STRO("rule"), P_INTO("min"), P_INTO("tile_t"),
|
||||
P_INTO("stride_t"), P_INTO("min_t"), P_INT("scale"),
|
||||
P_INTO("scale_t"), P_INT("p"), P_INT("C"),
|
||||
P_STRO("order"), P_STR("dtype") };
|
||||
static const RadOperandSpec oTileStitch[] = { { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 },
|
||||
{ "first", RAD_OPD_IN, 0 },
|
||||
{ "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pStftMel[] = { P_INT("M"), P_INT("hop"), P_INT("nfft"), P_INT("n_mel"),
|
||||
P_INT("ch"), P_STR("dtype") };
|
||||
static const RadOperandSpec oStftMel[] = { { "x", RAD_OPD_IN, 0 }, { "basis", RAD_OPD_WEIGHT, 0 },
|
||||
{ "mel", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pBweUp[] = { P_INT("M"), P_INT("ratio"), P_INT("ch"), P_STR("dtype") };
|
||||
static const RadOperandSpec oBweUp[] = { { "x", RAD_OPD_IN, 0 }, { "res", RAD_OPD_IN, 0 },
|
||||
{ "y", RAD_OPD_OUT, 0 } };
|
||||
|
||||
/* ---- video sparse attention (r4d_vsa.hip); the same specs as libref's. `segs` cuts the packed
|
||||
* rows into dense segments and the video grid, `geom` is the request's latent geometry; `sel` is
|
||||
* vsa_select's output and attn_vsa's input. `v` of vsa_select is read only for `coarse`. */
|
||||
@@ -2761,6 +2855,12 @@ static const RadOpSchema kSchemas[] = {
|
||||
"dense attention over cu_seqlens segments (rows cu/cu_div), with attn_paged's window "
|
||||
"rule over a segment's positions and optional blocks of `block` rows that attend "
|
||||
"within themselves."),
|
||||
SCHEMA("attn_cross", pAttnCross, oAttnCross,
|
||||
"attn_dense with each entry's keys a run of their own: queries rows [cu[s], cu[s+1]), "
|
||||
"keys and values rows [cu_k[s], cu_k[s+1]); `causal` counts from each run's start."),
|
||||
SCHEMA("attn_na3d", pAttnNa3d, oAttnNa3d,
|
||||
"3-D neighborhood attention over the voxels of geom = (T, H, W): each query sees the "
|
||||
"kt x kh x kw window centred on it, shifted inward at the border."),
|
||||
SCHEMA("qk_norm_rope_gate", pQkNormRopeGate, oQkNormRopeGate,
|
||||
"split [q|gate] per head, QK RMS norm over the head, partial NeoX RoPE and the gate "
|
||||
"copy, in one pass. Not docs/OPS.md's qk_norm_rope: different operands, and a "
|
||||
@@ -3137,6 +3237,14 @@ static const RadOpSchema kSchemas[] = {
|
||||
SCHEMA("ln_mod_quant_fp8", pLnModQ, oLnModQ,
|
||||
"gated 1: x = bf16(x + bf16(bf16(tanh(g[seq])) * y)) first; then z = ln_mod(x) and "
|
||||
"(q, scale) = quant_act_fp8(z, group), z written when bound."),
|
||||
SCHEMA("table_add", pTableAdd, oTableAdd,
|
||||
"y[r, l n + c] = x[r, c] + t[l, c]: a shared modulation row plus each of L learned rows, "
|
||||
"f32 sum rounded once."),
|
||||
SCHEMA("chan_stats", pChanStats, oChanStats,
|
||||
"a latent through per-channel statistics held as weights: denorm rd(rd(x std) + mean), "
|
||||
"norm rd(rd(x - mean) / std); std is s, or sqrt(s + eps) with var 1."),
|
||||
SCHEMA("mix_rows", pMixRows, oMixRows,
|
||||
"y[r, c] = sum_i w[i] x[r k + i, c], i < k: a Linear(k, 1) across k consecutive rows."),
|
||||
SCHEMA("gate_add", pGateAdd, oGateAdd,
|
||||
"x = bf16(x + bf16(bf16(tanh(g[seq])) * y)): a residual through its sequence's gate; "
|
||||
"with `act` none the gate is g itself, x = bf16(x + bf16(g[seq] * y))."),
|
||||
@@ -3205,6 +3313,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
SCHEMA("interleave2", pInterleave, oInterleave2, "two streams interleaved."),
|
||||
SCHEMA("iota", pIota, oIota, "y[i] = start + i * step."),
|
||||
SCHEMA("cu_repeat", pCuRepeat, oCuRepeat, "bounds of equal sequences, y[j] = j * len[0] * mult."),
|
||||
SCHEMA("int_affine", pIntAffine, oIntAffine,
|
||||
"y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists."),
|
||||
SCHEMA("snake_aa", pSnakeAa, oSnakeAa,
|
||||
"BigVGAN's alias-free SnakeBeta over each sequence, f32: replicate-padded, upsampled "
|
||||
"`ratio` times by `f_up`, SnakeBeta, filtered by `f_down` at stride `ratio`."),
|
||||
@@ -3247,6 +3357,44 @@ static const RadOpSchema kSchemas[] = {
|
||||
SCHEMA("flow_renoise", pFlowRenoise, oFlowRenoise,
|
||||
"x = (1 - sigma) x + sigma z, z the (seed, stream) normal stream at element k n + c, "
|
||||
"each step one f32 rounding."),
|
||||
SCHEMA("rope_split", pRopeSplit, oRopeSplit,
|
||||
"LTX-2's split rotary over fractional coordinates: the pairs of all heads on one "
|
||||
"ladder, the first `pad` unrotated, the axes interleaved; each head's halves turned "
|
||||
"against each other in f32."),
|
||||
SCHEMA("head_gate", pHeadGate, oHeadGate,
|
||||
"x = rd(x rd(2 rd(sigmoid(g)))) for each head's values."),
|
||||
SCHEMA("ltx_guide", pLtxGuide, oLtxGuide,
|
||||
"LTX-2's sampler step: the passes' clean estimates combined (CFG, STG, modality), an "
|
||||
"optional rescale by the deviations' ratio, the velocity back and the Euler step, f32."),
|
||||
SCHEMA("pixel_norm", pPixelNorm, oPixelNorm,
|
||||
"an RMS norm over each row's n values as bf16 tensors compute it, every step rounded "
|
||||
"to y's dtype; rsqrt or div form, optionally silu; `ileave` L writes x's row t L + l "
|
||||
"to columns c L + l of y's row t."),
|
||||
SCHEMA("d2s3d", pD2s3d, oD2s3d,
|
||||
"depth to space over voxel rows, the first st - 1 frames dropped."),
|
||||
SCHEMA("s2d3d", pS2d3d, oS2d3d,
|
||||
"space to depth over voxel rows, `tpre` leading frames prepended: a packed row each "
|
||||
"box (copy) or each `group` packed channels averaged (mean); `add` adds into y."),
|
||||
SCHEMA("pix_patch", pPixPatch, oPixPatch,
|
||||
"an image [H, W C] to patch rows [H/p, (W/p) C p p], order wh or hw."),
|
||||
SCHEMA("patch_pix8", pPixPatch, oPixPatch,
|
||||
"patch rows [R, w C p p] to RGB bytes [R p, w p C] by to_rgba8's rule."),
|
||||
SCHEMA("vol_index", pVolIndex, oVolIndex,
|
||||
"a volume's voxel coordinates (t, i, j), component-major."),
|
||||
SCHEMA("tile_grid", pTileGrid, oTileGrid,
|
||||
"the tiles of a grid as diffusers cuts them (rule stride or intervals), in space and "
|
||||
"optionally time, one row (t, h, w, t0, y0, x0, k, count) a tile."),
|
||||
SCHEMA("tile_crop", pTileCrop, oTileCrop,
|
||||
"one tile's voxels out of a volume, box (t, h, w, t0, y0, x0)."),
|
||||
SCHEMA("tile_stitch", pTileStitch, oTileStitch,
|
||||
"decoded tiles to RGB bytes: diffusers' in-place blend_v then blend_h, then blend_t "
|
||||
"across time bands, each tile kept to its stride, patch_pix8's bytes."),
|
||||
SCHEMA("stft_logmel", pStftMel, oStftMel,
|
||||
"each channel's causal log-mel spectrogram from a windowed DFT basis and a mel "
|
||||
"filterbank, every stored tensor rounded to y's dtype."),
|
||||
SCHEMA("bwe_up", pBweUp, oBweUp,
|
||||
"y = clamp(rd(res + up(x)), -1, 1), x raised `ratio` times by a Hann-windowed sinc "
|
||||
"resampler."),
|
||||
SCHEMA("vsa_select", pVsa, oVsaSelect,
|
||||
"video sparse attention's selection over tiles of at most 64 rows (dense segments in "
|
||||
"chunks, the video grid in tile_t x tile_h x tile_w boxes): f32 tile means of q and k, "
|
||||
@@ -3504,6 +3652,60 @@ static const RadConstraint cAttnDecodeGqH256G6Bs4Bf16[] = {
|
||||
C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
|
||||
C_EQ("group", 128), C_IN("act", "sigmoid"),
|
||||
};
|
||||
/* The fp8_v4 and k6_v4 caches on the QSA layers' two ratios (r4d_attn_paged_gqa8.hip's
|
||||
* R4D_ATTN_V4): the fp8 rows' constraints at those kv_dtype values. */
|
||||
static const RadConstraint cAttnPrefillH256G12Fp8v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4),
|
||||
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeH256G12Fp8v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4),
|
||||
C_GE("causal", 0), C_LE("q_len", 5), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeGqH256G12Fp8v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4),
|
||||
C_GE("causal", 0), C_LE("q_len", 5), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"),
|
||||
C_EQ("group", 128), C_IN("act", "sigmoid"),
|
||||
};
|
||||
static const RadConstraint cAttnPrefillH256G12K6v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4),
|
||||
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeH256G12K6v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4),
|
||||
C_GE("causal", 0), C_LE("q_len", 5), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeGqH256G12K6v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4),
|
||||
C_GE("causal", 0), C_LE("q_len", 5), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"),
|
||||
C_EQ("group", 128), C_IN("act", "sigmoid"),
|
||||
};
|
||||
static const RadConstraint cAttnPrefillH256G6Bs4Fp8v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4),
|
||||
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeH256G6Bs4Fp8v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4),
|
||||
C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeGqH256G6Bs4Fp8v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4),
|
||||
C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"),
|
||||
C_EQ("group", 128), C_IN("act", "sigmoid"),
|
||||
};
|
||||
static const RadConstraint cAttnPrefillH256G6Bs4K6v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4),
|
||||
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeH256G6Bs4K6v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4),
|
||||
C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeGqH256G6Bs4K6v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4),
|
||||
C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"),
|
||||
C_EQ("group", 128), C_IN("act", "sigmoid"),
|
||||
};
|
||||
static const RadConstraint cAttnPrefillH128G8Fp8[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 8), C_EQ("block_size", 16),
|
||||
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
|
||||
@@ -3571,6 +3773,9 @@ static const RadConstraint cAttnLocalRel[] = {
|
||||
};
|
||||
/* `cast` widening bf16 -> f32: an exact conversion, the form a pooled embedding leaves the
|
||||
* device in. */
|
||||
static const RadConstraint cCastF32[] = {
|
||||
C_IN("from", "f32"), C_IN("to", "f32"),
|
||||
};
|
||||
static const RadConstraint cCastWiden[] = {
|
||||
C_IN("from", "bf16"), C_IN("to", "f32"),
|
||||
};
|
||||
@@ -3584,20 +3789,30 @@ static const RadConstraint cCastF16[] = {
|
||||
static const RadConstraint cCastNarrow[] = {
|
||||
C_IN("from", "f32"), C_IN("to", "bf16"),
|
||||
};
|
||||
/* The encoder's dense attention: bidirectional, any window, at the (head_dim, gqa) pairs
|
||||
* r4d_attn_dense_bf16.hip compiles. */
|
||||
/* Dense attention at the (head_dim, gqa) pairs r4d_attn_dense_bf16.hip compiles: an encoder's,
|
||||
* bidirectional with any window, or a text encoder's causal prompt. gqa 1 at 256 and 512 is
|
||||
* attn_dense_small_h256's and the wide kernel's. */
|
||||
/* Causal or not at head_dim 64: a vision tower's heads, and a codec's sliding causal layers. */
|
||||
static const RadConstraint cAttnDenseH64[] = {
|
||||
C_EQ("head_dim", 64), C_EQ("gqa", 1), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnDenseH256G2[] = {
|
||||
C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("causal", 0), C_IN("dtype", "bf16"),
|
||||
C_EQ("head_dim", 256), C_EQ("gqa", 2), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnDenseH256G4[] = {
|
||||
C_EQ("head_dim", 256), C_EQ("gqa", 4), C_EQ("causal", 0), C_IN("dtype", "bf16"),
|
||||
C_EQ("head_dim", 256), C_EQ("gqa", 4), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnDenseH256G8[] = {
|
||||
C_EQ("head_dim", 256), C_DIV("gqa", 8), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnDenseH512G2[] = {
|
||||
C_EQ("head_dim", 512), C_EQ("gqa", 2), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnDenseH512G4[] = {
|
||||
C_EQ("head_dim", 512), C_EQ("gqa", 4), C_EQ("causal", 0), C_IN("dtype", "bf16"),
|
||||
C_EQ("head_dim", 512), C_EQ("gqa", 4), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnDenseH512G8[] = {
|
||||
C_EQ("head_dim", 512), C_DIV("gqa", 8), C_IN("dtype", "bf16"),
|
||||
};
|
||||
/* A head in a wave's registers with a rotary pair in one lane: head_dim a multiple of 32 up to
|
||||
* 1024. The shim refuses a rotary_dim whose half is not a multiple of 32 (neox) by name. */
|
||||
@@ -3871,16 +4086,9 @@ static const RadConstraint cMlaProject[] = { C_GE("M", 1),
|
||||
/* The matrix row outranks the wave row (mla_attn_bf16) at every M, the pairing walking the union
|
||||
* of both rows' pages: measured cold on gfx1201 (r4d_selftest --perfmla), a 2048-row chunk
|
||||
* with DSA tables (fill topk:16) takes 7.1 ms against 12.4 ms on the wave row and 13.0 ms on the
|
||||
* positional pairing, fresh 3.8 against 6.3 ms, a decode step of 8x6 rows 0.23 against 0.82 ms.
|
||||
* RADIANCE_MLA_MATRIX_MAX_M lowers the bound, read once as the table loads; 0 is never. */
|
||||
static long long mla_matrix_max_m() {
|
||||
const char* e = std::getenv("RADIANCE_MLA_MATRIX_MAX_M");
|
||||
char* end = nullptr;
|
||||
const long long v = e && *e ? std::strtoll(e, &end, 10) : -1;
|
||||
return end && !*end && v >= 0 ? (v < 65535 ? v : 65535) : 65535;
|
||||
}
|
||||
* positional pairing, fresh 3.8 against 6.3 ms, a decode step of 8x6 rows 0.23 against 0.82 ms. */
|
||||
static const RadConstraint cMlaMatrix[] = { C_GE("M", 1),
|
||||
C_LE("M", mla_matrix_max_m()),
|
||||
C_LE("M", 65535),
|
||||
C_EQ("latent_dim", 512),
|
||||
C_GE("heads", 8),
|
||||
C_LE("heads", 64),
|
||||
@@ -4605,6 +4813,16 @@ static const RadConstraint cAttnPrefixSelf[] = {
|
||||
static const RadConstraint cAttnDenseH128[] = {
|
||||
C_EQ("head_dim", 128), C_LE("gqa", 8), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnCrossH64[] = {
|
||||
C_EQ("head_dim", 64), C_LE("gqa", 8), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnNa3d[] = { C_EQ("head_dim", 64), C_IN("dtype", "bf16 f32") };
|
||||
static const RadConstraint cAttnDenseH384[] = {
|
||||
C_EQ("head_dim", 384), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnDenseH512[] = {
|
||||
C_EQ("head_dim", 512), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnDenseH768[] = {
|
||||
C_EQ("head_dim", 768), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"),
|
||||
};
|
||||
@@ -4729,6 +4947,15 @@ static const RadKernelInfo kKernels[] = {
|
||||
nullptr, nullptr, r4d_rad_cast, nullptr, nullptr, nullptr,
|
||||
r4d_shape_cast },
|
||||
|
||||
{ "cast_f32_f32", "cast", "elem",
|
||||
"y = x, f32 to f32 -- a strided row copy through libr4d's 2D copy",
|
||||
"any M and n; both row pitches are read off the operands",
|
||||
"f32 in, f32 out, byte-for-byte",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cCastF32), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_cast, nullptr, nullptr, nullptr,
|
||||
r4d_shape_cast },
|
||||
|
||||
{ "cast_bf16_f32", "cast", "elem",
|
||||
"y = x, bf16 widened to f32",
|
||||
"any M and n; both row pitches are read off the operands",
|
||||
@@ -5013,6 +5240,15 @@ static const RadKernelInfo kKernels[] = {
|
||||
nullptr, nullptr, r4d_rad_fill, nullptr, nullptr, nullptr,
|
||||
r4d_shape_fill },
|
||||
|
||||
{ "fill_f32", "fill", "elem",
|
||||
"constant fill, a row a workgroup",
|
||||
"any M, n; a row pitch is honoured",
|
||||
"f32 out, the value exactly",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cF32Row), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_fill, nullptr, nullptr, nullptr,
|
||||
r4d_shape_fill },
|
||||
|
||||
{ "sigmoid_bf16", "sigmoid", "elem",
|
||||
"logistic sigmoid, grid-strided over the whole extent",
|
||||
"any extent; contiguous in and out",
|
||||
@@ -5791,6 +6027,129 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
nullptr, nullptr,
|
||||
r4d_shape_attn_paged_gate_quant, nullptr, r4d_fuse_attn_paged_gate_quant },
|
||||
|
||||
/* The fp8_v4 and k6_v4 caches on Flash-Next's QSA layers: gqa12 at one and two ranks, gqa6 with
|
||||
* 4-token pages at four. A token's row is 400 bytes (E4M3 K, int4 V, f16 group scales) or 352
|
||||
* (int6 K, int4 V); the layouts are RAD_KVQ_*'s (abi/rad_builder.h). */
|
||||
{ "attn_prefill_h256_gqa12_fp8v4", "attn_paged", "attn",
|
||||
"paged causal attention, query-tiled (prefill / chunked prefill)",
|
||||
"head_dim 256, 12 queries per kv head, paged block 4, varlen",
|
||||
"bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 out",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
|
||||
ROW(cAttnPrefillH256G12Fp8v4), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa12_fp8v4, nullptr, nullptr, nullptr,
|
||||
nullptr },
|
||||
|
||||
{ "attn_decode_h256_gqa12_fp8v4", "attn_paged", "attn",
|
||||
"paged attention, causal or not, split-KV (decode / speculative verify / draft block)",
|
||||
"head_dim 256, 12 queries per kv head, paged block 4, q_len*gqa <= 64, no window",
|
||||
"bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 out, f16 partials",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeH256G12Fp8v4), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_h256_gqa12_fp8v4, r4d_rad_attn_decode_h256_gqa12_fp8v4_scratch,
|
||||
nullptr, nullptr,
|
||||
nullptr },
|
||||
|
||||
{ "attn_decode_gq_h256_gqa12_fp8v4", "attn_paged_gate_quant", "attn",
|
||||
"paged split-KV decode attention with the output gate and the fp8 quantiser in the merge",
|
||||
"attn_decode_h256_gqa12_fp8v4's geometry; gate_quant_fp8 over the merged (token, head) rows: "
|
||||
"sigmoid only, group 128, the gate 16-byte aligned with a pitch of 8, the codes 8-byte aligned",
|
||||
"bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 gated out, E4M3 codes with an f32 scale per 128 columns",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeGqH256G12Fp8v4), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_gq_h256_gqa12_fp8v4, r4d_rad_attn_decode_h256_gqa12_fp8v4_scratch,
|
||||
nullptr, nullptr,
|
||||
nullptr, nullptr, r4d_fuse_attn_paged_gate_quant },
|
||||
|
||||
{ "attn_prefill_h256_gqa12_k6v4", "attn_paged", "attn",
|
||||
"paged causal attention, query-tiled (prefill / chunked prefill)",
|
||||
"head_dim 256, 12 queries per kv head, paged block 4, varlen",
|
||||
"bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 out",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
|
||||
ROW(cAttnPrefillH256G12K6v4), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa12_k6v4, nullptr, nullptr, nullptr,
|
||||
nullptr },
|
||||
|
||||
{ "attn_decode_h256_gqa12_k6v4", "attn_paged", "attn",
|
||||
"paged attention, causal or not, split-KV (decode / speculative verify / draft block)",
|
||||
"head_dim 256, 12 queries per kv head, paged block 4, q_len*gqa <= 64, no window",
|
||||
"bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 out, f16 partials",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeH256G12K6v4), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_h256_gqa12_k6v4, r4d_rad_attn_decode_h256_gqa12_k6v4_scratch,
|
||||
nullptr, nullptr,
|
||||
nullptr },
|
||||
|
||||
{ "attn_decode_gq_h256_gqa12_k6v4", "attn_paged_gate_quant", "attn",
|
||||
"paged split-KV decode attention with the output gate and the fp8 quantiser in the merge",
|
||||
"attn_decode_h256_gqa12_k6v4's geometry; gate_quant_fp8 over the merged (token, head) rows: "
|
||||
"sigmoid only, group 128, the gate 16-byte aligned with a pitch of 8, the codes 8-byte aligned",
|
||||
"bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 gated out, E4M3 codes with an f32 scale per 128 columns",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeGqH256G12K6v4), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_gq_h256_gqa12_k6v4, r4d_rad_attn_decode_h256_gqa12_k6v4_scratch,
|
||||
nullptr, nullptr,
|
||||
nullptr, nullptr, r4d_fuse_attn_paged_gate_quant },
|
||||
|
||||
{ "attn_prefill_h256_gqa6_bs4_fp8v4", "attn_paged", "attn",
|
||||
"paged causal attention, query-tiled (prefill / chunked prefill)",
|
||||
"head_dim 256, 6 queries per kv head, paged block 4, varlen",
|
||||
"bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 out",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
|
||||
ROW(cAttnPrefillH256G6Bs4Fp8v4), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa6_fp8v4, nullptr, nullptr, nullptr,
|
||||
nullptr },
|
||||
|
||||
{ "attn_decode_h256_gqa6_bs4_fp8v4", "attn_paged", "attn",
|
||||
"paged attention, causal or not, split-KV (decode / speculative verify / draft block)",
|
||||
"head_dim 256, 6 queries per kv head, paged block 4, q_len*gqa <= 64, no window",
|
||||
"bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 out, f16 partials",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeH256G6Bs4Fp8v4), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_h256_gqa6_fp8v4, r4d_rad_attn_decode_h256_gqa6_fp8v4_scratch,
|
||||
nullptr, nullptr,
|
||||
nullptr },
|
||||
|
||||
{ "attn_decode_gq_h256_gqa6_bs4_fp8v4", "attn_paged_gate_quant", "attn",
|
||||
"paged split-KV decode attention with the output gate and the fp8 quantiser in the merge",
|
||||
"attn_decode_h256_gqa6_bs4_fp8v4's geometry; gate_quant_fp8 over the merged (token, head) rows: "
|
||||
"sigmoid only, group 128, the gate 16-byte aligned with a pitch of 8, the codes 8-byte aligned",
|
||||
"bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 gated out, E4M3 codes with an f32 scale per 128 columns",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeGqH256G6Bs4Fp8v4), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_gq_h256_gqa6_fp8v4, r4d_rad_attn_decode_h256_gqa6_fp8v4_scratch,
|
||||
nullptr, nullptr,
|
||||
nullptr, nullptr, r4d_fuse_attn_paged_gate_quant },
|
||||
|
||||
{ "attn_prefill_h256_gqa6_bs4_k6v4", "attn_paged", "attn",
|
||||
"paged causal attention, query-tiled (prefill / chunked prefill)",
|
||||
"head_dim 256, 6 queries per kv head, paged block 4, varlen",
|
||||
"bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 out",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
|
||||
ROW(cAttnPrefillH256G6Bs4K6v4), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa6_k6v4, nullptr, nullptr, nullptr,
|
||||
nullptr },
|
||||
|
||||
{ "attn_decode_h256_gqa6_bs4_k6v4", "attn_paged", "attn",
|
||||
"paged attention, causal or not, split-KV (decode / speculative verify / draft block)",
|
||||
"head_dim 256, 6 queries per kv head, paged block 4, q_len*gqa <= 64, no window",
|
||||
"bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 out, f16 partials",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeH256G6Bs4K6v4), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_h256_gqa6_k6v4, r4d_rad_attn_decode_h256_gqa6_k6v4_scratch,
|
||||
nullptr, nullptr,
|
||||
nullptr },
|
||||
|
||||
{ "attn_decode_gq_h256_gqa6_bs4_k6v4", "attn_paged_gate_quant", "attn",
|
||||
"paged split-KV decode attention with the output gate and the fp8 quantiser in the merge",
|
||||
"attn_decode_h256_gqa6_bs4_k6v4's geometry; gate_quant_fp8 over the merged (token, head) rows: "
|
||||
"sigmoid only, group 128, the gate 16-byte aligned with a pitch of 8, the codes 8-byte aligned",
|
||||
"bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 gated out, E4M3 codes with an f32 scale per 128 columns",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeGqH256G6Bs4K6v4), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_gq_h256_gqa6_k6v4, r4d_rad_attn_decode_h256_gqa6_k6v4_scratch,
|
||||
nullptr, nullptr,
|
||||
nullptr, nullptr, r4d_fuse_attn_paged_gate_quant },
|
||||
|
||||
{ "attn_prefill_h128_gqa8_fp8kv", "attn_paged", "attn",
|
||||
"paged causal attention, query-tiled (prefill / chunked prefill)",
|
||||
"head_dim 128, 8 queries per kv head, paged block 16, varlen",
|
||||
@@ -5887,7 +6246,8 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
nullptr, nullptr, r4d_rad_attn_dense },
|
||||
|
||||
{ "attn_dense_h256_gqa2_bf16", "attn_dense", "attn",
|
||||
"dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window",
|
||||
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or "
|
||||
"causal with an optional window behind",
|
||||
"head_dim 256, two query heads a KV head in one workgroup, the key range cut to the window",
|
||||
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
@@ -5895,21 +6255,52 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
nullptr, nullptr, r4d_rad_attn_dense },
|
||||
|
||||
{ "attn_dense_h256_gqa4_bf16", "attn_dense", "attn",
|
||||
"dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window",
|
||||
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or "
|
||||
"causal with an optional window behind",
|
||||
"head_dim 256, four query heads a KV head in one workgroup, the key range cut to the window",
|
||||
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH256G4), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense },
|
||||
|
||||
{ "attn_dense_h256_gqa8_bf16", "attn_dense", "attn",
|
||||
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or "
|
||||
"causal with an optional window behind",
|
||||
"head_dim 256, eight query heads a KV head in one workgroup (a multiple of eight as several), "
|
||||
"the key range cut to the window",
|
||||
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH256G8), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense },
|
||||
|
||||
{ "attn_dense_h512_gqa2_bf16", "attn_dense", "attn",
|
||||
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or "
|
||||
"causal with an optional window behind",
|
||||
"head_dim 512 split across two waves, two query heads a KV head in one workgroup",
|
||||
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH512G2), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense },
|
||||
|
||||
{ "attn_dense_h512_gqa4_bf16", "attn_dense", "attn",
|
||||
"dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window",
|
||||
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or "
|
||||
"causal with an optional window behind",
|
||||
"head_dim 512 split across two waves, four query heads a KV head in one workgroup",
|
||||
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH512G4), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense },
|
||||
|
||||
{ "attn_dense_h512_gqa8_bf16", "attn_dense", "attn",
|
||||
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or "
|
||||
"causal with an optional window behind",
|
||||
"head_dim 512 split across two waves, eight query heads a KV head in one workgroup (a "
|
||||
"multiple of eight as several workgroups)",
|
||||
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH512G8), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense },
|
||||
|
||||
/* -------------------------------------------------------------------------- gated delta net */
|
||||
{ "gdn_chunk_scan_k128_v128_c64_bf16", "gdn_chunk_scan", "gdn",
|
||||
"gated delta net chunked scan: WY recompute, state recurrence and output in one kernel",
|
||||
@@ -7496,6 +7887,46 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
ROW(cAttnDenseH128), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense_h128 },
|
||||
|
||||
{ "attn_cross_h128_bf16", "attn_cross", "attn",
|
||||
"dense varlen attention with the keys bounded apart from the queries (cross attention)",
|
||||
"head_dim 128, 1/2/4/8 query heads a KV head; attn_dense_h128's kernel",
|
||||
"bf16 query / key / value / out, bf16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH128), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_cross },
|
||||
|
||||
{ "attn_cross_h64_bf16", "attn_cross", "attn",
|
||||
"dense varlen attention with the keys bounded apart from the queries (cross attention)",
|
||||
"head_dim 64, 1/2/4/8 query heads a KV head; attn_dense_h128's kernel at 64",
|
||||
"bf16 query / key / value / out, bf16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnCrossH64), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_cross },
|
||||
|
||||
{ "attn_na3d_h64", "attn_na3d", "attn",
|
||||
"3-D neighborhood attention: a thread a (query, head), the window's keys streamed through the "
|
||||
"caches, libref's two passes",
|
||||
"head_dim 64, any window, row pitches honoured", "bf16 or f32 q / k / v / out, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnNa3d), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_na3d },
|
||||
|
||||
{ "attn_dense_h384_bf16", "attn_dense", "attn",
|
||||
"one 384-wide head over every row of a segment: an image encoder's mid-block attention",
|
||||
"head_dim 384 split across eight waves, 16 queries a workgroup",
|
||||
"bf16 query / key / value / out, bf16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH384), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense_wide },
|
||||
|
||||
{ "attn_dense_h512_bf16", "attn_dense", "attn",
|
||||
"one 512-wide head over every row of a segment: an image encoder's mid-block attention",
|
||||
"head_dim 512 split across eight waves, 16 queries a workgroup",
|
||||
"bf16 query / key / value / out, bf16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH512), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense_wide },
|
||||
|
||||
{ "attn_dense_h768_bf16", "attn_dense", "attn",
|
||||
"one 768-wide head over every row of a segment: an image encoder's mid-block attention",
|
||||
"head_dim 768 split across eight waves, 16 queries a workgroup",
|
||||
@@ -7527,6 +7958,38 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
ROW(cGenRows8), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_ln_mod },
|
||||
|
||||
{ "table_add_bf16", "table_add", "elem",
|
||||
"a shared modulation row plus each block's learned table row, every block in one launch",
|
||||
"any M, row pitches honoured; n a multiple of 8",
|
||||
"bf16",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenRows8), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_table_add },
|
||||
|
||||
{ "chan_stats_bf16", "chan_stats", "elem",
|
||||
"a VAE latent through its per-channel statistics (running mean and variance, or mean and std)",
|
||||
"any M, row pitches honoured; n a multiple of 8",
|
||||
"bf16",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenRows8), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_chan_stats },
|
||||
|
||||
{ "chan_stats_f32", "chan_stats", "elem",
|
||||
"a latent kept in f32 through its VAE's per-channel statistics",
|
||||
"any M, row pitches honoured",
|
||||
"f32 x and y, bf16 or f32 statistics, every step rounded to f32",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cF32Row), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_chan_stats },
|
||||
|
||||
{ "mix_rows_bf16", "mix_rows", "elem",
|
||||
"a learned weighted sum of k consecutive rows (a Linear(k, 1) over a stacked axis)",
|
||||
"any M, row pitches honoured; n a multiple of 8",
|
||||
"bf16",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenRows8), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_mix_rows },
|
||||
|
||||
{ "gate_add_bf16", "gate_add", "elem",
|
||||
"x += tanh(gate row) * y, the reference's three roundings; with `act` none the gate as it is",
|
||||
"any M, row pitches honoured",
|
||||
@@ -7809,6 +8272,13 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
nullptr, 0, NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_cu_repeat },
|
||||
|
||||
{ "int_affine", "int_affine", "elem",
|
||||
"integers derived from device geometry: one wave, the lists by value", "up to 16 values",
|
||||
"i32",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
nullptr, 0, NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_int_affine },
|
||||
|
||||
{ "attn_dense_small_h256_bf16", "attn_dense", "attn",
|
||||
"dense attention over short sequences, causal or not: a depth decoder's frame positions",
|
||||
"head_dim 256, one query head a key head, sequences of at most 32 rows, a workgroup a (sequence, "
|
||||
@@ -7958,6 +8428,103 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenF32), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_flow_renoise },
|
||||
|
||||
{ "rope_split", "rope_split", "elem",
|
||||
"LTX-2's rotary: a workgroup a (head, 64 rows), the head's ladder in LDS, sincosf a pair",
|
||||
"any M, row pitches honoured; head_dim / 2 dividing 256; up to four axes",
|
||||
"bf16 or f32 x, f32 or i32 positions",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_rope_split },
|
||||
|
||||
{ "head_gate", "head_gate", "elem",
|
||||
"each head times 2 sigmoid of its logit: a thread a value",
|
||||
"any M, row pitches honoured", "bf16 logits, bf16 or f32 x",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_head_gate },
|
||||
|
||||
{ "ltx_guide", "ltx_guide", "elem",
|
||||
"LTX-2's guided step: f64 deviation sums in up to 1024 parts, then the step in place",
|
||||
"any M and n, row pitches honoured", "f32 latent, bf16 or f32 velocities",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_ltx_guide },
|
||||
|
||||
{ "pixel_norm", "pixel_norm", "norm",
|
||||
"an RMS norm as bf16 tensors compute it: a wave a row, its sum of squares a wave reduction",
|
||||
"any M and n, row pitches honoured", "bf16 or f32 x and y",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_pixel_norm },
|
||||
|
||||
{ "d2s3d", "d2s3d", "elem",
|
||||
"depth to space over voxel rows: a thread a value, the volume off the device",
|
||||
"any C and factors, row pitches honoured", "bf16 or f32 x and y, i32 geom",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_d2s3d },
|
||||
|
||||
{ "s2d3d", "s2d3d", "elem",
|
||||
"space to depth over voxel rows, copy or group mean, optionally added: a thread a value",
|
||||
"any C and factors, row pitches honoured", "bf16 or f32 x and y, i32 geom",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_s2d3d },
|
||||
|
||||
{ "pix_patch", "pix_patch", "elem",
|
||||
"an image to patch rows: a thread a value",
|
||||
"dense 2-D operands, row pitches honoured", "bf16 or f32 x and y",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_pix_patch },
|
||||
|
||||
{ "patch_pix8", "patch_pix8", "elem",
|
||||
"patch rows to RGB bytes: a thread a byte",
|
||||
"dense 2-D operands, row pitches honoured", "bf16 or f32 x, u8 y",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_patch_pix8 },
|
||||
|
||||
{ "vol_index", "vol_index", "elem",
|
||||
"a volume's voxel coordinates: a thread a voxel", "i32, a dense [3, n]", "i32",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
nullptr, 0, NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_vol_index },
|
||||
|
||||
{ "tile_grid", "tile_grid", "elem",
|
||||
"a tiled decode's boxes off a device volume: a thread a row", "contiguous i32", "i32",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
nullptr, 0, NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_tile_grid },
|
||||
|
||||
{ "tile_crop", "tile_crop", "elem",
|
||||
"a tile's voxels out of a volume: a thread a value, the box read on the device",
|
||||
"row pitches honoured", "bf16 or f32 x and y, i32 geom and box",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_tile_crop },
|
||||
|
||||
{ "tile_stitch", "tile_stitch", "elem",
|
||||
"decoded tiles blended to RGB bytes: a thread a byte, up to four tiles read",
|
||||
"dense 2-D operands, row pitches honoured", "bf16 or f32 x, u8 y, i32 geom and first",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_tile_stitch },
|
||||
|
||||
{ "stft_logmel", "stft_logmel", "elem",
|
||||
"a causal log-mel spectrogram: a workgroup a (frame, channel), the frame in LDS",
|
||||
"nfft up to 4096, row pitches honoured", "bf16 or f32 operands",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_stft_logmel },
|
||||
|
||||
{ "bwe_up", "bwe_up", "elem",
|
||||
"a sinc-resampled waveform plus a residual, clamped: a thread a value, the taps by value",
|
||||
"ratio up to 9, row pitches honoured", "bf16 or f32 operands",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_bwe_up },
|
||||
};
|
||||
|
||||
/* ================================================================================== the exports */
|
||||
|
||||
+1738
-877
File diff suppressed because it is too large.
Load diff
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user