diff --git a/CMakeLists.txt b/CMakeLists.txt index 80dda3fc..a6fbedcf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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) diff --git a/Dockerfile b/Dockerfile index 14cd05d7..d0c0c375 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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}" \ diff --git a/NOTICE b/NOTICE index 0d450ed3..b4769e03 100644 --- a/NOTICE +++ b/NOTICE @@ -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. diff --git a/README.md b/README.md index 390a22c4..d1546995 100644 --- a/README.md +++ b/README.md @@ -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` | diff --git a/abi/rad_abi.h b/abi/rad_abi.h index ad302026..292e14b4 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -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: diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 839904da..5b1713c5 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -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); diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index c7694a95..912a25b4 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -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 */ diff --git a/arch/common/rad_arch.h b/arch/common/rad_arch.h index d593f816..c138838a 100644 --- a/arch/common/rad_arch.h +++ b/arch/common/rad_arch.h @@ -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); diff --git a/arch/common/rad_block_mhc.h b/arch/common/rad_block_mhc.h index 71bdaec5..67b21d15 100644 --- a/arch/common/rad_block_mhc.h +++ b/arch/common/rad_block_mhc.h @@ -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; } diff --git a/arch/common/rad_tp_split.h b/arch/common/rad_tp_split.h index 48217c60..68a92125 100644 --- a/arch/common/rad_tp_split.h +++ b/arch/common/rad_tp_split.h @@ -4,19 +4,12 @@ #ifndef RAD_TP_SPLIT_H #define RAD_TP_SPLIT_H #include "rad_arch.h" -#include 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; } diff --git a/arch/common/rad_vae2d.h b/arch/common/rad_vae2d.h new file mode 100644 index 00000000..f228c5ad --- /dev/null +++ b/arch/common/rad_vae2d.h @@ -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 + +#include +#include +#include +#include +#include + +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 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 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 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> 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> 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 */ diff --git a/arch/flux3/CMakeLists.txt b/arch/flux3/CMakeLists.txt new file mode 100644 index 00000000..1e15fd62 --- /dev/null +++ b/arch/flux3/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/flux3 -B build -DCMAKE_PREFIX_PATH=`); 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) diff --git a/arch/flux3/flux3.cpp b/arch/flux3/flux3.cpp new file mode 100644 index 00000000..3eb721ac --- /dev/null +++ b/arch/flux3/flux3.cpp @@ -0,0 +1,1247 @@ +/* flux3 -- FLUX.3 [klein] (the step-distilled release and its base): text and up to ten + * reference pictures to an RGB image. + * + * ============================== THE MODEL ============================== + * + * Three networks behind one prompt (diffusers' FLUX.3 modular pipeline): + * + * Conditioning network: 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 + * sits at position 1 and attends to the prompt alone (`attn_cross`, the core's `valid_cu`). The + * generator reads eight hidden states per token (after layers 3, 7, ..., 31) side by side, + * 20480 values, through `context_embedder`. + * + * Denoiser: a 5.6B diffusion transformer over three modes, the text, the reference pictures' + * latents (VAE-encoded, the generator's own encoder; the conditioning network never sees them) + * and the image. Every block is parallel: `h += gate (attn(n) + mlp(n))`, `n` a LayerNorm with + * no affine times (1 + scale) plus shift. Five blocks per mode run each mode on its own, then + * 28 joint blocks run all three together; each mode takes its own shift, scale and gate from + * its own projection of the timestep embedding (the text and pictures at time 0, the image at + * the step's), separately for the early and the joint blocks. The step-distilled release is a + * flow map: the embedding of the time the step goes to is added to every mode's. A four-axis + * rotary (t, h, w, l) over the joint sequence: text along l, the image at (0, h/2, w/2, 0) and + * reference k at l = -(1 + k). + * + * Since every row changes with the step, nothing is cached as keys: the conditioning pass + * leaves each lane's text and reference rows (after their embedders) in its store, and every + * denoising step runs the three modes' early blocks over them and the image (mode-major rows) + * and the joint blocks over the entries ([text | pictures | image] each, the core's JOINT_STEP + * layout). + * + * Decoder: FLUX.2's VAE, 32 channels at 8x with GroupNorm and a single-head mid-block + * attention; a latent token is 2 x 2 of its pixels (128 values), normalised by the VAE's + * BatchNorm running statistics. + * + * The distilled release samples 16 steps without guidance, the base 50 with guidance 3.5 and an + * empty negative prompt; both a constant shift of 6.93. + * + * ============================== WHAT IS QUANTISED ============================== + * + * Every linear of the language model and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16 + * throughout when the first joint block's projection is plain; the embedders, the timestep MLPs, + * the modulations, the output layer and the VAE stay bf16. + * + * ============================== TENSOR PARALLEL ============================== + * + * The language model and the DiT blocks split by heads and feed-forward width. A parallel + * block's two branch outputs are added before their one all-reduce (the sum of the partial sums). + * Everything else, the VAE included (its GroupNorm reads the whole picture), runs on every rank. + */ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifndef FLUX3_NS +#define FLUX3_NS flux3 +#define FLUX3_ID "flux3" +#endif + +namespace FLUX3_NS { + +using namespace rad::arch; + +/* ================================================================== the model's constants */ +/* The largest image: 2048 x 2048 pixels, 16384 latent tokens; 1024 x 1024 is the default. */ +enum { kMaxImageTokens = 16384 }; +/* Reference pictures: ten at most, each shrunk to 1024 x 1024 pixels of area when larger. */ +enum { kMaxRefs = 10, kRefArea = 1024 * 1024 }; +/* The prompt with its padding, at most; the pipeline pads to a multiple of 80. */ +enum { kMaxText = 1040, kPadMultiple = 80 }; +/* A reference picture's latent tokens at most: its area over 16 x 16 and the slack of its sides' + * rounding (the driver's bound). */ +static inline int64_t ref_tokens_max() { return (int64_t)kRefArea / 256 * 11 / 10 + 64; } +/* The longest conditioning: the text and every reference picture's tokens. */ +static inline int64_t cond_rows() { return kMaxText + kMaxRefs * ref_tokens_max(); } +/* Images in flight. Each lane keeps both branches' conditioning (cond_rows() rows apiece). */ +enum { kMaxLanes = 4 }; +/* The language model's hidden states read: hidden_states[i], the output of layer i - 1. */ +static const int kTaps[] = { 4, 8, 12, 16, 20, 24, 28, 32 }; +enum { kNTaps = 8 }; +/* Modes, in the order the joint layout lays an entry out. */ +enum { kText = 0, kRefs = 1, kImage = 2 }; + +/* ================================================================== the model */ +struct TeLayer { + rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0; + LinearFP8 qkv{}, o{}, gate_up{}, down{}; + QuantFP8 q_h{}, q_attn{}, q_h2{}; + GateQuantFP8 gq{}; + rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_ar1 = 0, op_add1 = 0; + rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0, op_tap = 0; + int tap = -1; +}; + +/* A parallel block: the modulated LayerNorm (the previous block's gated sum added first), then + * attention and the SwiGLU from the same normed rows, their outputs added. */ +struct Block { + rad_weight w_qn = 0, w_kn = 0; + LinearFP8 qkv{}, o{}, ff_in{}, ff_out{}; + GateQuantFP8 gq{}; + QuantFP8 q_attn{}; + rad_op op_n = 0, op_qkr = 0, op_attn = 0, op_sum = 0, op_ar = 0; +}; + +enum : int { + kGrpCtx = 1000, + kGrpVaeEnc = 1100, + kGrpVaeDec = 1200, + kGrpDit = 2000, /* model-level weights; the blocks kGrpDit + 1.. */ +}; + +struct Model { + Names nm{""}; + Geom gt{}, gd{}; + bool flow_map = false; + std::string te_pre; + + /* ---- the language model and context_embedder */ + rad_weight w_tok = 0, w_ctx = 0; + rad_op op_embed = 0, op_iota = 0, op_ctx = 0, op_store_t = 0; + rad_buf b_tx = 0, b_tkv = 0, b_th2 = 0, b_tgu = 0, b_tidx = 0, b_taps = 0, b_ctx = 0; + ActFP8 a_th{}, a_tattn{}, a_tffn{}; + std::vector te; + + /* ---- the reference pictures: the encoder, the mode, 2 x 2 tokens, BatchNorm, the embedder */ + Vae enc{}; + VImg enc_q{}; + rad_weight w_bnm = 0, w_bnv = 0, w_xc = 0; + rad_op op_enc_mode = 0, op_enc_zero = 0, op_enc_s2d = 0, op_enc_bn = 0, op_xc = 0, + op_store_r = 0, op_lstore_lat = 0, op_lstore_mask = 0, op_ecu = 0; + rad_buf b_emode = 0, b_epack = 0, b_elat = 0, b_eemb = 0, b_ecu = 0; + double bn_eps = 1e-4; + + /* ---- the timestep and every modulation */ + rad_weight w_t1 = 0, w_t2 = 0, w_tt1 = 0, w_tt2 = 0, w_fmod = 0; + rad_weight w_early[3] = {}, w_single[3] = {}; + rad_op op_tp = 0, op_tpt = 0, op_one = 0, op_zero = 0, op_iota3 = 0; + rad_op op_t1 = 0, op_ts = 0, op_t2 = 0, op_tt1 = 0, op_tts = 0, op_tt2 = 0; + rad_op op_addt = 0, op_actimg = 0, op_actzero = 0, op_fmod = 0; + rad_op op_early[3] = {}, op_single[3] = {}, op_ilv[3] = {}; + rad_buf b_tp = 0, b_e1 = 0, b_e1s = 0, b_temb = 0, b_tpt = 0, b_tt1 = 0, b_tt1s = 0; + rad_buf b_ttgt = 0; + rad_buf b_aimg = 0, b_azero = 0, b_idx3 = 0, b_fmod = 0; + rad_buf b_early[3] = {}, b_smod[3] = {}, b_single = 0; + + /* ---- the DiT */ + int64_t C = 128; + int64_t t_ch = 256; /* the timestep sinusoid's width */ + rad_weight w_xi = 0; + rad_op op_randn = 0, op_lgather = 0, op_xi = 0, op_gtxt = 0, op_join = 0, op_g2 = 0, op_g3 = 0, + op_gimg = 0, op_nout = 0, op_pout = 0, op_euler = 0; + rad_buf b_lat = 0, b_xc = 0, b_h = 0, b_qkv = 0, b_o = 0, b_gu = 0, b_f = 0, b_sum = 0, + b_hi = 0, b_fz = 0, b_v = 0; + ActFP8 a_hm{}, a_attn{}, a_ffn{}; + std::vector mode[3], single; + LinearFP8 qkv0{}; + rad_weight w_pout = 0; + + /* ---- per-image state and conditioning store (PERSIST) */ + rad_buf b_state = 0, b_prev = 0, b_inp = 0, b_mask = 0, b_store = 0; + + /* ---- the decoder */ + Vae dec{}; + VImg dec_out{}; + rad_op op_dbn = 0, op_dzero = 0, op_unpack = 0, op_cu4 = 0, op_rgb = 0; + rad_buf b_dl = 0, b_decin = 0, b_cu4 = 0, b_img = 0; +}; + +static Model g_model[MAX_RANKS]; + +static std::vector meta_list(const RadModelMeta* m, const char* key) { + std::vector v; + const char* s = rad_meta_gets(m, key, nullptr); + while (s && *s) { + char* e = nullptr; + const double x = std::strtod(s, &e); + if (e == s) { ++s; continue; } + v.push_back(x); + s = e; + } + return v; +} + +static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype, + std::initializer_list shape, int access, int group) { + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, dtype, shape, access, RAD_SHARD_NONE, grp_layer(group)); +} + +/* A bf16 linear without a bias, read whole on every rank. */ +static rad_op dense(RadBuilder* b, Names& nm, const char* dn, const char* src, int64_t N, int64_t K, + int64_t rows, rad_buf in, rad_buf out, rad_weight* w, int access, int group) { + *w = wcopy(b, nm.f("%s.weight", dn), nm.ckpt("%s.weight", src), RAD_BF16, { N, K }, access, + group); + if (!*w) return 0; + return rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(*w)), + { in }, { out }); +} + +static rad_op unary(RadBuilder* b, const char* op, int64_t rows, int64_t n, rad_buf in, + rad_buf out) { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { in }, { out }); +} + +static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf y) { + return rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a, c }, { y }); +} + +static rad_op all_reduce(RadBuilder* b, const Geom& g, rad_buf x, int64_t rows) { + if (g.world <= 1) return 0; + return rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, rows * g.n_embd), + RAD_STR("dtype", "bf16"), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + { x }, { x }); +} + +/* ================================================================== check_format */ +static int check_format(const RadModelMeta* meta) { + const char* arch = rad_meta_gets(meta, "pipeline._class_name", ""); + if (std::strncmp(arch, "Flux3", 5) != 0) { + fprintf(stderr, "radiance: flux3: the container's pipeline is '%s', not FLUX.3's\n", arch); + return RAD_E_UNSUPPORTED; + } + if (rad_meta_geti(meta, "transformer.in_channels", 128) != 128 || + rad_meta_geti(meta, "vae.latent_channels", 32) != 32) { + fprintf(stderr, "radiance: flux3: the DiT must read 128-value tokens of a 32-channel " + "VAE\n"); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* ================================================================== declare */ +/* The language model up to its last tap; a tapped layer's output goes to its 2560 columns of the + * stacked row, which context_embedder reads. */ +static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gt; + Names& nm = m.nm; + const int64_t T = kMaxText; + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(), E = g.n_embd; + const char* pre = m.te_pre.c_str(); + + RAD_ARCH_TRY(map_copy(b, nm.f("te.token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre))); + m.w_tok = decl_w(b, nm.f("te.token_embd.weight"), RAD_BF16, { g.n_vocab_all, E }, + RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); + m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, E }); + m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, E }); + RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", E, T)); + m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim }); + m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim }); + RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim, T)); + m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, E }); + m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff }); + m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff, T)); + m.b_taps = decl_b(b, nm.f("te.taps"), RAD_BF16, { T, kNTaps * E }); + m.b_tidx = decl_b(b, nm.f("te.rows"), RAD_I32, { T }); + + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", E), + RAD_INT("n_vocab", g.n_vocab_all), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0)), + RAD_WEIGHTS(m.w_tok)), + {}, { m.b_tx }); + m.op_iota = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("start", 0), + RAD_INT("step", 1)), + RAD_NOWEIGHTS), + {}, { m.b_tidx }); + const std::vector sec = meta_list(meta, "text_config.rope_scaling.mrope_section"); + char sections[48]; + if (sec.size() == 3) + std::snprintf(sections, sizeof sections, "%d %d %d", (int)sec[0], (int)sec[1], (int)sec[2]); + else + std::snprintf(sections, sizeof sections, "24 20 20"); + const int n_run = kTaps[kNTaps - 1]; + if (g.n_layer < n_run) { + fprintf(stderr, "radiance: flux3: the text encoder has %lld layers; its last tap is after " + "layer %d\n", (long long)g.n_layer, n_run); + return RAD_E_INVAL; + } + m.te.resize((size_t)n_run); + for (int l = 0; l < n_run; ++l) { + TeLayer& L = m.te[(size_t)l]; + for (int t = 0; t < kNTaps; ++t) if (kTaps[t] == l + 1) L.tap = t; + const char* lp = nm.f("%s.layers.%d", pre, l); + L.w_n1 = wcopy(b, nm.f("te.blk.%d.attn_norm.weight", l), + nm.ckpt("%s.input_layernorm.weight", lp), RAD_F32, { E }, RAD_ACCESS_PER_TOKEN, l); + L.w_n2 = wcopy(b, nm.f("te.blk.%d.ffn_norm.weight", l), + nm.ckpt("%s.post_attention_layernorm.weight", lp), RAD_F32, { E }, + RAD_ACCESS_PER_TOKEN, l); + L.w_qn = wcopy(b, nm.f("te.blk.%d.q_norm.weight", l), nm.ckpt("%s.self_attn.q_norm.weight", lp), + RAD_BF16, { g.head_dim }, RAD_ACCESS_PER_TOKEN, l); + L.w_kn = wcopy(b, nm.f("te.blk.%d.k_norm.weight", l), nm.ckpt("%s.self_attn.k_norm.weight", lp), + RAD_BF16, { g.head_dim }, RAD_ACCESS_PER_TOKEN, l); + if (!L.w_n1 || !L.w_n2 || !L.w_qn || !L.w_kn) return RAD_E_INVAL; + L.op_n1 = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(L.w_n1)), + { m.b_tx }, { m.a_th.x }); + RAD_ARCH_TRY(L.q_h.declare(b, g, m.a_th, E)); + RAD_ARCH_TRY(L.qkv.declare(b, nm, g, nm.f("te.blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, E, + RAD_SHARD_ROW, grp_layer(l), + { nm.ckpt("%s.self_attn.q_proj.weight", lp), + nm.ckpt("%s.self_attn.k_proj.weight", lp), + nm.ckpt("%s.self_attn.v_proj.weight", lp) }, + m.a_th, m.b_tkv, T, { q_dim, kv_dim, kv_dim })); + L.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", g.theta), RAD_F64("eps", g.eps), + RAD_STR("mode", "imrope"), + RAD_INT("rotary_dim", g.head_dim), + RAD_STR("sections", nm.f("%s", sections))), + RAD_WEIGHTS(L.w_qn, L.w_kn)), + { m.b_tkv }, { m.b_tkv }); + /* The padding attends to the prompt only: its keys are the prompt's (valid_cu). */ + L.op_attn = rw(b, RAD_OP(b, "attn_cross", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)g.head_dim))), + RAD_NOWEIGHTS), + { m.b_tkv }, { m.a_tattn.x }); + RAD_ARCH_TRY(L.q_attn.declare(b, g, m.a_tattn, q_dim)); + RAD_ARCH_TRY(L.o.declare(b, nm, g, nm.f("te.blk.%d.attn_output", l), E, q_dim, + RAD_SHARD_COL, grp_layer(l), + { nm.ckpt("%s.self_attn.o_proj.weight", lp) }, m.a_tattn, m.b_th2, + T)); + L.op_ar1 = all_reduce(b, g, m.b_th2, T); + L.op_add1 = add_op(b, T, E, m.b_tx, m.b_th2, m.b_tx); + L.op_n2 = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(L.w_n2)), + { m.b_tx }, { m.a_th.x }); + RAD_ARCH_TRY(L.q_h2.declare(b, g, m.a_th, E)); + RAD_ARCH_TRY(L.gate_up.declare(b, nm, g, nm.f("te.blk.%d.ffn_gate_up", l), 2 * g.n_ff, E, + RAD_SHARD_ROW, grp_layer(l), + { nm.ckpt("%s.mlp.gate_proj.weight", lp), + nm.ckpt("%s.mlp.up_proj.weight", lp) }, + m.a_th, m.b_tgu, T, { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(L.gq.declare(b, g, m.b_tgu, m.a_tffn, g.n_ff, "silu", T, true)); + RAD_ARCH_TRY(L.down.declare(b, nm, g, nm.f("te.blk.%d.ffn_down", l), E, g.n_ff, + RAD_SHARD_COL, grp_layer(l), + { nm.ckpt("%s.mlp.down_proj.weight", lp) }, m.a_tffn, m.b_th2, + T)); + L.op_ar2 = all_reduce(b, g, m.b_th2, T); + L.op_add2 = add_op(b, T, E, m.b_tx, m.b_th2, m.b_tx); + if (L.tap >= 0) + L.op_tap = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_tx, m.b_tidx, m.b_taps }, { m.b_taps }); + if (!L.op_n1 || !L.op_qkr || !L.op_attn || !L.op_add1 || !L.op_n2 || !L.op_add2 || + (L.tap >= 0 && !L.op_tap)) + return RAD_E_INVAL; + } + /* ---- context_embedder over the stacked taps, into every lane's store */ + const int64_t D = m.gd.n_embd; + m.b_ctx = decl_b(b, nm.f("ctx.out"), RAD_BF16, { T, D }); + m.op_ctx = dense(b, nm, "ctx", "transformer.context_embedder", D, kNTaps * E, T, m.b_taps, + m.b_ctx, &m.w_ctx, RAD_ACCESS_PER_REQUEST, kGrpCtx); + m.op_store_t = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_INT("stride", 2 * cond_rows()), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ctx, m.b_store }, { m.b_store }); + return m.op_embed && m.op_iota && m.op_ctx && m.op_store_t ? RAD_OK : RAD_E_INVAL; +} + +/* FLUX.2's VAE encoder for the reference pictures (and a repainted picture), its mode, the 2 x 2 + * tokens, the BatchNorm, and the reference embedder into the store. */ +static int declare_encoder(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Vae& v = m.enc; + Names& nm = m.nm; + v.nm = &nm; + v.b = b; + v.scope = "venc"; + v.down = true; + v.first_group = kGrpVaeEnc; + v.base_px = ref_tokens_max() * 256 > (int64_t)kMaxImageTokens * 256 + ? ref_tokens_max() * 256 : (int64_t)kMaxImageTokens * 256; + /* The mid-block attends over the 8x grid: four of the pass's 16x tokens a 16x token. */ + m.b_ecu = decl_b(b, nm.f("venc.cu"), RAD_I32, { 2 }); + m.op_ecu = rw(b, RAD_OP(b, "cu_repeat", RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", 4)), + RAD_NOWEIGHTS), + {}, { m.b_ecu }); + if (!m.op_ecu) return RAD_E_INVAL; + std::vector ch = meta_list(meta, "vae.block_out_channels"); + if (ch.empty()) ch = { 128, 256, 512, 512 }; + const int64_t nres = rad_meta_geti(meta, "vae.layers_per_block", 2); + const int64_t groups = rad_meta_geti(meta, "vae.norm_num_groups", 32); + const int64_t zc = rad_meta_geti(meta, "vae.latent_channels", 32); + const double eps = 1e-6; + const int64_t nb = (int64_t)ch.size(); + VImg x = v.conv(VImg{ 0, 3, 0 }, (int64_t)ch[0], 3, 1, 1, "same", "vae.encoder.conv_in"); + for (int64_t i = 0; i < nb; ++i) { + for (int64_t r = 0; r < nres; ++r) + x = v.resblock_gn(x, (int64_t)ch[(size_t)i], + nm.f("vae.encoder.down_blocks.%lld.resnets.%lld", (long long)i, + (long long)r), groups, eps); + if (i + 1 < nb) + x = v.conv(x, x.ch, 3, 2, 1, "down", + nm.f("vae.encoder.down_blocks.%lld.downsamplers.0.conv", (long long)i)); + } + x = v.resblock_gn(x, x.ch, "vae.encoder.mid_block.resnets.0", groups, eps); + x = v.attention_gn(x, "vae.encoder.mid_block.attentions.0", groups, eps); + x = v.resblock_gn(x, x.ch, "vae.encoder.mid_block.resnets.1", groups, eps); + x = v.gnorm(x, true, "vae.encoder.conv_norm_out", groups, eps); + x = v.conv(x, 2 * zc, 3, 1, 1, "same", "vae.encoder.conv_out"); + m.enc_q = v.conv(x, 2 * zc, 1, 1, 1, "same", "vae.quant_conv"); + if (!m.enc_q.buf) return RAD_E_INVAL; + RAD_ARCH_TRY(v.attn_reads(m.b_ecu)); + /* The mode (the first zc channels) as a dense image, its 2 x 2 tokens (s2d_avg_add over one + * value a group is a plain space-to-depth into c 4 + 2 i + j), then the BatchNorm. */ + const int64_t px8 = v.px_at(m.enc_q.lvl), tok = (px8 + 3) / 4; + m.b_emode = decl_b(b, nm.f("venc.mode"), RAD_BF16, { px8, zc }); + m.b_epack = decl_b(b, nm.f("venc.pack"), RAD_BF16, { tok, 4 * zc }); + m.b_elat = decl_b(b, nm.f("venc.lat"), RAD_BF16, { tok, 4 * zc }); + m.b_eemb = decl_b(b, nm.f("venc.emb"), RAD_BF16, { tok, m.gd.n_embd }); + std::string ones, zeros; + for (int64_t k = 0; k < zc; ++k) { ones += k ? " 1" : "1"; zeros += k ? " 0" : "0"; } + static thread_local std::string s_ones, s_zeros; + s_ones = ones; + s_zeros = zeros; + m.op_enc_mode = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, px8), RAD_INT("n", zc), + RAD_STR("mul", s_ones.c_str()), + RAD_STR("add", s_zeros.c_str()), RAD_STR("mode", "fma"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.enc_q.buf }, { m.b_emode }); + m.op_enc_zero = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, tok), RAD_INT("n", 4 * zc), + RAD_STR("dtype", "bf16"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_epack }); + m.op_enc_s2d = rw(b, RAD_OP(b, "s2d_avg_add", + RAD_PARAMS(RAD_RANGE("M", 1, tok), RAD_INT("cin", zc), + RAD_INT("cout", 4 * zc), RAD_INT("ft", 1), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_emode, m.b_epack }, { m.b_epack }); + m.w_bnm = wcopy(b, nm.f("vae.bn.mean"), nm.ckpt("vae.bn.running_mean"), RAD_BF16, { 4 * zc }, + RAD_ACCESS_PER_REQUEST, kGrpVaeEnc); + m.w_bnv = wcopy(b, nm.f("vae.bn.var"), nm.ckpt("vae.bn.running_var"), RAD_BF16, { 4 * zc }, + RAD_ACCESS_PER_REQUEST, kGrpVaeEnc); + m.bn_eps = rad_meta_getf(meta, "vae.batch_norm_eps", 1e-4); + m.op_enc_bn = rw(b, RAD_OP(b, "chan_stats", + RAD_PARAMS(RAD_RANGE("M", 1, tok), RAD_INT("n", 4 * zc), + RAD_STR("mode", "norm"), RAD_INT("var", 1), + RAD_F64("eps", m.bn_eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_bnm, m.w_bnv)), + { m.b_epack }, { m.b_elat }); + /* A reference's tokens through its embedder into the store after the text; a repainted + * picture's into its lanes with the mask. */ + m.op_xc = dense(b, nm, "dit.x_cond", "transformer.x_embedders.image_cond", m.gd.n_embd, 4 * zc, + tok, m.b_elat, m.b_eemb, &m.w_xc, RAD_ACCESS_PER_REQUEST, kGrpDit); + m.op_store_r = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, tok), RAD_INT("n", m.gd.n_embd), + RAD_INT("stride", 2 * cond_rows()), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_eemb, m.b_store }, { m.b_store }); + m.op_lstore_lat = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxImageTokens), + RAD_INT("n", 4 * zc), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_elat, m.b_inp }, { m.b_inp }); + m.op_lstore_mask = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxImageTokens), + RAD_INT("n", 1), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_mask }, { m.b_mask }); + return m.op_enc_mode && m.op_enc_zero && m.op_enc_s2d && m.w_bnm && m.w_bnv && m.op_enc_bn && + m.op_xc && m.op_store_r && m.op_lstore_lat && m.op_lstore_mask + ? RAD_OK : RAD_E_INVAL; +} + +/* One parallel block's weights and ops over at most `rows` rows. `gated`: the norm adds the + * previous block's gated sum first. */ +static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, const char* dn, + int grp, int64_t rows, bool gated, const char* sections, rad_buf mod) { + Geom& g = m.gd; + Names& nm = m.nm; + const int64_t D = g.n_embd, qd = g.q_dim(), hd = g.head_dim; + const double eps = g.eps; + B.w_qn = wcopy(b, nm.f("%s.q_norm.weight", dn), nm.ckpt("%s.attn.norm_q.weight", pre), RAD_F32, + { hd }, RAD_ACCESS_PER_TOKEN, grp); + B.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), nm.ckpt("%s.attn.norm_k.weight", pre), RAD_F32, + { hd }, RAD_ACCESS_PER_TOKEN, grp); + if (!B.w_qn || !B.w_kn) return RAD_E_INVAL; + const bool q = !g.w_bf16; + auto norm = [&](bool gt) { + rad_op op = q ? RAD_OP(b, "rms_mod_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", D), + RAD_F64("eps", eps), RAD_INT("group", RAD_FP8_BLOCK), + RAD_INT("gated", gt ? 1 : 0), RAD_STR("dtype", "bf16"), + RAD_STR("norm", "layer")), + RAD_NOWEIGHTS) + : RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", D), + RAD_F64("eps", eps), RAD_INT("gated", gt ? 1 : 0), + RAD_STR("dtype", "bf16"), RAD_STR("norm", "layer")), + RAD_NOWEIGHTS); + if (!op) return op; + /* The residual, the modulation table and, gated, the branch sum. */ + rad_buf rd[4] = { m.b_xc, m.b_h, mod, m.b_sum }; + rad_buf wq[3] = { m.a_hm.q, m.a_hm.s, m.b_h }; + rad_buf wb[2] = { m.a_hm.x, m.b_h }; + rad_op_reads(b, op, rd, gt ? 4 : 3); + if (q) rad_op_writes(b, op, wq, 3); + else rad_op_writes(b, op, wb, 2); + return op; + }; + B.op_n = norm(gated); + RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), 3 * qd, D, RAD_SHARD_ROW, + grp_layer(grp), + { nm.ckpt("%s.attn.to_q.weight", pre), + nm.ckpt("%s.attn.to_k.weight", pre), + nm.ckpt("%s.attn.to_v.weight", pre) }, + m.a_hm, m.b_qkv, rows, { qd, qd, qd })); + B.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", hd), + RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head), + RAD_F64("theta", g.theta), RAD_F64("eps", eps), + RAD_STR("mode", "gptj_blocks"), RAD_INT("rotary_dim", hd), + RAD_STR("sections", sections)), + RAD_WEIGHTS(B.w_qn, B.w_kn)), + { m.b_qkv }, { m.b_qkv }); + B.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd))), + RAD_NOWEIGHTS), + { m.b_qkv }, { m.a_attn.x }); + RAD_ARCH_TRY(B.q_attn.declare(b, g, m.a_attn, qd)); + RAD_ARCH_TRY(B.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_COL, + grp_layer(grp), { nm.ckpt("%s.attn.to_out.0.weight", pre) }, m.a_attn, + m.b_o, rows)); + RAD_ARCH_TRY(B.ff_in.declare(b, nm, g, nm.f("%s.ffn_in", dn), 2 * g.n_ff, D, RAD_SHARD_ROW, + grp_layer(grp), { nm.ckpt("%s.ff.linear_in.weight", pre) }, m.a_hm, + m.b_gu, rows, { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(B.gq.declare(b, g, m.b_gu, m.a_ffn, g.n_ff, "silu", rows, true)); + RAD_ARCH_TRY(B.ff_out.declare(b, nm, g, nm.f("%s.ffn_out", dn), D, g.n_ff, RAD_SHARD_COL, + grp_layer(grp), { nm.ckpt("%s.ff.linear_out.weight", pre) }, + m.a_ffn, m.b_f, rows)); + B.op_sum = add_op(b, rows, D, m.b_o, m.b_f, m.b_sum); + B.op_ar = all_reduce(b, g, m.b_sum, rows); + return B.op_n && B.op_qkr && B.op_attn && B.op_sum ? RAD_OK : RAD_E_INVAL; +} + +static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gd; + Names& nm = m.nm; + const int64_t T = g.max_tok, S = g.max_seqs, D = g.n_embd, C = m.C; + const int gx = kGrpDit; + const int64_t NI = std::min(T, 2 * (int64_t)kMaxImageTokens); + const int64_t te = rad_meta_geti(meta, "transformer.timestep_channels", 256); + m.t_ch = te; + + /* ---- timestep embeddings, the MLP over 2 S rows at once: rows [0, S) the image's time, rows + * [S, 2 S) time 0's, whose sinusoid is [cos 0 | sin 0], ones then zeros. With a flow map the + * target time's embedding is added to both halves. silu of each half feeds the modulations. + * Every op is issued once a step: an op issued again over other buffers would outrun the + * arena's plan, which orders buffers by declaration. */ + m.b_tp = decl_b(b, nm.f("dit.tp"), RAD_BF16, { 2 * S, te }); + m.b_e1 = decl_b(b, nm.f("dit.e1"), RAD_BF16, { 2 * S, D }); + m.b_e1s = decl_b(b, nm.f("dit.e1s"), RAD_BF16, { 2 * S, D }); + m.b_temb = decl_b(b, nm.f("dit.temb"), RAD_BF16, { 2 * S, D }); + m.b_aimg = decl_b(b, nm.f("dit.a_img"), RAD_BF16, { S, D }); + m.b_azero = decl_b(b, nm.f("dit.a_zero"), RAD_BF16, { S, D }); + auto tstep = [&](rad_buf out) { + return rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", te), + RAD_F64("scale", 1000.0), RAD_F64("max_period", 10000.0), + RAD_INT("round", 3), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { out }); + }; + m.op_tp = tstep(m.b_tp); + auto fill = [&](double v) { + return rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", te / 2), + RAD_STR("dtype", "bf16"), RAD_F64("value", v)), + RAD_NOWEIGHTS), + {}, { m.b_tp }); + }; + m.op_one = fill(1.0); + m.op_zero = fill(0.0); + m.op_t1 = dense(b, nm, "dit.t1", "transformer.timestep_embedder.linear_1", D, te, 2 * S, + m.b_tp, m.b_e1, &m.w_t1, RAD_ACCESS_PER_TOKEN, gx); + m.op_ts = unary(b, "silu", 2 * S, D, m.b_e1, m.b_e1s); + m.op_t2 = dense(b, nm, "dit.t2", "transformer.timestep_embedder.linear_2", D, D, 2 * S, m.b_e1s, + m.b_temb, &m.w_t2, RAD_ACCESS_PER_TOKEN, gx); + if (m.flow_map) { + m.b_tpt = decl_b(b, nm.f("dit.tp_tgt"), RAD_BF16, { S, te }); + m.b_tt1 = decl_b(b, nm.f("dit.tt1"), RAD_BF16, { S, D }); + m.b_tt1s = decl_b(b, nm.f("dit.tt1s"), RAD_BF16, { S, D }); + m.b_ttgt = decl_b(b, nm.f("dit.t_tgt"), RAD_BF16, { S, D }); + m.op_tpt = tstep(m.b_tpt); + m.op_tt1 = dense(b, nm, "dit.tt1", "transformer.target_timestep_embedder.linear_1", D, te, + S, m.b_tpt, m.b_tt1, &m.w_tt1, RAD_ACCESS_PER_TOKEN, gx); + m.op_tts = unary(b, "silu", S, D, m.b_tt1, m.b_tt1s); + m.op_tt2 = dense(b, nm, "dit.tt2", "transformer.target_timestep_embedder.linear_2", D, D, + S, m.b_tt1s, m.b_ttgt, &m.w_tt2, RAD_ACCESS_PER_TOKEN, gx); + /* Issued on each half of the same buffers. */ + m.op_addt = add_op(b, S, D, m.b_temb, m.b_ttgt, m.b_temb); + if (!m.op_tpt || !m.op_tt1 || !m.op_tts || !m.op_tt2 || !m.op_addt) return RAD_E_INVAL; + } + m.op_actimg = unary(b, "silu", S, D, m.b_temb, m.b_aimg); + m.op_actzero = unary(b, "silu", S, D, m.b_temb, m.b_azero); + if (!m.op_tp || !m.op_one || !m.op_zero || !m.op_t1 || !m.op_ts || !m.op_t2 || !m.op_actimg || + !m.op_actzero) + return RAD_E_INVAL; + + /* ---- every mode's modulations: the early ones by mode (each mode's blocks find an entry's + * row by their own cu), the joint ones interleaved as [3 S, 3 D], entry e's mode k at row + * 3 e + k (the joint blocks find a row's segment by mode_cu) */ + static const char* kModeName[3] = { "txt", "image_cond", "image" }; + m.b_idx3 = decl_b(b, nm.f("dit.idx3"), RAD_I32, { S }); + m.op_iota3 = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("start", 0), RAD_INT("step", 3)), + RAD_NOWEIGHTS), + {}, { m.b_idx3 }); + m.b_single = decl_b(b, nm.f("dit.mod_single"), RAD_BF16, { 3 * S, 3 * D }); + for (int k = 0; k < 3; ++k) { + const rad_buf act = k == kImage ? m.b_aimg : m.b_azero; + m.b_early[k] = decl_b(b, nm.f("dit.mod_early.%d", k), RAD_BF16, { S, 3 * D }); + m.b_smod[k] = decl_b(b, nm.f("dit.mod_s.%d", k), RAD_BF16, { S, 3 * D }); + m.op_early[k] = dense(b, nm, nm.f("dit.early.%s", kModeName[k]), + nm.ckpt("transformer.early_stream_modulations.%s.linear", kModeName[k]), + 3 * D, D, S, act, m.b_early[k], &m.w_early[k], RAD_ACCESS_PER_TOKEN, gx); + m.op_single[k] = dense(b, nm, nm.f("dit.single.%s", kModeName[k]), + nm.ckpt("transformer.single_stream_modulations.%s.linear", + kModeName[k]), + 3 * D, D, S, act, m.b_smod[k], &m.w_single[k], RAD_ACCESS_PER_TOKEN, + gx); + m.op_ilv[k] = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", 3 * D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_smod[k], m.b_idx3, m.b_single }, { m.b_single }); + if (!m.op_early[k] || !m.op_single[k] || !m.op_ilv[k]) return RAD_E_INVAL; + } + /* The output layer's (scale, shift) from silu(image temb), reordered to (shift, scale). */ + { + const char* src = nm.ckpt("transformer.norm_out.linear.weight"); + RAD_ARCH_TRY(map_rows(b, nm.f("dit.norm_out.weight"), { { src, (int)D, D }, { src, 0, D } })); + m.w_fmod = decl_w(b, nm.f("dit.norm_out.weight"), RAD_BF16, { 2 * D, D }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(gx)); + m.b_fmod = decl_b(b, nm.f("dit.mod_out"), RAD_BF16, { S, 2 * D }); + m.op_fmod = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", 2 * D), + RAD_INT("K", D), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_fmod)), + { m.b_aimg }, { m.b_fmod }); + if (!m.w_fmod || !m.op_fmod) return RAD_E_INVAL; + } + + /* ---- the rows: the image's latents through its embedder, the store's text and pictures, + * all mode-major in `xc` (text, pictures, image), then joined entry by entry into `h` */ + m.b_lat = decl_b(b, nm.f("dit.lat"), RAD_BF16, { NI, C }); + m.b_xc = decl_b(b, nm.f("dit.xc"), RAD_BF16, { T, D }); + m.b_h = decl_b(b, nm.f("dit.h"), RAD_BF16, { T, D }); + m.op_randn = rw(b, RAD_OP(b, "randn_lanes", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state }, { m.b_state }); + m.op_lgather = rw(b, RAD_OP(b, "lane_gather", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state }, { m.b_lat }); + m.op_xi = dense(b, nm, "dit.x_img", "transformer.x_embedders.image", D, C, NI, m.b_lat, m.b_xc, + &m.w_xi, RAD_ACCESS_PER_TOKEN, gx); + m.op_gtxt = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_store }, { m.b_xc }); + if (!m.op_randn || !m.op_lgather || !m.op_xi || !m.op_gtxt) return RAD_E_INVAL; + + /* ---- the blocks' buffers */ + const int64_t qd = g.q_dim(); + m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D }); + RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D)); + m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, 3 * qd }); + m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd }); + RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd)); + m.b_o = decl_b(b, nm.f("dit.o"), RAD_BF16, { T, D }); + m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff }); + m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff)); + m.b_f = decl_b(b, nm.f("dit.f"), RAD_BF16, { T, D }); + m.b_sum = decl_b(b, nm.f("dit.sum"), RAD_BF16, { T, D }); + + const std::vector ax = meta_list(meta, "transformer.axes_dims_rope"); + if (!ax.empty() && (ax.size() != 4 || (int64_t)(ax[0] + ax[1] + ax[2] + ax[3]) != g.head_dim)) { + fprintf(stderr, "radiance: flux3: transformer.axes_dims_rope must be four widths summing " + "to the head\n"); + return RAD_E_INVAL; + } + const char* sections = ax.empty() ? "16 16 16 16" + : nm.f("%d %d %d %d", (int)ax[0] / 2, (int)ax[1] / 2, + (int)ax[2] / 2, (int)ax[3] / 2); + + /* The early blocks, five a mode, then the joint blocks; the ops are declared in issue + * order: text, pictures, image, joint. */ + const int64_t nl = rad_meta_geti(meta, "transformer.num_layers", 5); + const int64_t ns = rad_meta_geti(meta, "transformer.num_single_layers", 28); + int grp = kGrpDit + 1; + for (int k = 0; k < 3; ++k) { + m.mode[k].resize((size_t)nl); + for (int64_t i = 0; i < nl; ++i) { + const char* pre = k == kText + ? nm.ckpt("transformer.txt_mode_blocks.%d", (int)i) + : nm.ckpt("transformer.mode_blocks.%s.%d", kModeName[k], (int)i); + RAD_ARCH_TRY(declare_block(b, m, m.mode[k][(size_t)i], pre, + nm.f("dit.mode.%d.%d", k, (int)i), grp++, T, i > 0, + sections, m.b_early[k])); + } + } + /* The early stacks' last sums gated in where each mode's rows lie in the mode-major order, + * then the rows joined. */ + m.op_g2 = rw(b, RAD_OP(b, "gate_add", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16"), RAD_STR("act", "none")), + RAD_NOWEIGHTS), + { m.b_sum, m.b_early[0], m.b_early[1], m.b_early[2], m.b_xc }, { m.b_xc }); + m.op_join = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_xc, m.b_h }, { m.b_h }); + m.single.resize((size_t)ns); + for (int64_t i = 0; i < ns; ++i) + RAD_ARCH_TRY(declare_block(b, m, m.single[(size_t)i], + nm.ckpt("transformer.single_transformer_blocks.%d", (int)i), + nm.f("dit.single.%d", (int)i), grp++, T, i > 0, sections, + m.b_single)); + /* The joint stack's last sum gated in. */ + m.op_g3 = rw(b, RAD_OP(b, "gate_add", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16"), RAD_STR("act", "none")), + RAD_NOWEIGHTS), + { m.b_sum, m.b_single, m.b_h }, { m.b_h }); + if (!m.op_g3) return RAD_E_INVAL; + + /* ---- the output: the image rows, the final adaptive LayerNorm, proj_out, the step */ + m.b_hi = decl_b(b, nm.f("dit.h_img"), RAD_BF16, { NI, D }); + m.b_fz = decl_b(b, nm.f("dit.fz"), RAD_BF16, { NI, D }); + m.b_v = decl_b(b, nm.f("dit.v"), RAD_BF16, { NI, C }); + m.op_gimg = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_h }, { m.b_hi }); + m.op_nout = rw(b, RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", D), RAD_F64("eps", g.eps), + RAD_INT("gated", 0), RAD_STR("dtype", "bf16"), + RAD_STR("norm", "layer")), + RAD_NOWEIGHTS), + { m.b_fmod, m.b_hi }, { m.b_hi, m.b_fz }); + m.op_pout = dense(b, nm, "dit.proj_out", "transformer.proj_out", C, D, NI, m.b_fz, m.b_v, + &m.w_pout, RAD_ACCESS_PER_TOKEN, gx); + m.op_euler = rw(b, RAD_OP(b, "flow_euler", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_v, m.b_inp, m.b_mask, m.b_state, m.b_prev }, { m.b_state, m.b_prev }); + return m.op_g2 && m.op_join && m.op_gimg && m.op_nout && m.op_pout && m.op_euler + ? RAD_OK : RAD_E_INVAL; +} + +/* FLUX.2's VAE decoder: the latent denormalised by the BatchNorm, unpacked to 32 channels, then + * GroupNorm residual blocks, the mid-block attention and nearest-neighbour upsampling, run whole + * on every rank. */ +static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Vae& v = m.dec; + Names& nm = m.nm; + v.nm = &nm; + v.b = b; + v.scope = "vdec"; + v.down = false; + v.first_group = kGrpVaeDec; + v.base_px = (int64_t)kMaxImageTokens * 4; + std::vector ch = meta_list(meta, "vae.decoder_block_out_channels"); + if (ch.empty()) ch = meta_list(meta, "vae.block_out_channels"); + if (ch.empty()) ch = { 128, 256, 512, 512 }; + const int64_t nres = rad_meta_geti(meta, "vae.layers_per_block", 2); + const int64_t groups = rad_meta_geti(meta, "vae.norm_num_groups", 32); + const int64_t zc = rad_meta_geti(meta, "vae.latent_channels", 32); + const double eps = 1e-6; + const int64_t NT = kMaxImageTokens; + m.b_dl = decl_b(b, nm.f("vdec.lat"), RAD_BF16, { NT, 4 * zc }); + m.b_decin = decl_b(b, nm.f("vdec.in"), RAD_BF16, { 4 * NT, zc }); + m.b_cu4 = decl_b(b, nm.f("vdec.cu"), RAD_I32, { 2 }); + m.op_dbn = rw(b, RAD_OP(b, "chan_stats", + RAD_PARAMS(RAD_RANGE("M", 1, NT), RAD_INT("n", 4 * zc), + RAD_STR("mode", "denorm"), RAD_INT("var", 1), + RAD_F64("eps", m.bn_eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_bnm, m.w_bnv)), + { m.b_state, m.b_prev }, { m.b_dl }); + m.op_dzero = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 4 * NT), RAD_INT("n", zc), + RAD_STR("dtype", "bf16"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_decin }); + m.op_unpack = rw(b, RAD_OP(b, "d2s_add", + RAD_PARAMS(RAD_RANGE("M", 1, 4 * NT), RAD_INT("cin", 4 * zc), + RAD_INT("cout", zc), RAD_INT("ft", 1), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_dl, m.b_decin }, { m.b_decin }); + m.op_cu4 = rw(b, RAD_OP(b, "cu_repeat", RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", 4)), + RAD_NOWEIGHTS), + {}, { m.b_cu4 }); + if (!m.op_dbn || !m.op_dzero || !m.op_unpack || !m.op_cu4) return RAD_E_INVAL; + const std::vector rch(ch.rbegin(), ch.rend()); + VImg x{ m.b_decin, zc, 0 }; + if (rad_meta_geti(meta, "vae.use_post_quant_conv", 1)) + x = v.conv(x, zc, 1, 1, 1, "same", "vae.post_quant_conv"); + x = v.conv(x, (int64_t)rch[0], 3, 1, 1, "same", "vae.decoder.conv_in"); + x = v.resblock_gn(x, x.ch, "vae.decoder.mid_block.resnets.0", groups, eps); + x = v.attention_gn(x, "vae.decoder.mid_block.attentions.0", groups, eps); + x = v.resblock_gn(x, x.ch, "vae.decoder.mid_block.resnets.1", groups, eps); + for (size_t i = 0; i < rch.size(); ++i) { + for (int64_t r = 0; r < nres + 1; ++r) + x = v.resblock_gn(x, (int64_t)rch[i], + nm.f("vae.decoder.up_blocks.%d.resnets.%d", (int)i, (int)r), groups, + eps); + if (i + 1 < rch.size()) + x = v.conv(x, x.ch, 3, 1, 2, "same", nm.f("vae.decoder.up_blocks.%d.upsamplers.0.conv", + (int)i)); + } + x = v.gnorm(x, true, "vae.decoder.conv_norm_out", groups, eps); + m.dec_out = v.conv(x, 3, 3, 1, 1, "same", "vae.decoder.conv_out"); + if (!m.dec_out.buf) return RAD_E_INVAL; + RAD_ARCH_TRY(v.attn_reads(m.b_cu4)); + const int64_t px = (int64_t)kMaxImageTokens * 256; + m.b_img = decl_b(b, nm.f("image_out"), RAD_U8, { px * 3 }, RAD_BUF_PERSIST); + m.op_rgb = rw(b, RAD_OP(b, "to_rgba8", + RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("n", 3), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.dec_out.buf }, { m.b_img }); + return m.op_rgb ? RAD_OK : RAD_E_INVAL; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(check_format(meta)); + RAD_ARCH_TRY(geom_from(m.gt, meta, ctx, "bf16", RAD_BF16)); + Names& nm = m.nm; + m.te_pre = std::strstr(rad_meta_gets(meta, "architectures", ""), "ForConditionalGeneration") + ? "model.language_model" : "language_model"; + m.flow_map = rad_meta_geti(meta, "transformer.flow_map", 0) != 0; + + Geom& gd = m.gd; + gd = m.gt; + gd.head_dim = rad_meta_geti(meta, "transformer.attention_head_dim", 128); + gd.n_head_all = rad_meta_geti(meta, "transformer.num_attention_heads", 24); + gd.n_head_kv_all = gd.n_head_all; + gd.n_embd = gd.head_dim * gd.n_head_all; + gd.n_ff_all = (int64_t)(gd.n_embd * rad_meta_getf(meta, "transformer.mlp_ratio", 3.0)); + gd.eps = (float)rad_meta_getf(meta, "transformer.eps", 1e-6); + gd.theta = (float)rad_meta_getf(meta, "transformer.rope_theta", 10000.0); + gd.n_layer = rad_meta_geti(meta, "transformer.num_single_layers", 28); + RAD_ARCH_TRY(divide_or_fail(gd.n_head_all, gd.world, "transformer.num_attention_heads", + &gd.n_head)); + gd.n_head_kv = gd.n_head; + gd.kv_off = 0; + RAD_ARCH_TRY(divide_or_fail(gd.n_ff_all, gd.world, "the DiT's feed-forward width", &gd.n_ff)); + if (m.gt.n_embd * kNTaps != rad_meta_geti(meta, "transformer.joint_attention_dim", 20480)) { + fprintf(stderr, "radiance: flux3: the DiT reads %lld-wide conditioning and %d taps of the " + "text encoder are %lld\n", + (long long)rad_meta_geti(meta, "transformer.joint_attention_dim", 0), kNTaps, + (long long)(m.gt.n_embd * kNTaps)); + return RAD_E_INVAL; + } + m.C = rad_meta_geti(meta, "transformer.in_channels", 128); + { + LinearFP8& probe = m.qkv0; + RAD_ARCH_TRY(probe.probe(b, nm, gd, "dit.single.0.attn_qkv", + { "transformer.single_transformer_blocks.0.attn.to_q.weight", + "transformer.single_transformer_blocks.0.attn.to_k.weight", + "transformer.single_transformer_blocks.0.attn.to_v.weight" })); + RadEncoding e{}; + const bool plain = weight_enc(b, nm.f("dit.single.0.attn_qkv.weight"), &e) && + rad_enc_is(&e, "plain"); + gd.w_bf16 = m.gt.w_bf16 = plain; + } + + const int64_t lane_rows = (int64_t)kMaxLanes * kMaxImageTokens; + m.b_state = decl_b(b, nm.f("lat_state"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST); + m.b_prev = decl_b(b, nm.f("lat_preview"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST); + m.b_inp = decl_b(b, nm.f("lat_repaint"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST); + m.b_mask = decl_b(b, nm.f("lat_mask"), RAD_F32, { lane_rows, 1 }, RAD_BUF_PERSIST); + m.b_store = decl_b(b, nm.f("cond_store"), RAD_BF16, + { 2 * (int64_t)kMaxLanes * cond_rows(), gd.n_embd }, RAD_BUF_PERSIST); + RAD_ARCH_TRY(declare_te(b, meta, m)); + RAD_ARCH_TRY(declare_encoder(b, meta, m)); + RAD_ARCH_TRY(declare_dit(b, meta, m)); + RAD_ARCH_TRY(declare_decoder(b, meta, m)); + + if (!ctx->shape_probe) { + RadGeneratorDecl d{}; + d.name = m.flow_map ? "flux-3-image-klein" : "flux-3-image-klein-base"; + d.layout = RAD_GEN_LAYOUT_JOINT_STEP; + d.tmpl_text = "<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"; + d.tmpl_edit = d.tmpl_text; + d.drop_prefix = ""; + d.latent_channels = m.C; + d.latent_scale = 16; + d.size_multiple = 16; + d.pixel_channels = 3; + d.slot_rows = 1; + d.max_tokens = kMaxImageTokens; + d.max_refs = kMaxRefs; + d.ref_area = kRefArea; + d.ref_shrink_only = 1; + d.default_width = 1024; + d.default_height = 1024; + d.default_steps = m.flow_map ? 16 : 50; + d.shift = rad_meta_getf(meta, "scheduler.shift", 6.93); + d.dyn_shift = (int32_t)rad_meta_geti(meta, "scheduler.use_dynamic_shifting", 0); + d.shift_exp = std::strcmp(rad_meta_gets(meta, "scheduler.time_shift_type", "exponential"), + "exponential") == 0; + d.base_shift = rad_meta_getf(meta, "scheduler.base_shift", 0.5); + d.max_shift = rad_meta_getf(meta, "scheduler.max_shift", 1.15); + d.base_seq = rad_meta_geti(meta, "scheduler.base_image_seq_len", 256); + d.max_seq = rad_meta_geti(meta, "scheduler.max_image_seq_len", 4096); + d.shift_terminal = rad_meta_getf(meta, "scheduler.shift_terminal", 0.0); + d.default_cfg = m.flow_map ? 1.0 : 3.5; + d.default_negative = ""; + d.max_lanes = kMaxLanes; + d.image_out = m.b_img; + d.cond_rows = cond_rows(); + d.rope_hw_scale = 0.5; + d.rope_text_l = 1; + d.pad_multiple = kPadMultiple; + d.pad_token = (int32_t)rad_meta_geti(meta, "pad_token_id", + rad_meta_geti(meta, "text_config.pad_token_id", 151643)); + RAD_ARCH_TRY(rad_declare_generator(b, &d)); + } + rad_note(b, "rank %d/%d: FLUX.3 [klein]%s -- text encoder %d of %lld layers, DiT %zu x 3 early " + "+ %zu joint blocks (%lld heads a rank, ff %lld), %s linears", + m.gt.rank, m.gt.world, m.flow_map ? " (flow map)" : " base", kTaps[kNTaps - 1], + (long long)m.gt.n_layer, m.mode[0].size(), m.single.size(), (long long)gd.n_head, + (long long)gd.n_ff, gd.w_bf16 ? "bf16" : "block-fp8"); + return RAD_OK; +} + +/* ================================================================== step */ +static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) { + const Geom& g = m.gt; + const RadGenBatch* G = batch->gen_b; + const int64_t T = batch->n_tok, E = g.n_embd; + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), + brows(m.b_tx, T)); + RAD_ISSUE_N(c, m.op_iota, T, brows(m.b_tidx, T)); + const RadOperand pos = praw2(batch->rope_pos, RAD_I32, 3, T); + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, 2); + const RadOperand cuk = praw(G->valid_cu, RAD_I32, 2); + for (const TeLayer& L : m.te) { + RAD_ISSUE_N(c, L.op_n1, T, brows(m.b_tx, T), RAD_W(L.w_n1), brows(m.a_th.x, T)); + L.q_h.step(c, T); + L.qkv.step(c, m.a_th, m.b_tkv, T); + RAD_ISSUE_N(c, L.op_qkr, T, brows(m.b_tkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn)); + RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_tkv, 0, q_dim, T), bcol(m.b_tkv, q_dim, kv_dim, T), + bcol(m.b_tkv, q_dim + kv_dim, kv_dim, T), cu, cuk, brows(m.a_tattn.x, T)); + L.q_attn.step(c, T); + L.o.step(c, m.a_tattn, m.b_th2, T); + if (L.op_ar1) RAD_ISSUE_N(c, L.op_ar1, T * E, brows(m.b_th2, T), RAD_NONE); + RAD_ISSUE_N(c, L.op_add1, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + RAD_ISSUE_N(c, L.op_n2, T, brows(m.b_tx, T), RAD_W(L.w_n2), brows(m.a_th.x, T)); + L.q_h2.step(c, T); + L.gate_up.step(c, m.a_th, m.b_tgu, T); + L.gq.step(c, m.b_tgu, T); + L.down.step(c, m.a_tffn, m.b_th2, T); + if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, T * E, brows(m.b_th2, T), RAD_NONE); + RAD_ISSUE_N(c, L.op_add2, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + if (L.tap >= 0) + RAD_ISSUE_N(c, L.op_tap, T, brows(m.b_tx, T), brows(m.b_tidx, T), + bcol(m.b_taps, L.tap * E, E, T)); + } +} + +/* One picture through the encoder to its normalised tokens in `elat` (n tokens). */ +static int64_t step_encode(RadCtx* c, const Model& m, const uint16_t* px, int64_t h, int64_t w, + const int32_t* px_cu) { + RAD_ISSUE_N(c, m.op_ecu, 2, praw(px_cu + 1, RAD_I32, 1), brows(m.b_ecu, 2)); + m.enc.issue(c, h, w, brows(m.b_ecu, 2), px); + const int64_t h8 = h / 8, w8 = w / 8, n8 = h8 * w8, n = n8 / 4, zc = m.C / 4; + RAD_ISSUE_N(c, m.op_enc_mode, n8, bcol(m.enc_q.buf, 0, zc, n8), brows(m.b_emode, n8)); + RAD_ISSUE_N(c, m.op_enc_zero, n, brows(m.b_epack, n)); + RAD_ISSUE_N(c, m.op_enc_s2d, n, RAD_P_T2(rad_buf_ptr(c, m.b_emode), RAD_BF16, h8, w8 * zc), + RAD_P_T2(rad_buf_ptr(c, m.b_epack), RAD_BF16, h8 / 2, (w8 / 2) * m.C)); + RAD_ISSUE_N(c, m.op_enc_bn, n, brows(m.b_epack, n), RAD_W(m.w_bnm), RAD_W(m.w_bnv), + brows(m.b_elat, n)); + return n; +} + +/* The conditioning: the text through the language model and context_embedder, each reference + * picture through the encoder and its embedder, all into every lane's store at this branch; a + * repainted picture's tokens and its mask into the lanes. */ +static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t T = batch->n_tok, D = m.gd.n_embd; + const int64_t base = (int64_t)G->branch * cond_rows(); + const int64_t store_rows = 2 * (int64_t)kMaxLanes * cond_rows(); + const RadOperand lanes = praw(G->lane, RAD_I32, G->n_lane); + step_te(c, batch, m); + RAD_ISSUE_N(c, m.op_ctx, T, brows(m.b_taps, T), RAD_W(m.w_ctx), brows(m.b_ctx, T)); + RAD_ISSUE_N(c, m.op_store_t, T, brows(m.b_ctx, T), lanes, + brow_slice(m.b_store, base, store_rows - base, D)); + int64_t row = T; + const int64_t n_ref = G->n_px - (G->inpaint ? 1 : 0); + for (int64_t i = 0; i < G->n_px; ++i) { + const int32_t off = G->px_h[3 * i], ph = G->px_h[3 * i + 1], pw = G->px_h[3 * i + 2]; + const uint16_t* px = (const uint16_t*)G->px + (int64_t)off * 3; + const int64_t n = step_encode(c, m, px, ph, pw, G->px_cu + 2 * i); + if (i < n_ref) { + RAD_ISSUE_N(c, m.op_xc, n, brows(m.b_elat, n), RAD_W(m.w_xc), brows(m.b_eemb, n)); + RAD_ISSUE_N(c, m.op_store_r, n, brows(m.b_eemb, n), lanes, + brow_slice(m.b_store, base + row, store_rows - base - row, D)); + row += n; + } else { + const int64_t L = (int64_t)kMaxLanes * kMaxImageTokens; + RAD_ISSUE_N(c, m.op_lstore_lat, n, brows(m.b_elat, n), lanes, brows(m.b_inp, L)); + RAD_ISSUE_N(c, m.op_lstore_mask, n, praw2(G->inp_mask, RAD_F32, n, 1), lanes, + brows(m.b_mask, L)); + } + } +} + +/* A stack of parallel blocks over `R` rows of `x` from row `r0`: `acu` bounds the attention, + * `mcu` the modulation's segments, `s` the [shift | scale] rows and `gt` the gate rows. */ +static void step_blocks(RadCtx* c, const Model& m, const std::vector& stack, rad_buf x, + int64_t r0, int64_t R, const RadOperand& acu, const RadOperand& mcu, + const RadOperand& s, const RadOperand& gt, const RadOperand& pos) { + const Geom& g = m.gd; + const int64_t D = g.n_embd, qd = g.q_dim(), nD = D / RAD_FP8_BLOCK; + const bool q8 = !g.w_bf16; + const RadOperand xv = brow_slice(x, r0, R, D); + for (size_t i = 0; i < stack.size(); ++i) { + const Block& B = stack[i]; + const bool gated = i > 0; + if (q8) + RAD_ISSUE_N(c, B.op_n, R, gated ? brows(m.b_sum, R) : RAD_NONE, gated ? gt : RAD_NONE, + s, RAD_NONE, mcu, xv, brows(m.a_hm.q, R), brows(m.a_hm.s, R), RAD_NONE); + else + RAD_ISSUE_N(c, B.op_n, R, gated ? brows(m.b_sum, R) : RAD_NONE, gated ? gt : RAD_NONE, + s, RAD_NONE, mcu, xv, brows(m.a_hm.x, R)); + B.qkv.step(c, m.a_hm, m.b_qkv, R); + RAD_ISSUE_N(c, B.op_qkr, R, brows(m.b_qkv, R), pos, RAD_W(B.w_qn), RAD_W(B.w_kn)); + RAD_ISSUE_N(c, B.op_attn, R, bcol(m.b_qkv, 0, qd, R), bcol(m.b_qkv, qd, qd, R), + bcol(m.b_qkv, 2 * qd, qd, R), acu, brows(m.a_attn.x, R)); + B.q_attn.step(c, R); + B.o.step(c, m.a_attn, m.b_o, R); + B.ff_in.step(c, m.a_hm, m.b_gu, R); + B.gq.step(c, m.b_gu, R); + B.ff_out.step(c, m.a_ffn, m.b_f, R); + RAD_ISSUE_N(c, B.op_sum, R, brows(m.b_o, R), brows(m.b_f, R), brows(m.b_sum, R)); + if (B.op_ar) RAD_ISSUE_N(c, B.op_ar, R * D, brows(m.b_sum, R), RAD_NONE); + } + (void)nD; +} + +static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const Geom& g = m.gd; + const int64_t N = batch->n_tok, S = batch->n_seq, NI = G->n_img, C = m.C, D = g.n_embd; + const int64_t nt = G->n_mode_h[kText], nr = G->n_mode_h[kRefs]; + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1); + const RadOperand icu = praw(G->img_cu, RAD_I32, S + 1); + const RadOperand lanes = praw(G->lane, RAD_I32, S); + const int64_t LR = (int64_t)kMaxLanes * kMaxImageTokens; + + /* ---- the timestep embeddings and every modulation */ + RAD_ISSUE_N(c, m.op_tp, S, praw(G->sigma, RAD_F32, S), brows(m.b_tp, S)); + RAD_ISSUE_N(c, m.op_one, S, bcol_at(m.b_tp, S, m.t_ch, 0, m.t_ch / 2, S)); + RAD_ISSUE_N(c, m.op_zero, S, bcol_at(m.b_tp, S, m.t_ch, m.t_ch / 2, m.t_ch / 2, S)); + RAD_ISSUE_N(c, m.op_t1, 2 * S, brows(m.b_tp, 2 * S), RAD_W(m.w_t1), brows(m.b_e1, 2 * S)); + RAD_ISSUE_N(c, m.op_ts, 2 * S, brows(m.b_e1, 2 * S), brows(m.b_e1s, 2 * S)); + RAD_ISSUE_N(c, m.op_t2, 2 * S, brows(m.b_e1s, 2 * S), RAD_W(m.w_t2), brows(m.b_temb, 2 * S)); + if (m.flow_map) { + RAD_ISSUE_N(c, m.op_tpt, S, praw(G->sigma_next, RAD_F32, S), brows(m.b_tpt, S)); + RAD_ISSUE_N(c, m.op_tt1, S, brows(m.b_tpt, S), RAD_W(m.w_tt1), brows(m.b_tt1, S)); + RAD_ISSUE_N(c, m.op_tts, S, brows(m.b_tt1, S), brows(m.b_tt1s, S)); + RAD_ISSUE_N(c, m.op_tt2, S, brows(m.b_tt1s, S), RAD_W(m.w_tt2), brows(m.b_ttgt, S)); + for (int64_t h = 0; h < 2; ++h) + RAD_ISSUE_N(c, m.op_addt, S, brow_slice(m.b_temb, h * S, S, D), brows(m.b_ttgt, S), + brow_slice(m.b_temb, h * S, S, D)); + } + RAD_ISSUE_N(c, m.op_actimg, S, brows(m.b_temb, S), brows(m.b_aimg, S)); + RAD_ISSUE_N(c, m.op_actzero, S, brow_slice(m.b_temb, S, S, D), brows(m.b_azero, S)); + RAD_ISSUE_N(c, m.op_iota3, S, brows(m.b_idx3, S)); + for (int k = 0; k < 3; ++k) { + const rad_buf act = k == kImage ? m.b_aimg : m.b_azero; + RAD_ISSUE_N(c, m.op_early[k], S, brows(act, S), RAD_W(m.w_early[k]), + brows(m.b_early[k], S)); + RAD_ISSUE_N(c, m.op_single[k], S, brows(act, S), RAD_W(m.w_single[k]), + brows(m.b_smod[k], S)); + RAD_ISSUE_N(c, m.op_ilv[k], S, brows(m.b_smod[k], S), brows(m.b_idx3, S), + brow_slice(m.b_single, k, 3 * S - k, 3 * D)); + } + RAD_ISSUE_N(c, m.op_fmod, S, brows(m.b_aimg, S), RAD_W(m.w_fmod), brows(m.b_fmod, S)); + + /* ---- the rows, mode-major in `xc`: the store's text and pictures, the image's latents */ + RAD_ISSUE_N(c, m.op_randn, NI, praw(G->flags, RAD_I32, S), praw(G->seed, RAD_U32, 2 * S), + lanes, icu, brows(m.b_state, LR)); + RAD_ISSUE_N(c, m.op_lgather, NI, brows(m.b_state, LR), lanes, icu, brows(m.b_lat, NI)); + RAD_ISSUE_N(c, m.op_xi, NI, brows(m.b_lat, NI), RAD_W(m.w_xi), + brow_slice(m.b_xc, nt + nr, NI, D)); + if (nt + nr > 0) + RAD_ISSUE_N(c, m.op_gtxt, nt + nr, brows(m.b_store, 2 * (int64_t)kMaxLanes * cond_rows()), + praw(G->mode_src, RAD_I32, nt + nr), brows(m.b_xc, nt + nr)); + + /* ---- each mode's early blocks over its own rows, the last sum gated in */ + const int64_t r0[3] = { 0, nt, nt + nr }, rn[3] = { nt, nr, NI }; + const float* mpos = G->mode_rope_f; + for (int k = 0; k < 3; ++k) { + if (rn[k] <= 0) continue; + const RadOperand mc = praw(G->mode_ccu + k * (S + 1), RAD_I32, S + 1); + const RadOperand s = bcol(m.b_early[k], 0, 2 * D, S), gt = bcol(m.b_early[k], 2 * D, D, S); + /* This mode's positions, a dense [4, rn] block at 4 r0. */ + step_blocks(c, m, m.mode[k], m.b_xc, r0[k], rn[k], mc, mc, s, gt, + praw2(mpos + 4 * r0[k], RAD_F32, 4, rn[k])); + RAD_ISSUE_N(c, m.op_g2, rn[k], brows(m.b_sum, rn[k]), gt, mc, + brow_slice(m.b_xc, r0[k], rn[k], D)); + } + /* ---- joined entry by entry, the joint blocks, the last sum gated in */ + RAD_ISSUE_N(c, m.op_join, N, brows(m.b_xc, N), praw(G->mode_rows, RAD_I32, N), + brows(m.b_h, N)); + const RadOperand mcu = praw(G->mode_cu, RAD_I32, 3 * S + 1); + const RadOperand ss = bcol(m.b_single, 0, 2 * D, 3 * S), sg = bcol(m.b_single, 2 * D, D, 3 * S); + step_blocks(c, m, m.single, m.b_h, 0, N, cu, mcu, ss, sg, praw2(G->rope_f, RAD_F32, 4, N)); + RAD_ISSUE_N(c, m.op_g3, N, brows(m.b_sum, N), sg, mcu, brows(m.b_h, N)); + + /* ---- the image rows out */ + RAD_ISSUE_N(c, m.op_gimg, NI, brows(m.b_h, N), praw(G->img_rows, RAD_I32, NI), + brows(m.b_hi, NI)); + RAD_ISSUE_N(c, m.op_nout, NI, RAD_NONE, RAD_NONE, brows(m.b_fmod, S), RAD_NONE, icu, + brows(m.b_hi, NI), brows(m.b_fz, NI)); + RAD_ISSUE_N(c, m.op_pout, NI, brows(m.b_fz, NI), RAD_W(m.w_pout), brows(m.b_v, NI)); + RAD_ISSUE_N(c, m.op_euler, NI, brows(m.b_v, NI), praw(G->sigma, RAD_F32, S), + praw(G->sigma_next, RAD_F32, S), praw(G->cfg, RAD_F32, S), + praw(G->pair, RAD_I32, S), lanes, praw(G->flags, RAD_I32, S), + praw(G->seed, RAD_U32, 2 * S), icu, brows(m.b_inp, LR), brows(m.b_mask, LR), + brows(m.b_state, LR), brows(m.b_prev, LR)); + (void)C; +} + +static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t H = G->dec_height / 16, W = G->dec_width / 16, n = H * W, C = m.C; + const rad_buf src = G->dec_preview ? m.b_prev : m.b_state; + RAD_ISSUE_N(c, m.op_dbn, n, brow_slice(src, (int64_t)G->dec_lane * kMaxImageTokens, n, C), + RAD_W(m.w_bnm), RAD_W(m.w_bnv), brows(m.b_dl, n)); + const int64_t zc = C / 4, H0 = 2 * H, W0 = 2 * W; + RAD_ISSUE_N(c, m.op_dzero, H0 * W0, brows(m.b_decin, H0 * W0)); + RAD_ISSUE_N(c, m.op_unpack, H0 * W0, RAD_P_T2(rad_buf_ptr(c, m.b_dl), RAD_BF16, H, W * C), + RAD_P_T2(rad_buf_ptr(c, m.b_decin), RAD_BF16, H0, W0 * zc)); + RAD_ISSUE_N(c, m.op_cu4, 2, praw(batch->cu_seqlens + 1, RAD_I32, 1), brows(m.b_cu4, 2)); + m.dec.issue(c, H0, W0, brows(m.b_cu4, 2), nullptr); + const int64_t npx = (int64_t)G->dec_height * G->dec_width; + RAD_ISSUE_N(c, m.op_rgb, npx, RAD_P_T2(rad_buf_ptr(c, m.dec_out.buf), RAD_BF16, npx, 3), + RAD_P_T2(rad_buf_ptr(c, m.b_img), RAD_U8, npx, 3)); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (!batch->gen || !batch->gen_b) { + rad_step_fail(c, "flux3 is an image generator and runs generator passes only"); + return; + } + switch (batch->gen) { + case RAD_GEN_PASS_COND: step_cond(c, batch, m); return; + case RAD_GEN_PASS_DENOISE: step_denoise(c, batch, m); return; + case RAD_GEN_PASS_DECODE: step_decode(c, batch, m); return; + default: rad_step_fail(c, "flux3: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +/* The rows a pass carries: an image at the largest size with one reference picture and its + * longest text, both branches of guidance. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->gen_rows = 2 * ((int64_t)kMaxImageTokens + kMaxText + ref_tokens_max()); + out->gen_patches = 0; + return RAD_OK; +} + +} /* namespace FLUX3_NS */ + +#ifndef RAD_ARCH_NO_EXPORTS +/* One more level of expansion so `#NS` sees the expanded namespace. */ +#define FLUX3_PROBE_X(NS) RAD_ARCH_PROBE(NS) +#define FLUX3_PLUGIN_X(NS, ...) RAD_ARCH_PLUGIN(NS, __VA_ARGS__) +FLUX3_PROBE_X(FLUX3_NS) +FLUX3_PLUGIN_X(FLUX3_NS, FLUX3_ID, "", "0.1.0", + "FLUX.3 [klein] and its base: Qwen3-VL-4B's stacked layers, a 5.6B three-mode " + "diffusion transformer over the text, up to ten reference pictures and the image, " + "and FLUX.2's VAE; bf16 or block-fp8 linears") +#endif diff --git a/arch/flux3distilled/CMakeLists.txt b/arch/flux3distilled/CMakeLists.txt new file mode 100644 index 00000000..e7c3a492 --- /dev/null +++ b/arch/flux3distilled/CMakeLists.txt @@ -0,0 +1,11 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/flux3distilled -B build -DCMAKE_PREFIX_PATH=`); 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) diff --git a/arch/flux3distilled/flux3distilled.cpp b/arch/flux3distilled/flux3distilled.cpp new file mode 100644 index 00000000..418932bd --- /dev/null +++ b/arch/flux3distilled/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" diff --git a/arch/gemma3/gemma3.cpp b/arch/gemma3/gemma3.cpp index 058635f8..6580ff94 100644 --- a/arch/gemma3/gemma3.cpp +++ b/arch/gemma3/gemma3.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; } diff --git a/arch/glm5next/glm5next.cpp b/arch/glm5next/glm5next.cpp index 4b443707..1e8c394f 100644 --- a/arch/glm5next/glm5next.cpp +++ b/arch/glm5next/glm5next.cpp @@ -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 models[MAX_RANKS]; static thread_local std::unique_ptr 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; diff --git a/arch/krea2/CMakeLists.txt b/arch/krea2/CMakeLists.txt new file mode 100644 index 00000000..d59a4ae7 --- /dev/null +++ b/arch/krea2/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/krea2 -B build -DCMAKE_PREFIX_PATH=`); 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) diff --git a/arch/krea2/krea2.cpp b/arch/krea2/krea2.cpp new file mode 100644 index 00000000..9e994f53 --- /dev/null +++ b/arch/krea2/krea2.cpp @@ -0,0 +1,1389 @@ +/* krea2 -- Krea 2 (Raw and Turbo): text to an RGB image. + * + * ============================== THE MODEL ============================== + * + * Three networks behind one prompt (diffusers' Krea2Pipeline): + * + * Conditioning network: the language model of Qwen3-VL-4B over the prompt in Qwen-Image's + * template. The generator reads twelve of its hidden states per token (after layers 1, 4, ..., + * 34, before any final norm) and drops the template's fixed system turn. + * + * Denoiser: a 12.9B single-stream diffusion transformer. A small text-fusion transformer first + * turns each token's twelve tapped states into one row: two blocks attending across the twelve + * (a token's taps are twelve consecutive rows here), a learned Linear(12, 1) over them + * (`mix_rows`), two blocks attending across the tokens, then `txt_in` to the DiT's width. The + * 28 blocks run over one joint sequence, the text and then the image, every row of it modulated + * by the step's timestep: `h += gate1 attn(norm1(h)(1 + scale1) + shift1)`, `h += gate2 + * mlp(norm2(h)(1 + scale2) + shift2)`, where the six modulation rows are one projection of the + * timestep embedding shared by every block plus a learned table of each block's own + * (`table_add`), gates without tanh. Attention is grouped (48 query heads, 12 key heads) with a + * sigmoid output gate, q/k RMS norms and a three-axis rotary (text at the origin, an image token + * at (0, row, column)). Every RMS norm is zero-centred, its gain 1 + w in f32. + * + * Since the text rows change with the step, nothing is cached: the conditioning pass leaves the + * text rows `txt_in` makes in each lane's store, and every denoising step runs them with the + * image (the core's JOINT_STEP layout, abi/rad_builder.h). + * + * Decoder: Qwen-Image's VAE (Wan 2.1's, its causal 3-D convolutions on one frame), 16 latent + * channels at 8x; a latent token is 2 x 2 of its pixels (64 values), so 16 pixels a token side. + * + * Raw samples 28 steps with guidance 4.5 in the card's terms (cond + 4.5 (cond - uncond), an + * empty negative prompt) on a resolution-shifted schedule; Turbo 8 steps without guidance at a + * fixed shift. Both come from the container's scheduler configuration and pipeline name. + * + * ============================== WHAT IS QUANTISED ============================== + * + * One plugin serves bf16 and block-fp8 containers: every linear of the language model, of the + * text fusion and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16 throughout when the first + * DiT projection is plain. txt_in, img_in, the timestep MLP and modulation, the final layer and + * the VAE stay bf16. + * + * ============================== TENSOR PARALLEL ============================== + * + * The language model, the text fusion and the DiT blocks split by heads and feed-forward width, + * an all-reduce after each output projection; everything else is replicated. The decoder splits + * by rows after its mid-block, as Qwen-Image 2.1's does (rad_vae2d.h). + */ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace krea2 { + +using namespace rad::arch; + +/* ================================================================== the model's constants */ +/* The largest image: 2048 x 2048 pixels, 16384 latent tokens. 1024 x 1024 is the default. */ +enum { kMaxImageTokens = 16384 }; +/* The longest conditioning in rows: the pipeline's max_sequence_length. The prompt the language + * model reads is that plus the template's system turn, at most kTeRows. */ +enum { kCondRows = 512, kTeRows = kCondRows + 64 }; +/* Images in flight, and so the lanes of latent state. */ +enum { kMaxLanes = 8 }; +/* The language model's hidden states the generator reads: hidden_states[i] for these i, the + * output of layer i - 1. Layers past the last tap are not run. */ +static const int kTaps[] = { 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35 }; +enum { kNTaps = 12 }; + +static const char* kSysPrompt = + "Describe the image by detailing the color, shape, size, texture, quantity, text, spatial " + "relationships of the objects and background:"; + +/* ================================================================== the model */ +struct TeLayer { + rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0; + LinearFP8 qkv{}, o{}, gate_up{}, down{}; + QuantFP8 q_h{}, q_attn{}, q_h2{}; + GateQuantFP8 gq{}; + rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_ar1 = 0, op_add1 = 0; + rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0, op_tap = 0; + int tap = -1; /* this layer's output is tap `tap`, or none */ +}; + +/* A text-fusion block: pre-norm attention (q/k norms, no rotary, sigmoid output gate) and a + * SwiGLU, each added back to its residual `x`. */ +struct FuseBlock { + rad_buf x = 0; + rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0; + LinearFP8 qkv{}, gate{}, o{}, gate_up{}, down{}; + QuantFP8 q_h{}, q_h2{}, q_attn{}; + GateQuantFP8 gq{}; + rad_op op_n1 = 0, op_qkn = 0, op_attn = 0, op_gq = 0, op_sig = 0, op_ar1 = 0, op_add1 = 0; + rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0; +}; + +struct DitLayer { + rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0, w_tab = 0; + rad_op op_tab = 0; /* the shared modulation plus this block's table, into its columns */ + LinearFP8 qkv{}, gate{}, o{}, gate_up{}, down{}; + QuantFP8 q_attn{}; + GateQuantFP8 gq{}; + rad_op op_n1 = 0, op_n2 = 0, op_qkr = 0, op_attn = 0, op_gq = 0, op_sig = 0; + rad_op op_ar1 = 0, op_ar2 = 0; +}; + +/* Weight groups (movement units) by network. */ +enum : int { + kGrpFuse = 1000, /* the text fusion's blocks, kGrpFuse + i */ + kGrpTxtIn = 1100, + kGrpVaeDec = 1200, + kGrpDit = 2000, /* the DiT's model-level weights; its blocks kGrpDit + 1.. */ +}; + +struct Model { + Names nm{""}; + Geom gt{}, gf{}, gd{}; /* the language model's, the text fusion's and the DiT's geometry */ + bool turbo = false; + std::string te_pre; /* the language model's tensor prefix */ + + /* ---- the language model */ + rad_weight w_tok = 0; + rad_op op_embed = 0, op_iota = 0; + rad_buf b_tx = 0, b_tkv = 0, b_th2 = 0, b_tgu = 0, b_tidx = 0; + ActFP8 a_th{}, a_tattn{}, a_tffn{}; + std::vector te; + rad_buf b_taps = 0; /* [T * 12, n_embd]: token t's tap i at row 12 t + i */ + + /* ---- the text fusion: the layer-wise blocks over the taps themselves, the refiner blocks + * over the mixed rows `b_ft` */ + rad_buf b_fqkv = 0, b_fg = 0, b_fo = 0, b_fgu = 0, b_fcu = 0; + ActFP8 a_fh{}, a_fattn{}, a_fffn{}; + rad_op op_fcu = 0, op_mix = 0; + rad_weight w_mix = 0; + std::vector lw, rf; /* the layer-wise and the refiner blocks */ + rad_buf b_ft = 0; /* [T, n_embd] the mixed rows, the refiner's residual */ + + /* ---- txt_in: zero-centred RMSNorm, a linear, gelu_tanh, a linear, into the lanes */ + rad_weight w_txn = 0, w_tx1 = 0, b_tx1 = 0, w_tx2 = 0, b_tx2 = 0; + rad_op op_txn = 0, op_tx1 = 0, op_txg = 0, op_tx2 = 0, op_store = 0; + rad_buf b_txa = 0, b_txb = 0, b_txt = 0; + + /* ---- the timestep: embedding, MLP, the shared modulation and every block's tables */ + rad_weight w_t1 = 0, b_t1 = 0, w_t2 = 0, b_t2 = 0, w_mod = 0, b_mod = 0, w_ftab = 0; + rad_op op_temb = 0, op_t1 = 0, op_tg = 0, op_t2 = 0, op_tg2 = 0, op_mod = 0, op_ftab = 0; + rad_buf b_tproj = 0, b_te1 = 0, b_te1g = 0, b_temb = 0, b_tembg = 0, b_tmod = 0, b_mods = 0, + b_fmod = 0; + + /* ---- the DiT */ + int64_t C = 64; /* latent channels a token */ + rad_weight w_imgin = 0, b_imgin = 0; + rad_op op_randn = 0, op_lgather = 0, op_imgin = 0, op_join = 0, op_g2 = 0, op_gimg = 0; + rad_buf b_lat = 0, b_himg = 0, b_h = 0, b_qkv = 0, b_g = 0, b_ao = 0, b_gu = 0, b_hi = 0; + ActFP8 a_hm{}, a_attn{}, a_ffn{}; + std::vector dit; + LinearFP8 qkv0{}; + rad_weight w_fn = 0, w_pout = 0, b_pout = 0; + rad_op op_fn = 0, op_pout = 0, op_euler = 0; + rad_buf b_fz = 0, b_v = 0; + + /* ---- the per-image state and the conditioning store (PERSIST) */ + rad_buf b_state = 0, b_prev = 0, b_store = 0; + + /* ---- the VAE */ + Vae dec{}; + VImg dec_out{}; + rad_buf b_dl = 0, b_dl2 = 0, b_decin = 0, b_cu4 = 0, b_img = 0, b_rgbf = 0; + rad_op op_dinv = 0, op_dadd = 0, op_dzero = 0, op_unpack = 0, op_cu4 = 0, op_rgb = 0; + rad_op op_bands = 0, op_rgb_bands = 0; + std::string inv_std, mean, ones, zeros; +}; + +static Model g_model[MAX_RANKS]; + +/* A space-separated list off the container (rad-convert flattens arrays that way). */ +static std::vector meta_list(const RadModelMeta* m, const char* key) { + std::vector v; + const char* s = rad_meta_gets(m, key, nullptr); + while (s && *s) { + char* e = nullptr; + const double x = std::strtod(s, &e); + if (e == s) { ++s; continue; } + v.push_back(x); + s = e; + } + return v; +} + +static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype, + std::initializer_list shape, int access, int group) { + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, dtype, shape, access, RAD_SHARD_NONE, grp_layer(group)); +} + +/* A bf16 linear with a bias, read whole on every rank. */ +static rad_op dense_bias(RadBuilder* b, Names& nm, const char* dn, const char* src, int64_t N, + int64_t K, int64_t rows, rad_buf in, rad_buf out, rad_weight* w, + rad_weight* bias, int access, int group) { + *w = wcopy(b, nm.f("%s.weight", dn), nm.ckpt("%s.weight", src), RAD_BF16, { N, K }, access, + group); + *bias = wcopy(b, nm.f("%s.bias", dn), nm.ckpt("%s.bias", src), RAD_BF16, { N }, access, group); + if (!*w || !*bias) return 0; + return rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(*w, *bias)), + { in }, { out }); +} + +static rad_op unary(RadBuilder* b, const char* op, int64_t rows, int64_t n, rad_buf in, + rad_buf out) { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { in }, { out }); +} + +static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf y) { + return rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a, c }, { y }); +} + +static rad_op all_reduce(RadBuilder* b, const Geom& g, rad_buf x, int64_t rows) { + if (g.world <= 1) return 0; + return rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, rows * g.n_embd), + RAD_STR("dtype", "bf16"), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + { x }, { x }); +} + +/* A zero-centred RMSNorm (gain 1 + w in f32, the norm and gain rounded once): rmsnorm's + * `wadd`. */ +static rad_op zc_norm(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, + rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_STR("dtype", "bf16"), RAD_F64("wadd", 1.0)), + RAD_WEIGHTS(w)), + { x }, { y }); +} + +/* The attention's sigmoid output gate: `gate_quant_fp8` (gate, multiply and the out projection's + * quantiser in one pass) over fp8 linears, or `sigmoid` then `mul` over bf16 ones and wherever no + * loaded library declares the fused op (the out projection's quantiser then runs on its own). + * Rows are (token, head) pairs of `head_dim` columns. Returns the gate op; `sig` is the pair's + * sigmoid, written into `g` itself. */ +static rad_op out_gate(RadBuilder* b, const Geom& g, int64_t rows, int64_t width, rad_buf gate, + const ActFP8& attn, rad_op* sig) { + const int64_t hd = g.head_dim; + if (g.w_bf16 || !rad_op_declared(b, "gate_quant_fp8")) { + *sig = rw(b, RAD_OP(b, "sigmoid", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { gate }, { gate }); + return rw(b, RAD_OP(b, "mul", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { attn.x, gate }, { attn.x }); + } + *sig = 0; + return rw(b, RAD_OP(b, "gate_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, rows * (width / hd)), RAD_INT("n", hd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16"), + RAD_STR("act", "sigmoid")), + RAD_NOWEIGHTS), + { gate, attn.x }, { attn.cq(), attn.cs(), attn.x }); +} + +/* ================================================================== check_format */ +static int check_format(const RadModelMeta* meta) { + const char* arch = rad_meta_gets(meta, "pipeline._class_name", ""); + if (std::strncmp(arch, "Krea2", 5) != 0) { + fprintf(stderr, "radiance: krea2: the container's pipeline is '%s', not Krea 2's\n", arch); + return RAD_E_UNSUPPORTED; + } + if (rad_meta_geti(meta, "transformer.num_text_layers", kNTaps) != kNTaps || + rad_meta_geti(meta, "vae.z_dim", 16) != 16 || + rad_meta_geti(meta, "transformer.in_channels", 64) != 64) { + fprintf(stderr, "radiance: krea2: the DiT must read twelve tapped layers and 64-value " + "tokens of a 16-channel VAE\n"); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* ================================================================== declare */ +static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gt; + Names& nm = m.nm; + const int64_t T = kTeRows; /* the prompt with its system turn */ + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + const char* pre = m.te_pre.c_str(); + + RAD_ARCH_TRY(map_copy(b, nm.f("te.token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre))); + m.w_tok = decl_w(b, nm.f("te.token_embd.weight"), RAD_BF16, { g.n_vocab_all, g.n_embd }, + RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); + m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, g.n_embd }); + m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, g.n_embd }); + RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", g.n_embd, T)); + m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim }); + m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim }); + RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim, T)); + m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, g.n_embd }); + m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff }); + m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff, T)); + m.b_taps = decl_b(b, nm.f("te.taps"), RAD_BF16, { (int64_t)kTeRows * kNTaps, g.n_embd }); + m.b_tidx = decl_b(b, nm.f("te.tap_idx"), RAD_I32, { T }); + + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab_all), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0)), + RAD_WEIGHTS(m.w_tok)), + {}, { m.b_tx }); + /* Row 12 t of the taps for token t; a tap i is scattered at row offset i. */ + m.op_iota = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), RAD_INT("start", 0), + RAD_INT("step", kNTaps)), + RAD_NOWEIGHTS), + {}, { m.b_tidx }); + + const std::vector sec = meta_list(meta, "text_config.rope_scaling.mrope_section"); + char sections[48]; + if (sec.size() == 3) + std::snprintf(sections, sizeof sections, "%d %d %d", (int)sec[0], (int)sec[1], (int)sec[2]); + else + std::snprintf(sections, sizeof sections, "24 20 20"); + + /* Layers up to the last tap only. */ + const int n_run = kTaps[kNTaps - 1]; + if (g.n_layer < n_run) { + fprintf(stderr, "radiance: krea2: the text encoder has %lld layers; its last tap is after " + "layer %d\n", (long long)g.n_layer, n_run); + return RAD_E_INVAL; + } + m.te.resize((size_t)n_run); + for (int l = 0; l < n_run; ++l) { + TeLayer& L = m.te[(size_t)l]; + for (int t = 0; t < kNTaps; ++t) if (kTaps[t] == l + 1) L.tap = t; + const char* lp = nm.f("%s.layers.%d", pre, l); + L.w_n1 = wcopy(b, nm.f("te.blk.%d.attn_norm.weight", l), + nm.ckpt("%s.input_layernorm.weight", lp), RAD_F32, { g.n_embd }, + RAD_ACCESS_PER_TOKEN, l); + L.w_n2 = wcopy(b, nm.f("te.blk.%d.ffn_norm.weight", l), + nm.ckpt("%s.post_attention_layernorm.weight", lp), RAD_F32, { g.n_embd }, + RAD_ACCESS_PER_TOKEN, l); + L.w_qn = wcopy(b, nm.f("te.blk.%d.q_norm.weight", l), nm.ckpt("%s.self_attn.q_norm.weight", lp), + RAD_BF16, { g.head_dim }, RAD_ACCESS_PER_TOKEN, l); + L.w_kn = wcopy(b, nm.f("te.blk.%d.k_norm.weight", l), nm.ckpt("%s.self_attn.k_norm.weight", lp), + RAD_BF16, { g.head_dim }, RAD_ACCESS_PER_TOKEN, l); + if (!L.w_n1 || !L.w_n2 || !L.w_qn || !L.w_kn) return RAD_E_INVAL; + L.op_n1 = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(L.w_n1)), + { m.b_tx }, { m.a_th.x }); + RAD_ARCH_TRY(L.q_h.declare(b, g, m.a_th, g.n_embd)); + RAD_ARCH_TRY(L.qkv.declare(b, nm, g, nm.f("te.blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, + g.n_embd, RAD_SHARD_ROW, grp_layer(l), + { nm.ckpt("%s.self_attn.q_proj.weight", lp), + nm.ckpt("%s.self_attn.k_proj.weight", lp), + nm.ckpt("%s.self_attn.v_proj.weight", lp) }, + m.a_th, m.b_tkv, T, { q_dim, kv_dim, kv_dim })); + L.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", g.theta), RAD_F64("eps", g.eps), + RAD_STR("mode", "imrope"), + RAD_INT("rotary_dim", g.head_dim), + RAD_STR("sections", nm.f("%s", sections))), + RAD_WEIGHTS(L.w_qn, L.w_kn)), + { m.b_tkv }, { m.b_tkv }); + L.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)g.head_dim)), + RAD_INT("max_seqlen", T)), + RAD_NOWEIGHTS), + { m.b_tkv }, { m.a_tattn.x }); + RAD_ARCH_TRY(L.q_attn.declare(b, g, m.a_tattn, q_dim)); + RAD_ARCH_TRY(L.o.declare(b, nm, g, nm.f("te.blk.%d.attn_output", l), g.n_embd, q_dim, + RAD_SHARD_COL, grp_layer(l), + { nm.ckpt("%s.self_attn.o_proj.weight", lp) }, m.a_tattn, m.b_th2, + T)); + L.op_ar1 = all_reduce(b, g, m.b_th2, T); + L.op_add1 = add_op(b, T, g.n_embd, m.b_tx, m.b_th2, m.b_tx); + L.op_n2 = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(L.w_n2)), + { m.b_tx }, { m.a_th.x }); + RAD_ARCH_TRY(L.q_h2.declare(b, g, m.a_th, g.n_embd)); + RAD_ARCH_TRY(L.gate_up.declare(b, nm, g, nm.f("te.blk.%d.ffn_gate_up", l), 2 * g.n_ff, + g.n_embd, RAD_SHARD_ROW, grp_layer(l), + { nm.ckpt("%s.mlp.gate_proj.weight", lp), + nm.ckpt("%s.mlp.up_proj.weight", lp) }, + m.a_th, m.b_tgu, T, { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(L.gq.declare(b, g, m.b_tgu, m.a_tffn, g.n_ff, "silu", T, true)); + RAD_ARCH_TRY(L.down.declare(b, nm, g, nm.f("te.blk.%d.ffn_down", l), g.n_embd, g.n_ff, + RAD_SHARD_COL, grp_layer(l), + { nm.ckpt("%s.mlp.down_proj.weight", lp) }, m.a_tffn, m.b_th2, + T)); + L.op_ar2 = all_reduce(b, g, m.b_th2, T); + L.op_add2 = add_op(b, T, g.n_embd, m.b_tx, m.b_th2, m.b_tx); + if (L.tap >= 0) + L.op_tap = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), RAD_INT("n", g.n_embd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_tx, m.b_tidx, m.b_taps }, { m.b_taps }); + if (!L.op_n1 || !L.op_qkr || !L.op_attn || !L.op_add1 || !L.op_n2 || !L.op_add2 || + (L.tap >= 0 && !L.op_tap)) + return RAD_E_INVAL; + } + return m.op_embed && m.op_iota ? RAD_OK : RAD_E_INVAL; +} + +/* One text-fusion block over at most `rows` rows of the residual `x`. */ +static int declare_fuse_block(RadBuilder* b, Model& m, FuseBlock& F, const char* pre, int grp, + int64_t rows, rad_buf x) { + F.x = x; + Geom& g = m.gf; + Names& nm = m.nm; + const int64_t D = g.n_embd, qd = g.q_dim(), hd = g.head_dim; + const double eps = g.eps; + const char* dn = nm.f("fuse.%d", grp - kGrpFuse); + F.w_n1 = wcopy(b, nm.f("%s.norm1.weight", dn), nm.ckpt("%s.norm1.weight", pre), RAD_F32, { D }, + RAD_ACCESS_PER_REQUEST, grp); + F.w_n2 = wcopy(b, nm.f("%s.norm2.weight", dn), nm.ckpt("%s.norm2.weight", pre), RAD_F32, { D }, + RAD_ACCESS_PER_REQUEST, grp); + F.w_qn = wcopy(b, nm.f("%s.q_norm.weight", dn), nm.ckpt("%s.attn.norm_q.weight", pre), RAD_F32, + { hd }, RAD_ACCESS_PER_REQUEST, grp); + F.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), nm.ckpt("%s.attn.norm_k.weight", pre), RAD_F32, + { hd }, RAD_ACCESS_PER_REQUEST, grp); + if (!F.w_n1 || !F.w_n2 || !F.w_qn || !F.w_kn) return RAD_E_INVAL; + F.op_n1 = zc_norm(b, rows, D, eps, F.w_n1, F.x, m.a_fh.x); + RAD_ARCH_TRY(F.q_h.declare(b, g, m.a_fh, D)); + RAD_ARCH_TRY(F.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), 3 * qd, D, RAD_SHARD_ROW, + grp_layer(grp), + { nm.ckpt("%s.attn.to_q.weight", pre), + nm.ckpt("%s.attn.to_k.weight", pre), + nm.ckpt("%s.attn.to_v.weight", pre) }, + m.a_fh, m.b_fqkv, rows, { qd, qd, qd })); + RAD_ARCH_TRY(F.gate.declare(b, nm, g, nm.f("%s.attn_gate", dn), qd, D, RAD_SHARD_ROW, + grp_layer(grp), { nm.ckpt("%s.attn.to_gate.weight", pre) }, m.a_fh, + m.b_fg, rows)); + /* q/k norms alone (no rotary in the fusion), zero-centred. */ + F.op_qkn = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", hd), + RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head), + RAD_F64("theta", 10000.0), RAD_F64("eps", eps), + RAD_INT("rotary_dim", 0), RAD_F64("wadd", 1.0)), + RAD_WEIGHTS(F.w_qn, F.w_kn)), + { m.b_fqkv }, { m.b_fqkv }); + F.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd))), + RAD_NOWEIGHTS), + { m.b_fqkv }, { m.a_fattn.x }); + F.op_gq = out_gate(b, g, rows, qd, m.b_fg, m.a_fattn, &F.op_sig); + if (F.op_sig) RAD_ARCH_TRY(F.q_attn.declare(b, g, m.a_fattn, qd)); + RAD_ARCH_TRY(F.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_COL, + grp_layer(grp), { nm.ckpt("%s.attn.to_out.0.weight", pre) }, + m.a_fattn, m.b_fo, rows)); + F.op_ar1 = all_reduce(b, g, m.b_fo, rows); + F.op_add1 = add_op(b, rows, D, F.x, m.b_fo, F.x); + F.op_n2 = zc_norm(b, rows, D, eps, F.w_n2, F.x, m.a_fh.x); + RAD_ARCH_TRY(F.q_h2.declare(b, g, m.a_fh, D)); + RAD_ARCH_TRY(F.gate_up.declare(b, nm, g, nm.f("%s.ffn_gate_up", dn), 2 * g.n_ff, D, + RAD_SHARD_ROW, grp_layer(grp), + { nm.ckpt("%s.ff.gate.weight", pre), + nm.ckpt("%s.ff.up.weight", pre) }, + m.a_fh, m.b_fgu, rows, { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(F.gq.declare(b, g, m.b_fgu, m.a_fffn, g.n_ff, "silu", rows, true)); + RAD_ARCH_TRY(F.down.declare(b, nm, g, nm.f("%s.ffn_down", dn), D, g.n_ff, RAD_SHARD_COL, + grp_layer(grp), { nm.ckpt("%s.ff.down.weight", pre) }, m.a_fffn, + m.b_fo, rows)); + F.op_ar2 = all_reduce(b, g, m.b_fo, rows); + F.op_add2 = add_op(b, rows, D, F.x, m.b_fo, F.x); + if (!F.op_n1 || !F.op_qkn || !F.op_attn || !F.op_gq || !F.op_add1 || !F.op_n2 || !F.op_add2) + return RAD_E_INVAL; + return RAD_OK; +} + +static int declare_fusion(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gf; + Names& nm = m.nm; + const int64_t D = g.n_embd, qd = g.q_dim(); + const int64_t RL = (int64_t)kCondRows * kNTaps; /* the layer-wise blocks' rows */ + m.a_fh.x = decl_b(b, nm.f("fuse.h"), RAD_BF16, { RL, D }); + RAD_ARCH_TRY(m.a_fh.declare_qs(b, nm, g, "fuse.h", D, RL)); + m.b_fqkv = decl_b(b, nm.f("fuse.qkv"), RAD_BF16, { RL, 3 * qd }); + m.b_fg = decl_b(b, nm.f("fuse.gate"), RAD_BF16, { RL, qd }); + m.a_fattn.x = decl_b(b, nm.f("fuse.attn"), RAD_BF16, { RL, qd }); + RAD_ARCH_TRY(m.a_fattn.declare_qs(b, nm, g, "fuse.attn", qd, RL)); + m.b_fo = decl_b(b, nm.f("fuse.o"), RAD_BF16, { RL, D }); + m.b_fgu = decl_b(b, nm.f("fuse.gate_up"), RAD_BF16, { RL, 2 * g.n_ff }); + m.a_fffn.x = decl_b(b, nm.f("fuse.ffn"), RAD_BF16, { RL, g.n_ff }); + RAD_ARCH_TRY(m.a_fffn.declare_qs(b, nm, g, "fuse.ffn", g.n_ff, RL)); + m.b_fcu = decl_b(b, nm.f("fuse.cu"), RAD_I32, { kCondRows + 1 }); + m.b_ft = decl_b(b, nm.f("fuse.out"), RAD_BF16, { kCondRows, D }); + + /* The layer-wise blocks attend within each token's twelve rows: cu 0, 12, 24, ... */ + m.op_fcu = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, kCondRows + 1), RAD_INT("start", 0), + RAD_INT("step", kNTaps)), + RAD_NOWEIGHTS), + {}, { m.b_fcu }); + const int nlw = (int)rad_meta_geti(meta, "transformer.num_layerwise_text_blocks", 2); + const int nrf = (int)rad_meta_geti(meta, "transformer.num_refiner_text_blocks", 2); + m.lw.resize((size_t)nlw); + m.rf.resize((size_t)nrf); + for (int i = 0; i < nlw; ++i) { + RAD_ARCH_TRY(declare_fuse_block(b, m, m.lw[(size_t)i], + nm.f("transformer.text_fusion.layerwise_blocks.%d", i), + kGrpFuse + i, RL, m.b_taps)); + /* Their attention reads the twelve-row bounds. */ + RAD_ARCH_TRY(rad_op_reads(b, m.lw[(size_t)i].op_attn, &m.b_fcu, 1)); + } + RAD_ARCH_TRY(map_copy(b, nm.f("fuse.mix.weight"), + nm.ckpt("transformer.text_fusion.projector.weight"))); + /* The release stores the projector, embedders, modulations and output layer f32, which are + * served bf16 as diffusers runs them: a recipe casts them. */ + if (weight_codes_dtype(b, "fuse.mix.weight", RAD_BF16) != RAD_BF16) { + fprintf(stderr, "radiance: krea2: 'fuse.mix.weight' is stored %s; convert with " + "data/recipes/krea-2-bf16.recipe or krea-2-fp8.recipe, which cast the " + "release's f32 tensors\n", + rad_dtype_name(weight_codes_dtype(b, "fuse.mix.weight", RAD_BF16))); + return RAD_E_UNSUPPORTED; + } + m.w_mix = decl_w(b, nm.f("fuse.mix.weight"), RAD_BF16, { 1, kNTaps }, RAD_ACCESS_PER_REQUEST, + RAD_SHARD_NONE, grp_layer(kGrpFuse)); + m.op_mix = rw(b, RAD_OP(b, "mix_rows", + RAD_PARAMS(RAD_RANGE("M", 1, kCondRows), RAD_INT("n", D), + RAD_INT("k", kNTaps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_mix)), + { m.b_taps }, { m.b_ft }); + for (int i = 0; i < nrf; ++i) + RAD_ARCH_TRY(declare_fuse_block(b, m, m.rf[(size_t)i], + nm.f("transformer.text_fusion.refiner_blocks.%d", i), + kGrpFuse + nlw + i, kCondRows, m.b_ft)); + if (!m.op_fcu || !m.w_mix || !m.op_mix) return RAD_E_INVAL; + + /* ---- txt_in, into each lane's conditioning store */ + const int64_t Dd = m.gd.n_embd; + m.b_txa = decl_b(b, nm.f("txt.a"), RAD_BF16, { kCondRows, D }); + m.b_txb = decl_b(b, nm.f("txt.b"), RAD_BF16, { kCondRows, Dd }); + m.b_txt = decl_b(b, nm.f("txt.out"), RAD_BF16, { kCondRows, Dd }); + m.w_txn = wcopy(b, nm.f("txt.norm.weight"), nm.ckpt("transformer.txt_in.norm.weight"), RAD_F32, + { D }, RAD_ACCESS_PER_REQUEST, kGrpTxtIn); + m.op_txn = zc_norm(b, kCondRows, D, g.eps, m.w_txn, m.b_ft, m.b_txa); + m.op_tx1 = dense_bias(b, nm, "txt.l1", "transformer.txt_in.linear_1", Dd, D, kCondRows, m.b_txa, + m.b_txb, &m.w_tx1, &m.b_tx1, RAD_ACCESS_PER_REQUEST, kGrpTxtIn); + m.op_txg = unary(b, "gelu_tanh", kCondRows, Dd, m.b_txb, m.b_txb); + m.op_tx2 = dense_bias(b, nm, "txt.l2", "transformer.txt_in.linear_2", Dd, Dd, kCondRows, + m.b_txb, m.b_txt, &m.w_tx2, &m.b_tx2, RAD_ACCESS_PER_REQUEST, kGrpTxtIn); + /* Lane l's branch b at rows (2 l + b) kCondRows: the store's `stride` is two branches. */ + m.op_store = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, kCondRows), RAD_INT("n", Dd), + RAD_INT("stride", 2 * (int64_t)kCondRows), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_txt, m.b_store }, { m.b_store }); + return m.w_txn && m.op_txn && m.op_tx1 && m.op_txg && m.op_tx2 && m.op_store ? RAD_OK + : RAD_E_INVAL; +} + +/* The DiT's six modulation rows, reordered to rms_mod's [shift | scale] pairs: the checkpoint + * holds (prescale, preshift, pregate, postscale, postshift, postgate). */ +static int map_mod_rows(RadBuilder* b, const char* declared, const char* src, int64_t D) { + return map_rows(b, declared, { { src, (int)D, D }, { src, 0, D }, { src, (int)(2 * D), D }, + { src, (int)(4 * D), D }, { src, (int)(3 * D), D }, + { src, (int)(5 * D), D } }); +} + +static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gd; + Names& nm = m.nm; + const int64_t T = g.max_tok, S = g.max_seqs; + const int64_t D = g.n_embd, hd = g.head_dim, qd = g.q_dim(), kvd = g.kv_dim(); + const int64_t C = m.C, L = g.n_layer; + const double eps = g.eps; + const int gx = kGrpDit; + const int64_t NI = std::min(T, 2 * (int64_t)kMaxImageTokens); /* image rows a pass */ + + /* ---- the timestep: [cos | sin] of 1000 bf16(t) over 256, linear, gelu_tanh, linear (temb); + * the shared modulation from gelu_tanh(temb), then each block's table added (table_add), and + * the final layer's from temb itself. */ + const int64_t te = rad_meta_geti(meta, "transformer.timestep_embed_dim", 256); + m.b_tproj = decl_b(b, nm.f("dit.tproj"), RAD_BF16, { S, te }); + m.b_te1 = decl_b(b, nm.f("dit.te1"), RAD_BF16, { S, D }); + m.b_te1g = decl_b(b, nm.f("dit.te1g"), RAD_BF16, { S, D }); + m.b_temb = decl_b(b, nm.f("dit.temb"), RAD_BF16, { S, D }); + m.b_tembg = decl_b(b, nm.f("dit.tembg"), RAD_BF16, { S, D }); + m.b_tmod = decl_b(b, nm.f("dit.tmod"), RAD_BF16, { S, 6 * D }); + m.b_mods = decl_b(b, nm.f("dit.mods"), RAD_BF16, { S, L * 6 * D }); + m.b_fmod = decl_b(b, nm.f("dit.fmod"), RAD_BF16, { S, 2 * D }); + m.op_temb = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", te), + RAD_F64("scale", 1000.0), RAD_F64("max_period", 10000.0), + RAD_INT("round", 2), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_tproj }); + m.op_t1 = dense_bias(b, nm, "dit.t1", "transformer.time_embed.linear_1", D, te, S, m.b_tproj, + m.b_te1, &m.w_t1, &m.b_t1, RAD_ACCESS_PER_TOKEN, gx); + m.op_tg = unary(b, "gelu_tanh", S, D, m.b_te1, m.b_te1g); + m.op_t2 = dense_bias(b, nm, "dit.t2", "transformer.time_embed.linear_2", D, D, S, m.b_te1g, + m.b_temb, &m.w_t2, &m.b_t2, RAD_ACCESS_PER_TOKEN, gx); + m.op_tg2 = unary(b, "gelu_tanh", S, D, m.b_temb, m.b_tembg); + RAD_ARCH_TRY(map_mod_rows(b, nm.f("dit.mod.weight"), nm.ckpt("transformer.time_mod_proj.weight"), + D)); + m.w_mod = decl_w(b, nm.f("dit.mod.weight"), RAD_BF16, { 6 * D, D }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(gx)); + RAD_ARCH_TRY(map_mod_rows(b, nm.f("dit.mod.bias"), nm.ckpt("transformer.time_mod_proj.bias"), + D)); + m.b_mod = decl_w(b, nm.f("dit.mod.bias"), RAD_BF16, { 6 * D }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(gx)); + if (!m.w_mod || !m.b_mod) return RAD_E_INVAL; + m.op_mod = rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", 6 * D), RAD_INT("K", D), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_mod, m.b_mod)), + { m.b_tembg }, { m.b_tmod }); + /* Each block's table, its six rows reordered as the projection's, added to the shared + * modulation into the block's 6D columns of `mods` (declared with the blocks). */ + /* The final layer's (scale, shift), reordered to (shift, scale). */ + { + const char* src = nm.ckpt("transformer.final_layer.scale_shift_table"); + RAD_ARCH_TRY(map_rows(b, nm.f("dit.final.table"), { { src, 1, 1 }, { src, 0, 1 } })); + m.w_ftab = decl_w(b, nm.f("dit.final.table"), RAD_BF16, { 2, D }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(gx)); + } + m.op_ftab = rw(b, RAD_OP(b, "table_add", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", D), RAD_INT("L", 2), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_ftab)), + { m.b_temb }, { m.b_fmod }); + if (!m.op_temb || !m.op_t1 || !m.op_tg || !m.op_t2 || !m.op_tg2 || !m.op_mod || !m.w_ftab || + !m.op_ftab) + return RAD_E_INVAL; + + /* ---- the input rows: the image's latents a lane at a time through img_in, joined with the + * lanes' text rows into the pass's [text | image] entries */ + m.b_lat = decl_b(b, nm.f("dit.lat"), RAD_BF16, { NI, C }); + m.b_himg = decl_b(b, nm.f("dit.himg"), RAD_BF16, { NI, D }); + m.b_h = decl_b(b, nm.f("dit.h"), RAD_BF16, { T, D }); + m.op_randn = rw(b, RAD_OP(b, "randn_lanes", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state }, { m.b_state }); + m.op_lgather = rw(b, RAD_OP(b, "lane_gather", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state }, { m.b_lat }); + m.op_imgin = dense_bias(b, nm, "dit.img_in", "transformer.img_in", D, C, NI, m.b_lat, m.b_himg, + &m.w_imgin, &m.b_imgin, RAD_ACCESS_PER_TOKEN, gx); + m.op_join = rw(b, RAD_OP(b, "gather_rows2", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_store, m.b_himg }, { m.b_h }); + if (!m.op_randn || !m.op_lgather || !m.op_imgin || !m.op_join) return RAD_E_INVAL; + + /* ---- the blocks */ + m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D }); + RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D)); + m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, qd + 2 * kvd }); + m.b_g = decl_b(b, nm.f("dit.gate"), RAD_BF16, { T, qd }); + m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd }); + RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd)); + m.b_ao = decl_b(b, nm.f("dit.ao"), RAD_BF16, { T, D }); + m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff }); + m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff)); + + const std::vector ax = meta_list(meta, "transformer.axes_dims_rope"); + const int64_t a0 = ax.size() == 3 ? (int64_t)ax[0] : 32, a1 = ax.size() == 3 ? (int64_t)ax[1] : 48, + a2 = ax.size() == 3 ? (int64_t)ax[2] : 48; + if (a0 + a1 + a2 != hd) { + fprintf(stderr, "radiance: krea2: transformer.axes_dims_rope must sum to the head\n"); + return RAD_E_INVAL; + } + const char* sections = nm.f("%lld %lld %lld", (long long)a0 / 2, (long long)a1 / 2, + (long long)a2 / 2); + const double theta = rad_meta_getf(meta, "transformer.rope_theta", 1000.0); + + /* The modulated norm, gated by the branch before it when `gated`, into the next linear's + * input (codes for fp8, the bf16 plane for bf16). */ + auto mod_norm = [&](rad_weight w, bool gated) { + const bool q = !g.w_bf16; + rad_op op = q ? RAD_OP(b, "rms_mod_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16"), + RAD_F64("wadd", 1.0), RAD_INT("norm_once", 1)), + RAD_WEIGHTS(w)) + : RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps), + RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16"), + RAD_F64("wadd", 1.0), RAD_INT("norm_once", 1)), + RAD_WEIGHTS(w)); + if (!op) return op; + rad_buf rd[3] = { m.b_mods, m.b_h, m.b_ao }; + rad_buf wq[3] = { m.a_hm.q, m.a_hm.s, m.b_h }; + rad_buf wb[2] = { m.a_hm.x, m.b_h }; + rad_op_reads(b, op, rd, gated ? 3 : 2); + if (q) rad_op_writes(b, op, wq, 3); + else rad_op_writes(b, op, wb, 2); + return op; + }; + + m.dit.resize((size_t)L); + for (int64_t l = 0; l < L; ++l) { + DitLayer& B = m.dit[(size_t)l]; + const int li = (int)l; + const int grp = kGrpDit + 1 + li; + const char* pre = nm.ckpt("transformer.transformer_blocks.%d", li); + const char* dn = nm.f("dit.blk.%d", li); + B.w_n1 = wcopy(b, nm.f("%s.norm1.weight", dn), nm.ckpt("%s.norm1.weight", pre), RAD_BF16, + { D }, RAD_ACCESS_PER_TOKEN, grp); + B.w_n2 = wcopy(b, nm.f("%s.norm2.weight", dn), nm.ckpt("%s.norm2.weight", pre), RAD_BF16, + { D }, RAD_ACCESS_PER_TOKEN, grp); + B.w_qn = wcopy(b, nm.f("%s.q_norm.weight", dn), nm.ckpt("%s.attn.norm_q.weight", pre), + RAD_F32, { hd }, RAD_ACCESS_PER_TOKEN, grp); + B.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), nm.ckpt("%s.attn.norm_k.weight", pre), + RAD_F32, { hd }, RAD_ACCESS_PER_TOKEN, grp); + if (!B.w_n1 || !B.w_n2 || !B.w_qn || !B.w_kn) return RAD_E_INVAL; + { + const char* src = nm.ckpt("%s.scale_shift_table", pre); + RAD_ARCH_TRY(map_rows(b, nm.f("%s.table", dn), + { { src, 1, 1 }, { src, 0, 1 }, { src, 2, 1 }, { src, 4, 1 }, + { src, 3, 1 }, { src, 5, 1 } })); + B.w_tab = decl_w(b, nm.f("%s.table", dn), RAD_BF16, { 6, D }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(grp)); + B.op_tab = rw(b, RAD_OP(b, "table_add", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", 6 * D), + RAD_INT("L", 1), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(B.w_tab)), + { m.b_tmod, m.b_mods }, { m.b_mods }); + if (!B.w_tab || !B.op_tab) return RAD_E_INVAL; + } + B.op_n1 = mod_norm(B.w_n1, l > 0); + if (l == 0) B.qkv = m.qkv0; + RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), qd + 2 * kvd, D, + RAD_SHARD_ROW, grp_layer(grp), + { nm.ckpt("%s.attn.to_q.weight", pre), + nm.ckpt("%s.attn.to_k.weight", pre), + nm.ckpt("%s.attn.to_v.weight", pre) }, + m.a_hm, m.b_qkv, 0, { qd, kvd, kvd })); + RAD_ARCH_TRY(B.gate.declare(b, nm, g, nm.f("%s.attn_gate", dn), qd, D, RAD_SHARD_ROW, + grp_layer(grp), { nm.ckpt("%s.attn.to_gate.weight", pre) }, + m.a_hm, m.b_g)); + B.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("n_head", g.n_head), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", theta), RAD_F64("eps", eps), + RAD_STR("mode", "gptj_blocks"), + RAD_INT("rotary_dim", hd), RAD_STR("sections", sections), + RAD_F64("wadd", 1.0)), + RAD_WEIGHTS(B.w_qn, B.w_kn)), + { m.b_qkv }, { m.b_qkv }); + B.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd))), + RAD_NOWEIGHTS), + { m.b_qkv }, { m.a_attn.x }); + B.op_gq = out_gate(b, g, T, qd, m.b_g, m.a_attn, &B.op_sig); + if (B.op_sig) RAD_ARCH_TRY(B.q_attn.declare(b, g, m.a_attn, qd)); + RAD_ARCH_TRY(B.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_COL, + grp_layer(grp), { nm.ckpt("%s.attn.to_out.0.weight", pre) }, + m.a_attn, m.b_ao)); + B.op_ar1 = all_reduce(b, g, m.b_ao, T); + B.op_n2 = mod_norm(B.w_n2, true); + RAD_ARCH_TRY(B.gate_up.declare(b, nm, g, nm.f("%s.ffn_gate_up", dn), 2 * g.n_ff, D, + RAD_SHARD_ROW, grp_layer(grp), + { nm.ckpt("%s.ff.gate.weight", pre), + nm.ckpt("%s.ff.up.weight", pre) }, + m.a_hm, m.b_gu, 0, { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(B.gq.declare(b, g, m.b_gu, m.a_ffn, g.n_ff, "silu", 0, true)); + RAD_ARCH_TRY(B.down.declare(b, nm, g, nm.f("%s.ffn_down", dn), D, g.n_ff, RAD_SHARD_COL, + grp_layer(grp), { nm.ckpt("%s.ff.down.weight", pre) }, m.a_ffn, + m.b_ao)); + B.op_ar2 = all_reduce(b, g, m.b_ao, T); + if (!B.op_n1 || !B.op_qkr || !B.op_attn || !B.op_gq || !B.op_n2) return RAD_E_INVAL; + } + + /* ---- the output: the last block's feed-forward gated in, the image's rows picked out, the + * final adaptive norm and proj_out, and the sampler's step */ + m.b_hi = decl_b(b, nm.f("dit.h_img"), RAD_BF16, { NI, D }); + m.b_fz = decl_b(b, nm.f("dit.fz"), RAD_BF16, { NI, D }); + m.b_v = decl_b(b, nm.f("dit.v"), RAD_BF16, { NI, C }); + m.op_g2 = rw(b, RAD_OP(b, "gate_add", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16"), RAD_STR("act", "none")), + RAD_NOWEIGHTS), + { m.b_ao, m.b_mods, m.b_h }, { m.b_h }); + m.op_gimg = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_h }, { m.b_hi }); + m.w_fn = wcopy(b, nm.f("dit.final.norm.weight"), nm.ckpt("transformer.final_layer.norm.weight"), + RAD_BF16, { D }, RAD_ACCESS_PER_TOKEN, gx); + m.op_fn = rw(b, RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", D), RAD_F64("eps", eps), + RAD_INT("gated", 0), RAD_STR("dtype", "bf16"), + RAD_F64("wadd", 1.0), RAD_INT("norm_once", 1)), + RAD_WEIGHTS(m.w_fn)), + { m.b_fmod, m.b_hi }, { m.b_hi, m.b_fz }); + m.op_pout = dense_bias(b, nm, "dit.proj_out", "transformer.final_layer.linear", C, D, NI, + m.b_fz, m.b_v, &m.w_pout, &m.b_pout, RAD_ACCESS_PER_TOKEN, gx); + m.op_euler = rw(b, RAD_OP(b, "flow_euler", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_v, m.b_state, m.b_prev }, { m.b_state, m.b_prev }); + return m.op_g2 && m.op_gimg && m.w_fn && m.op_fn && m.op_pout && m.op_euler ? RAD_OK + : RAD_E_INVAL; +} + +/* The decoder: the latent denormalised, the 2 x 2 tokens unpacked to the VAE's 16 channels, then + * Wan 2.1's decoder on one frame. Its resblock, conv_in, conv_out and post_quant_conv convolutions + * are causal 3-D ones read at their last tap; the attention's and the upsamplers' are 2-D. */ +static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Vae& v = m.dec; + Names& nm = m.nm; + v.nm = &nm; + v.b = b; + v.scope = "vdec"; + v.down = false; + v.first_group = kGrpVaeDec; + v.base_px = (int64_t)kMaxImageTokens * 4; + v.form = VAE_CONV_CAUSAL; + const int64_t base = rad_meta_geti(meta, "vae.base_dim", 96); + const int64_t zd = rad_meta_geti(meta, "vae.z_dim", 16); + const int64_t nres = rad_meta_geti(meta, "vae.num_res_blocks", 2); + std::vector mult = meta_list(meta, "vae.dim_mult"); + std::vector td = meta_list(meta, "vae.temperal_downsample"); + if (mult.empty()) mult = { 1, 2, 4, 4 }; + if (td.empty()) td = { 0, 1, 1 }; + const std::vector mean = meta_list(meta, "vae.latents_mean"); + const std::vector sd = meta_list(meta, "vae.latents_std"); + if ((int64_t)mean.size() != zd || (int64_t)sd.size() != zd || mult.size() != 4) { + fprintf(stderr, "radiance: krea2: the VAE's latents_mean / latents_std / dim_mult are not " + "Wan 2.1's\n"); + return RAD_E_INVAL; + } + /* The packed channel c 4 + k reads latent channel c: the statistics repeated four times. The + * reference divides by bf16(1 / std) and adds the mean, each rounded. */ + for (int64_t k = 0; k < 4 * zd; ++k) { + char t[64]; + std::snprintf(t, sizeof t, "%s%.9g", k ? " " : "", 1.0 / sd[(size_t)(k / 4)]); + m.inv_std += t; + std::snprintf(t, sizeof t, "%s%.9g", k ? " " : "", mean[(size_t)(k / 4)]); + m.mean += t; + m.ones += k ? " 1" : "1"; + m.zeros += k ? " 0" : "0"; + } + const int64_t NT = kMaxImageTokens; + m.b_dl = decl_b(b, nm.f("vdec.lat"), RAD_BF16, { NT, 4 * zd }); + m.b_dl2 = decl_b(b, nm.f("vdec.lat2"), RAD_BF16, { NT, 4 * zd }); + m.b_decin = decl_b(b, nm.f("vdec.in"), RAD_BF16, { 4 * NT, zd }); + m.b_cu4 = decl_b(b, nm.f("vdec.cu"), RAD_I32, { 2 }); + m.op_dinv = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, NT), RAD_INT("n", 4 * zd), + RAD_STR("mul", m.inv_std.c_str()), + RAD_STR("add", m.zeros.c_str()), RAD_STR("mode", "inv"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state, m.b_prev }, { m.b_dl }); + m.op_dadd = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, NT), RAD_INT("n", 4 * zd), + RAD_STR("mul", m.ones.c_str()), + RAD_STR("add", m.mean.c_str()), RAD_STR("mode", "fma"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_dl }, { m.b_dl2 }); + m.op_dzero = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 4 * NT), RAD_INT("n", zd), + RAD_STR("dtype", "bf16"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_decin }); + m.op_unpack = rw(b, RAD_OP(b, "d2s_add", + RAD_PARAMS(RAD_RANGE("M", 1, 4 * NT), RAD_INT("cin", 4 * zd), + RAD_INT("cout", zd), RAD_INT("ft", 1), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_dl2, m.b_decin }, { m.b_decin }); + m.op_cu4 = rw(b, RAD_OP(b, "cu_repeat", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", 4)), + RAD_NOWEIGHTS), + {}, { m.b_cu4 }); + if (!m.op_dinv || !m.op_dadd || !m.op_dzero || !m.op_unpack || !m.op_cu4) return RAD_E_INVAL; + + /* dims = base * [mult[-1]] + mult reversed; up block i reads dims[i] (halved after an + * upsampler) and writes dims[i + 1]. */ + std::vector dims{ base * (int64_t)mult.back() }; + for (int i = 3; i >= 0; --i) dims.push_back(base * (int64_t)mult[(size_t)i]); + VImg x{ m.b_decin, zd, 0 }; + x = v.conv(x, zd, 1, 1, 1, "same", "vae.post_quant_conv"); + x = v.conv(x, dims[0], 3, 1, 1, "same", "vae.decoder.conv_in"); + x = v.resblock(x, dims[0], "vae.decoder.mid_block.resnets.0"); + v.form = VAE_CONV_2D; + x = v.attention(x, "vae.decoder.mid_block.attentions.0"); + v.form = VAE_CONV_CAUSAL; + x = v.resblock(x, dims[0], "vae.decoder.mid_block.resnets.1"); + v.band_from = (int)v.ops.size(); + v.whole.push_back(m.b_decin); + for (const VOp& o : v.ops) v.whole.push_back(o.y.buf); + for (int i = 0; i < 4; ++i) { + for (int r = 0; r < nres + 1; ++r) + x = v.resblock(x, dims[(size_t)i + 1], nm.f("vae.decoder.up_blocks.%d.resnets.%d", i, r)); + if (i != 3) { + v.form = VAE_CONV_2D; + x = v.conv(x, dims[(size_t)i + 1] / 2, 3, 1, 2, "same", + nm.f("vae.decoder.up_blocks.%d.upsamplers.0.resample.1", i)); + v.form = VAE_CONV_CAUSAL; + } + } + x = v.norm(x, true, "vae.decoder.norm_out", 4); + m.dec_out = v.conv(x, 3, 3, 1, 1, "same", "vae.decoder.conv_out"); + if (!m.dec_out.buf) return RAD_E_INVAL; + RAD_ARCH_TRY(v.attn_reads(m.b_cu4)); + const int64_t px = (int64_t)kMaxImageTokens * 256; + m.b_img = decl_b(b, nm.f("image_out"), RAD_U8, { px * 3 }, RAD_BUF_PERSIST); + m.op_rgb = rw(b, RAD_OP(b, "to_rgba8", + RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("n", 3), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.dec_out.buf }, { m.b_img }); + if (!m.op_rgb) return RAD_E_INVAL; + v.halo = v.band_halo(); + if (v.halo <= 0) { + fprintf(stderr, "radiance: krea2: the decoder after its mid-block is not row-local\n"); + return RAD_E_INVAL; + } + /* More than one rank: each runs a band of the tail and the bands are gathered (qwenimage21's + * scheme: a band is ceil(H / world) latent rows plus a halo each side). Level 0 is the + * unpacked latent, two rows a token row, eight pixels a latent row. */ + const int world = m.gt.world; + if (world > 1) { + const int64_t H0 = 4 * (int64_t)kMaxImageTokens; + const int64_t bpx = (H0 / world + H0 / (2 * v.halo) + 1) * 64; + m.b_rgbf = decl_b(b, nm.f("vdec.bands"), RAD_BF16, { world * bpx, 3 }); + m.op_bands = rw(b, RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", world), + RAD_RANGE("numel", 1, bpx * 3), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.dec_out.buf }, { m.b_rgbf }); + m.op_rgb_bands = rw(b, RAD_OP(b, "to_rgba8", + RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("n", 3), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_rgbf }, { m.b_img }); + if (!m.op_bands || !m.op_rgb_bands) return RAD_E_INVAL; + } + return RAD_OK; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(check_format(meta)); + RAD_ARCH_TRY(geom_from(m.gt, meta, ctx, "bf16", RAD_BF16)); + Names& nm = m.nm; + /* Qwen3VLModel's tensors (language_model.*) or a ...ForConditionalGeneration's + * (model.language_model.*). */ + m.te_pre = std::strstr(rad_meta_gets(meta, "architectures", ""), "ForConditionalGeneration") + ? "model.language_model" : "language_model"; + m.turbo = std::strstr(rad_meta_gets(meta, "pipeline._class_name", ""), "Turbo") != nullptr || + rad_meta_geti(meta, "pipeline.is_distilled", 0) != 0; + + /* ---- the text fusion's and the DiT's geometry, off the transformer's config */ + Geom& gf = m.gf; + gf = m.gt; + gf.n_embd = rad_meta_geti(meta, "transformer.text_hidden_dim", 2560); + gf.n_head_all = rad_meta_geti(meta, "transformer.text_num_attention_heads", 20); + gf.n_head_kv_all = rad_meta_geti(meta, "transformer.text_num_key_value_heads", gf.n_head_all); + gf.head_dim = gf.n_embd / gf.n_head_all; + gf.n_ff_all = rad_meta_geti(meta, "transformer.text_intermediate_size", 6912); + gf.eps = (float)rad_meta_getf(meta, "transformer.norm_eps", 1e-5); + gf.max_tok = (int64_t)kCondRows * kNTaps; + RAD_ARCH_TRY(divide_or_fail(gf.n_head_all, gf.world, "the text fusion's heads", &gf.n_head)); + RAD_ARCH_TRY(divide_or_fail(gf.n_head_kv_all, gf.world, "the text fusion's KV heads", + &gf.n_head_kv)); + RAD_ARCH_TRY(divide_or_fail(gf.n_ff_all, gf.world, "the text fusion's feed-forward width", + &gf.n_ff)); + if (gf.n_head != gf.n_head_kv || gf.head_dim != 128) { + fprintf(stderr, "radiance: krea2: the text fusion must be multi-head at head_dim 128\n"); + return RAD_E_UNSUPPORTED; + } + Geom& gd = m.gd; + gd = m.gt; + gd.n_layer = rad_meta_geti(meta, "transformer.num_layers", 28); + gd.head_dim = rad_meta_geti(meta, "transformer.attention_head_dim", 128); + gd.n_head_all = rad_meta_geti(meta, "transformer.num_attention_heads", 48); + gd.n_head_kv_all = rad_meta_geti(meta, "transformer.num_key_value_heads", 12); + gd.n_embd = gd.head_dim * gd.n_head_all; + gd.n_ff_all = rad_meta_geti(meta, "transformer.intermediate_size", 16384); + gd.eps = (float)rad_meta_getf(meta, "transformer.norm_eps", 1e-5); + RAD_ARCH_TRY(divide_or_fail(gd.n_head_all, gd.world, "transformer.num_attention_heads", + &gd.n_head)); + RAD_ARCH_TRY(divide_or_fail(gd.n_head_kv_all, gd.world, "transformer.num_key_value_heads", + &gd.n_head_kv)); + RAD_ARCH_TRY(divide_or_fail(gd.n_ff_all, gd.world, "the DiT's feed-forward width", &gd.n_ff)); + gd.kv_off = 0; + if (gd.n_layer >= 1000 || gf.n_layer > kGrpTxtIn - kGrpFuse) return RAD_E_UNSUPPORTED; + m.C = rad_meta_geti(meta, "transformer.in_channels", 64); + + /* ---- bf16 or block fp8: what the container holds for the first DiT projection decides it + * for every linear of every network (rad_fp8.h, Geom::w_bf16). */ + { + LinearFP8& probe = m.qkv0; + RAD_ARCH_TRY(probe.probe(b, nm, gd, "dit.blk.0.attn_qkv", + { "transformer.transformer_blocks.0.attn.to_q.weight", + "transformer.transformer_blocks.0.attn.to_k.weight", + "transformer.transformer_blocks.0.attn.to_v.weight" })); + RadEncoding e{}; + const bool plain = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e) && + rad_enc_is(&e, "plain"); + gd.w_bf16 = gf.w_bf16 = m.gt.w_bf16 = plain; + } + + /* ---- the per-image state, the conditioning store, and in issue order the language model, + * the text fusion, the DiT and the decoder */ + const int64_t lane_rows = (int64_t)kMaxLanes * kMaxImageTokens; + m.b_state = decl_b(b, nm.f("lat_state"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST); + m.b_prev = decl_b(b, nm.f("lat_preview"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST); + m.b_store = decl_b(b, nm.f("cond_store"), RAD_BF16, + { 2 * (int64_t)kMaxLanes * kCondRows, gd.n_embd }, RAD_BUF_PERSIST); + RAD_ARCH_TRY(declare_te(b, meta, m)); + RAD_ARCH_TRY(declare_fusion(b, meta, m)); + RAD_ARCH_TRY(declare_dit(b, meta, m)); + RAD_ARCH_TRY(declare_decoder(b, meta, m)); + + /* ---- what the core drives */ + if (!ctx->shape_probe) { + static thread_local std::string tmpl, drop; + tmpl = std::string("<|im_start|>system\n") + kSysPrompt + + "<|im_end|>\n<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"; + drop = std::string("<|im_start|>system\n") + kSysPrompt + "<|im_end|>\n<|im_start|>user\n"; + RadGeneratorDecl d{}; + d.name = m.turbo ? "krea-2-turbo" : "krea-2"; + d.layout = RAD_GEN_LAYOUT_JOINT_STEP; + d.tmpl_text = tmpl.c_str(); + d.tmpl_edit = tmpl.c_str(); + d.drop_prefix = drop.c_str(); + d.latent_channels = m.C; + d.latent_scale = 16; + d.size_multiple = 16; + d.pixel_channels = 3; + d.slot_rows = 1; + d.max_tokens = kMaxImageTokens; + d.max_refs = 0; + d.ref_area = 1; + d.default_width = 1024; + d.default_height = 1024; + /* Raw: 28 steps on the resolution-shifted schedule, guidance 4.5 in the card's terms. + * Turbo: 8 steps at a fixed mu of 1.15 (base and max shift equal), no guidance. */ + d.default_steps = m.turbo ? 8 : 28; + d.n_sigmas = 0; + d.sigmas = nullptr; + d.shift = rad_meta_getf(meta, "scheduler.shift", 1.0); + d.dyn_shift = (int32_t)rad_meta_geti(meta, "scheduler.use_dynamic_shifting", 1); + d.shift_exp = std::strcmp(rad_meta_gets(meta, "scheduler.time_shift_type", "exponential"), + "exponential") == 0; + d.base_shift = m.turbo ? 1.15 : rad_meta_getf(meta, "scheduler.base_shift", 0.5); + d.max_shift = m.turbo ? 1.15 : rad_meta_getf(meta, "scheduler.max_shift", 1.15); + d.base_seq = rad_meta_geti(meta, "scheduler.base_image_seq_len", 256); + d.max_seq = rad_meta_geti(meta, "scheduler.max_image_seq_len", 6400); + d.shift_terminal = rad_meta_getf(meta, "scheduler.shift_terminal", 0.0); + d.cfg_original = 1; + d.default_cfg = m.turbo ? 0.0 : 4.5; + d.default_negative = ""; + d.max_lanes = kMaxLanes; + d.image_out = m.b_img; + d.cond_rows = kCondRows; + d.rope_hw_scale = 1.0; + d.rope_text_l = 0; + RAD_ARCH_TRY(rad_declare_generator(b, &d)); + } + rad_note(b, "rank %d/%d: Krea 2%s -- text encoder %d of %lld layers, text fusion %zu + %zu " + "blocks, DiT %lld blocks (%lld/%lld heads a rank, ff %lld), %s linears", + m.gt.rank, m.gt.world, m.turbo ? " Turbo" : "", kTaps[kNTaps - 1], + (long long)m.gt.n_layer, m.lw.size(), m.rf.size(), (long long)gd.n_layer, + (long long)gd.n_head, (long long)gd.n_head_kv, (long long)gd.n_ff, + gd.w_bf16 ? "bf16" : "block-fp8"); + return RAD_OK; +} + +/* ================================================================== step */ +/* The language model over the prompt (the system turn included, as the reference runs it), each + * tapped layer's rows scattered to the taps at row 12 t + i. */ +static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) { + const Geom& g = m.gt; + const int64_t T = batch->n_tok; + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), + brows(m.b_tx, T)); + RAD_ISSUE_N(c, m.op_iota, T, brows(m.b_tidx, T)); + const RadOperand pos = praw2(batch->rope_pos, RAD_I32, 3, T); + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, 2); + for (const TeLayer& L : m.te) { + RAD_ISSUE_N(c, L.op_n1, T, brows(m.b_tx, T), RAD_W(L.w_n1), brows(m.a_th.x, T)); + L.q_h.step(c, T); + L.qkv.step(c, m.a_th, m.b_tkv, T); + RAD_ISSUE_N(c, L.op_qkr, T, brows(m.b_tkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn)); + RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_tkv, 0, q_dim, T), bcol(m.b_tkv, q_dim, kv_dim, T), + bcol(m.b_tkv, q_dim + kv_dim, kv_dim, T), cu, brows(m.a_tattn.x, T)); + L.q_attn.step(c, T); + L.o.step(c, m.a_tattn, m.b_th2, T); + if (L.op_ar1) RAD_ISSUE_N(c, L.op_ar1, T * g.n_embd, brows(m.b_th2, T), RAD_NONE); + RAD_ISSUE_N(c, L.op_add1, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + RAD_ISSUE_N(c, L.op_n2, T, brows(m.b_tx, T), RAD_W(L.w_n2), brows(m.a_th.x, T)); + L.q_h2.step(c, T); + L.gate_up.step(c, m.a_th, m.b_tgu, T); + L.gq.step(c, m.b_tgu, T); + L.down.step(c, m.a_tffn, m.b_th2, T); + if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, T * g.n_embd, brows(m.b_th2, T), RAD_NONE); + RAD_ISSUE_N(c, L.op_add2, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + if (L.tap >= 0) + RAD_ISSUE_N(c, L.op_tap, T, brows(m.b_tx, T), brows(m.b_tidx, T), + brow_slice(m.b_taps, L.tap, (int64_t)kTeRows * kNTaps - L.tap, + g.n_embd)); + } +} + +/* One text-fusion block over `R` rows of its residual from row `r0`, bounded by `cu`. */ +static void step_fuse(RadCtx* c, const Model& m, const FuseBlock& F, int64_t r0, int64_t R, + const RadOperand& cu) { + const Geom& g = m.gf; + const int64_t D = g.n_embd, qd = g.q_dim(), hd = g.head_dim; + const RadOperand x = brow_slice(F.x, r0, R, D); + RAD_ISSUE_N(c, F.op_n1, R, x, RAD_W(F.w_n1), brows(m.a_fh.x, R)); + F.q_h.step(c, R); + F.qkv.step(c, m.a_fh, m.b_fqkv, R); + F.gate.step(c, m.a_fh, m.b_fg, R); + RAD_ISSUE_N(c, F.op_qkn, R, brows(m.b_fqkv, R), RAD_NONE, RAD_W(F.w_qn), RAD_W(F.w_kn)); + RAD_ISSUE_N(c, F.op_attn, R, bcol(m.b_fqkv, 0, qd, R), bcol(m.b_fqkv, qd, qd, R), + bcol(m.b_fqkv, 2 * qd, qd, R), cu, brows(m.a_fattn.x, R)); + if (F.op_sig) { + RAD_ISSUE_N(c, F.op_sig, R, brows(m.b_fg, R), brows(m.b_fg, R)); + RAD_ISSUE_N(c, F.op_gq, R, brows(m.a_fattn.x, R), brows(m.b_fg, R), brows(m.a_fattn.x, R)); + F.q_attn.step(c, R); + } else { + const int64_t rh = R * (qd / hd), nb = hd / RAD_FP8_BLOCK; + RAD_ISSUE_N(c, F.op_gq, rh, RAD_P_T2(rad_buf_ptr(c, m.b_fg), RAD_BF16, rh, hd), + RAD_P_T2(rad_buf_ptr(c, m.a_fattn.x), RAD_BF16, rh, hd), + RAD_P_T2(rad_buf_ptr(c, m.a_fattn.cq()), RAD_F8E4M3, rh, hd), + RAD_P_T2(rad_buf_ptr(c, m.a_fattn.cs()), RAD_F32, rh, nb), + RAD_P_T2(rad_buf_ptr(c, m.a_fattn.x), RAD_BF16, rh, hd)); + } + F.o.step(c, m.a_fattn, m.b_fo, R); + if (F.op_ar1) RAD_ISSUE_N(c, F.op_ar1, R * D, brows(m.b_fo, R), RAD_NONE); + RAD_ISSUE_N(c, F.op_add1, R, x, brows(m.b_fo, R), x); + RAD_ISSUE_N(c, F.op_n2, R, x, RAD_W(F.w_n2), brows(m.a_fh.x, R)); + F.q_h2.step(c, R); + F.gate_up.step(c, m.a_fh, m.b_fgu, R); + F.gq.step(c, m.b_fgu, R); + F.down.step(c, m.a_fffn, m.b_fo, R); + if (F.op_ar2) RAD_ISSUE_N(c, F.op_ar2, R * D, brows(m.b_fo, R), RAD_NONE); + RAD_ISSUE_N(c, F.op_add2, R, x, brows(m.b_fo, R), x); +} + +/* The conditioning: the language model's taps, the text fusion over the tokens after the system + * turn (the layer-wise blocks over each token's twelve taps, the mix, the refiner over the + * tokens), txt_in, and the rows into every lane's store at this branch. */ +static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t P = G->rows, drop = batch->n_tok - P; + const int64_t D = m.gf.n_embd, Dd = m.gd.n_embd, RL = P * kNTaps; + step_te(c, batch, m); + RAD_ISSUE_N(c, m.op_fcu, P + 1, brows(m.b_fcu, P + 1)); + for (const FuseBlock& F : m.lw) step_fuse(c, m, F, drop * kNTaps, RL, brows(m.b_fcu, P + 1)); + RAD_ISSUE_N(c, m.op_mix, P, brow_slice(m.b_taps, drop * kNTaps, RL, D), RAD_W(m.w_mix), + brows(m.b_ft, P)); + const RadOperand cu = praw(G->seg_cu, RAD_I32, 2); + for (const FuseBlock& F : m.rf) step_fuse(c, m, F, 0, P, cu); + RAD_ISSUE_N(c, m.op_txn, P, brows(m.b_ft, P), RAD_W(m.w_txn), brows(m.b_txa, P)); + RAD_ISSUE_N(c, m.op_tx1, P, brows(m.b_txa, P), RAD_W(m.w_tx1), RAD_W(m.b_tx1), RAD_NONE, + brows(m.b_txb, P)); + RAD_ISSUE_N(c, m.op_txg, P, brows(m.b_txb, P), brows(m.b_txb, P)); + RAD_ISSUE_N(c, m.op_tx2, P, brows(m.b_txb, P), RAD_W(m.w_tx2), RAD_W(m.b_tx2), RAD_NONE, + brows(m.b_txt, P)); + RAD_ISSUE_N(c, m.op_store, P, brows(m.b_txt, P), praw(G->lane, RAD_I32, G->n_lane), + brow_slice(m.b_store, (int64_t)G->branch * kCondRows, + 2 * (int64_t)kMaxLanes * kCondRows - G->branch * kCondRows, Dd)); +} + +/* One denoising step: the entries' modulation, the joint rows, the blocks, and the image rows' + * output through the sampler. */ +static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const Geom& g = m.gd; + const int64_t N = batch->n_tok, S = batch->n_seq, NI = G->n_img; + const int64_t D = g.n_embd, qd = g.q_dim(), kvd = g.kv_dim(), hd = g.head_dim; + const int64_t L = g.n_layer, W = L * 6 * D, nD = D / RAD_FP8_BLOCK; + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1); + const RadOperand icu = praw(G->img_cu, RAD_I32, S + 1); + const RadOperand lanes = praw(G->lane, RAD_I32, S); + const int64_t LR = (int64_t)kMaxLanes * kMaxImageTokens; + + /* ---- modulation: the timestep MLP, the shared projection, each block's table, the final */ + RAD_ISSUE_N(c, m.op_temb, S, praw(G->sigma, RAD_F32, S), brows(m.b_tproj, S)); + RAD_ISSUE_N(c, m.op_t1, S, brows(m.b_tproj, S), RAD_W(m.w_t1), RAD_W(m.b_t1), RAD_NONE, + brows(m.b_te1, S)); + RAD_ISSUE_N(c, m.op_tg, S, brows(m.b_te1, S), brows(m.b_te1g, S)); + RAD_ISSUE_N(c, m.op_t2, S, brows(m.b_te1g, S), RAD_W(m.w_t2), RAD_W(m.b_t2), RAD_NONE, + brows(m.b_temb, S)); + RAD_ISSUE_N(c, m.op_tg2, S, brows(m.b_temb, S), brows(m.b_tembg, S)); + RAD_ISSUE_N(c, m.op_mod, S, brows(m.b_tembg, S), RAD_W(m.w_mod), RAD_W(m.b_mod), RAD_NONE, + brows(m.b_tmod, S)); + RAD_ISSUE_N(c, m.op_ftab, S, brows(m.b_temb, S), RAD_W(m.w_ftab), brows(m.b_fmod, S)); + + /* ---- the rows: the images' latents (noise on a first step), img_in, joined with the text */ + RAD_ISSUE_N(c, m.op_randn, NI, praw(G->flags, RAD_I32, S), praw(G->seed, RAD_U32, 2 * S), + lanes, icu, brows(m.b_state, LR)); + RAD_ISSUE_N(c, m.op_lgather, NI, brows(m.b_state, LR), lanes, icu, brows(m.b_lat, NI)); + RAD_ISSUE_N(c, m.op_imgin, NI, brows(m.b_lat, NI), RAD_W(m.w_imgin), RAD_W(m.b_imgin), RAD_NONE, + brows(m.b_himg, NI)); + RAD_ISSUE_N(c, m.op_join, N, brows(m.b_store, 2 * (int64_t)kMaxLanes * kCondRows), + brows(m.b_himg, NI), praw(G->src, RAD_I32, N), brows(m.b_h, N)); + + /* ---- the blocks; block l's modulation is columns [6 l D, 6 (l + 1) D) of `mods`: + * (preshift, prescale), pregate, (postshift, postscale), postgate */ + const RadOperand pos = praw2(G->rope_f, RAD_F32, 4, N); + auto mod = [&](int64_t l, int k, int width) { return bcol_at(m.b_mods, 0, W, (6 * l + k) * D, + width * D, S); }; + const bool q8 = !g.w_bf16; + for (int64_t l = 0; l < L; ++l) { + const DitLayer& B = m.dit[(size_t)l]; + /* The block's modulation: the shared projection plus its own table, into its columns. */ + RAD_ISSUE_N(c, B.op_tab, S, brows(m.b_tmod, S), RAD_W(B.w_tab), + bcol_at(m.b_mods, 0, W, l * 6 * D, 6 * D, S)); + if (q8) + RAD_ISSUE_N(c, B.op_n1, N, l > 0 ? brows(m.b_ao, N) : RAD_NONE, + l > 0 ? mod(l - 1, 5, 1) : RAD_NONE, mod(l, 0, 2), RAD_W(B.w_n1), cu, + brows(m.b_h, N), brows(m.a_hm.q, N), brows(m.a_hm.s, N), RAD_NONE); + else + RAD_ISSUE_N(c, B.op_n1, N, l > 0 ? brows(m.b_ao, N) : RAD_NONE, + l > 0 ? mod(l - 1, 5, 1) : RAD_NONE, mod(l, 0, 2), RAD_W(B.w_n1), cu, + brows(m.b_h, N), brows(m.a_hm.x, N)); + B.qkv.step(c, m.a_hm, m.b_qkv, N); + B.gate.step(c, m.a_hm, m.b_g, N); + RAD_ISSUE_N(c, B.op_qkr, N, brows(m.b_qkv, N), pos, RAD_W(B.w_qn), RAD_W(B.w_kn)); + RAD_ISSUE_N(c, B.op_attn, N, bcol(m.b_qkv, 0, qd, N), bcol(m.b_qkv, qd, kvd, N), + bcol(m.b_qkv, qd + kvd, kvd, N), cu, brows(m.a_attn.x, N)); + if (B.op_sig) { + RAD_ISSUE_N(c, B.op_sig, N, brows(m.b_g, N), brows(m.b_g, N)); + RAD_ISSUE_N(c, B.op_gq, N, brows(m.a_attn.x, N), brows(m.b_g, N), brows(m.a_attn.x, N)); + B.q_attn.step(c, N); + } else { + const int64_t rh = N * (qd / hd), nb = hd / RAD_FP8_BLOCK; + RAD_ISSUE_N(c, B.op_gq, rh, RAD_P_T2(rad_buf_ptr(c, m.b_g), RAD_BF16, rh, hd), + RAD_P_T2(rad_buf_ptr(c, m.a_attn.x), RAD_BF16, rh, hd), + RAD_P_T2(rad_buf_ptr(c, m.a_attn.cq()), RAD_F8E4M3, rh, hd), + RAD_P_T2(rad_buf_ptr(c, m.a_attn.cs()), RAD_F32, rh, nb), + RAD_P_T2(rad_buf_ptr(c, m.a_attn.x), RAD_BF16, rh, hd)); + } + B.o.step(c, m.a_attn, m.b_ao, N); + if (B.op_ar1) RAD_ISSUE_N(c, B.op_ar1, N * D, brows(m.b_ao, N), RAD_NONE); + if (q8) + RAD_ISSUE_N(c, B.op_n2, N, brows(m.b_ao, N), mod(l, 2, 1), mod(l, 3, 2), RAD_W(B.w_n2), + cu, brows(m.b_h, N), brows(m.a_hm.q, N), brows(m.a_hm.s, N), RAD_NONE); + else + RAD_ISSUE_N(c, B.op_n2, N, brows(m.b_ao, N), mod(l, 2, 1), mod(l, 3, 2), RAD_W(B.w_n2), + cu, brows(m.b_h, N), brows(m.a_hm.x, N)); + B.gate_up.step(c, m.a_hm, m.b_gu, N); + B.gq.step(c, m.b_gu, N); + B.down.step(c, m.a_ffn, m.b_ao, N); + if (B.op_ar2) RAD_ISSUE_N(c, B.op_ar2, N * D, brows(m.b_ao, N), RAD_NONE); + } + (void)nD; + /* ---- the last block's feed-forward gated in, the image rows out, the final layer */ + RAD_ISSUE_N(c, m.op_g2, N, brows(m.b_ao, N), mod(L - 1, 5, 1), cu, brows(m.b_h, N)); + RAD_ISSUE_N(c, m.op_gimg, NI, brows(m.b_h, N), praw(G->img_rows, RAD_I32, NI), + brows(m.b_hi, NI)); + RAD_ISSUE_N(c, m.op_fn, NI, RAD_NONE, RAD_NONE, brows(m.b_fmod, S), RAD_W(m.w_fn), icu, + brows(m.b_hi, NI), brows(m.b_fz, NI)); + RAD_ISSUE_N(c, m.op_pout, NI, brows(m.b_fz, NI), RAD_W(m.w_pout), RAD_W(m.b_pout), RAD_NONE, + brows(m.b_v, NI)); + RAD_ISSUE_N(c, m.op_euler, NI, brows(m.b_v, NI), praw(G->sigma, RAD_F32, S), + praw(G->sigma_next, RAD_F32, S), praw(G->cfg, RAD_F32, S), + praw(G->pair, RAD_I32, S), lanes, praw(G->flags, RAD_I32, S), + praw(G->seed, RAD_U32, 2 * S), icu, RAD_NONE, RAD_NONE, brows(m.b_state, LR), + brows(m.b_prev, LR)); +} + +/* One image's latent to RGB: denormalised, unpacked to the VAE's grid, decoded (in row bands + * with more than one rank). */ +static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t H = G->dec_height / 16, W = G->dec_width / 16, n = H * W, C = m.C; + const rad_buf src = G->dec_preview ? m.b_prev : m.b_state; + RAD_ISSUE_N(c, m.op_dinv, n, brow_slice(src, (int64_t)G->dec_lane * kMaxImageTokens, n, C), + brows(m.b_dl, n)); + RAD_ISSUE_N(c, m.op_dadd, n, brows(m.b_dl, n), brows(m.b_dl2, n)); + const int64_t zd = C / 4, H0 = 2 * H, W0 = 2 * W; + RAD_ISSUE_N(c, m.op_dzero, H0 * W0, brows(m.b_decin, H0 * W0)); + RAD_ISSUE_N(c, m.op_unpack, H0 * W0, + RAD_P_T2(rad_buf_ptr(c, m.b_dl2), RAD_BF16, H, W * C), + RAD_P_T2(rad_buf_ptr(c, m.b_decin), RAD_BF16, H0, W0 * zd)); + RAD_ISSUE_N(c, m.op_cu4, 2, praw(batch->cu_seqlens + 1, RAD_I32, 1), brows(m.b_cu4, 2)); + const RadOperand cu = brows(m.b_cu4, 2); + const int64_t npx = (int64_t)G->dec_height * G->dec_width; + const int world = m.gt.world, rank = m.gt.rank; + const int64_t band = (H0 + world - 1) / world, halo = m.dec.halo; + if (!m.op_bands || band + 2 * halo >= H0) { + m.dec.issue(c, H0, W0, cu, nullptr); + RAD_ISSUE_N(c, m.op_rgb, npx, RAD_P_T2(rad_buf_ptr(c, m.dec_out.buf), RAD_BF16, npx, 3), + RAD_P_T2(rad_buf_ptr(c, m.b_img), RAD_U8, npx, 3)); + return; + } + m.dec.issue(c, H0, W0, cu, nullptr, 0, (size_t)m.dec.band_from); + const int64_t a = rank * band; + const int64_t lo = std::max(0, a - halo), hi = std::min(H0, a + band + halo); + m.dec.issue(c, hi - lo, W0, cu, nullptr, (size_t)m.dec.band_from, (size_t)-1, lo); + const int64_t bpx = band * 8 * W0 * 8; + const char* out = (const char*)rad_buf_ptr(c, m.dec_out.buf) + + (a - lo) * 8 * W0 * 8 * 3 * (int64_t)sizeof(uint16_t); + RAD_ISSUE_N(c, m.op_bands, bpx * 3, RAD_P_T2(out, RAD_BF16, bpx, 3), + RAD_P_T2(rad_buf_ptr(c, m.b_rgbf), RAD_BF16, world * bpx, 3)); + RAD_ISSUE_N(c, m.op_rgb_bands, npx, RAD_P_T2(rad_buf_ptr(c, m.b_rgbf), RAD_BF16, npx, 3), + RAD_P_T2(rad_buf_ptr(c, m.b_img), RAD_U8, npx, 3)); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (!batch->gen || !batch->gen_b) { + rad_step_fail(c, "krea2 is an image generator and runs generator passes only"); + return; + } + switch (batch->gen) { + case RAD_GEN_PASS_COND: step_cond(c, batch, m); return; + case RAD_GEN_PASS_DENOISE: step_denoise(c, batch, m); return; + case RAD_GEN_PASS_DECODE: step_decode(c, batch, m); return; + default: rad_step_fail(c, "krea2: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +/* The rows a pass carries: one image at the largest size with guidance, its text both ways. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->gen_rows = 2 * ((int64_t)kMaxImageTokens + kCondRows); + out->gen_patches = 0; + return RAD_OK; +} + +} /* namespace krea2 */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(krea2) +RAD_ARCH_PLUGIN(krea2, "krea2", "", "0.1.0", + "Krea 2 / Krea 2 Turbo: Qwen3-VL-4B taps through a text-fusion transformer, a 12.9B " + "single-stream diffusion transformer over the joint text and image, and Wan 2.1's " + "VAE; bf16 or block-fp8 linears") +#endif diff --git a/arch/ltx2/CMakeLists.txt b/arch/ltx2/CMakeLists.txt new file mode 100644 index 00000000..1388a407 --- /dev/null +++ b/arch/ltx2/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/ltx2 -B build -DCMAKE_PREFIX_PATH=`); 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) diff --git a/arch/ltx2/ltx2.cpp b/arch/ltx2/ltx2.cpp new file mode 100644 index 00000000..e0e9f6b5 --- /dev/null +++ b/arch/ltx2/ltx2.cpp @@ -0,0 +1,4193 @@ +/* ltx2 -- LTX-2.5: a video and its stereo soundtrack from text, or from text and a first frame. + * + * ============================== THE MODEL ============================== + * + * diffusers' LTX2Pipeline (LTX-2.5's components, Lightricks/LTX-2.5-Diffusers): + * + * Text encoder: Gemma 4's language model over the prompt, left-padded to 1024 tokens (no + * template; the tokenizer's and around it). Every layer's output is kept -- the + * embeddings, each layer's but the last, and the final norm of the last -- and each token's + * stack of them is RMS-normed per layer and flattened channel-major. + * + * Connectors: per modality a projection of that stack to the DiT's width (video 4096, audio + * 2048), then 1024 rows -- the prompt's tokens, the rest filled from 128 learnable registers -- + * through eight bidirectional transformer blocks with a split rotary over the row index. + * + * Denoiser: a dual-stream DiT, 48 blocks over the video's latents (1 x 1 patches of 128 channels, + * 32 pixels a latent, 8 frames a latent frame) and the soundtrack's (25 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, each behind an adaptive norm; the soundtrack's the same + * against the video. Every attention is gated per head (2 sigmoid of a logit) and normalises q + * and k across all heads. + * + * Guidance: up to four DiT evaluations a step -- the prompt, the negative prompt, the prompt with + * block 28's self-attentions bypassed (spatio-temporal guidance) and the prompt without the + * cross-modal attentions -- combined in the clean-estimate space with a rescale + * (abi/rad_builder.h, RadVideoGenDecl::guidance; the op ltx_guide). + * + * Video VAE: a causal 3D-conv decoder (four up blocks of residual blocks, depth-to-space + * resampling, PerChannelRMSNorm), 4 x 4 pixel patches out; its encoder takes a first frame in. + * + * Audio: a causal 2D-conv decoder to a stereo log-mel spectrogram at 16 kHz, a BigVGAN vocoder + * to 16 kHz, and a bandwidth extender (its own vocoder over the waveform's log-mel spectrogram + * plus a sinc-resampled skip) to 48 kHz. + * + * Latent upsampler (latent_upsampler/): two-times spatial upscaling of the video latent for the + * two-stage recipe (a distilled release's stage-2 rungs, RadVideoGenDecl::refine_rungs). + * + * Duration head (duration_head/): the length the prompt implies, pooled by one learned query + * from both connectors' output (RadVideoGenDecl::duration_out). + * + * Diffusion decoder (diffusion_decoder/): the release's second decoder, on request + * (RadVideoGenDecl::decoders): neighbourhood-attention stages over the latent, then one denoising + * step over pixel patches, tile by tile (declare_ddec says how). + * + * The passes are the core's video generator (core/gen/video_driver.h): + * + * VCOND the text encoder over both prompts, the connectors into the lane's text rows, the + * duration head over the prompt's, and with a first frame the VAE encoder into the + * lane's clean first latent frame. + * VSTEP the step's modulation tables, then each guidance evaluation the request needs, then + * one ltx_guide a modality; with a first frame, its latent frame restored. + * ADECODE the soundtrack: the audio VAE, the vocoder, the bandwidth extender. + * VDECODE chunk 0 decodes the whole video into the lane's tile store, a tile at a time for a + * frame larger than the default canvas; every chunk then stitches its frames to bytes. + * VUPSCALE the latent upsampler, then both latents re-noised for the second stage. + * + * ============================== PRECISION ============================== + * + * Every network computes in bf16, as the reference loads it; the latents, the guidance and the + * sampler are f32. The text encoder's, the connectors' and the DiT's large linears are bf16 or + * block fp8 as the container holds them (data/recipes/ltx-2.5-fp8.recipe); the vocoder runs in + * f32 (its anti-aliased activation's kernels are f32), its log-mel input rounded where the + * reference's bf16 one is. + * + * ============================== LIMITS ============================== + * + * One rank (TP 1): the DiT's q and k norms span every head, which a head split would cut. A step + * carries 121 frames at 1920 x 1088 at most; the diffusion decoder decodes the default canvas's + * area at most. The prompt enhancer and the temporal upsampler (the DFR pipeline's) are not run. + */ +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace ltx2 { + +using namespace rad::arch; + +/* ================================================================== the model's constants */ +/* Connector rows a prompt: the text encoder's padded length. */ +enum { kTextRows = 1024 }; +/* Requests holding state at once: one denoising, one conditioned and waiting. */ +enum { kMaxLanes = 2 }; +/* Evaluations a request may take, and the base model's default. */ +enum { kMaxSteps = 64, kDefSteps = 30 }; +/* Time: 24 frames a second; a video of n chunks is 8 n + 1 frames over n + 1 latent frames. A + * decode pass is a chunk of frames; chunk 0 decodes the whole video, a tile at a time. */ +enum { kFps = 24, kFpc = 8, kFtail = 1, kLpc = 1, kLtail = 1, kDecLat = 2 }; +enum { kMinChunks = 2, kMaxChunks = 20, kDefChunks = 15 }; +/* Space: 32 pixels a latent; sides multiples of 32 from 256, 3:1 at most; the release's 960 x 544 + * canvas by default, and four times its area at most -- the two-stage recipe's 1920 x 1088. A + * step holds at most the video rows of 121 frames at that size. */ +enum { kScale = 32, kMult = 32, kMinSide = 256, kMaxAspect = 3 }; +enum { kDefW = 960, kDefH = 544, kMaxArea = 4 * kDefW * kDefH }; +enum { kMaxVideoRows = 16 * (2 * kDefW / kScale) * (2 * kDefH / kScale) }; +/* The VAE decodes a frame of the default canvas's latents or fewer whole, as the pipeline does + * without tiling; a larger one in diffusers' tiles (enable_tiling: 512 pixels every 448, 16 latents + * every 14), blended where they overlap (tile_stitch). */ +enum { kVaeLat = kDefW * kDefH / (kScale * kScale), kTile = 16, kTileStride = 14 }; +/* The video latent's channels (a 1 x 1 patch), the VAE's pixel patch and its channels. */ +enum { kC = 128, kPix = 4, kPixC = 3 * kPix * kPix }; +/* The soundtrack: 25 latents a second of 8 channels x 16 mel bins, packed channel-major; its + * spectrogram 64 bins at 16 kHz with 160-sample hops; 48 kHz stereo out. */ +enum { kAudioRate = 25, kAudioCh = 2, kAudioC = 128, kLatCh = 8, kLatMel = 16, kMel = 64 }; +enum { kRate = 48000, kVocRate = 16000, kMelHop = 160 }; +/* Guidance terms (RadVideoGenBatch::guidance): the video's then the soundtrack's four. */ +enum { kGsV = 0, kStgV = 1, kMsV = 2, kGsA = 4, kStgA = 5, kMsA = 6 }; +/* The block whose self-attentions spatio-temporal guidance bypasses. */ +enum { kStgBlock = 28 }; +/* An evaluation of the DiT within a step: the prompt, the negative prompt, the prompt with STG, + * the prompt without the cross-modal attentions. */ +enum { kPassCond = 0, kPassUncond = 1, kPassStg = 2, kPassIso = 3, kPasses = 4 }; + +/* ================================================================== geometry, on the host */ +static int64_t max_lat_frames() { return (int64_t)kLpc * kMaxChunks + kLtail; } +static int64_t max_patches() { return (int64_t)kMaxArea / (kScale * kScale); } +static int64_t max_video_rows() { return kMaxVideoRows; } +static int64_t max_frames() { return (int64_t)kFpc * kMaxChunks + kFtail; } +static int64_t max_audio() { return (max_frames() * kAudioRate + kFps / 2) / kFps + 1; } +static int64_t max_step_rows() { return kTextRows + max_audio() + max_video_rows(); } +/* The spectrogram's frames for n audio latents (the audio VAE's causal upsampling). */ +static int64_t mel_frames(int64_t n) { return 4 * n - 3; } + +/* The VAE's tiles of an h x w latent grid, as tile_grid cuts them: one when the frame is the + * untiled decoder's, else a tile every kTileStride latents, kTile long or to the edge. */ +struct VaeTile { int64_t h, w; }; +static bool vae_tiled(int64_t h, int64_t w) { return h * w > kVaeLat; } +static std::vector vae_tiles(int64_t h, int64_t w) { + if (!vae_tiled(h, w)) return { { h, w } }; + std::vector t; + for (int64_t y0 = 0; y0 < h; y0 += kTileStride) + for (int64_t x0 = 0; x0 < w; x0 += kTileStride) + t.push_back({ std::min(kTile, h - y0), std::min(kTile, w - x0) }); + return t; +} + +/* The step's rotary coordinates, flat (the core hands them through as RadVideoGenBatch::pos): the + * video's (t, y, x) midpoints as [3, S] component-major, then the soundtrack's time midpoints, + * f32 as the reference computes them (LTX2AudioVideoRotaryPosEmbed's prepare_*_coords at 24 + * frames a second). A latent frame f spans pixel frames [max(8 f - 7, 0), 8 f + 1) over the fps; + * a latent (h, w) pixels [32 h, 32 h + 32); an audio latent mel frames [max(4 f - 3, 0), 4 f + 1) + * at 160 / 16000 s a frame. */ +static int64_t positions(const RadVideoGeom* g, float* pos, int64_t cap) { + if (!g || g->n_text < 1 || g->lat_frames < 1 || g->lat_h < 1 || g->lat_w < 1 || g->n_audio < 1) + return RAD_E_INVAL; + const int64_t F = g->lat_frames, H = g->lat_h, W = g->lat_w, S = F * H * W, A = g->n_audio; + const int64_t rows = g->n_text + A + S; + if (S > max_video_rows()) return RAD_E_INVAL; + if (!pos) return rows; + if (cap < rows) return RAD_E_INVAL; + float* pt = pos; + float* py = pos + S; + float* px = pos + 2 * S; + float* pa = pos + 3 * S; + int64_t r = 0; + for (int64_t f = 0; f < F; ++f) { + const float t0 = std::max(8.0f * (float)f + 1.0f - 8.0f, 0.0f) / (float)kFps; + const float t1 = std::max(8.0f * (float)(f + 1) + 1.0f - 8.0f, 0.0f) / (float)kFps; + const float tm = (t0 + t1) / 2.0f; + for (int64_t h = 0; h < H; ++h) + for (int64_t w = 0; w < W; ++w, ++r) { + pt[r] = tm; + py[r] = (32.0f * (float)h + 32.0f * (float)(h + 1)) / 2.0f; + px[r] = (32.0f * (float)w + 32.0f * (float)(w + 1)) / 2.0f; + } + } + for (int64_t f = 0; f < A; ++f) { + const float m0 = std::max(4.0f * (float)f + 1.0f - 4.0f, 0.0f); + const float m1 = std::max(4.0f * (float)(f + 1) + 1.0f - 4.0f, 0.0f); + const float s0 = m0 * (float)kMelHop / (float)kVocRate; + const float s1 = m1 * (float)kMelHop / (float)kVocRate; + pa[f] = (s0 + s1) / 2.0f; + } + return rows; +} + +/* ================================================================== linears */ +/* An activation a linear reads: its bf16 plane and, for block-fp8 linears, its codes, which a + * quantiser makes from the plane (QuantFP8). */ +struct Act { + ActFP8 a{}; + QuantFP8 q{}; + int64_t n = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t rows, + int64_t width) { + n = width; + a.x = decl_b(b, nm.f("%s", name), RAD_BF16, { rows, width }); + if (!a.x) return RAD_E_INVAL; + Geom gg = g; + gg.max_tok = rows; + RAD_ARCH_TRY(a.declare_qs(b, nm, gg, name, width, rows)); + return q.declare(b, gg, a, width); + } + /* The codes of rows [r0, r0 + rows), at those rows' count. */ + void step(RadCtx* c, int64_t rows, int64_t r0 = 0) const { + if (!q.op || rows <= 0) return; + RAD_ISSUE_N(c, q.op, rows, brow_slice(a.x, r0, rows, n), brow_slice(a.cq(), r0, rows, n), + brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK)); + } +}; + +/* A linear, y = x W^T (+ b): `gemm_nt_bias` over the bf16 plane for a bf16 weight (the bias in the + * GEMM's one rounding, as torch's), or `gemm_nt_q` over the codes for a block-fp8 one with the + * bias added after (`table_add`, one more rounding). `small` keeps a weight bf16 in any container + * (a gate's logits: too few rows for 128-row fp8 blocks). The input and output rows may sit at + * different offsets of their buffers. */ +struct Lin { + LinearFP8 l{}; + rad_weight w = 0, bias = 0; + rad_op op = 0, op_b = 0; + bool fp8 = false; + bool mapped = false; /* the weight's name map was made already (a probe's) */ + int64_t N = 0, K = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, + std::initializer_list wsrc, std::initializer_list bsrc, + std::initializer_list parts, int64_t n_out, int64_t n_in, int access, + int group, const Act& in, rad_buf y, int64_t max_rows, bool small = false) { + N = n_out; + K = n_in; + const char* wn = nm.f("%s.weight", base); + const char* bn = nm.f("%s.bias", base); + if (bsrc.size()) { + if (bsrc.size() == 1) RAD_ARCH_TRY(map_copy(b, bn, *bsrc.begin())); + else RAD_ARCH_TRY(map_concat(b, bn, bsrc)); + bias = decl_w(b, bn, RAD_BF16, { N }, access, RAD_SHARD_NONE, grp_layer(group)); + if (!bias) return RAD_E_INVAL; + } + fp8 = !(g.w_bf16 || small); + if (!fp8) { + if (mapped) {} + else if (wsrc.size() == 1) RAD_ARCH_TRY(map_copy(b, wn, *wsrc.begin())); + else RAD_ARCH_TRY(map_concat(b, wn, wsrc)); + w = decl_w(b, wn, RAD_BF16, { N, K }, access, RAD_SHARD_NONE, grp_layer(group)); + if (!w) return RAD_E_INVAL; + op = bias ? rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, max_rows), RAD_INT("N", N), + RAD_INT("K", K), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)), + { in.a.x }, { y }) + : rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, max_rows), RAD_INT("N", N), + RAD_INT("K", K), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { in.a.x }, { y }); + return op ? RAD_OK : RAD_E_INVAL; + } + l.access = access; + l.mapped = mapped; + RAD_ARCH_TRY(l.declare(b, nm, g, base, N, K, RAD_SHARD_NONE, grp_layer(group), wsrc, in.a, y, + max_rows, parts)); + if (l.bf16 || l.i8 || l.mx || l.w4 || l.paro || l.paro5) { + fprintf(stderr, "radiance: ltx2: '%s' is not block fp8; this plugin reads bf16 or " + "block-fp8 linears\n", base); + return RAD_E_UNSUPPORTED; + } + op = l.op; + if (bias) + op_b = rw(b, RAD_OP(b, "table_add", + RAD_PARAMS(RAD_RANGE("M", 1, max_rows), RAD_INT("n", N), + RAD_INT("L", 1), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(bias)), + { y }, { y }); + return op && (!bias || op_b) ? RAD_OK : RAD_E_INVAL; + } + + /* Input rows [ri, ri + rows) to output rows [ro, ro + rows). */ + void step(RadCtx* c, const Act& in, rad_buf y, int64_t rows, int64_t ri = 0, + int64_t ro = 0) const { + if (rows <= 0) return; + const RadOperand out = brow_slice(y, ro, rows, N); + if (!fp8) { + if (bias) + RAD_ISSUE_N(c, op, rows, brow_slice(in.a.x, ri, rows, K), RAD_W(w), RAD_W(bias), + RAD_NONE, out); + else + RAD_ISSUE_N(c, op, rows, brow_slice(in.a.x, ri, rows, K), RAD_W(w), out); + return; + } + RAD_ISSUE_N(c, op, rows, brow_slice(in.a.q, ri, rows, K), + brow_slice(in.a.s, ri, rows, K / RAD_FP8_BLOCK), RAD_W(l.w), RAD_W(l.ws), out, + RAD_NONE, RAD_NONE); + if (op_b) RAD_ISSUE_N(c, op_b, rows, out, RAD_W(bias), out); + } +}; + +/* A weight copied as the checkpoint holds it, read whole. */ +static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype, + std::initializer_list shape, int access, int group) { + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, dtype, shape, access, RAD_SHARD_NONE, grp_layer(group)); +} + +static rad_op unary(RadBuilder* b, const char* op, int64_t rows, int64_t n, const char* dtype, + rad_buf in, rad_buf out) { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", dtype)), + RAD_NOWEIGHTS), + { in }, { out }); +} + +static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, const char* dtype, rad_buf a, rad_buf c, + rad_buf y) { + return rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", dtype)), + RAD_NOWEIGHTS), + { a, c }, { y }); +} + +static rad_op cast_op(RadBuilder* b, int64_t rows, int64_t n, const char* from, const char* to, + rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("from", from), + RAD_STR("to", to)), + RAD_NOWEIGHTS), + { x }, { y }); +} + +/* An RMS norm over n with an optional gain (none: a gain of one), bf16. */ +static rad_op rms_op(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, rad_buf x, + rad_buf y) { + return rw(b, w ? RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)) + : RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { x }, { y }); +} + +/* `norm(x) (1 + scale) + shift`, the shift and scale one row of the table `st` per entry of + * `cu_seqlens`; with `gated` the branch before it gated in first (x += g y, g a row of `gt`). + * `norm` rms, layer or none, without a gain. */ +static rad_op mod_op(RadBuilder* b, int64_t rows, int64_t n, double eps, bool gated, + const char* norm, rad_buf st, rad_buf gt, rad_buf x, rad_buf y, rad_buf z) { + rad_op op = RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16"), + RAD_STR("norm", norm)), + RAD_NOWEIGHTS); + if (!op) return 0; + rad_buf rd[4] = { st, x, gt, y }; + rad_buf wr[2] = { x, z }; + rad_op_reads(b, op, rd, gated ? 4 : 2); + rad_op_writes(b, op, wr, 2); + return op; +} + +/* x += g y, the gate one row per entry of `cu_seqlens`, no activation. */ +static rad_op gate_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf table, rad_buf y, rad_buf x) { + return rw(b, RAD_OP(b, "gate_add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16"), RAD_STR("act", "none")), + RAD_NOWEIGHTS), + { y, table, x }, { x }); +} + +/* A space-separated list off the container (rad-convert flattens arrays that way). */ +static std::vector meta_list(const RadModelMeta* m, const char* key) { + std::vector v; + const char* s = rad_meta_gets(m, key, nullptr); + while (s && *s) { + char* e = nullptr; + const double x = std::strtod(s, &e); + if (e == s) { ++s; continue; } + v.push_back(x); + s = e; + } + return v; +} + +static std::string ints(std::initializer_list v) { + std::string s; + for (long long x : v) { + char t[24]; + std::snprintf(t, sizeof t, "%s%lld", s.empty() ? "" : " ", x); + s += t; + } + return s; +} + +/* ================================================================== the model's parts */ +/* A text encoder layer: sliding or full attention, each class its own head geometry and rotary. */ +struct TeLayer { + bool full = false, v_from_k = false; + int64_t nh = 0, nkv = 0, hd = 0, rot = 0; + double theta = 0.0; + rad_weight w_in = 0, w_pa = 0, w_pf = 0, w_ff = 0, w_qn = 0, w_kn = 0, w_sc = 0; + Lin q{}, k{}, v{}, o{}, gu{}, down{}; + rad_op op_in = 0, op_vn = 0, op_qn = 0, op_kn = 0, op_rq = 0, op_rk = 0, op_attn = 0; + rad_op op_pa = 0, op_add1 = 0, op_pf = 0, op_act = 0, op_ff = 0, op_add2 = 0, op_sc = 0; + rad_op op_keep = 0; +}; +/* An attention class's rows: q, k, v and the attention's output. */ +struct TeClass { + rad_buf q = 0, k = 0, v = 0; + Act o{}; +}; + +/* An attention: q (k and v from the same rows for a self-attention), the per-head gate's logits, q + * and k RMS-normed across every head, the output projection. A cross-attention's k and v come from + * the context's rows. */ +struct Attn { + int64_t H = 0, hd = 0, inner = 0; + rad_weight w_qn = 0, w_kn = 0; + Lin qkv{}, kv{}, gate{}, out{}; + rad_op op_qn = 0, op_kn = 0, op_rq = 0, op_rk = 0, op_attn = 0, op_hg = 0, op_v = 0; +}; + +struct ConnBlock { + Attn at{}; + Lin up{}, down{}; + rad_op op_n1 = 0, op_add1 = 0, op_n2 = 0, op_act = 0, op_add2 = 0; +}; +/* A modality's connector: the stack's projection, the registers and the blocks. */ +struct Conn { + int64_t D = 0, H = 0, hd = 0, ff = 0; + double mult = 1.0; /* sqrt(D / text width), the normed stack's scale */ + rad_weight w_reg = 0; /* the registers, tiled to kTextRows rows */ + Lin proj{}; + rad_op op_norm = 0, op_reg = 0, op_nout = 0; + Act a_in{}, a_h{}, a_attn{}, a_ffn{}; + rad_buf b_x = 0, b_qkv = 0, b_g = 0, b_o = 0, b_up = 0; + rad_buf b_text = 0; /* PERSIST [lanes * 2 * kTextRows, D]: a lane's two prompts */ + std::vector blk; +}; + +/* A DiT block. The modulation tables are each block's learned rows plus the step's shared ones, + * made once a step into the step's tables (DitStep). */ +struct DitBlock { + Attn sv{}, sa{}, tv{}, ta{}, a2v{}, v2a{}; + Lin fv_up{}, fv_down{}, fa_up{}, fa_down{}; + rad_weight t_v = 0, t_a = 0, t_p = 0, t_pa = 0, t_cv = 0, t_cvg = 0, t_ca = 0, t_cag = 0; + rad_op op_tv = 0, op_ta = 0, op_tp = 0, op_tpa = 0, op_tcv = 0, op_tcvg = 0, op_tca = 0; + rad_op op_tcag = 0; + /* Video: the self-attention's norm (gated by the previous block's feed-forward), the text + * query's (gated by the self-attention), the text's modulation, the text gate, the two + * cross-modal modulations, the cross-modal gate, the feed-forward's norm ungated and gated by + * the text (a pass without the cross-modal attentions), the activation. Audio the same. */ + rad_op m1v = 0, m2v = 0, mtv = 0, g2v = 0, mav = 0, mvv = 0, gcv = 0, m3v = 0, m3vg = 0; + rad_op actv = 0; + rad_op m1a = 0, m2a = 0, mta = 0, g2a = 0, maa = 0, mva = 0, gca = 0, m3a = 0, m3ag = 0; + rad_op acta = 0; +}; + +/* One AdaLayerNormSingle: the timestep's MLP to `emb`, then SiLU and a linear to `temb`. */ +struct Ada { + int64_t d = 0, k = 0; + rad_weight w1 = 0, b1 = 0, w2 = 0, b2 = 0, wl = 0, bl = 0; + rad_op op1 = 0, ops1 = 0, op2 = 0, ops2 = 0, opl = 0; + rad_buf h = 0, hs = 0, emb = 0, es = 0, temb = 0; +}; + +/* A 3D residual block of the video VAE: PerChannelRMSNorm and SiLU, a convolution, again, the + * residual added. */ +struct VRes { + int64_t C = 0; + rad_weight w1 = 0, b1 = 0, w2 = 0, b2 = 0; + rad_op op_n1 = 0, op_c1 = 0, op_n2 = 0, op_c2 = 0; +}; +/* An up block: the upsampler's convolution and depth to space, then its residual blocks. */ +struct VUp { + int64_t cin = 0, cout = 0, st = 1, sh = 1, sw = 1, conv_out = 0; + rad_weight w = 0, b = 0; + rad_op op_conv = 0, op_d2s = 0, op_geom = 0; + rad_buf geom = 0; /* its output volume, i32 [3] */ + std::vector res; +}; +/* A down block: its residual blocks, then the downsampler's convolution, space to depth, and the + * input's group mean added. */ +struct VDown { + int64_t cin = 0, cout = 0, st = 1, sh = 1, sw = 1, conv_out = 0, group = 1; + std::vector res; + rad_weight w = 0, b = 0; + rad_op op_conv = 0, op_mean = 0, op_s2d = 0, op_geom = 0, op_geom_in = 0, op_next = 0; + rad_buf geom = 0, geom_in = 0; /* its convolution's volume, and its input's */ +}; + +/* An audio VAE residual block (2D, causal along time): PixelNorm and SiLU, conv, again, the + * input (or its 1x1 shortcut) added. */ +struct ARes { + int64_t cin = 0, cout = 0; + rad_weight w1 = 0, b1 = 0, w2 = 0, b2 = 0, ws = 0, bs = 0; + rad_op op_n1 = 0, op_c1 = 0, op_n2 = 0, op_c2 = 0, op_sc = 0, op_add = 0; +}; + +/* A vocoder convolution and an anti-aliased SnakeBeta (f32). */ +struct VConv { + rad_weight w = 0, b = 0; + rad_op op = 0; +}; +struct VAct { + rad_weight alpha = 0, beta = 0, up = 0, down = 0; + rad_op op = 0; +}; +struct VUnit { + VAct a1{}, a2{}; + VConv c1{}, c2{}; +}; +struct VStage { + int64_t ch = 0, rate = 0, k = 0; + VConv up{}; + VUnit u[3][3]; /* resnet j, dilation d */ + rad_op op_cu = 0, op_sum = 0, op_avg = 0; +}; +/* A vocoder (the base one or the bandwidth extender's). */ +struct Voc { + int64_t in = 0, hidden = 0, out = 0, mult = 1; + std::vector rates, ks, rk; + VConv cin{}, cout{}; + VAct act{}; + std::vector st; + rad_op op_cu0 = 0; + rad_buf in_buf = 0, wav = 0; /* its input [rows, 128] and output [rows, 2], f32 */ + std::vector cu, h, avg, t1, t2, amp[3]; +}; + +/* A latent upsampler residual block: conv, GroupNorm, SiLU, conv, GroupNorm, the residual added, + * SiLU. */ +struct URes { + rad_weight c1w = 0, c1b = 0, n1w = 0, n1b = 0, c2w = 0, c2b = 0, n2w = 0, n2b = 0; + rad_op op_c1 = 0, op_n1 = 0, op_c2 = 0, op_n2 = 0, op_add = 0, op_act = 0; +}; + +/* The diffusion decoder's neighbourhood-attention block: a deterministic stage's (pre-norm) or a + * diffusion block's (the latent context added, its norms modulated by the shared table plus its + * own). */ +struct DdBlock { + int64_t C = 0, ff = 0, kt = 0, kh = 0, kw = 0, chunk = 0; + int slot = 0; /* the q|k|v and gate|up buffers of its width */ + rad_weight w_n1 = 0, w_n2 = 0, w_nq = 0, w_nk = 0, w_o = 0, b_o = 0, w_gu = 0, w_down = 0; + rad_weight w_ctx = 0, b_ctx = 0, w_sst = 0; + rad_op op_n1 = 0, op_rope = 0, op_attn = 0, op_o = 0; + rad_op op_n2 = 0, op_gu = 0, op_act = 0, op_down = 0, op_add2 = 0; + rad_op op_ctx = 0, op_mod = 0; + /* q|k|v of a group of heads as one weight (the three projections' rows of the group), and its + * gemm into the q|k|v buffer: every head in one group, or in the diffusion stage one a group. */ + std::vector w_qkvh, b_qkvh; + std::vector op_qkvh; +}; +/* A deterministic stage: its blocks, then its pixel-shuffle upsample (a linear, then depth to + * space; the last stage's keeps the duplicate leading frame on a tile that does not start the + * video). */ +struct DdStage { + int64_t C = 0, cout = 0, st = 1, sh = 1, sw = 1; + std::vector blk; + rad_weight w_up = 0, b_up = 0; + rad_op op_proj = 0, op_d2s = 0, op_d2s_keep = 0, op_geom = 0, op_pos = 0; + rad_buf geom = 0; /* PERSIST: the stage's volume (its input grid) */ +}; + +/* Weight groups (movement units) by network. */ +enum : int { + kGrpConn = 1000, + kGrpTemb = 1100, + kGrpDit = 2000, + kGrpVae = 3000, + kGrpVenc = 3100, + kGrpAudio = 3200, + kGrpVoc = 3300, + kGrpUps = 3400, + kGrpDur = 1200, + kGrpDdec = 3500, +}; + +struct Model { + Names nm{""}; + Geom gt{}, gd{}; /* text encoder and connectors (prompt rows), DiT (step rows) */ + int64_t maxS = 0, maxA = 0, maxPpf = 0, maxVox = 0; + std::vector rungs, refine; + + /* ---- the text encoder: Gemma 4's language model, every layer's output kept */ + int64_t tC = 0, tL = 0, tFF = 0, tRows = 0; + double teps = 1e-6; + rad_weight w_tok = 0, w_tnorm = 0; + rad_op op_embed = 0, op_keep0 = 0, op_tnorm = 0; + rad_buf b_tx = 0, b_th2 = 0, b_tgu = 0, b_stack = 0; + Act a_th{}, a_tffn{}; + TeClass cls[2]; /* sliding, full */ + std::vector te; + + /* ---- the connectors */ + Conn cv{}, ca{}; + rad_buf b_rows = 0; /* i32 {0, kTextRows, 2 kTextRows} */ + rad_buf b_rpos = 0; /* i32 [2 kTextRows]: a connector row's index in its prompt */ + rad_buf b_zero = 0; /* bf16 zeros, one row of the widest connector */ + rad_op op_rows = 0, op_rpos = 0, op_zero = 0; + + /* ---- the duration head: the length the prompt implies, off both connectors' output */ + bool dur = false; + int64_t dP = 0; /* the pooler's width */ + rad_weight dw_vp = 0, dw_vpb = 0, dw_vemb = 0, dw_ap = 0, dw_apb = 0, dw_aemb = 0, dw_qt = 0; + rad_weight dw_q = 0, dw_qb = 0, dw_k = 0, dw_kb = 0, dw_v = 0, dw_vb = 0, dw_o = 0, dw_ob = 0; + rad_weight dw_h = 0, dw_hb = 0, dw_out = 0, dw_outb = 0; + rad_op op_dvp = 0, op_dap = 0, op_dvemb = 0, op_daemb = 0, op_dq0 = 0, op_dq = 0, op_dk = 0; + rad_op op_dv = 0, op_dcu = 0, op_dcuk = 0, op_dattn = 0, op_do = 0, op_dh = 0, op_dout = 0; + rad_op op_dlog = 0; + rad_buf b_dtok = 0, b_dk = 0, b_dv = 0, b_dq0 = 0, b_dq = 0, b_dat = 0, b_do = 0, b_dh = 0; + rad_buf b_dl = 0, b_dcu = 0, b_dcuk = 0, b_dur = 0; + + /* ---- the DiT */ + int64_t D = 0, Da = 0, H = 0, Ha = 0, hd = 0, hda = 0, Dc = 0, ffv = 0, ffa = 0, nb = 0; + double eps = 1e-6; + /* the step's timestep inputs {0, sigma}, their sinusoids, the eight modulation MLPs */ + rad_buf b_tin = 0, b_tsin = 0; + rad_op op_tin0 = 0, op_tin1 = 0, op_tsin = 0; + Ada ad_v{}, ad_a{}, ad_p{}, ad_pa{}, ad_cv{}, ad_cvg{}, ad_ca{}, ad_cag{}; + /* the step's tables (PERSIST): every block's rows, then the output norms' */ + rad_buf b_mv = 0, b_ma = 0, b_mp = 0, b_mpa = 0, b_mcv = 0, b_mcvg = 0, b_mca = 0, b_mcag = 0; + rad_buf b_fv = 0, b_fa = 0; + rad_weight w_fv = 0, w_fa = 0; + rad_op op_fv = 0, op_fa = 0; + /* the lanes (PERSIST): both latents and the clean first latent frame */ + rad_buf b_vstate = 0, b_astate = 0, b_first = 0; + rad_op op_rnd_v = 0, op_rnd_a = 0, op_keep_first = 0; + /* an evaluation */ + Act a_lv{}, a_la{}; + Lin pin_v{}, pin_a{}, pout_v{}, pout_a{}; + rad_op op_lv = 0, op_la = 0; + rad_buf b_hv = 0, b_ha = 0, b_qkvv = 0, b_qkva = 0, b_gv = 0, b_ga = 0, b_ov = 0, b_oa = 0; + rad_buf b_qv = 0, b_qa = 0, b_kvtv = 0, b_kvta = 0; + rad_buf b_qxv = 0, b_qxa = 0, b_kvxv = 0, b_kvxa = 0, b_gxv = 0, b_gxa = 0; + rad_buf b_upv = 0, b_upa = 0; + Act a_hv{}, a_ha{}, a_ctxv{}, a_ctxa{}, a_nv{}, a_nv2{}, a_na{}, a_na2{}; + Act a_aov{}, a_aoa{}, a_xv{}, a_xa{}, a_ffv{}, a_ffa{}, a_fv{}, a_fa{}; + std::vector dit; + rad_op op_fnv = 0, op_fna = 0; + rad_buf b_vel_v[kPasses] = {}, b_vel_a[kPasses] = {}; /* PERSIST: each evaluation's */ + rad_buf b_gst = 0; + rad_op op_gv = 0, op_ga = 0; + + /* ---- the video VAE's decoder: the whole video, a tile at a time, into the lane's tile + * store; each chunk's frames stitched to bytes. A latent frame f is pixel frames + * vAt f + vBt; a latent vAhw patches a side. */ + int64_t vC0 = 0, vAt = 1, vBt = 0, vAhw = 1, maxTiles = 0, maxStore = 0, maxSide = 0; + rad_weight vd_mean = 0, vd_std = 0, w_vcin = 0, b_vcin = 0, w_vcout = 0, b_vcout = 0; + rad_op op_vlat = 0, op_vden = 0, op_vcin = 0, op_vnout = 0, op_vcout = 0; + rad_op op_vgrid1 = 0, op_vgrid = 0, op_vcrop = 0, op_vf0 = 0, op_vst1 = 0, op_vst = 0; + std::vector vmid; + std::vector vup; + rad_buf b_vlat = 0, b_vtlat = 0, b_va = 0, b_vb = 0, b_vc = 0, b_vtiles = 0, b_frames = 0; + rad_buf b_vgrid = 0, b_vf0 = 0; + + /* ---- its encoder: a first frame into the lane's clean first latent frame */ + bool venc = false; + int64_t eC0 = 0, eCout = 0; + rad_weight w_ecin = 0, b_ecin = 0, w_ecout = 0, b_ecout = 0; + rad_op op_epatch = 0, op_ecin = 0, op_enout = 0, op_ecout = 0, op_enorm = 0, op_ef32 = 0; + rad_op op_egeomL = 0; + std::vector vdown; + std::vector emid; + rad_buf b_egeomL = 0, b_epatch = 0, b_ea = 0, b_eb = 0, b_ec = 0, b_eout = 0, b_elat = 0; + + /* ---- the audio VAE's decoder and the vocoders */ + int64_t aC0 = 0; + std::string a_mean, a_std; + rad_op op_aden = 0, op_acast = 0, op_aunpack = 0, op_acin = 0, op_anout = 0; + rad_op op_acout[2] = {}, op_amel = 0; + rad_weight w_acin = 0, b_acin = 0, w_acout[2] = {}, b_acout[2] = {}, w_amean = 0, w_astd = 0; + ARes amid[2]; + std::vector> aup; /* level 2, 1, 0 */ + std::vector aups; /* the upsamples after levels 2 and 1 */ + std::vector aups_cp; /* each upsample's rows past the first, back */ + std::vector alev_c; + rad_buf b_aden = 0, b_alat = 0, b_aimg = 0, b_aa = 0, b_ab = 0, b_ac = 0, b_as = 0; + rad_buf b_amel16 = 0, b_amel = 0; + Voc voc{}, bwe{}; + rad_weight w_basis = 0, w_melb = 0; + rad_op op_stft = 0, op_bwe = 0, op_bmel = 0, op_tail = 0; + rad_buf b_bmel16 = 0, b_bmel = 0, b_audio = 0; + + /* ---- the latent upsampler */ + bool ups = false; + int64_t uC = 0; + rad_weight u_cinw = 0, u_cinb = 0, u_ninw = 0, u_ninb = 0, u_upw = 0, u_upb = 0; + rad_weight u_coutw = 0, u_coutb = 0; + rad_op op_uden = 0, op_ucast = 0, op_ucin = 0, op_unin = 0, op_uup = 0, op_ud2s = 0; + rad_op op_ucout = 0, op_unorm = 0, op_uf32 = 0, op_ukeep = 0, op_ufirst = 0; + rad_op op_urnv = 0, op_urna = 0; + std::vector u_pre, u_post; + rad_buf b_ua = 0, b_ub = 0, b_uc = 0, b_ust = 0, b_uin = 0, b_uout = 0, b_uden = 0; + + /* ---- the diffusion decoder (diffusion_decoder/): deterministic stages 0..2 over the whole + * latent into the feature volume, then per tile stage 3 and the one-step diffusion stage into + * the tile store */ + bool ddec = false; + std::vector dst; /* the four deterministic stages */ + std::vector dblk; /* the diffusion blocks */ + int64_t dV0 = 0, dV1 = 0, dV2 = 0, dV3 = 0, dV4 = 0, dV5 = 0, dTiles = 0; + rad_weight dw_cin = 0, db_cin = 0, dw_xin = 0, db_xin = 0, dw_nout = 0, dw_cout = 0, db_cout = 0; + rad_weight dw_t1 = 0, db_t1 = 0, dw_t2 = 0, db_t2 = 0, dw_ad = 0, db_ad = 0; + rad_op op_dpad = 0, op_dcin = 0, op_dtin = 0, op_dtsin = 0, op_dt1 = 0, op_dts = 0, op_dt2 = 0; + rad_op op_das = 0, op_dad = 0, op_ddcu = 0, op_dsig = 0, op_dtgeom = 0, op_dgrid = 0; + rad_op op_dcrop = 0, op_dpos4 = 0, op_dg5[4] = {}, op_dpos5 = 0, op_dz = 0, op_dxcast = 0; + rad_op op_dxin = 0, op_dnout = 0, op_ddout = 0, op_dst = 0; + std::vector op_dnoise; /* each tile's noise: its own stream */ + rad_buf b_dz = 0, b_dx = 0, b_dfeat = 0, b_d4 = 0, b_ddh = 0, b_dctx = 0, b_dn = 0; + rad_buf b_dqkv[4] = {}, b_dg[4] = {}; /* per width 2048, 1024, 512, 256: q|k|v, gate|up */ + rad_buf b_dao = 0; /* the diffusion stage's attention, its heads side by side */ + rad_buf b_da = 0, b_dmo = 0, b_dpos = 0, b_dxt = 0, b_dxb = 0, b_dtin = 0; + rad_buf b_dtsin = 0, b_dth = 0, b_dths = 0, b_dtemb = 0, b_dtes = 0, b_dmod = 0, b_dbmod = 0; + rad_buf b_ddcu = 0, b_dsig = 0, b_dtg = 0, b_dgrid = 0, b_dg5 = 0; +}; + +static Model g_model[MAX_RANKS]; + +/* ================================================================== check_format */ +static long long tgeti(const RadModelMeta* m, const char* key, long long def) { + char k[160]; + std::snprintf(k, sizeof k, "text_config.%s", key); + return rad_meta_geti(m, k, rad_meta_geti(m, key, def)); +} +static double tgetf(const RadModelMeta* m, const char* key, double def) { + char k[160]; + std::snprintf(k, sizeof k, "text_config.%s", key); + return rad_meta_getf(m, k, rad_meta_getf(m, key, def)); +} +static const char* tgets(const RadModelMeta* m, const char* key, const char* def) { + char k[160]; + std::snprintf(k, sizeof k, "text_config.%s", key); + return rad_meta_gets(m, k, rad_meta_gets(m, key, def)); +} + +/* What this plugin runs: LTX-2.5's components (LTX-2.3's are the same graph). Anything else is + * refused by name rather than run wrong. */ +static int check_format(const RadModelMeta* meta) { + const char* cls = rad_meta_gets(meta, "pipeline._class_name", ""); + if (std::strcmp(cls, "LTX2Pipeline") != 0 && std::strcmp(cls, "LTX2ImageToVideoPipeline") != 0) { + fprintf(stderr, "radiance: ltx2: the container's pipeline is '%s', not LTX2Pipeline\n", cls); + return RAD_E_UNSUPPORTED; + } + auto is = [&](const char* k, long long v) { return rad_meta_geti(meta, k, -9999) == v; }; + auto str = [&](const char* k, const char* v) { + return !std::strcmp(rad_meta_gets(meta, k, ""), v); + }; + struct Need { bool ok; const char* what; }; + const Need need[] = { + { is("transformer.patch_size", 1) && is("transformer.patch_size_t", 1) && + is("transformer.in_channels", kC) && is("transformer.out_channels", kC) && + is("transformer.audio_in_channels", kAudioC) && is("transformer.audio_patch_size", 1), + "1 x 1 x 1 patches of 128-channel video and audio latents" }, + { str("transformer.rope_type", "split") && is("transformer.gated_attn", 1) && + is("transformer.audio_gated_attn", 1) && is("transformer.cross_attn_mod", 1) && + is("transformer.audio_cross_attn_mod", 1) && is("transformer.perturbed_attn", 1) && + is("transformer.use_prompt_embeddings", 0) && is("transformer.use_prompt_adaln_single", 1), + "the 2.3 / 2.5 DiT (split rotary, gated attention, prompt modulation)" }, + { is("transformer.causal_offset", 1) && is("transformer.pos_embed_max_pos", 20) && + is("transformer.audio_pos_embed_max_pos", 20) && is("transformer.base_height", 2048) && + is("transformer.base_width", 2048) && is("transformer.audio_scale_factor", 4) && + is("transformer.audio_hop_length", kMelHop) && + is("transformer.audio_sampling_rate", kVocRate) && + str("transformer.vae_scale_factors", "8 32 32") && + is("transformer.timestep_scale_multiplier", 1000) && + is("transformer.cross_attn_timestep_scale_multiplier", 1000), + "the released rotary coordinates and timestep scales" }, + { is("connectors.per_modality_projections", 1) && str("connectors.rope_type", "split") && + is("connectors.video_gated_attn", 1) && is("connectors.audio_gated_attn", 1) && + is("connectors.connector_rope_base_seq_len", 4096), + "per-modality connectors with gated attention and a split rotary" }, + { is("vae.patch_size", kPix) && is("vae.patch_size_t", 1) && is("vae.latent_channels", kC) && + is("vae.timestep_conditioning", 0) && is("vae.decoder_causal", 0) && + is("vae.encoder_causal", 1) && str("vae.upsample_residual", "0 0 0 0") && + str("vae.decoder_inject_noise", "0 0 0 0 0") && + str("vae.decoder_spatial_padding_mode", "zeros") && + rad_meta_getf(meta, "vae.scaling_factor", 1.0) == 1.0, + "the 2.3 / 2.5 video VAE (4 x 4 patches, no timestep conditioning)" }, + { str("audio_vae.norm_type", "pixel") && str("audio_vae.causality_axis", "height") && + is("audio_vae.latent_channels", kLatCh) && is("audio_vae.mel_bins", kMel) && + is("audio_vae.mid_block_add_attention", 0) && is("audio_vae.output_channels", 2) && + is("audio_vae.base_channels", kAudioC) && + !rad_meta_gets(meta, "audio_vae.attn_resolutions", nullptr), + "the audio VAE (pixel norms, causal in time, 8 x 16 latents, no attention)" }, + { str("vocoder.act_fn", "snakebeta") && is("vocoder.antialias", 1) && + is("vocoder.antialias_ratio", 2) && is("vocoder.antialias_kernel_size", 12) && + is("vocoder.final_bias", 0) && !rad_meta_gets(meta, "vocoder.final_act_fn", nullptr) && + str("vocoder.bwe_act_fn", "snakebeta") && is("vocoder.bwe_antialias", 1) && + is("vocoder.bwe_final_bias", 0) && !rad_meta_gets(meta, "vocoder.bwe_final_act_fn", nullptr) && + is("vocoder.filter_length", 512) && is("vocoder.hop_length", 80) && + is("vocoder.window_length", 512) && is("vocoder.num_mel_channels", kMel) && + is("vocoder.input_sampling_rate", kVocRate) && + is("vocoder.output_sampling_rate", kRate) && is("vocoder.in_channels", 2 * kMel) && + is("vocoder.out_channels", 2) && is("vocoder.bwe_in_channels", 2 * kMel) && + is("vocoder.bwe_out_channels", 2), + "the vocoder with bandwidth extension (SnakeBeta, 16 to 48 kHz)" }, + }; + for (const Need& n : need) + if (!n.ok) { + fprintf(stderr, "radiance: ltx2: this plugin runs %s; the container's config differs\n", + n.what); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* ================================================================== the text encoder */ +/* Gemma 4's language model over both prompts at once (one sequence each, causal), at positions + * that end each prompt where a 1024-token left-padded sequence does (RadVideoGenDecl:: + * text_left_pad). Every output the connectors read lands in the stack, [T, C (L + 1)] read as + * [T (L + 1), C]: the embeddings, each layer's output but the last, and the last's final norm. */ +static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gt; + Names& nm = m.nm; + const int64_t T = m.tRows, C = m.tC, L = m.tL; + const int acc = RAD_ACCESS_PER_REQUEST; + const char* pre = "model.language_model"; + const double eps = m.teps; + + std::vector full; + RAD_ARCH_TRY(parse_layer_kinds("ltx2", tgets(meta, "layer_types", ""), { "full_attention" }, + "sliding_attention", &full)); + if ((int64_t)full.size() != L) { + fprintf(stderr, "radiance: ltx2: the text encoder names %zu layer types for %lld layers\n", + full.size(), (long long)L); + return RAD_E_INVAL; + } + const int64_t nh = tgeti(meta, "num_attention_heads", 0); + const int64_t hd_s = tgeti(meta, "head_dim", 0); + const int64_t kv_s = tgeti(meta, "num_key_value_heads", 0); + const int64_t hd_g0 = tgeti(meta, "global_head_dim", hd_s); + const int64_t kv_g0 = tgeti(meta, "num_global_key_value_heads", kv_s); + const double th_s = tgetf(meta, "rope_parameters.sliding_attention.rope_theta", 0.0); + const double th_g = tgetf(meta, "rope_parameters.full_attention.rope_theta", 0.0); + double prf = tgetf(meta, "rope_parameters.full_attention.partial_rotary_factor", 1.0); + const char* gtype = tgets(meta, "rope_parameters.full_attention.rope_type", "default"); + const int64_t win = tgeti(meta, "sliding_window", 0); + const long long k_eq_v = tgeti(meta, "attention_k_eq_v", 0); + if (nh <= 0 || hd_s <= 0 || kv_s <= 0 || !(th_s > 0.0) || !(th_g > 0.0) || + tgeti(meta, "num_kv_shared_layers", 0) != 0 || tgeti(meta, "attention_bias", 0) != 0 || + std::strcmp(tgets(meta, "hidden_activation", ""), "gelu_pytorch_tanh") != 0 || + tgeti(meta, "use_double_wide_mlp", 0) != 0 || + (std::strcmp(gtype, "proportional") && std::strcmp(gtype, "default"))) { + fprintf(stderr, "radiance: ltx2: the text encoder is not Gemma 4's dense language model " + "(no KV sharing, no biases, a tanh GELU, default or proportional rotary)\n"); + return RAD_E_UNSUPPORTED; + } + if (win > 0 && win < kTextRows) { + fprintf(stderr, "radiance: ltx2: a %lld-token sliding window shorter than the %d-token " + "prompt; this plugin runs the window as full attention\n", (long long)win, + (int)kTextRows); + return RAD_E_UNSUPPORTED; + } + + RAD_ARCH_TRY(map_copy(b, nm.f("te.token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre))); + m.w_tok = decl_w(b, nm.f("te.token_embd.weight"), RAD_BF16, { g.n_vocab_all, C }, + RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); + m.w_tnorm = wcopy(b, nm.f("te.norm.weight"), nm.ckpt("%s.norm.weight", pre), RAD_BF16, { C }, acc, + (int)L); + m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, C }); + m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, C }); + m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * m.tFF }); + m.b_stack = decl_b(b, nm.f("te.stack"), RAD_BF16, { T, C * (L + 1) }); + RAD_ARCH_TRY(m.a_th.declare(b, nm, g, "te.h", T, C)); + RAD_ARCH_TRY(m.a_tffn.declare(b, nm, g, "te.ffn", T, m.tFF)); + if (!m.w_tok || !m.w_tnorm) return RAD_E_INVAL; + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", C), + RAD_INT("n_vocab", g.n_vocab_all), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0), + RAD_F64("mult", std::sqrt((double)C))), + RAD_WEIGHTS(m.w_tok)), + {}, { m.b_tx }); + m.op_keep0 = cast_op(b, T, C, "bf16", "bf16", m.b_tx, m.b_stack); + + /* Each class's rows at its own head geometry. */ + for (int k = 0; k < 2; ++k) { + int64_t qd = 0, kvd = 0; + for (int64_t l = 0; l < L; ++l) { + if ((full[(size_t)l] != 0) != (k == 1)) continue; + const int64_t hd = tgeti(meta, nm.f("per_layer_config.%lld.head_dim", (long long)l), + k ? hd_g0 : hd_s); + const int64_t kv = tgeti(meta, nm.f("per_layer_config.%lld.num_key_value_heads", + (long long)l), k ? kv_g0 : kv_s); + qd = std::max(qd, nh * hd); + kvd = std::max(kvd, kv * hd); + } + if (!qd) continue; + TeClass& K = m.cls[k]; + K.q = decl_b(b, nm.f("te.q%d", k), RAD_BF16, { T, qd }); + K.k = decl_b(b, nm.f("te.k%d", k), RAD_BF16, { T, kvd }); + K.v = decl_b(b, nm.f("te.v%d", k), RAD_BF16, { T, kvd }); + RAD_ARCH_TRY(K.o.declare(b, nm, g, nm.f("te.attn%d", k), T, qd)); + } + + m.te.resize((size_t)L); + for (int64_t l = 0; l < L; ++l) { + TeLayer& Y = m.te[(size_t)l]; + const int li = (int)l; + Y.full = full[(size_t)l] != 0; + Y.nh = nh; + Y.hd = tgeti(meta, nm.f("per_layer_config.%d.head_dim", li), Y.full ? hd_g0 : hd_s); + Y.nkv = tgeti(meta, nm.f("per_layer_config.%d.num_key_value_heads", li), + Y.full ? kv_g0 : kv_s); + Y.theta = Y.full ? th_g : th_s; + Y.rot = Y.full ? (int64_t)(Y.hd * prf + 0.5) : Y.hd; + Y.v_from_k = Y.full && k_eq_v != 0; + if (Y.nkv <= 0 || nh % Y.nkv || Y.rot <= 0 || Y.rot > Y.hd || (Y.rot & 1)) return RAD_E_INVAL; + const TeClass& K = m.cls[Y.full ? 1 : 0]; + const int64_t qd = nh * Y.hd, kvd = Y.nkv * Y.hd; + const char* lp = nm.ckpt("%s.layers.%d", pre, li); + auto norm_w = [&](const char* what) { + return wcopy(b, nm.f("te.blk.%d.%s.weight", li, what), nm.ckpt("%s.%s.weight", lp, what), + RAD_BF16, { C }, acc, li); + }; + Y.w_in = norm_w("input_layernorm"); + Y.w_pa = norm_w("post_attention_layernorm"); + Y.w_pf = norm_w("pre_feedforward_layernorm"); + Y.w_ff = norm_w("post_feedforward_layernorm"); + Y.w_qn = wcopy(b, nm.f("te.blk.%d.q_norm.weight", li), nm.ckpt("%s.self_attn.q_norm.weight", lp), + RAD_BF16, { Y.hd }, acc, li); + Y.w_kn = wcopy(b, nm.f("te.blk.%d.k_norm.weight", li), nm.ckpt("%s.self_attn.k_norm.weight", lp), + RAD_BF16, { Y.hd }, acc, li); + Y.w_sc = wcopy(b, nm.f("te.blk.%d.layer_scalar", li), nm.ckpt("%s.layer_scalar", lp), RAD_BF16, + { 1 }, acc, li); + if (!Y.w_in || !Y.w_pa || !Y.w_pf || !Y.w_ff || !Y.w_qn || !Y.w_kn || !Y.w_sc) + return RAD_E_INVAL; + Y.op_in = rms_op(b, T, C, eps, Y.w_in, m.b_tx, m.a_th.a.x); + auto lin = [&](Lin& Z, const char* name, const char* src, int64_t N, int64_t Kd, const Act& in, + rad_buf y) { + return Z.declare(b, nm, g, nm.f("te.blk.%d.%s", li, name), + { nm.ckpt("%s.%s.weight", lp, src) }, {}, {}, N, Kd, acc, li, in, y, T); + }; + RAD_ARCH_TRY(lin(Y.q, "attn_q", "self_attn.q_proj", qd, C, m.a_th, K.q)); + RAD_ARCH_TRY(lin(Y.k, "attn_k", "self_attn.k_proj", kvd, C, m.a_th, K.k)); + if (!Y.v_from_k) RAD_ARCH_TRY(lin(Y.v, "attn_v", "self_attn.v_proj", kvd, C, m.a_th, K.v)); + /* v's weightless RMS norm, from k's raw rows when the class reads v from k (before k's + * own norm rewrites them); q and k per head with their gains; then the rotaries. */ + Y.op_vn = rw(b, RAD_OP(b, "rmsnorm_p", + RAD_PARAMS(RAD_RANGE("M", 1, T * Y.nkv), RAD_INT("n", Y.hd), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { Y.v_from_k ? K.k : K.v }, { K.v }); + Y.op_qn = rms_op(b, T * nh, Y.hd, eps, Y.w_qn, K.q, K.q); + Y.op_kn = rms_op(b, T * Y.nkv, Y.hd, eps, Y.w_kn, K.k, K.k); + auto rope = [&](int64_t heads, rad_buf x) { + return rw(b, RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", Y.hd), + RAD_INT("n_head", heads), RAD_INT("n_head_kv", 0), + RAD_F64("theta", Y.theta), RAD_F64("scale", 1.0), + RAD_STR("mode", "neox"), RAD_INT("rotary_dim", Y.rot), + RAD_STR("ladder", + Y.full && !std::strcmp(gtype, "proportional") + ? "head" : "rotary")), + RAD_NOWEIGHTS), + { x }, { x }); + }; + Y.op_rq = rope(nh, K.q); + Y.op_rk = rope(Y.nkv, K.k); + /* Gemma 4 scores q.k without 1 / sqrt(head_dim): the q and k norms' gains carry it. */ + Y.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", Y.hd), + RAD_INT("gqa", nh / Y.nkv), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), RAD_F64("scale", 1.0), + RAD_INT("max_seqlen", kTextRows)), + RAD_NOWEIGHTS), + { K.q, K.k, K.v }, { K.o.a.x }); + RAD_ARCH_TRY(lin(Y.o, "attn_output", "self_attn.o_proj", C, qd, K.o, m.b_th2)); + Y.op_pa = rms_op(b, T, C, eps, Y.w_pa, m.b_th2, m.b_th2); + Y.op_add1 = add_op(b, T, C, "bf16", m.b_tx, m.b_th2, m.b_tx); + Y.op_pf = rms_op(b, T, C, eps, Y.w_pf, m.b_tx, m.a_th.a.x); + { + const char* gw = nm.f("te.blk.%d.ffn_gate_up", li); + RAD_ARCH_TRY(Y.gu.declare(b, nm, g, gw, { nm.ckpt("%s.mlp.gate_proj.weight", lp), + nm.ckpt("%s.mlp.up_proj.weight", lp) }, + {}, { m.tFF, m.tFF }, 2 * m.tFF, C, acc, li, m.a_th, m.b_tgu, T)); + } + Y.op_act = rw(b, RAD_OP(b, "gelu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", m.tFF), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_tgu }, { m.a_tffn.a.x }); + RAD_ARCH_TRY(lin(Y.down, "ffn_down", "mlp.down_proj", C, m.tFF, m.a_tffn, m.b_th2)); + Y.op_ff = rms_op(b, T, C, eps, Y.w_ff, m.b_th2, m.b_th2); + Y.op_add2 = add_op(b, T, C, "bf16", m.b_tx, m.b_th2, m.b_tx); + Y.op_sc = rw(b, RAD_OP(b, "scale", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", C), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(Y.w_sc)), + { m.b_tx }, { m.b_tx }); + /* Into the stack: a layer's output but the last's, which is normed first. */ + if (l + 1 < L) Y.op_keep = cast_op(b, T, C, "bf16", "bf16", m.b_tx, m.b_stack); + if (!Y.op_in || !Y.op_vn || !Y.op_qn || !Y.op_kn || !Y.op_rq || !Y.op_rk || !Y.op_attn || + !Y.op_pa || !Y.op_add1 || !Y.op_pf || !Y.op_act || !Y.op_ff || !Y.op_add2 || !Y.op_sc || + (l + 1 < L && !Y.op_keep)) + return RAD_E_INVAL; + } + m.op_tnorm = rms_op(b, T, C, eps, m.w_tnorm, m.b_tx, m.b_stack); + return m.op_embed && m.op_keep0 && m.op_tnorm ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== attention */ +/* The rotary an attention's q and k take: LTX-2's split rotary over `n_dims` coordinates of a + * `dim`-wide row, each coordinate over its `max`; none when n_dims is 0. */ +struct Rope { + int64_t n_dims = 0, dim = 0; + const char* max = ""; +}; + +/* An attention's weights and ops (LTX2Attention): for a self-attention q|k|v from `xin` into `bq` + * [rows, 3 inner]; for a cross-attention q from `xin` into `bq` [rows_q, inner] and k|v from + * `kvin` into `bkv` [rows_k, 2 inner]. The gate's logits into `bg`, the attention into `ao`, the + * output projection into `y` [rows_q, odim]. Every linear has a bias. A self-attention also gets + * the value copy spatio-temporal guidance bypasses it with. */ +static int attn_declare(RadBuilder* b, Model& m, const Geom& g, Attn& A, const char* dn, + const char* src, int64_t H, int64_t hd, int64_t qdim, int64_t kvdim, + int64_t odim, bool self, const Act& xin, const Act* kvin, rad_buf bq, + rad_buf bkv, rad_buf bg, const Act& ao, rad_buf y, int64_t rows_q, + int64_t rows_k, int acc, int group, const Rope& rope, double eps) { + Names& nm = m.nm; + A.H = H; + A.hd = hd; + A.inner = H * hd; + const int64_t in = A.inner; + auto w = [&](const char* name) { return nm.ckpt("%s.%s.weight", src, name); }; + auto bs = [&](const char* name) { return nm.ckpt("%s.%s.bias", src, name); }; + if (self) + RAD_ARCH_TRY(A.qkv.declare(b, nm, g, nm.f("%s.qkv", dn), { w("to_q"), w("to_k"), w("to_v") }, + { bs("to_q"), bs("to_k"), bs("to_v") }, { in, in, in }, 3 * in, + qdim, acc, group, xin, bq, rows_q)); + else { + RAD_ARCH_TRY(A.qkv.declare(b, nm, g, nm.f("%s.q", dn), { w("to_q") }, { bs("to_q") }, {}, in, + qdim, acc, group, xin, bq, rows_q)); + RAD_ARCH_TRY(A.kv.declare(b, nm, g, nm.f("%s.kv", dn), { w("to_k"), w("to_v") }, + { bs("to_k"), bs("to_v") }, { in, in }, 2 * in, kvdim, acc, group, + *kvin, bkv, rows_k)); + } + RAD_ARCH_TRY(A.gate.declare(b, nm, g, nm.f("%s.gate", dn), { w("to_gate_logits") }, + { bs("to_gate_logits") }, {}, H, qdim, acc, group, xin, bg, rows_q, + true)); + RAD_ARCH_TRY(A.out.declare(b, nm, g, nm.f("%s.out", dn), { w("to_out.0") }, { bs("to_out.0") }, {}, + odim, in, acc, group, ao, y, rows_q)); + A.w_qn = wcopy(b, nm.f("%s.q_norm.weight", dn), w("norm_q"), RAD_BF16, { in }, acc, group); + A.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), w("norm_k"), RAD_BF16, { in }, acc, group); + if (!A.w_qn || !A.w_kn) return RAD_E_INVAL; + const rad_buf kb = self ? bq : bkv; + A.op_qn = rms_op(b, rows_q, in, eps, A.w_qn, bq, bq); + A.op_kn = rms_op(b, rows_k, in, eps, A.w_kn, kb, kb); + if (rope.n_dims) { + auto rop = [&](int64_t rows, rad_buf x) { + return rw(b, RAD_OP(b, "rope_split", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n_head", H), + RAD_INT("head_dim", hd), RAD_INT("dim", rope.dim), + RAD_INT("n_dims", rope.n_dims), RAD_F64("theta", 10000.0), + RAD_STR("max", rope.max), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { x }, { x }); + }; + A.op_rq = rop(rows_q, bq); + A.op_rk = rop(rows_k, kb); + if (!A.op_rq || !A.op_rk) return RAD_E_INVAL; + } + const double sc = 1.0 / std::sqrt((double)hd); + if (self) + A.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, rows_q), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), RAD_F64("scale", sc)), + RAD_NOWEIGHTS), + { bq }, { ao.a.x }); + else + A.op_attn = rw(b, RAD_OP(b, "attn_cross", + RAD_PARAMS(RAD_RANGE("M", 1, rows_q), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), RAD_F64("scale", sc)), + RAD_NOWEIGHTS), + { bq, bkv }, { ao.a.x }); + A.op_hg = rw(b, RAD_OP(b, "head_gate", + RAD_PARAMS(RAD_RANGE("M", 1, rows_q), RAD_INT("n_head", H), + RAD_INT("head_dim", hd), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { bg, ao.a.x }, { ao.a.x }); + if (self) A.op_v = cast_op(b, rows_q, in, "bf16", "bf16", bq, ao.a.x); + return A.op_qn && A.op_kn && A.op_attn && A.op_hg && (!self || A.op_v) ? RAD_OK : RAD_E_INVAL; +} + +/* q and k normed and turned, the attention, the gate: the attention part both kinds share once + * their projections ran. `cu` and (cross) `cu_k` bound the query and key rows; `pq` and `pk` the + * rotary coordinates. */ +static void attn_core(RadCtx* c, const Attn& A, bool self, rad_buf bq, rad_buf bkv, rad_buf bg, + const Act& ao, int64_t nq, int64_t nk, const RadOperand& cu, + const RadOperand& cu_k, const RadOperand& pq, const RadOperand& pk) { + const int64_t in = A.inner; + const RadOperand q = bcol(bq, 0, in, nq); + const RadOperand k = self ? bcol(bq, in, in, nk) : bcol(bkv, 0, in, nk); + const RadOperand v = self ? bcol(bq, 2 * in, in, nk) : bcol(bkv, in, in, nk); + RAD_ISSUE_N(c, A.op_qn, nq, q, RAD_W(A.w_qn), q); + RAD_ISSUE_N(c, A.op_kn, nk, k, RAD_W(A.w_kn), k); + if (A.op_rq) { + RAD_ISSUE_N(c, A.op_rq, nq, q, pq); + RAD_ISSUE_N(c, A.op_rk, nk, k, pk); + } + if (self) RAD_ISSUE_N(c, A.op_attn, nq, q, k, v, cu, brows(ao.a.x, nq)); + else RAD_ISSUE_N(c, A.op_attn, nq, q, k, v, cu, cu_k, brows(ao.a.x, nq)); + RAD_ISSUE_N(c, A.op_hg, nq, brows(bg, nq), brows(ao.a.x, nq)); +} + +/* ================================================================== the connectors */ +/* A modality's connector: the normed stack scaled to its width and projected, the registers in + * the rows past the prompt's tokens, eight blocks over 1024 rows a prompt, the final norm into the + * lane's text rows. */ +static int declare_conn(RadBuilder* b, const RadModelMeta* meta, Model& m, Conn& K, const char* md) { + Names& nm = m.nm; + const Geom& g = m.gt; + const int64_t T = m.tRows, C = m.tC, Lp = m.tL + 1, R = 2 * (int64_t)kTextRows; + const int acc = RAD_ACCESS_PER_REQUEST; + const int gx = kGrpConn + (md[0] == 'v' ? 0 : 50); + const double eps = 1e-6; + K.H = rad_meta_geti(meta, nm.f("connectors.%s_connector_num_attention_heads", md), 0); + K.hd = rad_meta_geti(meta, nm.f("connectors.%s_connector_attention_head_dim", md), 0); + K.D = rad_meta_geti(meta, nm.f("connectors.%s_hidden_dim", md), 0); + K.ff = 4 * K.D; + const int64_t layers = rad_meta_geti(meta, nm.f("connectors.%s_connector_num_layers", md), 0); + const int64_t regs = rad_meta_geti(meta, nm.f("connectors.%s_connector_num_learnable_registers", md), + 0); + if (K.H <= 0 || K.hd <= 0 || K.D != K.H * K.hd || layers <= 0 || regs <= 0 || + kTextRows % regs || kTextRows / regs > 8 || + rad_meta_geti(meta, "connectors.caption_channels", 0) != C || + rad_meta_geti(meta, "connectors.text_proj_in_factor", 0) != Lp) { + fprintf(stderr, "radiance: ltx2: the %s connector's geometry does not fit the text encoder " + "(%lld channels, %lld layers kept)\n", md, (long long)C, (long long)Lp); + return RAD_E_UNSUPPORTED; + } + K.mult = std::sqrt((double)K.D / (double)C); + const char* pre = nm.ckpt("connectors.%s_connector", md); + + /* The stack, per-layer RMS-normed over its channels and scaled, then the projection. */ + RAD_ARCH_TRY(K.a_in.declare(b, nm, g, nm.f("conn.%s.in", md), T, C * Lp)); + K.op_norm = rw(b, RAD_OP(b, "pixel_norm", + RAD_PARAMS(RAD_RANGE("M", 1, T * Lp), RAD_INT("n", C), RAD_F64("eps", eps), + RAD_STR("form", "rsqrt"), RAD_INT("ileave", Lp), + RAD_STR("dtype", "bf16"), RAD_F64("mult", K.mult)), + RAD_NOWEIGHTS), + { m.b_stack }, { K.a_in.a.x }); + K.b_x = decl_b(b, nm.f("conn.%s.x", md), RAD_BF16, { R, K.D }); + RAD_ARCH_TRY(K.proj.declare(b, nm, g, nm.f("conn.%s.proj", md), + { nm.ckpt("connectors.%s_text_proj_in.weight", md) }, + { nm.ckpt("connectors.%s_text_proj_in.bias", md) }, {}, K.D, C * Lp, + acc, gx, K.a_in, K.b_x, T)); + { + const char* wn = nm.f("conn.%s.registers", md); + const char* rs = nm.ckpt("%s.learnable_registers", pre); + const int reps = (int)(kTextRows / regs); + RadNameMap mp = map_base(wn, RAD_MAP_ROWS); + for (int i = 0; i < reps; ++i) { + mp.src[mp.n_src] = rs; + mp.src_index[mp.n_src] = 0; + mp.src_rows[mp.n_src] = regs; + ++mp.n_src; + } + RAD_ARCH_TRY(rad_decl_name_map(b, &mp)); + K.w_reg = decl_w(b, wn, RAD_BF16, { (int64_t)kTextRows, K.D }, acc, RAD_SHARD_NONE, + grp_layer(gx)); + if (!K.w_reg) return RAD_E_INVAL; + K.op_reg = rw(b, RAD_OP(b, "table_add", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", K.D), + RAD_INT("L", (int64_t)kTextRows), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(K.w_reg)), + { m.b_zero }, { K.b_x }); + } + + /* The blocks. */ + RAD_ARCH_TRY(K.a_h.declare(b, nm, g, nm.f("conn.%s.h", md), R, K.D)); + RAD_ARCH_TRY(K.a_attn.declare(b, nm, g, nm.f("conn.%s.attn", md), R, K.D)); + RAD_ARCH_TRY(K.a_ffn.declare(b, nm, g, nm.f("conn.%s.ffn", md), R, K.ff)); + K.b_qkv = decl_b(b, nm.f("conn.%s.qkv", md), RAD_BF16, { R, 3 * K.D }); + K.b_g = decl_b(b, nm.f("conn.%s.g", md), RAD_BF16, { R, K.H }); + K.b_o = decl_b(b, nm.f("conn.%s.o", md), RAD_BF16, { R, K.D }); + K.b_up = decl_b(b, nm.f("conn.%s.up", md), RAD_BF16, { R, K.ff }); + Rope rope{ 1, K.D, "4096" }; + K.blk.resize((size_t)layers); + for (int64_t l = 0; l < layers; ++l) { + ConnBlock& B = K.blk[(size_t)l]; + const char* bp = nm.ckpt("%s.transformer_blocks.%lld", pre, (long long)l); + const char* dn = nm.f("conn.%s.blk.%lld", md, (long long)l); + B.op_n1 = rms_op(b, R, K.D, eps, 0, K.b_x, K.a_h.a.x); + RAD_ARCH_TRY(attn_declare(b, m, g, B.at, dn, nm.ckpt("%s.attn1", bp), K.H, K.hd, K.D, K.D, K.D, + true, K.a_h, nullptr, K.b_qkv, 0, K.b_g, K.a_attn, K.b_o, R, R, acc, + gx, rope, eps)); + B.op_add1 = add_op(b, R, K.D, "bf16", K.b_x, K.b_o, K.b_x); + B.op_n2 = rms_op(b, R, K.D, eps, 0, K.b_x, K.a_h.a.x); + RAD_ARCH_TRY(B.up.declare(b, nm, g, nm.f("%s.ff_up", dn), + { nm.ckpt("%s.ff.net.0.proj.weight", bp) }, + { nm.ckpt("%s.ff.net.0.proj.bias", bp) }, {}, K.ff, K.D, acc, gx, + K.a_h, K.b_up, R)); + B.op_act = unary(b, "gelu_tanh", R, K.ff, "bf16", K.b_up, K.a_ffn.a.x); + RAD_ARCH_TRY(B.down.declare(b, nm, g, nm.f("%s.ff_down", dn), + { nm.ckpt("%s.ff.net.2.weight", bp) }, + { nm.ckpt("%s.ff.net.2.bias", bp) }, {}, K.D, K.ff, acc, gx, + K.a_ffn, K.b_o, R)); + B.op_add2 = add_op(b, R, K.D, "bf16", K.b_x, K.b_o, K.b_x); + if (!B.op_n1 || !B.op_add1 || !B.op_n2 || !B.op_act || !B.op_add2) return RAD_E_INVAL; + } + K.b_text = decl_b(b, nm.f("lane.%s_text", md), RAD_BF16, { (int64_t)kMaxLanes * R, K.D }, + RAD_BUF_PERSIST); + K.op_nout = rms_op(b, R, K.D, eps, 0, K.b_x, K.b_text); + return K.op_norm && K.op_reg && K.b_text && K.op_nout ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== the DiT */ +/* One AdaLayerNormSingle (`mod`): the [cos | sin] sinusoids of the step's timesteps through + * linear_1, SiLU and linear_2 to `emb`, then SiLU and `linear` to `temb`, bf16 throughout. `perm` + * reorders linear's output rows in blocks of d (LTX-2's cross-modal tables hold scale before + * shift; the norms take shift first). */ +static int ada_declare(RadBuilder* b, Model& m, Ada& A, const char* dn, const char* mod, int64_t d, + int64_t k, std::initializer_list perm = {}) { + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_TOKEN, gx = kGrpTemb; + A.d = d; + A.k = k; + const char* src = nm.ckpt("transformer.%s", mod); + A.w1 = wcopy(b, nm.f("%s.l1.weight", dn), nm.ckpt("%s.emb.timestep_embedder.linear_1.weight", src), + RAD_BF16, { d, 256 }, acc, gx); + A.b1 = wcopy(b, nm.f("%s.l1.bias", dn), nm.ckpt("%s.emb.timestep_embedder.linear_1.bias", src), + RAD_BF16, { d }, acc, gx); + A.w2 = wcopy(b, nm.f("%s.l2.weight", dn), nm.ckpt("%s.emb.timestep_embedder.linear_2.weight", src), + RAD_BF16, { d, d }, acc, gx); + A.b2 = wcopy(b, nm.f("%s.l2.bias", dn), nm.ckpt("%s.emb.timestep_embedder.linear_2.bias", src), + RAD_BF16, { d }, acc, gx); + const char* lw = nm.f("%s.lin.weight", dn); + const char* lb = nm.f("%s.lin.bias", dn); + if (perm.size()) { + std::vector pw, pb; + const char* sw = nm.ckpt("%s.linear.weight", src); + const char* sb = nm.ckpt("%s.linear.bias", src); + RadNameMap mw = map_base(lw, RAD_MAP_ROWS), mb = map_base(lb, RAD_MAP_ROWS); + for (int p : perm) { + mw.src[mw.n_src] = sw; + mw.src_index[mw.n_src] = (int)(p * d); + mw.src_rows[mw.n_src++] = d; + mb.src[mb.n_src] = sb; + mb.src_index[mb.n_src] = (int)(p * d); + mb.src_rows[mb.n_src++] = d; + } + RAD_ARCH_TRY(rad_decl_name_map(b, &mw)); + RAD_ARCH_TRY(rad_decl_name_map(b, &mb)); + A.wl = decl_w(b, lw, RAD_BF16, { k * d, d }, acc, RAD_SHARD_NONE, grp_layer(gx)); + A.bl = decl_w(b, lb, RAD_BF16, { k * d }, acc, RAD_SHARD_NONE, grp_layer(gx)); + } else { + A.wl = wcopy(b, lw, nm.ckpt("%s.linear.weight", src), RAD_BF16, { k * d, d }, acc, gx); + A.bl = wcopy(b, lb, nm.ckpt("%s.linear.bias", src), RAD_BF16, { k * d }, acc, gx); + } + if (!A.w1 || !A.b1 || !A.w2 || !A.b2 || !A.wl || !A.bl) return RAD_E_INVAL; + A.h = decl_b(b, nm.f("%s.h", dn), RAD_BF16, { 2, d }); + A.hs = decl_b(b, nm.f("%s.hs", dn), RAD_BF16, { 2, d }); + A.emb = decl_b(b, nm.f("%s.emb", dn), RAD_BF16, { 2, d }, RAD_BUF_PERSIST); + A.es = decl_b(b, nm.f("%s.es", dn), RAD_BF16, { 2, d }); + A.temb = decl_b(b, nm.f("%s.temb", dn), RAD_BF16, { 2, k * d }); + auto lin = [&](rad_weight w, rad_weight bb, int64_t N, int64_t K, rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bb)), + { x }, { y }); + }; + A.op1 = lin(A.w1, A.b1, d, 256, m.b_tsin, A.h); + A.ops1 = unary(b, "silu", 2, d, "bf16", A.h, A.hs); + A.op2 = lin(A.w2, A.b2, d, d, A.hs, A.emb); + A.ops2 = unary(b, "silu", 2, d, "bf16", A.emb, A.es); + A.opl = lin(A.wl, A.bl, k * d, d, A.es, A.temb); + return A.op1 && A.ops1 && A.op2 && A.ops2 && A.opl ? RAD_OK : RAD_E_INVAL; +} + +/* The module over rows [r0, r0 + n) of the step's timesteps' sinusoids `tsin`, into its own rows + * [r0, r0 + n). */ +static void ada_step(RadCtx* c, const Ada& A, rad_buf tsin, int64_t r0, int64_t n) { + const int64_t d = A.d, kd = A.k * A.d; + auto rows = [&](rad_buf h, int64_t w) { return brow_slice(h, r0, n, w); }; + RAD_ISSUE_N(c, A.op1, n, rows(tsin, 256), RAD_W(A.w1), RAD_W(A.b1), RAD_NONE, rows(A.h, d)); + RAD_ISSUE_N(c, A.ops1, n, rows(A.h, d), rows(A.hs, d)); + RAD_ISSUE_N(c, A.op2, n, rows(A.hs, d), RAD_W(A.w2), RAD_W(A.b2), RAD_NONE, rows(A.emb, d)); + RAD_ISSUE_N(c, A.ops2, n, rows(A.emb, d), rows(A.es, d)); + RAD_ISSUE_N(c, A.opl, n, rows(A.es, d), RAD_W(A.wl), RAD_W(A.bl), RAD_NONE, rows(A.temb, kd)); +} + +static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + const Geom& g = m.gd; + const int64_t S = m.maxS, A = m.maxA, R = kTextRows, L = m.nb; + const int64_t D = m.D, Da = m.Da, Dc = m.Dc; + const int acc = RAD_ACCESS_PER_TOKEN; + const double eps = m.eps; + const int64_t La = kMaxLanes; + + /* ---- the step's timesteps {0, sigma} (the first frame's and everything else's), their + * sinusoids, and the eight modulation MLPs */ + m.b_tin = decl_b(b, nm.f("dit.tin"), RAD_F32, { 2 }); + m.b_tsin = decl_b(b, nm.f("dit.tsin"), RAD_BF16, { 2, 256 }); + m.op_tin0 = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 2), RAD_STR("dtype", "f32"), + RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_tin }); + m.op_tin1 = cast_op(b, 1, 1, "f32", "f32", m.b_tin, m.b_tin); + /* t' = f32(1000 sigma), the timestep diffusers' scheduler hands the transformer. */ + m.op_tsin = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("n", 256), + RAD_F64("scale", 1000.0), RAD_F64("max_period", 10000.0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_tin }, { m.b_tsin }); + if (!m.op_tin0 || !m.op_tin1 || !m.op_tsin) return RAD_E_INVAL; + RAD_ARCH_TRY(ada_declare(b, m, m.ad_v, "dit.ada_v", "time_embed", D, 9)); + RAD_ARCH_TRY(ada_declare(b, m, m.ad_a, "dit.ada_a", "audio_time_embed", Da, 9)); + RAD_ARCH_TRY(ada_declare(b, m, m.ad_p, "dit.ada_p", "prompt_adaln", D, 2)); + RAD_ARCH_TRY(ada_declare(b, m, m.ad_pa, "dit.ada_pa", "audio_prompt_adaln", Da, 2)); + RAD_ARCH_TRY(ada_declare(b, m, m.ad_cv, "dit.ada_cv", "av_cross_attn_video_scale_shift", D, 4, + { 1, 0, 3, 2 })); + RAD_ARCH_TRY(ada_declare(b, m, m.ad_cvg, "dit.ada_cvg", "av_cross_attn_video_a2v_gate", D, 1)); + RAD_ARCH_TRY(ada_declare(b, m, m.ad_ca, "dit.ada_ca", "av_cross_attn_audio_scale_shift", Da, 4, + { 1, 0, 3, 2 })); + RAD_ARCH_TRY(ada_declare(b, m, m.ad_cag, "dit.ada_cag", "av_cross_attn_audio_v2a_gate", Da, 1)); + + /* ---- the step's tables (PERSIST): block l's rows at column l of each */ + m.b_mv = decl_b(b, nm.f("dit.mod_v"), RAD_BF16, { 2, L * 9 * D }, RAD_BUF_PERSIST); + m.b_ma = decl_b(b, nm.f("dit.mod_a"), RAD_BF16, { 1, L * 9 * Da }, RAD_BUF_PERSIST); + m.b_mp = decl_b(b, nm.f("dit.mod_p"), RAD_BF16, { 1, L * 2 * D }, RAD_BUF_PERSIST); + m.b_mpa = decl_b(b, nm.f("dit.mod_pa"), RAD_BF16, { 1, L * 2 * Da }, RAD_BUF_PERSIST); + m.b_mcv = decl_b(b, nm.f("dit.mod_cv"), RAD_BF16, { 1, L * 4 * D }, RAD_BUF_PERSIST); + m.b_mcvg = decl_b(b, nm.f("dit.mod_cvg"), RAD_BF16, { 1, L * D }, RAD_BUF_PERSIST); + m.b_mca = decl_b(b, nm.f("dit.mod_ca"), RAD_BF16, { 1, L * 4 * Da }, RAD_BUF_PERSIST); + m.b_mcag = decl_b(b, nm.f("dit.mod_cag"), RAD_BF16, { 1, L * Da }, RAD_BUF_PERSIST); + m.b_fv = decl_b(b, nm.f("dit.mod_fv"), RAD_BF16, { 2, 2 * D }, RAD_BUF_PERSIST); + m.b_fa = decl_b(b, nm.f("dit.mod_fa"), RAD_BF16, { 1, 2 * Da }, RAD_BUF_PERSIST); + auto table_op = [&](rad_weight t, int64_t rows, int64_t n, int64_t Lr, rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "table_add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_INT("L", Lr), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(t)), + { x }, { y }); + }; + m.w_fv = wcopy(b, nm.f("dit.out_table"), nm.ckpt("transformer.scale_shift_table"), RAD_BF16, + { 2, D }, acc, kGrpTemb); + m.w_fa = wcopy(b, nm.f("dit.audio_out_table"), nm.ckpt("transformer.audio_scale_shift_table"), + RAD_BF16, { 2, Da }, acc, kGrpTemb); + if (!m.w_fv || !m.w_fa) return RAD_E_INVAL; + m.op_fv = table_op(m.w_fv, 2, D, 2, m.ad_v.emb, m.b_fv); + m.op_fa = table_op(m.w_fa, 1, Da, 2, m.ad_a.emb, m.b_fa); + + /* ---- the lanes (PERSIST): both latents f32, the clean first latent frame */ + m.b_vstate = decl_b(b, nm.f("lane.video"), RAD_F32, { La * S, kC }, RAD_BUF_PERSIST); + m.b_astate = decl_b(b, nm.f("lane.audio"), RAD_F32, { La * A, kAudioC }, RAD_BUF_PERSIST); + m.b_first = decl_b(b, nm.f("lane.first"), RAD_F32, { La * m.maxPpf, kC }, RAD_BUF_PERSIST); + auto randn = [&](int64_t rows, int64_t stride, rad_buf x) { + return rw(b, RAD_OP(b, "randn_lanes", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", kC), + RAD_INT("stride", stride), RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { x }, { x }); + }; + m.op_rnd_v = randn(S, S, m.b_vstate); + m.op_rnd_a = randn(A, A, m.b_astate); + m.op_keep_first = cast_op(b, m.maxPpf, kC, "f32", "f32", m.b_first, m.b_vstate); + + /* ---- an evaluation's rows */ + RAD_ARCH_TRY(m.a_lv.declare(b, nm, g, "dit.lat_v", S, kC)); + RAD_ARCH_TRY(m.a_la.declare(b, nm, g, "dit.lat_a", A, kAudioC)); + m.op_lv = cast_op(b, S, kC, "f32", "bf16", m.b_vstate, m.a_lv.a.x); + m.op_la = cast_op(b, A, kAudioC, "f32", "bf16", m.b_astate, m.a_la.a.x); + m.b_hv = decl_b(b, nm.f("dit.hv"), RAD_BF16, { S, D }); + m.b_ha = decl_b(b, nm.f("dit.ha"), RAD_BF16, { A, Da }); + RAD_ARCH_TRY(m.pin_v.declare(b, nm, g, "dit.proj_in", { nm.ckpt("transformer.proj_in.weight") }, + { nm.ckpt("transformer.proj_in.bias") }, {}, D, kC, acc, kGrpDit, + m.a_lv, m.b_hv, S, true)); + RAD_ARCH_TRY(m.pin_a.declare(b, nm, g, "dit.audio_proj_in", + { nm.ckpt("transformer.audio_proj_in.weight") }, + { nm.ckpt("transformer.audio_proj_in.bias") }, {}, Da, kAudioC, acc, + kGrpDit, m.a_la, m.b_ha, A, true)); + RAD_ARCH_TRY(m.a_hv.declare(b, nm, g, "dit.hnv", S, D)); + RAD_ARCH_TRY(m.a_ha.declare(b, nm, g, "dit.hna", A, Da)); + RAD_ARCH_TRY(m.a_ctxv.declare(b, nm, g, "dit.ctx_v", R, D)); + RAD_ARCH_TRY(m.a_ctxa.declare(b, nm, g, "dit.ctx_a", R, Da)); + RAD_ARCH_TRY(m.a_nv.declare(b, nm, g, "dit.nv_a2v", S, D)); + RAD_ARCH_TRY(m.a_nv2.declare(b, nm, g, "dit.nv_v2a", S, D)); + RAD_ARCH_TRY(m.a_na.declare(b, nm, g, "dit.na_a2v", A, Da)); + RAD_ARCH_TRY(m.a_na2.declare(b, nm, g, "dit.na_v2a", A, Da)); + RAD_ARCH_TRY(m.a_aov.declare(b, nm, g, "dit.attn_v", S, D)); + RAD_ARCH_TRY(m.a_aoa.declare(b, nm, g, "dit.attn_a", A, Da)); + RAD_ARCH_TRY(m.a_xv.declare(b, nm, g, "dit.attn_a2v", S, Dc)); + RAD_ARCH_TRY(m.a_xa.declare(b, nm, g, "dit.attn_v2a", A, Dc)); + RAD_ARCH_TRY(m.a_ffv.declare(b, nm, g, "dit.ffn_v", S, m.ffv)); + RAD_ARCH_TRY(m.a_ffa.declare(b, nm, g, "dit.ffn_a", A, m.ffa)); + RAD_ARCH_TRY(m.a_fv.declare(b, nm, g, "dit.out_v", S, D)); + RAD_ARCH_TRY(m.a_fa.declare(b, nm, g, "dit.out_a", A, Da)); + m.b_qkvv = decl_b(b, nm.f("dit.qkv_v"), RAD_BF16, { S, 3 * D }); + m.b_qkva = decl_b(b, nm.f("dit.qkv_a"), RAD_BF16, { A, 3 * Da }); + m.b_gv = decl_b(b, nm.f("dit.gate_v"), RAD_BF16, { S, m.H }); + m.b_ga = decl_b(b, nm.f("dit.gate_a"), RAD_BF16, { A, m.Ha }); + m.b_ov = decl_b(b, nm.f("dit.o_v"), RAD_BF16, { S, D }); + m.b_oa = decl_b(b, nm.f("dit.o_a"), RAD_BF16, { A, Da }); + m.b_qv = decl_b(b, nm.f("dit.q_v"), RAD_BF16, { S, D }); + m.b_qa = decl_b(b, nm.f("dit.q_a"), RAD_BF16, { A, Da }); + m.b_kvtv = decl_b(b, nm.f("dit.kv_tv"), RAD_BF16, { R, 2 * D }); + m.b_kvta = decl_b(b, nm.f("dit.kv_ta"), RAD_BF16, { R, 2 * Da }); + m.b_qxv = decl_b(b, nm.f("dit.q_a2v"), RAD_BF16, { S, Dc }); + m.b_gxv = decl_b(b, nm.f("dit.gate_a2v"), RAD_BF16, { S, m.Ha }); + m.b_kvxa = decl_b(b, nm.f("dit.kv_a2v"), RAD_BF16, { A, 2 * Dc }); + m.b_qxa = decl_b(b, nm.f("dit.q_v2a"), RAD_BF16, { A, Dc }); + m.b_gxa = decl_b(b, nm.f("dit.gate_v2a"), RAD_BF16, { A, m.Ha }); + m.b_kvxv = decl_b(b, nm.f("dit.kv_v2a"), RAD_BF16, { S, 2 * Dc }); + m.b_upv = decl_b(b, nm.f("dit.up_v"), RAD_BF16, { S, m.ffv }); + m.b_upa = decl_b(b, nm.f("dit.up_a"), RAD_BF16, { A, m.ffa }); + + /* ---- the blocks */ + const Rope rv{ 3, D, "20 2048 2048" }, ra{ 1, Da, "20" }, rx{ 1, Dc, "20" }, none{}; + m.dit.resize((size_t)L); + for (int64_t l = 0; l < L; ++l) { + DitBlock& B = m.dit[(size_t)l]; + const int li = (int)l, gx = kGrpDit + 1 + li; + const char* bp = nm.ckpt("transformer.transformer_blocks.%d", li); + const char* dn = nm.f("dit.blk.%d", li); + auto attn = [&](Attn& At, const char* name, const char* src, int64_t H, int64_t hd, + int64_t qdim, int64_t kvdim, int64_t odim, bool self, const Act& xin, + const Act* kvin, rad_buf bq, rad_buf bkv, rad_buf bg, const Act& ao, rad_buf y, + int64_t rq, int64_t rk, const Rope& rope) { + return attn_declare(b, m, g, At, nm.f("%s.%s", dn, name), nm.ckpt("%s.%s", bp, src), H, hd, + qdim, kvdim, odim, self, xin, kvin, bq, bkv, bg, ao, y, rq, rk, acc, gx, + rope, eps); + }; + /* The step's tables: the block's learned rows plus the step's shared ones. */ + auto table = [&](rad_weight* w, const char* dname, const char* name, + std::initializer_list rows, int64_t d) { + const char* wn = nm.f("%s.%s", dn, dname); + bool natural = true; + int i = 0; + for (int r : rows) natural = natural && r == i++; + if (natural && (int64_t)rows.size() > 1) { + if (map_copy(b, wn, nm.ckpt("%s.%s", bp, name)) < 0) return RAD_E_INVAL; + } else { + if (rows.size() > 8) return RAD_E_INVAL; + RadNameMap mp = map_base(wn, RAD_MAP_ROWS); + for (int r : rows) { + mp.src[mp.n_src] = nm.ckpt("%s.%s", bp, name); + mp.src_index[mp.n_src] = r; + mp.src_rows[mp.n_src++] = 1; + } + if (rad_decl_name_map(b, &mp) < 0) return RAD_E_INVAL; + } + *w = decl_w(b, wn, RAD_BF16, { (int64_t)rows.size(), d }, acc, RAD_SHARD_NONE, + grp_layer(gx)); + return *w ? RAD_OK : RAD_E_INVAL; + }; + RAD_ARCH_TRY(table(&B.t_v, "table_v", "scale_shift_table", { 0, 1, 2, 3, 4, 5, 6, 7, 8 }, D)); + RAD_ARCH_TRY(table(&B.t_a, "table_a", "audio_scale_shift_table", { 0, 1, 2, 3, 4, 5, 6, 7, 8 }, + Da)); + RAD_ARCH_TRY(table(&B.t_p, "table_p", "prompt_scale_shift_table", { 0, 1 }, D)); + RAD_ARCH_TRY(table(&B.t_pa, "table_pa", "audio_prompt_scale_shift_table", { 0, 1 }, Da)); + RAD_ARCH_TRY(table(&B.t_cv, "table_cv", "video_a2v_cross_attn_scale_shift_table", { 1, 0, 3, 2 }, + D)); + RAD_ARCH_TRY(table(&B.t_cvg, "table_cvg", "video_a2v_cross_attn_scale_shift_table", { 4 }, D)); + RAD_ARCH_TRY(table(&B.t_ca, "table_ca", "audio_a2v_cross_attn_scale_shift_table", { 1, 0, 3, 2 }, + Da)); + RAD_ARCH_TRY(table(&B.t_cag, "table_cag", "audio_a2v_cross_attn_scale_shift_table", { 4 }, Da)); + B.op_tv = table_op(B.t_v, 2, 9 * D, 1, m.ad_v.temb, m.b_mv); + B.op_ta = table_op(B.t_a, 1, 9 * Da, 1, m.ad_a.temb, m.b_ma); + B.op_tp = table_op(B.t_p, 1, 2 * D, 1, m.ad_p.temb, m.b_mp); + B.op_tpa = table_op(B.t_pa, 1, 2 * Da, 1, m.ad_pa.temb, m.b_mpa); + B.op_tcv = table_op(B.t_cv, 1, 4 * D, 1, m.ad_cv.temb, m.b_mcv); + B.op_tcvg = table_op(B.t_cvg, 1, D, 1, m.ad_cvg.temb, m.b_mcvg); + B.op_tca = table_op(B.t_ca, 1, 4 * Da, 1, m.ad_ca.temb, m.b_mca); + B.op_tcag = table_op(B.t_cag, 1, Da, 1, m.ad_cag.temb, m.b_mcag); + + /* Self-attention (block 0's q|k|v was mapped by declare's format probe). */ + if (l == 0) B.sv.qkv.mapped = true; + B.m1v = mod_op(b, S, D, eps, l > 0, "rms", m.b_mv, m.b_mv, m.b_hv, m.b_ov, m.a_hv.a.x); + B.m1a = mod_op(b, A, Da, eps, l > 0, "rms", m.b_ma, m.b_ma, m.b_ha, m.b_oa, m.a_ha.a.x); + RAD_ARCH_TRY(attn(B.sv, "attn1", "attn1", m.H, m.hd, D, D, D, true, m.a_hv, nullptr, m.b_qkvv, 0, + m.b_gv, m.a_aov, m.b_ov, S, S, rv)); + RAD_ARCH_TRY(attn(B.sa, "audio_attn1", "audio_attn1", m.Ha, m.hda, Da, Da, Da, true, m.a_ha, + nullptr, m.b_qkva, 0, m.b_ga, m.a_aoa, m.b_oa, A, A, ra)); + /* Text cross-attention: the query's norm gated by the self-attention, the text keys and + * values modulated as they are. */ + B.m2v = mod_op(b, S, D, eps, true, "rms", m.b_mv, m.b_mv, m.b_hv, m.b_ov, m.a_hv.a.x); + B.m2a = mod_op(b, A, Da, eps, true, "rms", m.b_ma, m.b_ma, m.b_ha, m.b_oa, m.a_ha.a.x); + B.mtv = mod_op(b, R, D, eps, false, "none", m.b_mp, m.b_mp, m.cv.b_text, 0, m.a_ctxv.a.x); + B.mta = mod_op(b, R, Da, eps, false, "none", m.b_mpa, m.b_mpa, m.ca.b_text, 0, m.a_ctxa.a.x); + RAD_ARCH_TRY(attn(B.tv, "attn2", "attn2", m.H, m.hd, D, D, D, false, m.a_hv, &m.a_ctxv, m.b_qv, + m.b_kvtv, m.b_gv, m.a_aov, m.b_ov, S, R, none)); + RAD_ARCH_TRY(attn(B.ta, "audio_attn2", "audio_attn2", m.Ha, m.hda, Da, Da, Da, false, m.a_ha, + &m.a_ctxa, m.b_qa, m.b_kvta, m.b_ga, m.a_aoa, m.b_oa, A, R, none)); + /* The cross-modal attentions: both streams gated by their text attention, each normed + * twice (as queries and as keys), the attentions, their gates. */ + B.g2v = gate_op(b, S, D, m.b_mv, m.b_ov, m.b_hv); + B.g2a = gate_op(b, A, Da, m.b_ma, m.b_oa, m.b_ha); + B.mav = mod_op(b, S, D, eps, false, "rms", m.b_mcv, m.b_mcv, m.b_hv, 0, m.a_nv.a.x); + B.mvv = mod_op(b, S, D, eps, false, "rms", m.b_mcv, m.b_mcv, m.b_hv, 0, m.a_nv2.a.x); + B.maa = mod_op(b, A, Da, eps, false, "rms", m.b_mca, m.b_mca, m.b_ha, 0, m.a_na.a.x); + B.mva = mod_op(b, A, Da, eps, false, "rms", m.b_mca, m.b_mca, m.b_ha, 0, m.a_na2.a.x); + RAD_ARCH_TRY(attn(B.a2v, "a2v", "audio_to_video_attn", m.Ha, m.hda, D, Da, D, false, m.a_nv, + &m.a_na, m.b_qxv, m.b_kvxa, m.b_gxv, m.a_xv, m.b_ov, S, A, rx)); + RAD_ARCH_TRY(attn(B.v2a, "v2a", "video_to_audio_attn", m.Ha, m.hda, Da, D, Da, false, m.a_na2, + &m.a_nv2, m.b_qxa, m.b_kvxv, m.b_gxa, m.a_xa, m.b_oa, A, S, rx)); + B.gcv = gate_op(b, S, D, m.b_mcvg, m.b_ov, m.b_hv); + B.gca = gate_op(b, A, Da, m.b_mcag, m.b_oa, m.b_ha); + /* The feed-forward (the video's without biases). */ + B.m3v = mod_op(b, S, D, eps, false, "rms", m.b_mv, m.b_mv, m.b_hv, 0, m.a_hv.a.x); + B.m3a = mod_op(b, A, Da, eps, false, "rms", m.b_ma, m.b_ma, m.b_ha, 0, m.a_ha.a.x); + B.m3vg = mod_op(b, S, D, eps, true, "rms", m.b_mv, m.b_mv, m.b_hv, m.b_ov, m.a_hv.a.x); + B.m3ag = mod_op(b, A, Da, eps, true, "rms", m.b_ma, m.b_ma, m.b_ha, m.b_oa, m.a_ha.a.x); + RAD_ARCH_TRY(B.fv_up.declare(b, nm, g, nm.f("%s.ff_up", dn), + { nm.ckpt("%s.ff.net.0.proj.weight", bp) }, + {}, {}, m.ffv, D, acc, gx, m.a_hv, m.b_upv, S)); + B.actv = unary(b, "gelu_tanh", S, m.ffv, "bf16", m.b_upv, m.a_ffv.a.x); + RAD_ARCH_TRY(B.fv_down.declare(b, nm, g, nm.f("%s.ff_down", dn), + { nm.ckpt("%s.ff.net.2.weight", bp) }, + {}, {}, D, m.ffv, acc, gx, m.a_ffv, m.b_ov, S)); + RAD_ARCH_TRY(B.fa_up.declare(b, nm, g, nm.f("%s.audio_ff_up", dn), + { nm.ckpt("%s.audio_ff.net.0.proj.weight", bp) }, + { nm.ckpt("%s.audio_ff.net.0.proj.bias", bp) }, {}, m.ffa, + Da, acc, gx, m.a_ha, m.b_upa, A)); + B.acta = unary(b, "gelu_tanh", A, m.ffa, "bf16", m.b_upa, m.a_ffa.a.x); + RAD_ARCH_TRY(B.fa_down.declare(b, nm, g, nm.f("%s.audio_ff_down", dn), + { nm.ckpt("%s.audio_ff.net.2.weight", bp) }, + { nm.ckpt("%s.audio_ff.net.2.bias", bp) }, {}, Da, m.ffa, acc, gx, + m.a_ffa, m.b_oa, A)); + const rad_op all[] = { B.op_tv, B.op_ta, B.op_tp, B.op_tpa, B.op_tcv, B.op_tcvg, B.op_tca, + B.op_tcag, B.m1v, B.m1a, B.m2v, B.m2a, B.mtv, B.mta, B.g2v, B.g2a, + B.mav, B.mvv, B.maa, B.mva, B.gcv, B.gca, B.m3v, B.m3a, B.m3vg, + B.m3ag, B.actv, B.acta }; + for (rad_op o : all) + if (!o) return RAD_E_INVAL; + } + + /* ---- the output: the last feed-forward gated in, LayerNorm modulated by the output tables, + * proj_out; each evaluation's velocities (PERSIST, the guidance reads them all) */ + m.op_fnv = mod_op(b, S, D, eps, true, "layer", m.b_fv, m.b_mv, m.b_hv, m.b_ov, m.a_fv.a.x); + m.op_fna = mod_op(b, A, Da, eps, true, "layer", m.b_fa, m.b_ma, m.b_ha, m.b_oa, m.a_fa.a.x); + for (int p = 0; p < kPasses; ++p) { + m.b_vel_v[p] = decl_b(b, nm.f("dit.vel_v%d", p), RAD_BF16, { S, kC }, RAD_BUF_PERSIST); + m.b_vel_a[p] = decl_b(b, nm.f("dit.vel_a%d", p), RAD_BF16, { A, kAudioC }, RAD_BUF_PERSIST); + } + RAD_ARCH_TRY(m.pout_v.declare(b, nm, g, "dit.proj_out", { nm.ckpt("transformer.proj_out.weight") }, + { nm.ckpt("transformer.proj_out.bias") }, {}, kC, D, acc, kGrpDit, + m.a_fv, m.b_vel_v[0], S, true)); + RAD_ARCH_TRY(m.pout_a.declare(b, nm, g, "dit.audio_proj_out", + { nm.ckpt("transformer.audio_proj_out.weight") }, + { nm.ckpt("transformer.audio_proj_out.bias") }, {}, kAudioC, Da, acc, + kGrpDit, m.a_fa, m.b_vel_a[0], A, true)); + /* The other evaluations' velocities are written by the same heads. */ + for (int p = 1; p < kPasses; ++p) { + RAD_ARCH_TRY(rad_op_writes(b, m.pout_v.op, &m.b_vel_v[p], 1)); + RAD_ARCH_TRY(rad_op_writes(b, m.pout_a.op, &m.b_vel_a[p], 1)); + } + + /* ---- the guided step: each modality's latent from its evaluations */ + m.b_gst = decl_b(b, nm.f("dit.guide_stats"), RAD_F32, { 8200 }); + auto guide = [&](int64_t rows, rad_buf* vel, rad_buf x) { + rad_op op = RAD_OP(b, "ltx_guide", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", kC), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + if (!op) return op; + rad_buf rd[6] = { vel[0], vel[1], vel[2], vel[3], m.b_gst, x }; + rad_buf wr[2] = { m.b_gst, x }; + rad_op_reads(b, op, rd, 6); + rad_op_writes(b, op, wr, 2); + return op; + }; + m.op_gv = guide(S, m.b_vel_v, m.b_vstate); + m.op_ga = guide(A, m.b_vel_a, m.b_astate); + return m.op_fnv && m.op_fna && m.op_gv && m.op_ga && m.op_fv && m.op_fa && m.op_rnd_v && + m.op_rnd_a && m.op_keep_first && m.op_lv && m.op_la + ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== the video VAE */ +/* A residual block's ops at C channels over voxel rows (`rows` at most): PerChannelRMSNorm with its + * SiLU, conv1, again, conv2 with the input added. `tpad` is the frames' padding (the decoder's + * replicate, the encoder's causal). */ +static int vres_declare(RadBuilder* b, Model& m, VRes& Rb, const char* dn, const char* src, int64_t C, + int64_t rows, const char* tpad, int group, rad_buf x, rad_buf t, rad_buf h) { + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_TOKEN; + Rb.C = C; + Rb.w1 = wcopy(b, nm.f("%s.conv1.weight", dn), nm.ckpt("%s.conv1.conv.weight", src), RAD_BF16, + { C, C, 3, 3, 3 }, acc, group); + Rb.b1 = wcopy(b, nm.f("%s.conv1.bias", dn), nm.ckpt("%s.conv1.conv.bias", src), RAD_BF16, { C }, + acc, group); + Rb.w2 = wcopy(b, nm.f("%s.conv2.weight", dn), nm.ckpt("%s.conv2.conv.weight", src), RAD_BF16, + { C, C, 3, 3, 3 }, acc, group); + Rb.b2 = wcopy(b, nm.f("%s.conv2.bias", dn), nm.ckpt("%s.conv2.conv.bias", src), RAD_BF16, { C }, + acc, group); + if (!Rb.w1 || !Rb.b1 || !Rb.w2 || !Rb.b2) return RAD_E_INVAL; + auto norm = [&](rad_buf in, rad_buf out) { + return rw(b, RAD_OP(b, "pixel_norm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", C), RAD_F64("eps", 1e-8), + RAD_STR("form", "div"), RAD_STR("act", "silu"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { in }, { out }); + }; + auto conv = [&](rad_weight w, rad_weight bb, rad_buf in, rad_buf res, rad_buf out) { + const rad_op op = RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", C), + RAD_INT("cout", C), RAD_INT("k", 3), RAD_INT("kt", 3), + RAD_STR("dtype", "bf16"), RAD_STR("tpad", tpad)), + RAD_WEIGHTS(w, bb)); + return res ? rw(b, op, { in, res }, { out }) : rw(b, op, { in }, { out }); + }; + Rb.op_n1 = norm(x, t); + Rb.op_c1 = conv(Rb.w1, Rb.b1, t, 0, h); + Rb.op_n2 = norm(h, t); + Rb.op_c2 = conv(Rb.w2, Rb.b2, t, x, x); + return Rb.op_n1 && Rb.op_c1 && Rb.op_n2 && Rb.op_c2 ? RAD_OK : RAD_E_INVAL; +} + +/* A dense [rows, cols] view of an arena buffer, at element offset `off` (the VAE's buffers hold + * a different width at each scale). */ +static RadOperand view(RadCtx* c, rad_buf h, uint32_t dt, int64_t rows, int64_t cols, int64_t off = 0) { + const int64_t es = dt == RAD_F32 ? 4 : dt == RAD_U8 ? 1 : 2; + return RAD_P_T2((const char*)rad_buf_ptr(c, h) + off * es, dt, rows, cols); +} + +static void vres_step(RadCtx* c, const VRes& Rb, int64_t vox, const RadOperand& geom, rad_buf x, + rad_buf t, rad_buf h) { + const int64_t C = Rb.C; + const RadOperand X = view(c, x, RAD_BF16, vox, C), Tt = view(c, t, RAD_BF16, vox, C); + const RadOperand Hh = view(c, h, RAD_BF16, vox, C); + RAD_ISSUE_N(c, Rb.op_n1, vox, X, Tt); + RAD_ISSUE_N(c, Rb.op_c1, vox, Tt, RAD_W(Rb.w1), RAD_W(Rb.b1), geom, RAD_NONE, Hh); + RAD_ISSUE_N(c, Rb.op_n2, vox, Hh, Tt); + RAD_ISSUE_N(c, Rb.op_c2, vox, Tt, RAD_W(Rb.w2), RAD_W(Rb.b2), geom, X, X); +} + +/* The decoder (LTX2VideoDecoder3d, non-causal): conv_in, the mid block, four up blocks (the + * upsampler's convolution and depth to space, then residual blocks), PerChannelRMSNorm with SiLU, + * conv_out to 4 x 4 pixel patches. The whole video at once, a tile at a time (vae_tiles: one for a + * frame of kVaeLat latents or fewer), into the lane's tile store; each chunk's frames stitched to + * bytes from it. */ +static int declare_vae(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_TOKEN, gx = kGrpVae; + std::vector boc = meta_list(meta, "vae.decoder_block_out_channels"); + std::vector lpb = meta_list(meta, "vae.decoder_layers_per_block"); + std::vector uf = meta_list(meta, "vae.upsample_factor"); + const char* types = rad_meta_gets(meta, "vae.upsample_type", ""); + std::vector sts = meta_list(meta, "vae.decoder_spatio_temporal_scaling"); + std::vector ut; + for (const char* s = types; s && *s;) { + while (*s == ' ') ++s; + const char* e = s; + while (*e && *e != ' ') ++e; + if (e > s) ut.emplace_back(s, e); + s = e; + } + const size_t nup = boc.size(); + if (nup == 0 || lpb.size() != nup + 1 || uf.size() != nup || ut.size() != nup || + sts.size() != nup) { + fprintf(stderr, "radiance: ltx2: the VAE decoder's block lists disagree in length\n"); + return RAD_E_UNSUPPORTED; + } + std::reverse(boc.begin(), boc.end()); + std::reverse(lpb.begin(), lpb.end()); + std::reverse(uf.begin(), uf.end()); + std::reverse(sts.begin(), sts.end()); + + /* The volumes: latent (F, h, w) to (At F + Bt, Ah h, Aw w) after each up block; the scratch + * sized to the largest volume times channels any step of the network holds. */ + const int64_t F = max_lat_frames(), HW = kVaeLat; + int64_t At = 1, Bt = 0, Ahw = 1, C = (int64_t)boc[0], big = F * HW * C; + m.vC0 = C; + m.vup.resize(nup); + for (size_t i = 0; i < nup; ++i) { + VUp& U = m.vup[i]; + U.cout = (int64_t)boc[i] / (int64_t)uf[i]; + U.cin = C; + if (!sts[i]) { + fprintf(stderr, "radiance: ltx2: an up block without its upsampler\n"); + return RAD_E_UNSUPPORTED; + } + if (ut[i] == "spatiotemporal") { U.st = 2; U.sh = 2; U.sw = 2; } + else if (ut[i] == "temporal") { U.st = 2; U.sh = 1; U.sw = 1; } + else if (ut[i] == "spatial") { U.st = 1; U.sh = 2; U.sw = 2; } + else return RAD_E_UNSUPPORTED; + if (U.cout * (int64_t)uf[i] != C) { + fprintf(stderr, "radiance: ltx2: up block %zu would take %lld channels and has %lld; a " + "block that changes width first is not run\n", i, + (long long)(U.cout * (int64_t)uf[i]), (long long)C); + return RAD_E_UNSUPPORTED; + } + U.conv_out = C * U.st * U.sh * U.sw / (int64_t)uf[i]; + big = std::max(big, (At * F + Bt) * Ahw * HW * U.conv_out); + At *= U.st; + Bt = Bt * U.st - (U.st - 1); + Ahw *= U.sh * U.sw; + C = U.cout; + big = std::max(big, (At * F + Bt) * Ahw * HW * C); + } + const int64_t vox_out = (At * F + Bt) * Ahw * HW; + { + int64_t side = 1; + while (side * side < Ahw) ++side; + if (side * side != Ahw) return RAD_E_UNSUPPORTED; + /* The causal mapping tile_stitch reads: the first latent frame one frame. */ + if (Bt != 1 - At) return RAD_E_UNSUPPORTED; + m.vAt = At; + m.vBt = Bt; + m.vAhw = side; + } + /* The tile store holds the largest video's tiles: every size a request may ask for, at the + * most frames a step carries at that size. */ + for (int64_t Wd = kMinSide; Wd * kMinSide <= kMaxArea; Wd += kMult) + for (int64_t Hd = kMinSide; Wd * Hd <= kMaxArea; Hd += kMult) { + if (std::max(Wd, Hd) > kMaxAspect * std::min(Wd, Hd)) continue; + const int64_t h = Hd / kScale, w = Wd / kScale; + const int64_t Fl = std::min(max_lat_frames(), max_video_rows() / (h * w)); + if (Fl < (int64_t)kLpc * kMinChunks + kLtail) continue; + const std::vector tl = vae_tiles(h, w); + int64_t area = 0; + for (const VaeTile& t : tl) area += t.h * t.w; + m.maxStore = std::max(m.maxStore, (At * Fl + Bt) * Ahw * area); + m.maxTiles = std::max(m.maxTiles, (int64_t)tl.size()); + m.maxSide = std::max(m.maxSide, std::max(Wd, Hd)); + } + /* Every tile's crop reads the latent again after earlier tiles' decodes, which the planner's + * declaration order cannot see: kept. */ + m.b_vlat = decl_b(b, nm.f("vae.lat"), RAD_BF16, { m.maxS, kC }, RAD_BUF_PERSIST); + m.b_vtlat = decl_b(b, nm.f("vae.tile_lat"), RAD_BF16, { F * HW, kC }); + m.b_va = decl_b(b, nm.f("vae.a"), RAD_BF16, { big }); + m.b_vb = decl_b(b, nm.f("vae.b"), RAD_BF16, { big }); + m.b_vc = decl_b(b, nm.f("vae.c"), RAD_BF16, { big }); + m.b_vtiles = decl_b(b, nm.f("lane.tiles"), RAD_BF16, { m.maxStore, kPixC }, RAD_BUF_PERSIST); + /* The boxes are read through raw pointers the planner does not see: kept. */ + m.b_vgrid = decl_b(b, nm.f("vae.grid"), RAD_I32, { m.maxTiles, 8 }, RAD_BUF_PERSIST); + m.b_vf0 = decl_b(b, nm.f("vae.first_frame"), RAD_I32, { 1 }); + m.vd_mean = wcopy(b, nm.f("vae.latents_mean"), nm.ckpt("vae.latents_mean"), RAD_BF16, { kC }, + acc, gx); + m.vd_std = wcopy(b, nm.f("vae.latents_std"), nm.ckpt("vae.latents_std"), RAD_BF16, { kC }, acc, gx); + if (!m.vd_mean || !m.vd_std) return RAD_E_INVAL; + /* The latent to bf16 first, then denormalised in bf16, as the pipeline casts it. */ + m.op_vlat = cast_op(b, m.maxS, kC, "f32", "bf16", m.b_vstate, m.b_vlat); + m.op_vden = rw(b, RAD_OP(b, "chan_stats", + RAD_PARAMS(RAD_RANGE("M", 1, m.maxS), RAD_INT("n", kC), + RAD_STR("mode", "denorm"), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.vd_mean, m.vd_std)), + { m.b_vlat }, { m.b_vlat }); + auto conv = [&](rad_weight* w, rad_weight* bb, const char* dn, const char* src, int64_t cin, + int64_t cout, int64_t rows, rad_buf in, rad_buf out) -> rad_op { + *w = wcopy(b, nm.f("%s.weight", dn), nm.ckpt("%s.conv.weight", src), RAD_BF16, + { cout, cin, 3, 3, 3 }, acc, gx); + *bb = wcopy(b, nm.f("%s.bias", dn), nm.ckpt("%s.conv.bias", src), RAD_BF16, { cout }, acc, gx); + if (!*w || !*bb) return 0; + return rw(b, RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", cin), + RAD_INT("cout", cout), RAD_INT("k", 3), RAD_INT("kt", 3), + RAD_STR("dtype", "bf16"), RAD_STR("tpad", "replicate")), + RAD_WEIGHTS(*w, *bb)), + { in }, { out }); + }; + auto grid = [&](int64_t tile, int64_t stride) { + return rw(b, RAD_OP(b, "tile_grid", + RAD_PARAMS(RAD_RANGE("M", 1, m.maxTiles), RAD_INT("tile", tile), + RAD_INT("stride", stride)), + RAD_NOWEIGHTS), + {}, { m.b_vgrid }); + }; + /* One tile: a tile_grid row of the whole frame. */ + m.op_vgrid1 = grid(1 << 20, 1 << 20); + m.op_vgrid = grid(kTile, kTileStride); + m.op_vcrop = rw(b, RAD_OP(b, "tile_crop", + RAD_PARAMS(RAD_RANGE("M", 1, F * HW), RAD_INT("C", kC), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_vlat }, { m.b_vtlat }); + m.op_vcin = conv(&m.w_vcin, &m.b_vcin, "vae.dec.conv_in", "vae.decoder.conv_in", kC, m.vC0, F * HW, + m.b_vtlat, m.b_va); + const int64_t nmid = (int64_t)lpb[0]; + m.vmid.resize((size_t)nmid); + for (int64_t r = 0; r < nmid; ++r) + RAD_ARCH_TRY(vres_declare(b, m, m.vmid[(size_t)r], nm.f("vae.dec.mid.%lld", (long long)r), + nm.ckpt("vae.decoder.mid_block.resnets.%lld", (long long)r), m.vC0, + m.maxS, "replicate", gx, m.b_va, m.b_vb, m.b_vc)); + At = 1; + Bt = 0; + int64_t Ah = 1, Aw = 1; + for (size_t i = 0; i < nup; ++i) { + VUp& U = m.vup[i]; + const int64_t vin = (At * F + Bt) * Ah * Aw * HW; + At *= U.st; + Bt = Bt * U.st - (U.st - 1); + Ah *= U.sh; + Aw *= U.sw; + const int64_t vout = (At * F + Bt) * Ah * Aw * HW; + const char* dn = nm.f("vae.dec.up.%zu", i); + const char* src = nm.ckpt("vae.decoder.up_blocks.%zu", i); + U.op_conv = conv(&U.w, &U.b, nm.f("%s.conv", dn), nm.ckpt("%s.upsamplers.0.conv", src), U.cin, + U.conv_out, vin, m.b_va, m.b_vb); + U.op_d2s = rw(b, RAD_OP(b, "d2s3d", + RAD_PARAMS(RAD_RANGE("M", 1, vin), RAD_INT("C", U.cout), + RAD_INT("st", U.st), RAD_INT("sh", U.sh), RAD_INT("sw", U.sw), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_vb }, { m.b_va }); + /* Its output volume on the device, off the latent's (kept, so every reader finds it). */ + U.geom = decl_b(b, nm.f("%s.geom", dn), RAD_I32, { 3 }, RAD_BUF_PERSIST); + U.op_geom = rw(b, RAD_OP(b, "int_affine", + RAD_PARAMS(RAD_RANGE("M", 1, 3), RAD_STR("src", "0 1 2"), + RAD_STR("mul", ints({ At, Ah, Aw }).c_str()), + RAD_STR("add", ints({ Bt, 0, 0 }).c_str())), + RAD_NOWEIGHTS), + {}, { U.geom }); + if (!U.op_conv || !U.op_d2s || !U.op_geom) return RAD_E_INVAL; + const int64_t nres = (int64_t)lpb[i + 1]; + U.res.resize((size_t)nres); + for (int64_t r = 0; r < nres; ++r) + RAD_ARCH_TRY(vres_declare(b, m, U.res[(size_t)r], nm.f("%s.res.%lld", dn, (long long)r), + nm.ckpt("%s.resnets.%lld", src, (long long)r), U.cout, vout, + "replicate", gx, m.b_va, m.b_vb, m.b_vc)); + } + m.op_vnout = rw(b, RAD_OP(b, "pixel_norm", + RAD_PARAMS(RAD_RANGE("M", 1, vox_out), RAD_INT("n", C), + RAD_F64("eps", 1e-8), + RAD_STR("form", "div"), RAD_STR("act", "silu"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_va }, { m.b_vb }); + m.op_vcout = conv(&m.w_vcout, &m.b_vcout, "vae.dec.conv_out", "vae.decoder.conv_out", C, kPixC, + vox_out, m.b_vb, m.b_vtiles); + /* A chunk's frames to bytes: 4 x 4 patches, the column offset outer (LTX-2's patchifier), the + * tiles blended where they overlap; the chunk's first frame off the pass's geometry. */ + m.b_frames = decl_b(b, nm.f("frames_out"), RAD_U8, { (int64_t)(kFpc + kFtail) * kMaxArea, 3 }, + RAD_BUF_PERSIST); + m.op_vf0 = rw(b, RAD_OP(b, "int_affine", + RAD_PARAMS(RAD_RANGE("M", 1, 1), + RAD_STR("src", ints({ RAD_VGEOM_CHUNK_LAT0 }).c_str()), + RAD_STR("mul", ints({ kFpc / kLpc }).c_str()), + RAD_STR("add", "0")), + RAD_NOWEIGHTS), + {}, { m.b_vf0 }); + auto stitch = [&](int64_t tile, int64_t stride) { + return rw(b, RAD_OP(b, "tile_stitch", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)(kFpc + kFtail) * m.maxSide), + RAD_INT("tile", tile), RAD_INT("stride", stride), + RAD_INT("scale", m.vAhw), RAD_INT("scale_t", m.vAt), + RAD_INT("p", kPix), RAD_INT("C", 3), RAD_STR("order", "wh"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_vtiles, m.b_vf0 }, { m.b_frames }); + }; + m.op_vst1 = stitch(1 << 20, 1 << 20); + m.op_vst = stitch(kTile, kTileStride); + return m.op_vlat && m.op_vden && m.op_vcin && m.op_vnout && m.op_vcout && m.op_vgrid1 && + m.op_vgrid && m.op_vcrop && m.op_vf0 && m.op_vst1 && m.op_vst + ? RAD_OK + : RAD_E_INVAL; +} + +/* The encoder (LTX2VideoEncoder3d, causal) over one frame: the image in 4 x 4 patches, conv_in, + * four down blocks (residual blocks, then the downsampler: its convolution over the volume with + * its first st - 1 frames prepended, space to depth, the input's group mean added), the mid block, + * PerChannelRMSNorm with SiLU, conv_out; the mean's 128 channels normalised into the lane's clean + * first latent frame. A frame stays one frame through every temporal downsample. */ +static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_REQUEST, gx = kGrpVenc; + const std::vector boc = meta_list(meta, "vae.block_out_channels"); + const std::vector lpb = meta_list(meta, "vae.layers_per_block"); + const std::vector sts = meta_list(meta, "vae.spatio_temporal_scaling"); + const char* types = rad_meta_gets(meta, "vae.downsample_type", ""); + std::vector dt; + for (const char* s = types; s && *s;) { + while (*s == ' ') ++s; + const char* e = s; + while (*e && *e != ' ') ++e; + if (e > s) dt.emplace_back(s, e); + s = e; + } + const size_t nd = boc.size(); + if (nd == 0 || lpb.size() != nd + 1 || dt.size() != nd || sts.size() != nd) { + fprintf(stderr, "radiance: ltx2: the VAE encoder's block lists disagree in length\n"); + return RAD_E_UNSUPPORTED; + } + m.venc = true; + const int64_t HW = m.maxPpf; /* latents a frame at most */ + int64_t Ahw = 64, C = kC, big = Ahw * HW * kPixC; + m.eC0 = C; + m.vdown.resize(nd); + /* The volumes: input (1, 8 h, 8 w) in latent units; the conv's (1 + tpre) frames. */ + for (size_t i = 0; i < nd; ++i) { + VDown& Dn = m.vdown[i]; + Dn.cin = C; + Dn.cout = (int64_t)boc[i]; + if (!sts[i]) return RAD_E_UNSUPPORTED; + if (dt[i] == "spatiotemporal") { Dn.st = 2; Dn.sh = 2; Dn.sw = 2; } + else if (dt[i] == "temporal") { Dn.st = 2; Dn.sh = 1; Dn.sw = 1; } + else if (dt[i] == "spatial") { Dn.st = 1; Dn.sh = 2; Dn.sw = 2; } + else return RAD_E_UNSUPPORTED; + const int64_t P = Dn.st * Dn.sh * Dn.sw; + Dn.conv_out = Dn.cout / P; + Dn.group = Dn.cin * P / Dn.cout; + if (Dn.conv_out * P != Dn.cout || Dn.group * Dn.cout != Dn.cin * P) return RAD_E_UNSUPPORTED; + big = std::max(big, Ahw * HW * C); + big = std::max(big, Dn.st * Ahw * HW * Dn.conv_out); + Ahw /= Dn.sh * Dn.sw; + C = Dn.cout; + big = std::max(big, Ahw * HW * C); + } + if (Ahw != 1) { + fprintf(stderr, "radiance: ltx2: the VAE encoder does not reach the latent's 32-pixel scale\n"); + return RAD_E_UNSUPPORTED; + } + m.eCout = C; + big = std::max(big, HW * (kC + 1)); + m.b_epatch = decl_b(b, nm.f("venc.patch"), RAD_BF16, { 64 * HW, kPixC }); + m.b_ea = decl_b(b, nm.f("venc.a"), RAD_BF16, { big }); + m.b_eb = decl_b(b, nm.f("venc.b"), RAD_BF16, { big }); + m.b_ec = decl_b(b, nm.f("venc.c"), RAD_BF16, { big }); + m.b_eout = decl_b(b, nm.f("venc.out"), RAD_BF16, { HW, kC + 1 }); + m.b_elat = decl_b(b, nm.f("venc.lat"), RAD_BF16, { HW, kC }); + m.op_epatch = rw(b, RAD_OP(b, "pix_patch", + RAD_PARAMS(RAD_RANGE("M", 1, 8 * HW), RAD_INT("p", kPix), RAD_INT("C", 3), + RAD_STR("order", "wh"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_epatch }); + auto geom = [&](rad_buf* g, rad_op* op, const char* name, int64_t frames, int64_t mul) { + *g = decl_b(b, nm.f("venc.%s", name), RAD_I32, { 3 }, RAD_BUF_PERSIST); + *op = rw(b, RAD_OP(b, "int_affine", + RAD_PARAMS(RAD_RANGE("M", 1, 3), RAD_STR("src", "-1 1 2"), + RAD_STR("mul", ints({ 0, mul, mul }).c_str()), + RAD_STR("add", ints({ frames, 0, 0 }).c_str())), + RAD_NOWEIGHTS), + {}, { *g }); + return *g && *op ? RAD_OK : RAD_E_INVAL; + }; + RAD_ARCH_TRY(geom(&m.b_egeomL, &m.op_egeomL, "geom_mid", 1, 1)); + auto conv = [&](rad_weight* w, rad_weight* bb, const char* dn, const char* src, int64_t cin, + int64_t cout, int64_t rows, int64_t tpre, rad_buf in, rad_buf out) -> rad_op { + *w = wcopy(b, nm.f("%s.weight", dn), nm.ckpt("%s.conv.weight", src), RAD_BF16, + { cout, cin, 3, 3, 3 }, acc, gx); + *bb = wcopy(b, nm.f("%s.bias", dn), nm.ckpt("%s.conv.bias", src), RAD_BF16, { cout }, acc, gx); + if (!*w || !*bb) return 0; + return rw(b, RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", cin), + RAD_INT("cout", cout), RAD_INT("k", 3), RAD_INT("kt", 3), + RAD_STR("dtype", "bf16"), RAD_STR("tpad", "causal"), + RAD_INT("tpre", tpre)), + RAD_WEIGHTS(*w, *bb)), + { in }, { out }); + }; + m.op_ecin = conv(&m.w_ecin, &m.b_ecin, "venc.conv_in", "vae.encoder.conv_in", kPixC, kC, 64 * HW, 0, + m.b_epatch, m.b_ea); + if (!m.op_ecin) return RAD_E_INVAL; + Ahw = 64; + for (size_t i = 0; i < nd; ++i) { + VDown& Dn = m.vdown[i]; + const char* dn = nm.f("venc.down.%zu", i); + const char* src = nm.ckpt("vae.encoder.down_blocks.%zu", i); + const int64_t vin = Ahw * HW, nres = (int64_t)lpb[i]; + Dn.res.resize((size_t)nres); + for (int64_t r = 0; r < nres; ++r) + RAD_ARCH_TRY(vres_declare(b, m, Dn.res[(size_t)r], nm.f("%s.res.%lld", dn, (long long)r), + nm.ckpt("%s.resnets.%lld", src, (long long)r), Dn.cin, vin, + "causal", gx, m.b_ea, m.b_eb, m.b_ec)); + /* The residual's group mean into b, the convolution into c, its space to depth added. */ + const int64_t tpre = Dn.st - 1, sm = (int64_t)std::lround(std::sqrt((double)Ahw)); + Dn.op_mean = rw(b, RAD_OP(b, "s2d3d", + RAD_PARAMS(RAD_RANGE("M", 1, vin), RAD_INT("C", Dn.cin), + RAD_INT("st", Dn.st), RAD_INT("sh", Dn.sh), + RAD_INT("sw", Dn.sw), RAD_INT("tpre", tpre), + RAD_INT("group", Dn.group), RAD_STR("mode", "mean"), + RAD_INT("add", 0), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ea }, { m.b_eb }); + Dn.op_conv = conv(&Dn.w, &Dn.b, nm.f("%s.conv", dn), nm.ckpt("%s.downsamplers.0.conv", src), + Dn.cin, Dn.conv_out, vin, tpre, m.b_ea, m.b_ec); + Dn.op_s2d = rw(b, RAD_OP(b, "s2d3d", + RAD_PARAMS(RAD_RANGE("M", 1, Dn.st * vin), RAD_INT("C", Dn.conv_out), + RAD_INT("st", Dn.st), RAD_INT("sh", Dn.sh), + RAD_INT("sw", Dn.sw), RAD_STR("mode", "copy"), + RAD_INT("add", 1), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ec, m.b_eb }, { m.b_eb }); + /* The block's input volume and its convolution's ((1 + tpre) frames at this scale). */ + RAD_ARCH_TRY(geom(&Dn.geom_in, &Dn.op_geom_in, nm.f("geom_in%zu", i), 1, sm)); + RAD_ARCH_TRY(geom(&Dn.geom, &Dn.op_geom, nm.f("geom_conv%zu", i), 1 + tpre, sm)); + Ahw /= Dn.sh * Dn.sw; + /* The block's output (in b) back into the stream (a). */ + Dn.op_next = cast_op(b, Ahw * HW, Dn.cout, "bf16", "bf16", m.b_eb, m.b_ea); + if (!Dn.op_mean || !Dn.op_conv || !Dn.op_s2d || !Dn.op_next) return RAD_E_INVAL; + } + const int64_t nmid = (int64_t)lpb[nd]; + m.emid.resize((size_t)nmid); + for (int64_t r = 0; r < nmid; ++r) + RAD_ARCH_TRY(vres_declare(b, m, m.emid[(size_t)r], nm.f("venc.mid.%lld", (long long)r), + nm.ckpt("vae.encoder.mid_block.resnets.%lld", (long long)r), C, HW, + "causal", gx, m.b_ea, m.b_eb, m.b_ec)); + m.op_enout = rw(b, RAD_OP(b, "pixel_norm", + RAD_PARAMS(RAD_RANGE("M", 1, HW), RAD_INT("n", C), RAD_F64("eps", 1e-8), + RAD_STR("form", "div"), RAD_STR("act", "silu"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ea }, { m.b_eb }); + m.op_ecout = conv(&m.w_ecout, &m.b_ecout, "venc.conv_out", "vae.encoder.conv_out", C, kC + 1, HW, 0, + m.b_eb, m.b_eout); + m.op_enorm = rw(b, RAD_OP(b, "chan_stats", + RAD_PARAMS(RAD_RANGE("M", 1, HW), RAD_INT("n", kC), + RAD_STR("mode", "norm"), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.vd_mean, m.vd_std)), + { m.b_eout }, { m.b_elat }); + m.op_ef32 = cast_op(b, HW, kC, "bf16", "f32", m.b_elat, m.b_first); + return m.op_epatch && m.op_enout && m.op_ecout && m.op_enorm && m.op_ef32 && m.op_egeomL + ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== the soundtrack */ +/* An audio VAE residual block over an image of (time) rows x `w` mel columns: PixelNorm with SiLU, + * conv1 (causal along time), again, conv2, the input or its 1 x 1 shortcut added. */ +static int ares_declare(RadBuilder* b, Model& m, ARes& Rb, const char* dn, const char* src, + int64_t cin, int64_t cout, int64_t px, rad_buf x, rad_buf t, rad_buf h, + rad_buf s) { + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_TOKEN, gx = kGrpAudio; + Rb.cin = cin; + Rb.cout = cout; + auto conv = [&](rad_weight* w, rad_weight* bb, const char* name, int64_t ci, int64_t co, int64_t k, + rad_buf in, rad_buf out) -> rad_op { + *w = wcopy(b, nm.f("%s.%s.weight", dn, name), nm.ckpt("%s.%s.conv.weight", src, name), RAD_BF16, + { co, ci, k, k }, acc, gx); + *bb = wcopy(b, nm.f("%s.%s.bias", dn, name), nm.ckpt("%s.%s.conv.bias", src, name), RAD_BF16, + { co }, acc, gx); + if (!*w || !*bb) return 0; + return rw(b, RAD_OP(b, "conv2d_nhwc", + RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("cin", ci), RAD_INT("cout", co), + RAD_INT("k", k), RAD_INT("stride", 1), + RAD_STR("pad", k > 1 ? "causal" : "same"), RAD_INT("up", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(*w, *bb)), + { in }, { out }); + }; + auto norm = [&](int64_t n, rad_buf in, rad_buf out) { + return rw(b, RAD_OP(b, "pixel_norm", + RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("n", n), RAD_F64("eps", 1e-6), + RAD_STR("form", "div"), RAD_STR("act", "silu"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { in }, { out }); + }; + Rb.op_n1 = norm(cin, x, t); + Rb.op_c1 = conv(&Rb.w1, &Rb.b1, "conv1", cin, cout, 3, t, h); + Rb.op_n2 = norm(cout, h, t); + Rb.op_c2 = conv(&Rb.w2, &Rb.b2, "conv2", cout, cout, 3, t, h); + if (cin != cout) Rb.op_sc = conv(&Rb.ws, &Rb.bs, "nin_shortcut", cin, cout, 1, x, s); + Rb.op_add = add_op(b, px, cout, "bf16", cin != cout ? s : x, h, x); + return Rb.op_n1 && Rb.op_c1 && Rb.op_n2 && Rb.op_c2 && (cin == cout || Rb.op_sc) && Rb.op_add + ? RAD_OK : RAD_E_INVAL; +} + +static void ares_step(RadCtx* c, const ARes& Rb, int64_t H, int64_t W, rad_buf x, rad_buf t, + rad_buf h, rad_buf s) { + const int64_t px = H * W, ci = Rb.cin, co = Rb.cout; + RAD_ISSUE_N(c, Rb.op_n1, px, view(c, x, RAD_BF16, px, ci), view(c, t, RAD_BF16, px, ci)); + RAD_ISSUE_N(c, Rb.op_c1, px, view(c, t, RAD_BF16, H, W * ci), RAD_W(Rb.w1), RAD_W(Rb.b1), + view(c, h, RAD_BF16, H, W * co)); + RAD_ISSUE_N(c, Rb.op_n2, px, view(c, h, RAD_BF16, px, co), view(c, t, RAD_BF16, px, co)); + RAD_ISSUE_N(c, Rb.op_c2, px, view(c, t, RAD_BF16, H, W * co), RAD_W(Rb.w2), RAD_W(Rb.b2), + view(c, h, RAD_BF16, H, W * co)); + if (Rb.op_sc) { + RAD_ISSUE_N(c, Rb.op_sc, px, view(c, x, RAD_BF16, H, W * ci), RAD_W(Rb.ws), RAD_W(Rb.bs), + view(c, s, RAD_BF16, H, W * co)); + RAD_ISSUE_N(c, Rb.op_add, px, view(c, s, RAD_BF16, px, co), view(c, h, RAD_BF16, px, co), + view(c, x, RAD_BF16, px, co)); + } else { + RAD_ISSUE_N(c, Rb.op_add, px, view(c, x, RAD_BF16, px, co), view(c, h, RAD_BF16, px, co), + view(c, x, RAD_BF16, px, co)); + } +} + +/* A vocoder (LTX2Vocoder, f32) from `in` [rows, 128] to `V.wav` [rows x 160 or 240, 2]: conv_in, + * each stage an upsampling transposed convolution and the mean of three resnets (kernel 3, 7 and + * 11), each three dilations of anti-aliased SnakeBeta, dilated conv, again, conv and the residual; + * the last SnakeBeta and conv_out without a bias. `mult`: its input rows a mel frame of the audio + * VAE's output (the extender's input is at twice the rate). */ +static int voc_declare(RadBuilder* b, const RadModelMeta* meta, Model& m, Voc& V, const char* dn, + const char* src, const char* cfg, int64_t mult, rad_buf in) { + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_TOKEN, gx = kGrpVoc; + static const int64_t kDil[3] = { 1, 3, 5 }; + auto key = [&](const char* k) { return nm.f("vocoder.%s%s", cfg, k); }; + V.in = 2 * kMel; + V.out = 2; + V.mult = mult; + V.in_buf = in; + V.hidden = rad_meta_geti(meta, key("hidden_channels"), 0); + for (double x : meta_list(meta, key("upsample_factors"))) V.rates.push_back((int64_t)x); + for (double x : meta_list(meta, key("upsample_kernel_sizes"))) V.ks.push_back((int64_t)x); + for (double x : meta_list(meta, key("resnet_kernel_sizes"))) V.rk.push_back((int64_t)x); + const std::vector dil = meta_list(meta, key("resnet_dilations")); + const size_t ns = V.rates.size(); + bool ok = V.hidden > 0 && ns > 0 && V.ks.size() == ns && V.rk.size() == 3 && dil.size() == 9 && + (V.hidden >> ns) >= 1; + for (size_t i = 0; ok && i < 9; ++i) ok = (int64_t)dil[i] == kDil[i % 3]; + if (!ok) { + fprintf(stderr, "radiance: ltx2: the %svocoder is not a BigVGAN of three resnets a stage " + "at dilations 1, 3, 5 (hidden %lld, %zu stages, %zu kernels, %zu resnet " + "kernels, %zu dilations)\n", cfg, (long long)V.hidden, ns, V.ks.size(), + V.rk.size(), dil.size()); + return RAD_E_UNSUPPORTED; + } + /* Rows a stage: (4 n - 3) mel frames times the upsampling so far. */ + std::vector rows(ns + 1); + rows[0] = mel_frames(m.maxA) * mult; + for (size_t s = 0; s < ns; ++s) rows[s + 1] = rows[s] * V.rates[s]; + auto cu = [&](int64_t f) { + rad_buf y = decl_b(b, nm.f("%s.cu%lld", dn, (long long)f), RAD_I32, { 2 }, RAD_BUF_PERSIST); + V.cu.push_back(y); + return rw(b, RAD_OP(b, "int_affine", + RAD_PARAMS(RAD_RANGE("M", 1, 2), + RAD_STR("src", ints({ -1, RAD_VGEOM_N_AUDIO }).c_str()), + RAD_STR("mul", ints({ 0, 4 * f }).c_str()), + RAD_STR("add", ints({ 0, -3 * f }).c_str())), + RAD_NOWEIGHTS), + {}, { y }); + }; + auto wt = [&](const char* name, std::initializer_list shape) { + return wcopy(b, nm.f("%s.%s", dn, name), nm.ckpt("%s.%s", src, name), RAD_F32, shape, acc, gx); + }; + auto conv1 = [&](VConv& K, const char* name, int64_t ci, int64_t co, int64_t k, int64_t d, + bool bias, int64_t R, rad_buf x, rad_buf cub, rad_buf res, rad_buf y) { + K.w = wt(nm.f("%s.weight", name), { co, ci, k }); + if (bias) K.b = wt(nm.f("%s.bias", name), { co }); + if (!K.w || (bias && !K.b)) return RAD_E_INVAL; + rad_op op = bias ? RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("cin", ci), + RAD_INT("cout", co), + RAD_INT("k", k), RAD_INT("dil", d), RAD_STR("act", "none"), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(K.w, K.b)) + : RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("cin", ci), + RAD_INT("cout", co), + RAD_INT("k", k), RAD_INT("dil", d), RAD_STR("act", "none"), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(K.w)); + K.op = res ? rw(b, op, { x, cub, res }, { y }) : rw(b, op, { x, cub }, { y }); + return K.op ? RAD_OK : RAD_E_INVAL; + }; + auto act = [&](VAct& a, const char* name, int64_t ch, int64_t R, rad_buf x, rad_buf cub, rad_buf y) { + a.alpha = wt(nm.f("%s.act.alpha", name), { ch }); + a.beta = wt(nm.f("%s.act.beta", name), { ch }); + a.up = wt(nm.f("%s.upsample.filter", name), { 1, 1, 12 }); + a.down = wt(nm.f("%s.downsample.filter", name), { 1, 1, 12 }); + if (!a.alpha || !a.beta || !a.up || !a.down) return RAD_E_INVAL; + a.op = rw(b, RAD_OP(b, "snake_aa", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", ch), RAD_INT("ratio", 2), + RAD_INT("k", 12), RAD_INT("log", 1), RAD_STR("dtype", "f32")), + RAD_WEIGHTS(a.alpha, a.beta, a.up, a.down)), + { x, cub }, { y }); + return a.op ? RAD_OK : RAD_E_INVAL; + }; + V.op_cu0 = cu(mult); + V.h.resize(ns + 1); + V.avg.resize(ns + 1); + V.t1.resize(ns + 1); + V.t2.resize(ns + 1); + for (int j = 0; j < 3; ++j) V.amp[j].resize(ns + 1); + V.avg[0] = decl_b(b, nm.f("%s.h0", dn), RAD_F32, { rows[0], V.hidden }); + RAD_ARCH_TRY(conv1(V.cin, "conv_in", V.in, V.hidden, 7, 1, true, rows[0], in, V.cu[0], 0, V.avg[0])); + int64_t f = mult; + V.st.resize(ns); + for (size_t s = 0; s < ns; ++s) { + VStage& St = V.st[s]; + const int64_t ci = V.hidden >> s, co = V.hidden >> (s + 1), R = rows[s + 1]; + St.ch = co; + St.rate = V.rates[s]; + St.k = V.ks[s]; + f *= St.rate; + St.op_cu = cu(f); + V.h[s + 1] = decl_b(b, nm.f("%s.s%zu.in", dn, s), RAD_F32, { R, co }); + V.t1[s + 1] = decl_b(b, nm.f("%s.s%zu.t1", dn, s), RAD_F32, { R, co }); + V.t2[s + 1] = decl_b(b, nm.f("%s.s%zu.t2", dn, s), RAD_F32, { R, co }); + for (int j = 0; j < 3; ++j) + V.amp[j][s + 1] = decl_b(b, nm.f("%s.s%zu.amp%d", dn, s, j), RAD_F32, { R, co }); + St.up.w = wt(nm.f("upsamplers.%zu.weight", s), { ci, co, St.k }); + St.up.b = wt(nm.f("upsamplers.%zu.bias", s), { co }); + if (!St.up.w || !St.up.b || !St.op_cu) return RAD_E_INVAL; + St.up.op = rw(b, RAD_OP(b, "conv_t1d", + RAD_PARAMS(RAD_RANGE("M", 1, rows[s]), RAD_INT("cin", ci), + RAD_INT("cout", co), RAD_INT("stride", St.rate), + RAD_INT("k", St.k), RAD_INT("pad", (St.k - St.rate) / 2), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(St.up.w, St.up.b)), + { V.avg[s], V.cu[s] }, { V.h[s + 1] }); + if (!St.up.op) return RAD_E_INVAL; + for (int j = 0; j < 3; ++j) { + const int ri = (int)(s * 3) + j; + for (int d = 0; d < 3; ++d) { + VUnit& U = St.u[j][d]; + const rad_buf x = d == 0 ? V.h[s + 1] : V.amp[j][s + 1]; + RAD_ARCH_TRY(act(U.a1, nm.f("resnets.%d.acts1.%d", ri, d), co, R, x, V.cu[s + 1], + V.t1[s + 1])); + RAD_ARCH_TRY(conv1(U.c1, nm.f("resnets.%d.convs1.%d", ri, d), co, co, V.rk[(size_t)j], + kDil[d], true, R, V.t1[s + 1], V.cu[s + 1], 0, V.t2[s + 1])); + RAD_ARCH_TRY(act(U.a2, nm.f("resnets.%d.acts2.%d", ri, d), co, R, V.t2[s + 1], + V.cu[s + 1], V.t1[s + 1])); + RAD_ARCH_TRY(conv1(U.c2, nm.f("resnets.%d.convs2.%d", ri, d), co, co, V.rk[(size_t)j], 1, + true, R, V.t1[s + 1], V.cu[s + 1], x, V.amp[j][s + 1])); + } + } + V.avg[s + 1] = decl_b(b, nm.f("%s.s%zu.out", dn, s), RAD_F32, { R, co }); + St.op_sum = add_op(b, R, co, "f32", V.amp[0][s + 1], V.amp[1][s + 1], V.avg[s + 1]); + St.op_avg = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", co), + RAD_STR("dtype", "f32"), + RAD_F64("div", 3.0)), + RAD_NOWEIGHTS), + { V.avg[s + 1], V.amp[2][s + 1] }, { V.avg[s + 1] }); + if (!St.op_sum || !St.op_avg) return RAD_E_INVAL; + } + const int64_t Rn = rows[ns], cn = V.hidden >> ns; + V.wav = decl_b(b, nm.f("%s.wav", dn), RAD_F32, { Rn, V.out }); + RAD_ARCH_TRY(act(V.act, "act_out", cn, Rn, V.avg[ns], V.cu[ns], V.t1[ns])); + return conv1(V.cout, "conv_out", cn, V.out, 7, 1, false, Rn, V.t1[ns], V.cu[ns], 0, V.wav); +} + +/* The soundtrack: the latent denormalised (f32) and unpacked to an image of (time) x 16 mel bins + * of 8 channels, the audio VAE's decoder (causal along time) to a stereo log-mel spectrogram, + * channel-major [frames, 2 x 64]; the vocoder to 16 kHz; the bandwidth extender's log-mel of that, + * its vocoder, and the sinc-resampled skip, to 48 kHz. */ +static int declare_audio(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_TOKEN, gx = kGrpAudio; + const int64_t A = m.maxA, Tm = mel_frames(A); + const std::vector mult = meta_list(meta, "audio_vae.ch_mult"); + const int64_t base = rad_meta_geti(meta, "audio_vae.base_channels", 0); + const int64_t nrb = rad_meta_geti(meta, "audio_vae.num_res_blocks", 0); + if (mult.size() != 3 || nrb <= 0 || base <= 0) { + fprintf(stderr, "radiance: ltx2: the audio VAE is not three levels of residual blocks\n"); + return RAD_E_UNSUPPORTED; + } + m.aC0 = base * (int64_t)mult.back(); + m.b_aden = decl_b(b, nm.f("aud.den"), RAD_F32, { A, kAudioC }); + m.b_alat = decl_b(b, nm.f("aud.lat"), RAD_BF16, { A, kAudioC }); + m.b_aimg = decl_b(b, nm.f("aud.img"), RAD_BF16, { A * kLatMel, kLatCh }); + { + rad_weight& mw = m.w_amean; + rad_weight& sw = m.w_astd; + mw = wcopy(b, nm.f("aud.latents_mean"), nm.ckpt("audio_vae.latents_mean"), RAD_F32, { kAudioC }, + acc, gx); + sw = wcopy(b, nm.f("aud.latents_std"), nm.ckpt("audio_vae.latents_std"), RAD_F32, { kAudioC }, + acc, gx); + if (!mw || !sw) return RAD_E_INVAL; + m.op_aden = rw(b, RAD_OP(b, "chan_stats", + RAD_PARAMS(RAD_RANGE("M", 1, A), RAD_INT("n", kAudioC), + RAD_STR("mode", "denorm"), RAD_STR("dtype", "f32")), + RAD_WEIGHTS(mw, sw)), + { m.b_astate }, { m.b_aden }); + } + m.op_acast = cast_op(b, A, kAudioC, "f32", "bf16", m.b_aden, m.b_alat); + m.op_aunpack = rw(b, RAD_OP(b, "d2s3d", + RAD_PARAMS(RAD_RANGE("M", 1, A), RAD_INT("C", kLatCh), RAD_INT("st", 1), + RAD_INT("sh", 1), RAD_INT("sw", kLatMel), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_alat }, { m.b_aimg }); + /* The decoder's images (time x mel x channels), the largest the last upsample's output: + * (4 A - 2) x 64 of level 1's channels. */ + const int64_t big = std::max(4 * A * kMel * base * (int64_t)mult[1], + A * kLatMel * m.aC0 * 4); + m.b_aa = decl_b(b, nm.f("aud.a"), RAD_BF16, { big }); + m.b_ab = decl_b(b, nm.f("aud.b"), RAD_BF16, { big }); + m.b_ac = decl_b(b, nm.f("aud.c"), RAD_BF16, { big }); + m.b_as = decl_b(b, nm.f("aud.s"), RAD_BF16, { big }); + m.b_amel16 = decl_b(b, nm.f("aud.mel16"), RAD_BF16, { Tm, 2 * kMel }); + m.b_amel = decl_b(b, nm.f("aud.mel"), RAD_F32, { Tm, 2 * kMel }); + const int64_t pxmax = 4 * A * kMel; + auto conv = [&](rad_weight* w, rad_weight* bb, const char* dn, const char* src, int64_t ci, + int64_t co, int up, rad_buf in, rad_buf out, int row = -1) -> rad_op { + const char* wn = nm.f("%s.weight", dn); + const char* bn = nm.f("%s.bias", dn); + if (row >= 0) { + if (map_rows(b, wn, { { nm.ckpt("%s.conv.weight", src), row, 1 } }) < 0 || + map_rows(b, bn, { { nm.ckpt("%s.conv.bias", src), row, 1 } }) < 0) + return 0; + *w = decl_w(b, wn, RAD_BF16, { co, ci, 3, 3 }, acc, RAD_SHARD_NONE, grp_layer(gx)); + *bb = decl_w(b, bn, RAD_BF16, { co }, acc, RAD_SHARD_NONE, grp_layer(gx)); + } else { + *w = wcopy(b, wn, nm.ckpt("%s.conv.weight", src), RAD_BF16, { co, ci, 3, 3 }, acc, gx); + *bb = wcopy(b, bn, nm.ckpt("%s.conv.bias", src), RAD_BF16, { co }, acc, gx); + } + if (!*w || !*bb) return 0; + return rw(b, RAD_OP(b, "conv2d_nhwc", + RAD_PARAMS(RAD_RANGE("M", 1, pxmax), RAD_INT("cin", ci), RAD_INT("cout", co), + RAD_INT("k", 3), RAD_INT("stride", 1), RAD_STR("pad", "causal"), + RAD_INT("up", up), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(*w, *bb)), + { in }, { out }); + }; + const char* dec = "audio_vae.decoder"; + m.op_acin = conv(&m.w_acin, &m.b_acin, "aud.conv_in", nm.ckpt("%s.conv_in", dec), kLatCh, m.aC0, 1, + m.b_aimg, m.b_aa); + if (!m.op_acin) return RAD_E_INVAL; + for (int i = 0; i < 2; ++i) + RAD_ARCH_TRY(ares_declare(b, m, m.amid[i], nm.f("aud.mid.%d", i), + nm.ckpt("%s.mid.block_%d", dec, i + 1), m.aC0, m.aC0, pxmax, m.b_aa, + m.b_ab, m.b_ac, m.b_as)); + /* Levels 2, 1, 0: residual blocks, then (but after level 0) the nearest upsample, its causal + * conv, and the rows past the first back into the stream. */ + int64_t cin = m.aC0; + m.aup.resize(3); + m.aups.resize(2); + m.aups_cp.resize(2); + m.alev_c.resize(3); + for (int lev = 2; lev >= 0; --lev) { + const int64_t co = base * (int64_t)mult[(size_t)lev]; + m.alev_c[(size_t)lev] = co; + std::vector& blk = m.aup[(size_t)(2 - lev)]; + blk.resize((size_t)(nrb + 1)); + for (int64_t i = 0; i <= nrb; ++i) { + RAD_ARCH_TRY(ares_declare(b, m, blk[(size_t)i], nm.f("aud.up%d.%lld", lev, (long long)i), + nm.ckpt("%s.up.%d.block.%lld", dec, lev, (long long)i), cin, co, + pxmax, m.b_aa, m.b_ab, m.b_ac, m.b_as)); + cin = co; + } + if (lev > 0) { + VConv& U = m.aups[(size_t)(2 - lev)]; + U.op = conv(&U.w, &U.b, nm.f("aud.up%d.upsample", lev), + nm.ckpt("%s.up.%d.upsample.conv", dec, lev), + co, co, 2, m.b_aa, m.b_ab); + m.aups_cp[(size_t)(2 - lev)] = cast_op(b, pxmax, co, "bf16", "bf16", m.b_ab, m.b_aa); + if (!U.op || !m.aups_cp[(size_t)(2 - lev)]) return RAD_E_INVAL; + } + } + m.op_anout = rw(b, RAD_OP(b, "pixel_norm", + RAD_PARAMS(RAD_RANGE("M", 1, pxmax), RAD_INT("n", cin), + RAD_F64("eps", 1e-6), + RAD_STR("form", "div"), RAD_STR("act", "silu"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_aa }, { m.b_ab }); + /* conv_out one output channel at a time, each into its 64 columns of the spectrogram: the + * vocoder's channel-major layout (channel 64 + mel). */ + for (int ch = 0; ch < 2; ++ch) { + m.op_acout[ch] = conv(&m.w_acout[ch], &m.b_acout[ch], nm.f("aud.conv_out%d", ch), + nm.ckpt("%s.conv_out", dec), cin, 1, 1, m.b_ab, m.b_amel16, ch); + if (!m.op_acout[ch]) return RAD_E_INVAL; + } + m.op_amel = cast_op(b, Tm, 2 * kMel, "bf16", "f32", m.b_amel16, m.b_amel); + + /* The vocoder; the extender's log-mel of its waveform (rounded as the reference's bf16 one), + * its vocoder, the skip and the clamp into the soundtrack. */ + RAD_ARCH_TRY(voc_declare(b, meta, m, m.voc, "voc", "vocoder.vocoder", "", 1, m.b_amel)); + const int64_t Sw = Tm * kMelHop; + m.w_basis = wcopy(b, nm.f("voc.stft_basis"), nm.ckpt("vocoder.mel_stft.stft_fn.forward_basis"), + RAD_BF16, { 514, 1, 512 }, acc, kGrpVoc); + m.w_melb = wcopy(b, nm.f("voc.mel_basis"), nm.ckpt("vocoder.mel_stft.mel_basis"), RAD_BF16, + { kMel, 257 }, acc, kGrpVoc); + if (!m.w_basis || !m.w_melb) return RAD_E_INVAL; + m.b_bmel16 = decl_b(b, nm.f("bwe.mel16"), RAD_BF16, { Sw / 80, 2 * kMel }); + m.b_bmel = decl_b(b, nm.f("bwe.mel"), RAD_F32, { Sw / 80, 2 * kMel }); + m.op_stft = rw(b, RAD_OP(b, "stft_logmel", + RAD_PARAMS(RAD_RANGE("M", 1, Sw / 80), RAD_INT("hop", 80), + RAD_INT("nfft", 512), RAD_INT("n_mel", kMel), + RAD_INT("ch", 2), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_basis, m.w_melb)), + { m.voc.wav }, { m.b_bmel16 }); + m.op_bmel = cast_op(b, Sw / 80, 2 * kMel, "bf16", "f32", m.b_bmel16, m.b_bmel); + RAD_ARCH_TRY(voc_declare(b, meta, m, m.bwe, "bwe", "vocoder.bwe_generator", "bwe_", 2, m.b_bmel)); + /* The vocoders' f32 convolutions read f32 weights; a pipeline saved in bf16 holds them bf16, + * and the recipes cast them back (`voc.*` and `bwe.*`, cast dtype=f32). */ + for (const char* w : { "voc.conv_in.weight", "bwe.conv_in.weight" }) { + if (weight_codes_dtype(b, w, RAD_F32) != RAD_F32) { + fprintf(stderr, "radiance: ltx2: '%s' is stored %s; the vocoders run in f32 -- convert " + "with data/recipes/ltx-2.5-bf16.recipe or ltx-2.5-fp8.recipe, which " + "cast them\n", w, rad_dtype_name(weight_codes_dtype(b, w, RAD_F32))); + return RAD_E_UNSUPPORTED; + } + } + m.b_audio = decl_b(b, nm.f("audio_out"), RAD_F32, { A * ((int64_t)kRate / kAudioRate), kAudioCh }, + RAD_BUF_PERSIST); + m.op_bwe = rw(b, RAD_OP(b, "bwe_up", + RAD_PARAMS(RAD_RANGE("M", 1, 3 * Sw), RAD_INT("ratio", 3), RAD_INT("ch", 2), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.voc.wav, m.bwe.wav }, { m.b_audio }); + /* The samples past the decoder's (its causal frames are 3 short of 4 a latent): silence. */ + m.op_tail = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 3 * kMelHop * 3), RAD_INT("n", kAudioCh), + RAD_STR("dtype", "f32"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_audio }); + return m.op_aden && m.op_acast && m.op_aunpack && m.op_anout && m.op_amel && m.op_stft && + m.op_bmel && m.op_bwe && m.op_tail + ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== the latent upsampler */ +/* LTX2LatentUpsamplerModel (spatial x2, no rational resampler): the clean small latent + * denormalised (f32, then bf16), initial_conv, GroupNorm and SiLU, residual blocks, each frame's + * Conv2d to four times the channels and the pixel shuffle, residual blocks at the full size, + * final_conv; normalised again (bf16) into the lane. */ +static int declare_ups(RadBuilder* b, const RadModelMeta* meta, Model& m) { + if (!rad_meta_gets(meta, "latent_upsampler._class_name", nullptr)) return RAD_OK; + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_TOKEN, gx = kGrpUps; + const int64_t C = rad_meta_geti(meta, "latent_upsampler.mid_channels", 0); + const int64_t nb = rad_meta_geti(meta, "latent_upsampler.num_blocks_per_stage", 0); + if (std::strcmp(rad_meta_gets(meta, "latent_upsampler._class_name", ""), + "LTX2LatentUpsamplerModel") || + rad_meta_geti(meta, "latent_upsampler.in_channels", 0) != kC || + rad_meta_geti(meta, "latent_upsampler.dims", 0) != 3 || + rad_meta_geti(meta, "latent_upsampler.spatial_upsample", 0) != 1 || + rad_meta_geti(meta, "latent_upsampler.temporal_upsample", 1) != 0 || + rad_meta_geti(meta, "latent_upsampler.use_rational_resampler", 1) != 0 || C <= 0 || C % 32 || + nb <= 0) { + fprintf(stderr, "radiance: ltx2: latent_upsampler/ is not the spatial x2 upsampler this plugin " + "runs (3D, no rational resampler, GroupNorm over 32 groups)\n"); + return RAD_E_UNSUPPORTED; + } + m.ups = true; + m.uC = C; + /* the full size's voxels; the small size's are a quarter */ + const int64_t V = m.maxS; + auto wt = [&](const char* name, std::initializer_list shape) { + return wcopy(b, nm.f("ups.%s", name), nm.ckpt("latent_upsampler.%s", name), RAD_BF16, shape, acc, + gx); + }; + auto conv = [&](rad_weight w, rad_weight bb, int64_t ci, int64_t co, int64_t rows, rad_buf x, + rad_buf y) -> rad_op { + if (!w || !bb) return 0; + return rw(b, RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", ci), RAD_INT("cout", co), + RAD_INT("k", 3), RAD_INT("kt", 3), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bb)), + { x }, { y }); + }; + m.b_ust = decl_b(b, nm.f("ups.gn_stats"), RAD_F32, { 32 * (2 + 3 * 1024) }); + auto gnorm = [&](rad_weight w, rad_weight bb, bool silu, int64_t rows, rad_buf x, + rad_buf y) -> rad_op { + if (!w || !bb) return 0; + return rw(b, RAD_OP(b, "group_norm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", C), RAD_INT("groups", 32), + RAD_F64("eps", 1e-5), RAD_STR("act", silu ? "silu" : "none"), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bb)), + { x, m.b_ust }, { y, m.b_ust }); + }; + m.b_uin = decl_b(b, nm.f("ups.in"), RAD_BF16, { V, kC }); + m.b_ua = decl_b(b, nm.f("ups.a"), RAD_BF16, { V, C }); + m.b_ub = decl_b(b, nm.f("ups.b"), RAD_BF16, { V, C }); + m.b_uc = decl_b(b, nm.f("ups.c"), RAD_BF16, { V, C }); + m.b_uout = decl_b(b, nm.f("ups.out"), RAD_BF16, { V, kC }); + m.b_uden = decl_b(b, nm.f("ups.den"), RAD_F32, { V, kC }); + m.op_uden = rw(b, RAD_OP(b, "chan_stats", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("n", kC), + RAD_STR("mode", "denorm"), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(m.vd_mean, m.vd_std)), + { m.b_vstate }, { m.b_uden }); + m.op_ucast = cast_op(b, V, kC, "f32", "bf16", m.b_uden, m.b_uin); + m.u_cinw = wt("initial_conv.weight", { C, kC, 3, 3, 3 }); + m.u_cinb = wt("initial_conv.bias", { C }); + m.u_ninw = wt("initial_norm.weight", { C }); + m.u_ninb = wt("initial_norm.bias", { C }); + m.op_ucin = conv(m.u_cinw, m.u_cinb, kC, C, V, m.b_uin, m.b_ua); + m.op_unin = gnorm(m.u_ninw, m.u_ninb, true, V, m.b_ua, m.b_ua); + auto blocks = [&](const char* side, std::vector& list) { + list.resize((size_t)nb); + for (int64_t i = 0; i < nb; ++i) { + URes& U = list[(size_t)i]; + const char* p = nm.f("%s.%lld", side, (long long)i); + U.c1w = wt(nm.f("%s.conv1.weight", p), { C, C, 3, 3, 3 }); + U.c1b = wt(nm.f("%s.conv1.bias", p), { C }); + U.n1w = wt(nm.f("%s.norm1.weight", p), { C }); + U.n1b = wt(nm.f("%s.norm1.bias", p), { C }); + U.c2w = wt(nm.f("%s.conv2.weight", p), { C, C, 3, 3, 3 }); + U.c2b = wt(nm.f("%s.conv2.bias", p), { C }); + U.n2w = wt(nm.f("%s.norm2.weight", p), { C }); + U.n2b = wt(nm.f("%s.norm2.bias", p), { C }); + U.op_c1 = conv(U.c1w, U.c1b, C, C, V, m.b_ua, m.b_ub); + U.op_n1 = gnorm(U.n1w, U.n1b, true, V, m.b_ub, m.b_ub); + U.op_c2 = conv(U.c2w, U.c2b, C, C, V, m.b_ub, m.b_uc); + U.op_n2 = gnorm(U.n2w, U.n2b, false, V, m.b_uc, m.b_uc); + U.op_add = add_op(b, V, C, "bf16", m.b_uc, m.b_ua, m.b_ua); + U.op_act = unary(b, "silu", V, C, "bf16", m.b_ua, m.b_ua); + if (!U.op_c1 || !U.op_n1 || !U.op_c2 || !U.op_n2 || !U.op_add || !U.op_act) + return RAD_E_INVAL; + } + return RAD_OK; + }; + RAD_ARCH_TRY(blocks("res_blocks", m.u_pre)); + m.u_upw = wt("upsampler.0.weight", { 4 * C, C, 3, 3 }); + m.u_upb = wt("upsampler.0.bias", { 4 * C }); + if (!m.u_upw || !m.u_upb) return RAD_E_INVAL; + /* Each frame through Conv2d (issued a frame at a time), then the pixel shuffle over the volume + * (channel c 4 + 2 i_h + i_w to (2 h + i_h, 2 w + i_w)). */ + m.op_uup = rw(b, RAD_OP(b, "conv2d_nhwc", + RAD_PARAMS(RAD_RANGE("M", 1, V / 4), RAD_INT("cin", C), + RAD_INT("cout", 4 * C), + RAD_INT("k", 3), RAD_INT("stride", 1), RAD_STR("pad", "same"), + RAD_INT("up", 1), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.u_upw, m.u_upb)), + { m.b_ua }, { m.b_ub }); + m.op_ud2s = rw(b, RAD_OP(b, "d2s3d", + RAD_PARAMS(RAD_RANGE("M", 1, V / 4), RAD_INT("C", C), RAD_INT("st", 1), + RAD_INT("sh", 2), RAD_INT("sw", 2), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ub }, { m.b_ua }); + RAD_ARCH_TRY(blocks("post_upsample_res_blocks", m.u_post)); + m.u_coutw = wt("final_conv.weight", { kC, C, 3, 3, 3 }); + m.u_coutb = wt("final_conv.bias", { kC }); + m.op_ucout = conv(m.u_coutw, m.u_coutb, C, kC, V, m.b_ua, m.b_uout); + m.op_unorm = rw(b, RAD_OP(b, "chan_stats", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("n", kC), RAD_STR("mode", "norm"), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.vd_mean, m.vd_std)), + { m.b_uout }, { m.b_uout }); + m.op_uf32 = cast_op(b, V, kC, "bf16", "f32", m.b_uout, m.b_vstate); + /* With a first frame, its upscaled latent frame is the new clean one: kept aside before the + * re-noise and put back after. */ + m.op_ufirst = cast_op(b, m.maxPpf, kC, "f32", "f32", m.b_vstate, m.b_first); + m.op_ukeep = cast_op(b, m.maxPpf, kC, "f32", "f32", m.b_first, m.b_vstate); + auto renoise = [&](int64_t rows, rad_buf x) { + return rw(b, RAD_OP(b, "flow_renoise", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", kC), RAD_INT("stream", 1), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { x }, { x }); + }; + m.op_urnv = renoise(V, m.b_vstate); + m.op_urna = renoise(m.maxA, m.b_astate); + return m.op_uden && m.op_ucast && m.op_ucin && m.op_unin && m.op_uup && m.op_ud2s && m.op_ucout && + m.op_unorm && m.op_uf32 && m.op_ufirst && m.op_ukeep && m.op_urnv && m.op_urna + ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== the duration head */ +/* LTX2DurationHead: each connector's output for the prompt (not the negative) projected to the + * pooler's width with its modality's embedding added, the two runs concatenated, one learned query + * attending over them (four heads, no mask), the pooled row through a tanh-GELU MLP to the log of + * the length in seconds, which the core reads back (RadVideoGenDecl::duration_out). */ +static int declare_dur(RadBuilder* b, const RadModelMeta* meta, Model& m) { + if (!rad_meta_gets(meta, "duration_head._class_name", nullptr)) return RAD_OK; + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_TOKEN, gx = kGrpDur; + const int64_t P = rad_meta_geti(meta, "duration_head.pooler_hidden_dim", 0); + const int64_t Hm = rad_meta_geti(meta, "duration_head.mlp_hidden_dim", 0); + const int64_t nh = rad_meta_geti(meta, "duration_head.num_pooler_heads", 0); + if (std::strcmp(rad_meta_gets(meta, "duration_head._class_name", ""), "LTX2DurationHead") || + rad_meta_geti(meta, "duration_head.video_cross_attention_dim", 0) != m.cv.D || + rad_meta_geti(meta, "duration_head.audio_cross_attention_dim", 0) != m.ca.D || + rad_meta_geti(meta, "duration_head.num_queries", 0) != 1 || P <= 0 || Hm <= 0 || + nh <= 0 || P % nh || P / nh != 64 || P > std::max(m.cv.D, m.ca.D)) { + fprintf(stderr, "radiance: ltx2: duration_head/ is not the LTX2DurationHead this plugin " + "runs (the connectors' widths in, one query, heads of 64)\n"); + return RAD_E_UNSUPPORTED; + } + m.dur = true; + m.dP = P; + const int64_t R = kTextRows; + auto wt = [&](const char* name, std::initializer_list shape) { + return wcopy(b, nm.f("dur.%s", name), nm.ckpt("duration_head.%s", name), RAD_BF16, shape, + acc, gx); + }; + m.dw_vp = wt("video_input_proj.weight", { P, m.cv.D }); + m.dw_vpb = wt("video_input_proj.bias", { P }); + m.dw_vemb = wt("video_modality_emb", { 1, P }); + m.dw_ap = wt("audio_input_proj.weight", { P, m.ca.D }); + m.dw_apb = wt("audio_input_proj.bias", { P }); + m.dw_aemb = wt("audio_modality_emb", { 1, P }); + m.dw_qt = wt("attention_pooler.query_tokens", { 1, P }); + m.dw_q = wt("attention_pooler.to_q.weight", { P, P }); + m.dw_qb = wt("attention_pooler.to_q.bias", { P }); + m.dw_k = wt("attention_pooler.to_k.weight", { P, P }); + m.dw_kb = wt("attention_pooler.to_k.bias", { P }); + m.dw_v = wt("attention_pooler.to_v.weight", { P, P }); + m.dw_vb = wt("attention_pooler.to_v.bias", { P }); + m.dw_o = wt("attention_pooler.to_out.weight", { P, P }); + m.dw_ob = wt("attention_pooler.to_out.bias", { P }); + m.dw_h = wt("mlp_hidden.weight", { Hm, P }); + m.dw_hb = wt("mlp_hidden.bias", { Hm }); + m.dw_out = wt("mlp_out.weight", { 1, Hm }); + m.dw_outb = wt("mlp_out.bias", { 1 }); + m.b_dtok = decl_b(b, nm.f("dur.tok"), RAD_BF16, { 2 * R, P }); + m.b_dk = decl_b(b, nm.f("dur.k"), RAD_BF16, { 2 * R, P }); + m.b_dv = decl_b(b, nm.f("dur.v"), RAD_BF16, { 2 * R, P }); + m.b_dq0 = decl_b(b, nm.f("dur.query"), RAD_BF16, { 1, P }); + m.b_dq = decl_b(b, nm.f("dur.q"), RAD_BF16, { 1, P }); + m.b_dat = decl_b(b, nm.f("dur.attn"), RAD_BF16, { 1, P }); + m.b_do = decl_b(b, nm.f("dur.pooled"), RAD_BF16, { 1, P }); + m.b_dh = decl_b(b, nm.f("dur.hidden"), RAD_BF16, { 1, Hm }); + m.b_dl = decl_b(b, nm.f("dur.log"), RAD_BF16, { 1, 1 }); + m.b_dcu = decl_b(b, nm.f("dur.cu"), RAD_I32, { 2 }); + m.b_dcuk = decl_b(b, nm.f("dur.cu_k"), RAD_I32, { 2 }); + m.b_dur = decl_b(b, nm.f("dur.out"), RAD_F32, { 1 }, RAD_BUF_PERSIST); + auto gemm = [&](rad_weight w, rad_weight bb, int64_t rows, int64_t N, int64_t K, rad_buf x, + rad_buf y, const char* act) -> rad_op { + if (!w || !bb || !x || !y) return 0; + return rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16"), RAD_STR("act", act)), + RAD_WEIGHTS(w, bb)), + { x }, { y }); + }; + auto emb = [&](rad_weight w, int64_t rows, rad_buf x, rad_buf y) -> rad_op { + if (!w) return 0; + return rw(b, RAD_OP(b, "table_add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", P), RAD_INT("L", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { x }, { y }); + }; + auto iota = [&](int64_t step, rad_buf y) { + return rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("start", 0), + RAD_INT("step", step)), + RAD_NOWEIGHTS), + {}, { y }); + }; + m.op_dvp = gemm(m.dw_vp, m.dw_vpb, R, P, m.cv.D, m.cv.b_text, m.b_dtok, "none"); + m.op_dap = gemm(m.dw_ap, m.dw_apb, R, P, m.ca.D, m.ca.b_text, m.b_dtok, "none"); + m.op_dvemb = emb(m.dw_vemb, R, m.b_dtok, m.b_dtok); + m.op_daemb = emb(m.dw_aemb, R, m.b_dtok, m.b_dtok); + m.op_dq0 = emb(m.dw_qt, 1, m.b_zero, m.b_dq0); + m.op_dq = gemm(m.dw_q, m.dw_qb, 1, P, P, m.b_dq0, m.b_dq, "none"); + m.op_dk = gemm(m.dw_k, m.dw_kb, 2 * R, P, P, m.b_dtok, m.b_dk, "none"); + m.op_dv = gemm(m.dw_v, m.dw_vb, 2 * R, P, P, m.b_dtok, m.b_dv, "none"); + m.op_dcu = iota(1, m.b_dcu); + m.op_dcuk = iota(2 * R, m.b_dcuk); + m.op_dattn = rw(b, RAD_OP(b, "attn_cross", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("head_dim", P / nh), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_dq, m.b_dk, m.b_dv, m.b_dcu, m.b_dcuk }, { m.b_dat }); + m.op_do = gemm(m.dw_o, m.dw_ob, 1, P, P, m.b_dat, m.b_do, "none"); + m.op_dh = gemm(m.dw_h, m.dw_hb, 1, Hm, P, m.b_do, m.b_dh, "gelu_tanh"); + m.op_dout = gemm(m.dw_out, m.dw_outb, 1, 1, Hm, m.b_dh, m.b_dl, "none"); + m.op_dlog = cast_op(b, 1, 1, "bf16", "f32", m.b_dl, m.b_dur); + return m.op_dvp && m.op_dap && m.op_dvemb && m.op_daemb && m.op_dq0 && m.op_dq && m.op_dk && + m.op_dv && m.op_dcu && m.op_dcuk && m.op_dattn && m.op_do && m.op_dh && + m.op_dout && m.op_dlog + ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== the diffusion decoder */ +/* LTX2VideoDiffusionDecoder3d (LTX-2.5's diffusion_decoder/; diffusers' ltx2_diffusion_decoder.py), + * run as the README's diffusion decode runs it, its tiling on (enable_tiling). The latent, its last + * frame repeated twice past its end (the ghost frames NATTEN's inward-shifted border needs), goes + * through four deterministic stages of neighbourhood-attention blocks (pre-norm, a 3-D rotary over + * the voxel coordinates, a SwiGLU feed-forward), each followed by a pixel-shuffle upsample; the + * first three over the whole video into the feature volume. That volume is cut as _tile_intervals + * cuts it (768 pixels every 704, 80 frames every 56: on the feature grid 96 cells every 88 and 40 + * every 28, 6 at least), and each tile runs the fourth stage (the tile starting the video drops + * the upsample's duplicate leading frame; the one ending it its ghost frames) and one denoising + * step from noise -- x0 predicted at timestep 1 -- over 4 x 4 pixel patches: eight diffusion blocks + * conditioned on the fourth stage's output, their norms modulated by the timestep's shared table + * plus each block's own. The tiles' pixels go to the tile store and blend as tile_stitch does. */ +enum { kDdTile = 96, kDdStride = 88, kDdTileT = 40, kDdStrideT = 28, kDdLeast = 6, kDdGhost = 2, + kDdGhostCells = 8, kDdMaxTiles = 16 }; +/* A feed-forward launch's hidden rows: gate and up at most this many elements. */ +static const int64_t kDdFfElems = 64ll << 20; + +/* The decoder's cut of an axis (tile_grid's `intervals` rule) and the tiles of a feature grid. */ +struct DdTile { int64_t t, t0, h, w; bool origin, trailing; }; +static int64_t dd_count(int64_t L, int64_t tile, int64_t stride) { + if (L <= tile) return 1; + int64_t n = (L + stride - 1) / stride; + while (n > 1 && L - (n - 1) * stride < kDdLeast) --n; + return n; +} +static int64_t dd_len(int64_t L, int64_t k, int64_t tile, int64_t stride) { + return k == dd_count(L, tile, stride) - 1 ? L - k * stride : std::min(tile, L - k * stride); +} +static std::vector dd_tiles(int64_t T, int64_t H, int64_t W) { + std::vector v; + const int64_t nt = dd_count(T, kDdTileT, kDdStrideT), ni = dd_count(H, kDdTile, kDdStride); + const int64_t nj = dd_count(W, kDdTile, kDdStride); + for (int64_t kt = 0; kt < nt; ++kt) + for (int64_t i = 0; i < ni; ++i) + for (int64_t j = 0; j < nj; ++j) + v.push_back({ dd_len(T, kt, kDdTileT, kDdStrideT) + (kt == nt - 1 ? kDdGhostCells : 0), + kt * kDdStrideT, dd_len(H, i, kDdTile, kDdStride), + dd_len(W, j, kDdTile, kDdStride), kt == 0, kt == nt - 1 }); + return v; +} + +static rad_op dd_gemm(RadBuilder* b, rad_weight w, rad_weight bb, int64_t rows, int64_t N, int64_t K, + std::initializer_list rd, rad_buf y) { + if (!w) return 0; + rad_op op = bb ? RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bb)) + : RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + return rw(b, op, rd, { y }); +} + +/* One block's weights and ops over at most V voxels of residual `x`. */ +static int dd_block_declare(RadBuilder* b, Model& m, DdBlock& B, const char* dn, const char* src, + int64_t C, int slot, const int64_t* kernel, int64_t V, bool diff, rad_buf x) { + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_REQUEST, gx = kGrpDdec; + B.C = C; + B.ff = (C * 4 + 15) / 16 * 16; + B.kt = kernel[0]; + B.kh = kernel[1]; + B.kw = kernel[2]; + B.slot = slot; + B.chunk = std::min(V, kDdFfElems / (2 * B.ff)); + auto wt = [&](const char* name, std::initializer_list shape) { + return wcopy(b, nm.f("%s.%s", dn, name), nm.ckpt("%s.%s", src, name), RAD_BF16, shape, acc, gx); + }; + B.w_n1 = wt("norm1.weight", { C }); + /* The diffusion stage's q|k|v of every voxel would be three times its residual (3.7 GiB at the + * largest tile), so it projects and attends a head at a time into b_dao; the others take + * every head at once. */ + const int64_t gw = diff ? 64 : C; + for (int64_t g = 0; g < C / gw; ++g) { + const char* wn = nm.f("%s.attn.qkv%lld.weight", dn, (long long)g); + const char* bn = nm.f("%s.attn.qkv%lld.bias", dn, (long long)g); + RadNameMap mw = map_base(wn, RAD_MAP_ROWS), mb = map_base(bn, RAD_MAP_ROWS); + for (const char* pr : { "to_q", "to_k", "to_v" }) { + mw.src[mw.n_src] = nm.ckpt("%s.attn.%s.weight", src, pr); + mw.src_index[mw.n_src] = (int)(g * gw); + mw.src_rows[mw.n_src++] = gw; + mb.src[mb.n_src] = nm.ckpt("%s.attn.%s.bias", src, pr); + mb.src_index[mb.n_src] = (int)(g * gw); + mb.src_rows[mb.n_src++] = gw; + } + RAD_ARCH_TRY(rad_decl_name_map(b, &mw)); + RAD_ARCH_TRY(rad_decl_name_map(b, &mb)); + B.w_qkvh.push_back(decl_w(b, wn, RAD_BF16, { 3 * gw, C }, acc, RAD_SHARD_NONE, grp_layer(gx))); + B.b_qkvh.push_back(decl_w(b, bn, RAD_BF16, { 3 * gw }, acc, RAD_SHARD_NONE, grp_layer(gx))); + if (!B.w_qkvh.back() || !B.b_qkvh.back()) return RAD_E_INVAL; + } + B.w_nq = wt("attn.norm_q.weight", { 64 }); + B.w_nk = wt("attn.norm_k.weight", { 64 }); + B.w_o = wt("attn.to_out.0.weight", { C, C }); + B.b_o = wt("attn.to_out.0.bias", { C }); + B.w_n2 = wt("norm2.weight", { C }); + /* gate and up as one weight: one gemm writes whole rows of the gate|up buffer */ + const char* gun = nm.f("%s.mlp.w_gate_up.weight", dn); + RAD_ARCH_TRY(map_concat(b, gun, { nm.ckpt("%s.mlp.w_gate.weight", src), + nm.ckpt("%s.mlp.w_up.weight", src) })); + B.w_gu = decl_w(b, gun, RAD_BF16, { 2 * B.ff, C }, acc, RAD_SHARD_NONE, grp_layer(gx)); + B.w_down = wt("mlp.w_down.weight", { C, B.ff }); + if (!B.w_n1 || !B.w_nq || !B.w_nk || !B.w_o || !B.b_o || !B.w_n2 || !B.w_gu || !B.w_down) + return RAD_E_INVAL; + const rad_buf qkv = m.b_dqkv[slot], gu = m.b_dg[slot]; + auto modded = [&](rad_weight w) { + const rad_op op = RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("n", C), RAD_F64("eps", 1e-6), + RAD_INT("gated", 0), RAD_STR("dtype", "bf16"), + RAD_INT("norm_once", 1)), + RAD_WEIGHTS(w)); + if (!op) return (rad_op)0; + const rad_buf rd[3] = { m.b_dbmod, x, m.b_ddcu }; + const rad_buf wr[2] = { x, m.b_dn }; + rad_op_reads(b, op, rd, 3); + rad_op_writes(b, op, wr, 2); + return op; + }; + if (diff) { + B.w_ctx = wt("context_proj.weight", { C, C }); + B.b_ctx = wt("context_proj.bias", { C }); + /* The block's table rows (shift, scale) of the attention's norm, then of the MLP's: the + * reference's chunks 1, 0, 4 and 3, the order rms_mod reads them in. */ + const char* tn = nm.f("%s.mod_table", dn); + RadNameMap mp = map_base(tn, RAD_MAP_ROWS); + for (int r : { 1, 0, 4, 3 }) { + mp.src[mp.n_src] = nm.ckpt("%s.scale_shift_table", src); + mp.src_index[mp.n_src] = r; + mp.src_rows[mp.n_src++] = 1; + } + RAD_ARCH_TRY(rad_decl_name_map(b, &mp)); + B.w_sst = decl_w(b, tn, RAD_BF16, { 1, 4 * C }, acc, RAD_SHARD_NONE, grp_layer(gx)); + if (!B.w_ctx || !B.b_ctx || !B.w_sst) return RAD_E_INVAL; + B.op_ctx = dd_gemm(b, B.w_ctx, B.b_ctx, V, C, C, { m.b_dctx, x }, x); + B.op_mod = rw(b, RAD_OP(b, "table_add", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 4 * C), RAD_INT("L", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(B.w_sst)), + { m.b_dmod }, { m.b_dbmod }); + B.op_n1 = modded(B.w_n1); + B.op_n2 = modded(B.w_n2); + if (!B.op_ctx || !B.op_mod) return RAD_E_INVAL; + } else { + B.op_n1 = rms_op(b, V, C, 1e-6, B.w_n1, x, m.b_dn); + B.op_n2 = rms_op(b, V, C, 1e-6, B.w_n2, x, m.b_dn); + } + const int64_t nh = gw / 64; + const rad_buf ao = diff ? m.b_dao : m.b_dn; + for (size_t g = 0; g < B.w_qkvh.size(); ++g) { + B.op_qkvh.push_back(dd_gemm(b, B.w_qkvh[g], B.b_qkvh[g], V, 3 * gw, C, { m.b_dn }, qkv)); + if (!B.op_qkvh.back()) return RAD_E_INVAL; + } + B.op_rope = RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("head_dim", 64), + RAD_INT("n_head", nh), RAD_INT("n_head_kv", nh), + RAD_F64("theta", 10000.0), RAD_F64("eps", 1e-6), + RAD_STR("mode", "gptj_blocks"), RAD_INT("rotary_dim", 64), + RAD_STR("sections", "8 12 12")), + RAD_WEIGHTS(B.w_nq, B.w_nk)); + if (B.op_rope) { + const rad_buf rd[2] = { qkv, m.b_dpos }; + rad_op_reads(b, B.op_rope, rd, 2); + rad_op_writes(b, B.op_rope, &qkv, 1); + } + B.op_attn = rw(b, RAD_OP(b, "attn_na3d", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("head_dim", 64), + RAD_INT("kt", B.kt), RAD_INT("kh", B.kh), RAD_INT("kw", B.kw), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { qkv }, { ao }); + B.op_o = dd_gemm(b, B.w_o, B.b_o, V, C, C, { ao, x }, x); + B.op_gu = dd_gemm(b, B.w_gu, 0, B.chunk, 2 * B.ff, C, { m.b_dn }, gu); + B.op_act = rw(b, RAD_OP(b, "silu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, B.chunk), RAD_INT("n", B.ff), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { gu }, { m.b_da }); + B.op_down = dd_gemm(b, B.w_down, 0, B.chunk, C, B.ff, { m.b_da }, m.b_dmo); + B.op_add2 = add_op(b, B.chunk, C, "bf16", x, m.b_dmo, x); + return B.op_n1 && B.op_n2 && B.op_rope && B.op_attn && B.op_o && B.op_gu && B.op_act && + B.op_down && B.op_add2 + ? RAD_OK + : RAD_E_INVAL; +} + +static int declare_ddec(RadBuilder* b, const RadModelMeta* meta, Model& m) { + if (!rad_meta_gets(meta, "diffusion_decoder._class_name", nullptr)) return RAD_OK; + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_REQUEST, gx = kGrpDdec; + auto list = [&](const char* k) { return meta_list(meta, nm.f("diffusion_decoder.%s", k)); }; + const std::vector ch = list("decoder_stage_channels"), dep = list("decoder_stage_depths"); + const std::vector ker = list("decoder_stage_kernels"), str = list("decoder_upsample_strides"); + const std::vector red = list("decoder_upsample_channel_reductions"); + const std::vector k5 = list("decoder_stage5_kernel"); + const std::vector want_ch = { 2048, 1024, 512, 512, 256 }, want_dep = { 4, 6, 4, 2, 8 }; + const std::vector want_str = { 1, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2 }; + if (std::strcmp(rad_meta_gets(meta, "diffusion_decoder._class_name", ""), + "LTX2VideoDiffusionDecoderModel") || + rad_meta_geti(meta, "diffusion_decoder.decoder_head_dim", 0) != 64 || + rad_meta_geti(meta, "diffusion_decoder.latent_channels", 0) != kC || + rad_meta_geti(meta, "diffusion_decoder.patch_size", 0) != kPix || + rad_meta_geti(meta, "diffusion_decoder.out_channels", 0) != 3 || + rad_meta_geti(meta, "diffusion_decoder.decoder_t_emb_dim", 0) != 384 || + rad_meta_geti(meta, "diffusion_decoder.decoder_num_inference_steps", 0) != 1 || + std::strcmp(rad_meta_gets(meta, "diffusion_decoder.decoder_model_output_type", ""), "x0") || + rad_meta_getf(meta, "diffusion_decoder.decoder_timestep_scale_multiplier", 0.0) != 1000.0 || + ch != want_ch || dep != want_dep || str != want_str || ker.size() != 12 || k5.size() != 3 || + red != std::vector({ 2, 2, 1, 2 })) { + fprintf(stderr, "radiance: ltx2: diffusion_decoder/ is not the LTX-2.5 diffusion decoder this " + "plugin runs (stages 2048..256 of depths 4 6 4 2 8, one x0 step, heads of " + "64)\n"); + return RAD_E_UNSUPPORTED; + } + m.ddec = true; + /* The largest volumes: the default canvas's latents a frame (the decoder's own limit), the + * longest video, the feature grid four times finer, a tile's cells and the diffusion stage's + * voxels (two a cell a side, ghost frames included in the fourth stage's output). */ + const int64_t F = max_lat_frames(), A = kVaeLat, T0 = F + kDdGhost; + m.dV0 = T0 * A; + m.dV1 = 4 * m.dV0; + m.dV2 = (2 * T0 - 1) * 4 * A; + m.dV3 = (4 * T0 - 3) * 16 * A; + const int64_t cells = std::min((int64_t)kDdTile * kDdTile, 16 * A); + m.dV4 = ((int64_t)kDdTileT + kDdGhostCells) * cells; + const int64_t ctx_rows = 2 * ((int64_t)kDdTileT + kDdGhostCells) * 4 * cells; + m.dV5 = 2 * (int64_t)kDdTileT * 4 * cells; + m.dTiles = kDdMaxTiles; + const int64_t maxV = std::max({ m.dV0, m.dV1, m.dV2, m.dV4, m.dV5 }); + m.b_dz = decl_b(b, nm.f("ddec.lat"), RAD_BF16, { m.dV0, kC }); + m.b_dx = decl_b(b, nm.f("ddec.x"), RAD_BF16, { std::max({ m.dV0 * 2048, m.dV1 * 1024, m.dV2 * 512 }) }); + m.b_dfeat = decl_b(b, nm.f("ddec.features"), RAD_BF16, { m.dV3 * 512 }); + m.b_d4 = decl_b(b, nm.f("ddec.x4"), RAD_BF16, { m.dV4 * 512 }); + m.b_ddh = decl_b(b, nm.f("ddec.h"), RAD_BF16, { m.dV5 * 256 }); + m.b_dctx = decl_b(b, nm.f("ddec.ctx"), RAD_BF16, { ctx_rows * 256 }); + m.b_dn = decl_b(b, nm.f("ddec.n"), RAD_BF16, + { std::max({ m.dV0 * 2048, m.dV1 * 1024, m.dV2 * 512, m.dV4 * 512, m.dV5 * 256 }) }); + const int64_t widths[4] = { 2048, 1024, 512, 256 }; + const int64_t qrows[4] = { m.dV0, m.dV1, std::max(m.dV2, m.dV4), m.dV5 }; + for (int s = 0; s < 4; ++s) { + /* A width's q|k|v rows, which its stage's upsample also takes as scratch; the diffusion + * stage's holds one head's. */ + int64_t rows = qrows[s]; + if (s == 2) rows = std::max({ rows, (m.dV2 * 4096 + 1535) / 1536, (m.dV4 * 2048 + 1535) / 1536 }); + m.b_dqkv[s] = decl_b(b, nm.f("ddec.qkv%lld", (long long)widths[s]), RAD_BF16, + { rows, s == 3 ? 192 : 3 * widths[s] }); + m.b_dg[s] = decl_b(b, nm.f("ddec.gu%lld", (long long)widths[s]), RAD_BF16, + { kDdFfElems / (8 * widths[s]), 8 * widths[s] }); + } + m.b_dao = decl_b(b, nm.f("ddec.attn"), RAD_BF16, { m.dV5, 256 }); + m.b_da = decl_b(b, nm.f("ddec.act"), RAD_BF16, { kDdFfElems / 2 }); + m.b_dmo = decl_b(b, nm.f("ddec.ffo"), RAD_BF16, { std::max(kDdFfElems / 8, 1) }); + m.b_dpos = decl_b(b, nm.f("ddec.pos"), RAD_I32, { 3, maxV }); + m.b_dxt = decl_b(b, nm.f("ddec.noise"), RAD_F32, { m.dV5, (int64_t)kPixC }); + m.b_dxb = decl_b(b, nm.f("ddec.noise16"), RAD_BF16, { m.dV5, (int64_t)kPixC }); + m.b_dtin = decl_b(b, nm.f("ddec.t"), RAD_F32, { 1 }); + m.b_dtsin = decl_b(b, nm.f("ddec.tsin"), RAD_BF16, { 1, 256 }); + m.b_dth = decl_b(b, nm.f("ddec.th"), RAD_BF16, { 1, 384 }); + m.b_dths = decl_b(b, nm.f("ddec.ths"), RAD_BF16, { 1, 384 }); + m.b_dtemb = decl_b(b, nm.f("ddec.temb"), RAD_BF16, { 1, 384 }); + m.b_dtes = decl_b(b, nm.f("ddec.tes"), RAD_BF16, { 1, 384 }); + m.b_dmod = decl_b(b, nm.f("ddec.mod"), RAD_BF16, { 1, 1024 }, RAD_BUF_PERSIST); + m.b_dbmod = decl_b(b, nm.f("ddec.block_mod"), RAD_BF16, { 1, 1024 }); + m.b_ddcu = decl_b(b, nm.f("ddec.cu"), RAD_I32, { 2 }, RAD_BUF_PERSIST); + m.b_dsig = decl_b(b, nm.f("ddec.sigma"), RAD_F32, { 1 }, RAD_BUF_PERSIST); + m.b_dtg = decl_b(b, nm.f("ddec.tile_geom"), RAD_I32, { 3 }, RAD_BUF_PERSIST); + m.b_dgrid = decl_b(b, nm.f("ddec.grid"), RAD_I32, { (int64_t)kDdMaxTiles, 8 }, RAD_BUF_PERSIST); + m.b_dg5 = decl_b(b, nm.f("ddec.geom5"), RAD_I32, { 3 }, RAD_BUF_PERSIST); + auto wt = [&](const char* name, std::initializer_list shape) { + return wcopy(b, nm.f("ddec.%s", name), nm.ckpt("diffusion_decoder.decoder.%s", name), RAD_BF16, + shape, acc, gx); + }; + m.dw_cin = wt("conv_in.weight", { 2048, kC }); + m.db_cin = wt("conv_in.bias", { 2048 }); + m.dw_t1 = wt("t_embedder.timestep_embedder.linear_1.weight", { 384, 256 }); + m.db_t1 = wt("t_embedder.timestep_embedder.linear_1.bias", { 384 }); + m.dw_t2 = wt("t_embedder.timestep_embedder.linear_2.weight", { 384, 384 }); + m.db_t2 = wt("t_embedder.timestep_embedder.linear_2.bias", { 384 }); + { + /* The shared table's chunks 1, 0, 4 and 3 (rms_mod's shift then scale, the attention's then + * the MLP's); the context gate and the residual gates are not read. */ + const char* wn = nm.f("ddec.adaln.weight"); + const char* bn = nm.f("ddec.adaln.bias"); + RadNameMap mw = map_base(wn, RAD_MAP_ROWS), mb = map_base(bn, RAD_MAP_ROWS); + for (int p : { 1, 0, 4, 3 }) { + mw.src[mw.n_src] = nm.ckpt("diffusion_decoder.decoder.shared_adaln.proj.weight"); + mw.src_index[mw.n_src] = p * 256; + mw.src_rows[mw.n_src++] = 256; + mb.src[mb.n_src] = nm.ckpt("diffusion_decoder.decoder.shared_adaln.proj.bias"); + mb.src_index[mb.n_src] = p * 256; + mb.src_rows[mb.n_src++] = 256; + } + RAD_ARCH_TRY(rad_decl_name_map(b, &mw)); + RAD_ARCH_TRY(rad_decl_name_map(b, &mb)); + m.dw_ad = decl_w(b, wn, RAD_BF16, { 1024, 384 }, acc, RAD_SHARD_NONE, grp_layer(gx)); + m.db_ad = decl_w(b, bn, RAD_BF16, { 1024 }, acc, RAD_SHARD_NONE, grp_layer(gx)); + } + m.dw_xin = wt("conv_in_x_t.weight", { 256, (int64_t)kPixC }); + m.db_xin = wt("conv_in_x_t.bias", { 256 }); + m.dw_nout = wt("norm_out.weight", { 256 }); + m.dw_cout = wt("conv_out.weight", { (int64_t)kPixC, 256 }); + m.db_cout = wt("conv_out.bias", { (int64_t)kPixC }); + if (!m.dw_cin || !m.db_cin || !m.dw_t1 || !m.db_t1 || !m.dw_t2 || !m.db_t2 || !m.dw_ad || !m.db_ad || + !m.dw_xin || !m.db_xin || !m.dw_nout || !m.dw_cout || !m.db_cout) + return RAD_E_INVAL; + + /* ---- once a decode: the ghost frames, the shared modulation, the constants, the grids */ + m.op_dpad = cast_op(b, m.dV0, kC, "bf16", "bf16", m.b_vlat, m.b_dz); + m.op_dtin = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 1), RAD_STR("dtype", "f32"), + RAD_F64("value", 1.0)), + RAD_NOWEIGHTS), + {}, { m.b_dtin }); + m.op_dtsin = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 256), + RAD_F64("scale", 1000.0), RAD_F64("max_period", 10000.0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_dtin }, { m.b_dtsin }); + m.op_dt1 = dd_gemm(b, m.dw_t1, m.db_t1, 1, 384, 256, { m.b_dtsin }, m.b_dth); + m.op_dts = unary(b, "silu", 1, 384, "bf16", m.b_dth, m.b_dths); + m.op_dt2 = dd_gemm(b, m.dw_t2, m.db_t2, 1, 384, 384, { m.b_dths }, m.b_dtemb); + m.op_das = unary(b, "silu", 1, 384, "bf16", m.b_dtemb, m.b_dtes); + m.op_dad = dd_gemm(b, m.dw_ad, m.db_ad, 1, 1024, 384, { m.b_dtes }, m.b_dmod); + m.op_ddcu = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("start", 0), + RAD_INT("step", 1 << 30)), + RAD_NOWEIGHTS), + {}, { m.b_ddcu }); + m.op_dsig = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 1), RAD_STR("dtype", "f32"), + RAD_F64("value", 1.0)), + RAD_NOWEIGHTS), + {}, { m.b_dsig }); + auto affine = [&](const char* src, std::initializer_list mul, + std::initializer_list add, rad_buf y) { + return rw(b, RAD_OP(b, "int_affine", + RAD_PARAMS(RAD_RANGE("M", 1, 3), RAD_STR("src", src), + RAD_STR("mul", ints(mul).c_str()), + RAD_STR("add", ints(add).c_str())), + RAD_NOWEIGHTS), + {}, { y }); + }; + /* The tiles cut the feature grid without its ghost cells: 4 F - 3 frames. */ + m.op_dtgeom = affine("0 1 2", { 4, 4, 4 }, { -3, 0, 0 }, m.b_dtg); + m.op_dgrid = rw(b, RAD_OP(b, "tile_grid", + RAD_PARAMS(RAD_RANGE("M", 1, kDdMaxTiles), RAD_INT("tile", kDdTile), + RAD_INT("stride", kDdStride), RAD_STR("rule", "intervals"), + RAD_INT("min", kDdLeast), RAD_INT("tile_t", kDdTileT), + RAD_INT("stride_t", kDdStrideT), RAD_INT("min_t", kDdLeast), + RAD_INT("tail", kDdGhostCells)), + RAD_NOWEIGHTS), + { m.b_dtg }, { m.b_dgrid }); + m.op_dcin = dd_gemm(b, m.dw_cin, m.db_cin, m.dV0, 2048, kC, { m.b_dz }, m.b_dx); + + /* ---- the deterministic stages: the first three over the whole latent, the fourth per tile */ + m.dst.resize(4); + const int64_t svol[4] = { m.dV0, m.dV1, m.dV2, m.dV4 }; + /* each stage's volume off the latent's (F, h, w): (F + 2, h, w), (F + 2, 2h, 2w), + * (2 F + 3, 2h, 2w), and the feature grid (4 F + 5, 4h, 4w) the tiles are cut from */ + const long long gmul[4][3] = { { 1, 1, 1 }, { 1, 2, 2 }, { 2, 2, 2 }, { 4, 4, 4 } }; + const long long gadd[4] = { 2, 2, 3, 5 }; + for (int s = 0; s < 4; ++s) { + DdStage& S = m.dst[(size_t)s]; + S.C = (int64_t)ch[(size_t)s]; + S.cout = (int64_t)ch[(size_t)s + 1]; + S.st = (int64_t)str[(size_t)(3 * s)]; + S.sh = (int64_t)str[(size_t)(3 * s + 1)]; + S.sw = (int64_t)str[(size_t)(3 * s + 2)]; + S.geom = decl_b(b, nm.f("ddec.s%d.geom", s), RAD_I32, { 3 }, RAD_BUF_PERSIST); + S.op_geom = affine("0 1 2", { gmul[s][0], gmul[s][1], gmul[s][2] }, { gadd[s], 0, 0 }, S.geom); + const rad_buf x = s < 3 ? m.b_dx : m.b_d4; + if (s == 3) + m.op_dcrop = rw(b, RAD_OP(b, "tile_crop", + RAD_PARAMS(RAD_RANGE("M", 1, m.dV4), RAD_INT("C", 512), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_dfeat }, { m.b_d4 }); + S.op_pos = rw(b, RAD_OP(b, "vol_index", RAD_PARAMS(RAD_RANGE("M", 1, maxV)), RAD_NOWEIGHTS), {}, + { m.b_dpos }); + const int slot = s == 0 ? 0 : s == 1 ? 1 : 2; + int64_t kk[3] = { (int64_t)ker[(size_t)(3 * s)], (int64_t)ker[(size_t)(3 * s + 1)], + (int64_t)ker[(size_t)(3 * s + 2)] }; + S.blk.resize((size_t)dep[(size_t)s]); + for (size_t l = 0; l < S.blk.size(); ++l) + RAD_ARCH_TRY(dd_block_declare(b, m, S.blk[l], nm.f("ddec.s%d.%zu", s, l), + nm.ckpt("diffusion_decoder.decoder.det_stages.%d.%zu", s, l), + S.C, slot, kk, svol[s], false, x)); + const int64_t P = S.st * S.sh * S.sw * S.C / (int64_t)red[(size_t)s]; + S.w_up = wcopy(b, nm.f("ddec.up%d.weight", s), + nm.ckpt("diffusion_decoder.decoder.upsamples.%d.proj.weight", s), RAD_BF16, + { P, S.C }, acc, gx); + S.b_up = wcopy(b, nm.f("ddec.up%d.bias", s), + nm.ckpt("diffusion_decoder.decoder.upsamples.%d.proj.bias", s), RAD_BF16, { P }, + acc, gx); + /* The upsample's linear into its width's q|k|v buffer; the fourth stage's into the 512 one too, + * so that the diffusion stage's is first touched by its blocks and its noise can share it. */ + const rad_buf scratch = m.b_dqkv[slot]; + const rad_buf dest = s < 2 ? m.b_dx : s == 2 ? m.b_dfeat : m.b_dctx; + S.op_proj = dd_gemm(b, S.w_up, S.b_up, svol[s], P, S.C, { x }, scratch); + auto d2s = [&](int64_t drop) { + return rw(b, RAD_OP(b, "d2s3d", + RAD_PARAMS(RAD_RANGE("M", 1, svol[s]), RAD_INT("C", S.cout), + RAD_INT("st", S.st), RAD_INT("sh", S.sh), RAD_INT("sw", S.sw), + RAD_INT("drop", drop), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { scratch }, { dest }); + }; + S.op_d2s = d2s(S.st - 1); + S.op_d2s_keep = s == 3 ? d2s(0) : 0; + if (!S.op_geom || !S.op_pos || !S.w_up || !S.b_up || !S.op_proj || !S.op_d2s || + (s == 3 && (!S.op_d2s_keep || !m.op_dcrop))) + return RAD_E_INVAL; + } + /* ---- the diffusion stage, per tile: its volume, positions, noise and blocks */ + { + /* (2 t - drop - ghost, 2 h, 2 w) off the tile's row: the tile starting the video drops a + * frame, the one ending it 16 ghost frames. */ + int v = 0; + for (int origin = 0; origin < 2; ++origin) + for (int trailing = 0; trailing < 2; ++trailing) + m.op_dg5[v++] = affine("0 1 2", { 2, 2, 2 }, + { -(origin ? 1 : 0) - (trailing ? 2 * kDdGhostCells : 0), 0, 0 }, + m.b_dg5); + } + m.op_dpos5 = rw(b, RAD_OP(b, "vol_index", RAD_PARAMS(RAD_RANGE("M", 1, maxV)), RAD_NOWEIGHTS), + { m.b_dg5 }, { m.b_dpos }); + m.op_dz = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, m.dV5), RAD_INT("n", kPixC), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, { m.b_dxt }); + m.op_dnoise.resize(kDdMaxTiles); + for (int k = 0; k < kDdMaxTiles; ++k) + m.op_dnoise[(size_t)k] = rw(b, RAD_OP(b, "flow_renoise", + RAD_PARAMS(RAD_RANGE("M", 1, m.dV5), RAD_INT("n", kPixC), + RAD_INT("stream", 2 + k), RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_dsig, m.b_dxt }, { m.b_dxt }); + m.op_dxcast = cast_op(b, m.dV5, kPixC, "f32", "bf16", m.b_dxt, m.b_dxb); + m.op_dxin = dd_gemm(b, m.dw_xin, m.db_xin, m.dV5, 256, kPixC, { m.b_dxb }, m.b_ddh); + m.dblk.resize((size_t)dep[4]); + const int64_t kk5[3] = { (int64_t)k5[0], (int64_t)k5[1], (int64_t)k5[2] }; + for (size_t l = 0; l < m.dblk.size(); ++l) + RAD_ARCH_TRY(dd_block_declare(b, m, m.dblk[l], nm.f("ddec.d.%zu", l), + nm.ckpt("diffusion_decoder.decoder.diff_blocks.%zu", l), 256, 3, + kk5, m.dV5, true, m.b_ddh)); + m.op_dnout = rms_op(b, m.dV5, 256, 1e-6, m.dw_nout, m.b_ddh, m.b_dn); + /* The tile's pixels to the store; it is the tile loop's last op, so the feature volume, which + * every tile's crop reads, stays live through the loop. */ + m.op_ddout = dd_gemm(b, m.dw_cout, m.db_cout, m.dV5, kPixC, 256, { m.b_dn, m.b_dfeat }, m.b_vtiles); + m.op_dst = rw(b, RAD_OP(b, "tile_stitch", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)(kFpc + kFtail) * m.maxSide), + RAD_INT("tile", kDdTile), RAD_INT("stride", kDdStride), + RAD_STR("rule", "intervals"), RAD_INT("min", kDdLeast), + RAD_INT("tile_t", kDdTileT), RAD_INT("stride_t", kDdStrideT), + RAD_INT("min_t", kDdLeast), RAD_INT("scale", 2), + RAD_INT("scale_t", 2), RAD_INT("p", kPix), RAD_INT("C", 3), + RAD_STR("order", "wh"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_vtiles, m.b_dtg, m.b_vf0 }, { m.b_frames }); + /* The store holds the largest video's tiles at the decoder's own largest canvas. */ + for (int64_t Wd = kMinSide; Wd * kMinSide <= kDefW * kDefH; Wd += kMult) + for (int64_t Hd = kMinSide; Wd * Hd <= kDefW * kDefH; Hd += kMult) { + if (std::max(Wd, Hd) > kMaxAspect * std::min(Wd, Hd)) continue; + int64_t rows = 0; + for (const DdTile& t : dd_tiles(4 * F - 3, 4 * (Hd / kScale), 4 * (Wd / kScale))) + rows += (2 * (t.t - (t.trailing ? kDdGhostCells : 0)) - (t.origin ? 1 : 0)) * 4 * t.h * t.w; + if (rows > m.maxStore || (int64_t)dd_tiles(4 * F - 3, 4 * (Hd / kScale), 4 * (Wd / kScale)).size() > kDdMaxTiles) { + fprintf(stderr, "radiance: ltx2: the diffusion decoder's tiles of %lldx%lld (%lld rows) " + "outgrow the tile store (%lld rows) or its %d tiles\n", + (long long)Wd, (long long)Hd, (long long)rows, (long long)m.maxStore, + (int)kDdMaxTiles); + return RAD_E_UNSUPPORTED; + } + } + return m.op_dpad && m.op_dtin && m.op_dtsin && m.op_dt1 && m.op_dts && m.op_dt2 && m.op_das && + m.op_dad && m.op_ddcu && m.op_dsig && m.op_dtgeom && m.op_dgrid && m.op_dcin && + m.op_dpos5 && m.op_dz && m.op_dxcast && m.op_dxin && m.op_dnout && m.op_ddout && + m.op_dst + ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== declare */ +/* The distilled release's trained sigmas, and its second stage's after the latent upsampler + * (diffusers' pipelines/ltx2/utils.py, DISTILLED_SIGMA_VALUES and + * STAGE_2_DISTILLED_SIGMA_VALUES). */ +static const double kDistilled[] = { 1.0, 0.99375, 0.9875, 0.98125, 0.975, 0.909375, 0.725, 0.421875 }; +static const double kStage2[] = { 0.909375, 0.725, 0.421875 }; + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + if (ctx->is_draft) { + fprintf(stderr, "radiance: ltx2: this plugin has no draft scope\n"); + return RAD_E_UNSUPPORTED; + } + if (ctx->world_size > 1) { + fprintf(stderr, "radiance: ltx2: runs on one rank (--tp 1): the DiT's q and k norms span " + "every head\n"); + return RAD_E_UNSUPPORTED; + } + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + Names& nm = m.nm; + RAD_ARCH_TRY(check_format(meta)); + + /* ---- the text encoder's geometry, off its config */ + m.tC = tgeti(meta, "hidden_size", 0); + m.tL = tgeti(meta, "num_hidden_layers", 0); + m.tFF = tgeti(meta, "intermediate_size", 0); + m.teps = tgetf(meta, "rms_norm_eps", 1e-6); + const int64_t vocab = tgeti(meta, "vocab_size", 0); + if (m.tC <= 0 || m.tL <= 0 || m.tFF <= 0 || vocab <= 0) { + fprintf(stderr, "radiance: ltx2: the text encoder's config names no width, depth or " + "vocabulary\n"); + return RAD_E_INVAL; + } + m.tRows = 2 * (int64_t)kTextRows; + Geom base{}; + base.rank = ctx->rank; + base.world = 1; + base.max_tok = ctx->max_tok; + base.max_seqs = ctx->max_seqs; + base.max_ctx = ctx->max_ctx; + base.n_vocab = base.n_vocab_all = vocab; + base.eps = (float)m.teps; + base.dtype = "bf16"; + base.act_dtype = RAD_BF16; + m.gt = base; + m.gt.max_tok = m.tRows; + m.gt.n_embd = m.tC; + m.gt.n_layer = m.tL; + m.gd = base; + + /* ---- the DiT's */ + m.H = rad_meta_geti(meta, "transformer.num_attention_heads", 0); + m.hd = rad_meta_geti(meta, "transformer.attention_head_dim", 0); + m.Ha = rad_meta_geti(meta, "transformer.audio_num_attention_heads", 0); + m.hda = rad_meta_geti(meta, "transformer.audio_attention_head_dim", 0); + m.nb = rad_meta_geti(meta, "transformer.num_layers", 0); + m.D = m.H * m.hd; + m.Da = m.Ha * m.hda; + m.Dc = m.Ha * m.hda; + m.ffv = 4 * m.D; + m.ffa = 4 * m.Da; + m.eps = rad_meta_getf(meta, "transformer.norm_eps", 1e-6); + if (m.D <= 0 || m.Da <= 0 || m.nb <= kStgBlock || + rad_meta_geti(meta, "transformer.cross_attention_dim", 0) != m.D || + rad_meta_geti(meta, "transformer.audio_cross_attention_dim", 0) != m.Da || + std::strcmp(rad_meta_gets(meta, "transformer.activation_fn", ""), "gelu-approximate") || + rad_meta_geti(meta, "transformer.ff_bias", 1) != 0 || + rad_meta_geti(meta, "transformer.audio_ff_bias", 0) != 1) { + fprintf(stderr, "radiance: ltx2: the DiT is not LTX-2.5's (%lld blocks of %lld + %lld wide, " + "block %d for spatio-temporal guidance, text at its width, a tanh GELU " + "feed-forward without biases on the video)\n", + (long long)m.nb, (long long)m.D, (long long)m.Da, (int)kStgBlock); + return RAD_E_UNSUPPORTED; + } + m.maxS = max_video_rows(); + m.maxA = max_audio(); + m.maxPpf = max_patches(); + if (ctx->max_tok < max_step_rows() || ctx->max_tok < m.tRows) { + fprintf(stderr, "radiance: ltx2: a pass carries %lld rows; the longest video's step needs " + "%lld\n", (long long)ctx->max_tok, (long long)max_step_rows()); + return RAD_E_INVAL; + } + + /* ---- bf16 or block fp8: what the container holds for the first DiT projection decides every + * large linear (rad_fp8.h, Geom::w_bf16) */ + { + LinearFP8 probe{}; + RAD_ARCH_TRY(probe.probe(b, nm, m.gd, "dit.blk.0.attn1.qkv", + { "transformer.transformer_blocks.0.attn1.to_q.weight", + "transformer.transformer_blocks.0.attn1.to_k.weight", + "transformer.transformer_blocks.0.attn1.to_v.weight" })); + RadEncoding e{}; + const bool plain = weight_enc(b, nm.f("dit.blk.0.attn1.qkv.weight"), &e) && + rad_enc_is(&e, "plain"); + m.gd.w_bf16 = m.gt.w_bf16 = plain; + } + + /* ---- the scheduler: the base model's shifted linspace, or the distilled release's sigmas */ + const bool distilled = rad_meta_geti(meta, "scheduler.use_dynamic_shifting", 1) == 0; + if (distilled) { + m.rungs.assign(std::begin(kDistilled), std::end(kDistilled)); + m.refine.assign(std::begin(kStage2), std::end(kStage2)); + } + + /* ---- in issue order: the conditioning pass, the step, the frames, the soundtrack, the + * upscale */ + RAD_ARCH_TRY(declare_te(b, meta, m)); + { + const int64_t wz = std::max(rad_meta_geti(meta, "connectors.video_hidden_dim", 0), + rad_meta_geti(meta, "connectors.audio_hidden_dim", 0)); + m.b_zero = decl_b(b, nm.f("conn.zero"), RAD_BF16, { 1, wz }, RAD_BUF_PERSIST); + m.b_rows = decl_b(b, nm.f("conn.rows"), RAD_I32, { 3 }, RAD_BUF_PERSIST); + m.b_rpos = decl_b(b, nm.f("conn.pos"), RAD_I32, { 2 * (int64_t)kTextRows }, RAD_BUF_PERSIST); + m.op_zero = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", wz), + RAD_STR("dtype", "bf16"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_zero }); + m.op_rows = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, 3), RAD_INT("start", 0), + RAD_INT("step", (int64_t)kTextRows)), + RAD_NOWEIGHTS), + {}, { m.b_rows }); + m.op_rpos = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, 2 * (int64_t)kTextRows), + RAD_INT("start", 0), + RAD_INT("step", 1), RAD_INT("period", (int64_t)kTextRows)), + RAD_NOWEIGHTS), + {}, { m.b_rpos }); + if (!m.b_zero || !m.op_zero || !m.op_rows || !m.op_rpos) return RAD_E_INVAL; + } + RAD_ARCH_TRY(declare_conn(b, meta, m, m.cv, "video")); + RAD_ARCH_TRY(declare_conn(b, meta, m, m.ca, "audio")); + if (m.cv.D != m.D || m.ca.D != m.Da) { + fprintf(stderr, "radiance: ltx2: the connectors' widths (%lld, %lld) are not the DiT's\n", + (long long)m.cv.D, (long long)m.ca.D); + return RAD_E_UNSUPPORTED; + } + RAD_ARCH_TRY(declare_dur(b, meta, m)); + RAD_ARCH_TRY(declare_dit(b, meta, m)); + RAD_ARCH_TRY(declare_vae(b, meta, m)); + RAD_ARCH_TRY(declare_venc(b, meta, m)); + RAD_ARCH_TRY(declare_audio(b, meta, m)); + RAD_ARCH_TRY(declare_ups(b, meta, m)); + RAD_ARCH_TRY(declare_ddec(b, meta, m)); + + if (!ctx->shape_probe) { + RadVideoGenDecl d{}; + d.name = distilled ? "ltx-2.5-distilled" : "ltx-2.5"; + /* Gemma's tokenizer wraps the prompt in and (its TemplateProcessing). */ + d.tmpl = "{prompt}"; + d.max_text = kTextRows; + d.fps_num = kFps; + d.fps_den = 1; + d.frames_per_chunk = kFpc; + d.frames_tail = kFtail; + d.latents_per_chunk = kLpc; + d.latents_tail = kLtail; + d.dec_latents = kDecLat; + d.min_chunks = kMinChunks; + d.max_chunks = kMaxChunks; + d.latent_scale = kScale; + d.latent_channels = kC; + d.patch = 1; + d.size_multiple = kMult; + d.min_side = kMinSide; + d.max_area = kMaxArea; + d.max_aspect = kMaxAspect; + d.default_width = kDefW; + d.default_height = kDefH; + d.default_chunks = kDefChunks; + d.sample_rate = kRate; + d.audio_rate = kAudioRate; + d.audio_channels = kAudioCh; + d.audio_latent_channels = kAudioC; + d.audio_streams = 1; + d.max_lanes = kMaxLanes; + d.frames_out = m.b_frames; + d.audio_out = m.b_audio; + d.sched_kind = 1; + d.base_shift = rad_meta_getf(meta, "scheduler.base_shift", 0.95); + d.max_shift = rad_meta_getf(meta, "scheduler.max_shift", 2.05); + d.base_seq = rad_meta_geti(meta, "scheduler.base_image_seq_len", 1024); + d.max_seq = rad_meta_geti(meta, "scheduler.max_image_seq_len", 4096); + if (distilled) { + d.n_rungs = (int32_t)m.rungs.size(); + d.rungs = m.rungs.data(); + d.default_steps = d.max_steps = d.n_rungs; + } else { + d.dyn_shift = 1; + d.shift_terminal = rad_meta_getf(meta, "scheduler.shift_terminal", 0.1); + d.default_steps = kDefSteps; + d.max_steps = kMaxSteps; + } + d.step_text_rows = kTextRows; + /* The base model is guided four ways a step by default; the distilled release unguided + * (one evaluation a step). */ + d.guidance = 1; + static const double kGuided[8] = { 3.0, 1.0, 3.0, 0.7, 7.0, 1.0, 3.0, 0.7 }; + static const double kPlain[8] = { 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0 }; + std::memcpy(d.guidance_default, distilled ? kPlain : kGuided, sizeof d.guidance_default); + d.image_cond = m.venc ? 1 : 0; + d.image_crf = 18; + d.text_left_pad = kTextRows; + /* The two-stage recipe: the distilled release at half size, the upsampler, its second + * stage's sigmas at the full size. */ + if (m.ups && distilled) { + d.upscale_max = 2.0; + d.upscale_exact = 1; + d.n_refine_rungs = (int32_t)m.refine.size(); + d.refine_rungs = m.refine.data(); + d.upscale_refine = d.n_refine_rungs; + } + /* The VAE decodes by default; the diffusion decoder, when the container has it, on request, + * up to the default canvas. */ + static const int64_t kDecArea[2] = { 0, (int64_t)kDefW * kDefH }; + if (m.ddec) { + d.decoders = "vae diffusion"; + d.decoder_max_area = kDecArea; + } + /* The duration head's bounds are the pipeline's defaults (LTX2AutoDurationStep). */ + if (m.dur) { + d.duration_out = m.b_dur; + d.duration_min = 1.0; + d.duration_max = 20.0; + d.duration_dtype = RAD_BF16; + } + RAD_ARCH_TRY(rad_declare_video_generator(b, &d)); + } + rad_note(b, "LTX-2.5%s: Gemma 4 text encoder %lld layers of %lld, connectors %zu + %zu blocks, " + "DiT %lld blocks (video %lld, audio %lld), %s linears; VAE %s, audio VAE + vocoder + " + "bandwidth extender%s%s", + distilled ? " distilled" : "", (long long)m.tL, (long long)m.tC, m.cv.blk.size(), + m.ca.blk.size(), (long long)m.nb, (long long)m.D, (long long)m.Da, + m.gd.w_bf16 ? "bf16" : "block-fp8", m.venc ? "decoder + encoder" : "decoder", + m.ups ? ", latent upsampler x2" : "", m.dur ? ", duration head" : ""); + return RAD_OK; +} + +/* ================================================================== step */ +/* A column slice of a table's rows [r0, r0 + n): `first` columns into a row of `pitch`. */ +static RadOperand tab(rad_buf t, int64_t r0, int64_t n, int64_t pitch, int64_t first, int64_t width) { + return bcol_at(t, r0, pitch, first, width, n); +} + +/* The conditioning pass: the text encoder over both prompts into the stack, each connector into + * the lane's text rows, and with a first frame the VAE encoder into the lane's clean frame. */ +static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + const int64_t T = batch->n_tok, Tn = V->n_neg, Tp = T - Tn, lane = V->lane; + const int64_t C = m.tC, L = m.tL, Lp = L + 1, np = Tn > 0 ? 2 : 1; + const RadOperand pos = praw(batch->positions, RAD_I32, T); + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, np + 1); + + /* ---- the text encoder */ + RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_tx, T)); + RAD_ISSUE_N(c, m.op_keep0, T, brows(m.b_tx, T), bcol(m.b_stack, 0, C, T)); + for (int64_t l = 0; l < L; ++l) { + const TeLayer& Y = m.te[(size_t)l]; + const TeClass& K = m.cls[Y.full ? 1 : 0]; + const int64_t qd = Y.nh * Y.hd, kvd = Y.nkv * Y.hd; + RAD_ISSUE_N(c, Y.op_in, T, brows(m.b_tx, T), RAD_W(Y.w_in), brows(m.a_th.a.x, T)); + m.a_th.step(c, T); + Y.q.step(c, m.a_th, K.q, T); + Y.k.step(c, m.a_th, K.k, T); + if (!Y.v_from_k) Y.v.step(c, m.a_th, K.v, T); + RAD_ISSUE_N(c, Y.op_vn, T * Y.nkv, brows(Y.v_from_k ? K.k : K.v, T), brows(K.v, T)); + RAD_ISSUE_N(c, Y.op_qn, T * Y.nh, brows(K.q, T), RAD_W(Y.w_qn), brows(K.q, T)); + RAD_ISSUE_N(c, Y.op_kn, T * Y.nkv, brows(K.k, T), RAD_W(Y.w_kn), brows(K.k, T)); + RAD_ISSUE_N(c, Y.op_rq, T, bcol(K.q, 0, qd, T), pos); + RAD_ISSUE_N(c, Y.op_rk, T, bcol(K.k, 0, kvd, T), pos); + RAD_ISSUE_N(c, Y.op_attn, T, bcol(K.q, 0, qd, T), bcol(K.k, 0, kvd, T), bcol(K.v, 0, kvd, T), cu, + bcol(K.o.a.x, 0, qd, T)); + K.o.step(c, T); + Y.o.step(c, K.o, m.b_th2, T); + RAD_ISSUE_N(c, Y.op_pa, T, brows(m.b_th2, T), RAD_W(Y.w_pa), brows(m.b_th2, T)); + RAD_ISSUE_N(c, Y.op_add1, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + RAD_ISSUE_N(c, Y.op_pf, T, brows(m.b_tx, T), RAD_W(Y.w_pf), brows(m.a_th.a.x, T)); + m.a_th.step(c, T); + Y.gu.step(c, m.a_th, m.b_tgu, T); + RAD_ISSUE_N(c, Y.op_act, T, brows(m.b_tgu, T), brows(m.a_tffn.a.x, T)); + m.a_tffn.step(c, T); + Y.down.step(c, m.a_tffn, m.b_th2, T); + RAD_ISSUE_N(c, Y.op_ff, T, brows(m.b_th2, T), RAD_W(Y.w_ff), brows(m.b_th2, T)); + RAD_ISSUE_N(c, Y.op_add2, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + RAD_ISSUE_N(c, Y.op_sc, T, brows(m.b_tx, T), RAD_W(Y.w_sc), brows(m.b_tx, T)); + if (Y.op_keep) + RAD_ISSUE_N(c, Y.op_keep, T, brows(m.b_tx, T), bcol(m.b_stack, (l + 1) * C, C, T)); + } + RAD_ISSUE_N(c, m.op_tnorm, T, brows(m.b_tx, T), RAD_W(m.w_tnorm), bcol(m.b_stack, L * C, C, T)); + + /* ---- the connectors */ + RAD_ISSUE_N(c, m.op_zero, 1, brows(m.b_zero, 1)); + RAD_ISSUE_N(c, m.op_rows, 3, brows(m.b_rows, 3)); + RAD_ISSUE_N(c, m.op_rpos, 2 * kTextRows, brows(m.b_rpos, 2 * kTextRows)); + const int64_t R = np * kTextRows; + const RadOperand ccu = brows(m.b_rows, np + 1); + const RadOperand rpos = brows(m.b_rpos, R); + for (const Conn* Kp : { &m.cv, &m.ca }) { + const Conn& K = *Kp; + const int64_t D = K.D; + RAD_ISSUE_N(c, K.op_norm, T * Lp, view(c, m.b_stack, RAD_BF16, T * Lp, C), + brows(K.a_in.a.x, T)); + K.a_in.step(c, T); + /* Every row the registers first, then the prompts' tokens over the front of each. */ + for (int64_t p = 0; p < np; ++p) + RAD_ISSUE_N(c, K.op_reg, 1, bcol(m.b_zero, 0, D, 1), RAD_W(K.w_reg), + view(c, K.b_x, RAD_BF16, 1, (int64_t)kTextRows * D, p * kTextRows * D)); + K.proj.step(c, K.a_in, K.b_x, Tp, 0, 0); + if (Tn > 0) K.proj.step(c, K.a_in, K.b_x, Tn, Tp, kTextRows); + for (const ConnBlock& B : K.blk) { + RAD_ISSUE_N(c, B.op_n1, R, brows(K.b_x, R), RAD_NONE, brows(K.a_h.a.x, R)); + K.a_h.step(c, R); + B.at.qkv.step(c, K.a_h, K.b_qkv, R); + B.at.gate.step(c, K.a_h, K.b_g, R); + attn_core(c, B.at, true, K.b_qkv, 0, K.b_g, K.a_attn, R, R, ccu, RAD_NONE, rpos, rpos); + K.a_attn.step(c, R); + B.at.out.step(c, K.a_attn, K.b_o, R); + RAD_ISSUE_N(c, B.op_add1, R, brows(K.b_x, R), brows(K.b_o, R), brows(K.b_x, R)); + RAD_ISSUE_N(c, B.op_n2, R, brows(K.b_x, R), RAD_NONE, brows(K.a_h.a.x, R)); + K.a_h.step(c, R); + B.up.step(c, K.a_h, K.b_up, R); + RAD_ISSUE_N(c, B.op_act, R, brows(K.b_up, R), brows(K.a_ffn.a.x, R)); + K.a_ffn.step(c, R); + B.down.step(c, K.a_ffn, K.b_o, R); + RAD_ISSUE_N(c, B.op_add2, R, brows(K.b_x, R), brows(K.b_o, R), brows(K.b_x, R)); + } + RAD_ISSUE_N(c, K.op_nout, R, brows(K.b_x, R), RAD_NONE, + brow_slice(K.b_text, lane * 2 * kTextRows, R, D)); + } + + /* ---- the duration head, over the prompt's rows of each connector */ + if (m.dur) { + const int64_t r0 = lane * 2 * kTextRows, P = m.dP; + RAD_ISSUE_N(c, m.op_dvp, kTextRows, brow_slice(m.cv.b_text, r0, kTextRows, m.cv.D), + RAD_W(m.dw_vp), RAD_W(m.dw_vpb), RAD_NONE, brows(m.b_dtok, kTextRows)); + RAD_ISSUE_N(c, m.op_dap, kTextRows, brow_slice(m.ca.b_text, r0, kTextRows, m.ca.D), + RAD_W(m.dw_ap), RAD_W(m.dw_apb), RAD_NONE, + brow_slice(m.b_dtok, kTextRows, kTextRows, P)); + RAD_ISSUE_N(c, m.op_dvemb, kTextRows, brows(m.b_dtok, kTextRows), RAD_W(m.dw_vemb), + brows(m.b_dtok, kTextRows)); + RAD_ISSUE_N(c, m.op_daemb, kTextRows, brow_slice(m.b_dtok, kTextRows, kTextRows, P), + RAD_W(m.dw_aemb), brow_slice(m.b_dtok, kTextRows, kTextRows, P)); + RAD_ISSUE_N(c, m.op_dq0, 1, bcol(m.b_zero, 0, P, 1), RAD_W(m.dw_qt), brows(m.b_dq0, 1)); + RAD_ISSUE_N(c, m.op_dq, 1, brows(m.b_dq0, 1), RAD_W(m.dw_q), RAD_W(m.dw_qb), RAD_NONE, + brows(m.b_dq, 1)); + RAD_ISSUE_N(c, m.op_dk, 2 * kTextRows, brows(m.b_dtok, 2 * kTextRows), RAD_W(m.dw_k), + RAD_W(m.dw_kb), RAD_NONE, brows(m.b_dk, 2 * kTextRows)); + RAD_ISSUE_N(c, m.op_dv, 2 * kTextRows, brows(m.b_dtok, 2 * kTextRows), RAD_W(m.dw_v), + RAD_W(m.dw_vb), RAD_NONE, brows(m.b_dv, 2 * kTextRows)); + RAD_ISSUE_N(c, m.op_dcu, 2, brows(m.b_dcu, 2)); + RAD_ISSUE_N(c, m.op_dcuk, 2, brows(m.b_dcuk, 2)); + RAD_ISSUE_N(c, m.op_dattn, 1, brows(m.b_dq, 1), brows(m.b_dk, 2 * kTextRows), + brows(m.b_dv, 2 * kTextRows), brows(m.b_dcu, 2), brows(m.b_dcuk, 2), + brows(m.b_dat, 1)); + RAD_ISSUE_N(c, m.op_do, 1, brows(m.b_dat, 1), RAD_W(m.dw_o), RAD_W(m.dw_ob), RAD_NONE, + brows(m.b_do, 1)); + RAD_ISSUE_N(c, m.op_dh, 1, brows(m.b_do, 1), RAD_W(m.dw_h), RAD_W(m.dw_hb), RAD_NONE, + brows(m.b_dh, 1)); + RAD_ISSUE_N(c, m.op_dout, 1, brows(m.b_dh, 1), RAD_W(m.dw_out), RAD_W(m.dw_outb), RAD_NONE, + brows(m.b_dl, 1)); + RAD_ISSUE_N(c, m.op_dlog, 1, brows(m.b_dl, 1), brows(m.b_dur, 1)); + } + + /* ---- a first frame through the VAE's encoder */ + if (!V->image || !m.venc) return; + const int64_t h = V->geom.lat_h, w = V->geom.lat_w, ppf = h * w; + const int64_t Hp = 8 * h, Wp = 8 * w, vin0 = Hp * Wp; + const RadOperand gd = praw(V->geom_d, RAD_I32, RAD_VGEOM_N); + RAD_ISSUE_N(c, m.op_epatch, Hp, RAD_P_T2(V->image, RAD_BF16, 32 * h, 32 * w * 3), + view(c, m.b_epatch, RAD_BF16, Hp, Wp * kPixC)); + RAD_ISSUE_N(c, m.op_egeomL, 3, gd, brows(m.b_egeomL, 3)); + for (const VDown& Dn : m.vdown) { + RAD_ISSUE_N(c, Dn.op_geom_in, 3, gd, brows(Dn.geom_in, 3)); + RAD_ISSUE_N(c, Dn.op_geom, 3, gd, brows(Dn.geom, 3)); + } + RAD_ISSUE_N(c, m.op_ecin, vin0, view(c, m.b_epatch, RAD_BF16, vin0, kPixC), RAD_W(m.w_ecin), + RAD_W(m.b_ecin), brows(m.vdown[0].geom_in, 3), RAD_NONE, + view(c, m.b_ea, RAD_BF16, vin0, m.eC0)); + int64_t vin = vin0; + for (const VDown& Dn : m.vdown) { + const RadOperand gin = brows(Dn.geom_in, 3); + for (const VRes& Rb : Dn.res) vres_step(c, Rb, vin, gin, m.b_ea, m.b_eb, m.b_ec); + const int64_t vout = vin / (Dn.sh * Dn.sw), tv = Dn.st * vin; + RAD_ISSUE_N(c, Dn.op_mean, vin, view(c, m.b_ea, RAD_BF16, vin, Dn.cin), gin, + view(c, m.b_eb, RAD_BF16, vout, Dn.cout)); + RAD_ISSUE_N(c, Dn.op_conv, vin, view(c, m.b_ea, RAD_BF16, vin, Dn.cin), RAD_W(Dn.w), RAD_W(Dn.b), + gin, RAD_NONE, view(c, m.b_ec, RAD_BF16, tv, Dn.conv_out)); + RAD_ISSUE_N(c, Dn.op_s2d, tv, view(c, m.b_ec, RAD_BF16, tv, Dn.conv_out), brows(Dn.geom, 3), + view(c, m.b_eb, RAD_BF16, vout, Dn.cout)); + RAD_ISSUE_N(c, Dn.op_next, vout, view(c, m.b_eb, RAD_BF16, vout, Dn.cout), + view(c, m.b_ea, RAD_BF16, vout, Dn.cout)); + vin = vout; + } + const RadOperand gl = brows(m.b_egeomL, 3); + for (const VRes& Rb : m.emid) vres_step(c, Rb, ppf, gl, m.b_ea, m.b_eb, m.b_ec); + RAD_ISSUE_N(c, m.op_enout, ppf, view(c, m.b_ea, RAD_BF16, ppf, m.eCout), + view(c, m.b_eb, RAD_BF16, ppf, m.eCout)); + RAD_ISSUE_N(c, m.op_ecout, ppf, view(c, m.b_eb, RAD_BF16, ppf, m.eCout), RAD_W(m.w_ecout), + RAD_W(m.b_ecout), gl, RAD_NONE, brows(m.b_eout, ppf)); + RAD_ISSUE_N(c, m.op_enorm, ppf, bcol(m.b_eout, 0, kC, ppf), RAD_W(m.vd_mean), RAD_W(m.vd_std), + brows(m.b_elat, ppf)); + RAD_ISSUE_N(c, m.op_ef32, ppf, brows(m.b_elat, ppf), + brow_slice(m.b_first, lane * m.maxPpf, ppf, kC)); +} + +/* One DiT evaluation into evaluation `p`'s velocities: the text of prompt `branch` (0 the prompt, 1 + * the negative), `stg` bypassing block 28's self-attentions, `iso` without the cross-modal + * attentions. */ +static void dit_eval(RadCtx* c, const RadVideoGenBatch* V, const Model& m, int p, int branch, bool stg, + bool iso) { + const RadVideoGeom& gm = V->geom; + const int64_t lane = V->lane, ppf = (int64_t)gm.lat_h * gm.lat_w; + const int64_t S = (int64_t)gm.lat_frames * ppf, A = gm.n_audio, R = kTextRows, L = m.nb; + const int64_t D = m.D, Da = m.Da; + const bool first = V->has_image != 0; + /* The video's rows take the first frame's modulation (timestep 0) or everything's: two table + * rows over the first latent frame and the rest, or the second row over all of them. */ + const int64_t vr0 = first ? 0 : 1, vn = first ? 2 : 1; + const RadOperand cuv = first ? praw(V->geom_d + RAD_VGEOM_FIRST_CU, RAD_I32, 3) + : praw(V->lat_cu, RAD_I32, 2); + const RadOperand cu1 = praw(V->lat_cu, RAD_I32, 2), cua = praw(V->lat_cu + 2, RAD_I32, 2); + const RadOperand cut = brows(m.b_rows, 2); + const RadOperand pv = praw2(V->pos, RAD_F32, 3, S), pvt = praw2(V->pos, RAD_F32, 1, S); + const RadOperand pa = praw2(V->pos + 3 * S, RAD_F32, 1, A); + auto mv = [&](int64_t l, int k, int n) { + return tab(m.b_mv, vr0, vn, L * 9 * D, l * 9 * D + k * D, n * D); + }; + auto ma = [&](int64_t l, int k, int n) { + return tab(m.b_ma, 0, 1, L * 9 * Da, l * 9 * Da + k * Da, n * Da); + }; + + RAD_ISSUE_N(c, m.op_lv, S, brow_slice(m.b_vstate, lane * m.maxS, S, kC), brows(m.a_lv.a.x, S)); + RAD_ISSUE_N(c, m.op_la, A, brow_slice(m.b_astate, lane * m.maxA, A, kAudioC), brows(m.a_la.a.x, A)); + m.pin_v.step(c, m.a_lv, m.b_hv, S); + m.pin_a.step(c, m.a_la, m.b_ha, A); + const RadOperand tv = brow_slice(m.cv.b_text, (lane * 2 + branch) * R, R, D); + const RadOperand ta = brow_slice(m.ca.b_text, (lane * 2 + branch) * R, R, Da); + + for (int64_t l = 0; l < L; ++l) { + const DitBlock& B = m.dit[(size_t)l]; + const bool g0 = l > 0; + /* ---- self-attention, gated after by gate_msa; spatio-temporal guidance takes v as is */ + RAD_ISSUE_N(c, B.m1v, S, g0 ? brows(m.b_ov, S) : RAD_NONE, g0 ? mv(l - 1, 5, 1) : RAD_NONE, + mv(l, 0, 2), RAD_NONE, cuv, brows(m.b_hv, S), brows(m.a_hv.a.x, S)); + RAD_ISSUE_N(c, B.m1a, A, g0 ? brows(m.b_oa, A) : RAD_NONE, g0 ? ma(l - 1, 5, 1) : RAD_NONE, + ma(l, 0, 2), RAD_NONE, cua, brows(m.b_ha, A), brows(m.a_ha.a.x, A)); + const bool bypass = stg && l == kStgBlock; + for (int s = 0; s < 2; ++s) { + const bool vid = s == 0; + const Attn& At = vid ? B.sv : B.sa; + const Act& in = vid ? m.a_hv : m.a_ha; + const Act& ao = vid ? m.a_aov : m.a_aoa; + const rad_buf bq = vid ? m.b_qkvv : m.b_qkva, bg = vid ? m.b_gv : m.b_ga; + const int64_t n = vid ? S : A; + in.step(c, n); + At.qkv.step(c, in, bq, n); + At.gate.step(c, in, bg, n); + if (bypass) { + RAD_ISSUE_N(c, At.op_v, n, bcol(bq, 2 * At.inner, At.inner, n), brows(ao.a.x, n)); + RAD_ISSUE_N(c, At.op_hg, n, brows(bg, n), brows(ao.a.x, n)); + } else { + attn_core(c, At, true, bq, 0, bg, ao, n, n, vid ? cu1 : cua, RAD_NONE, vid ? pv : pa, + vid ? pv : pa); + } + ao.step(c, n); + At.out.step(c, ao, vid ? m.b_ov : m.b_oa, n); + } + /* ---- text cross-attention: the query's norm gated by gate_msa, the text modulated as + * it is */ + RAD_ISSUE_N(c, B.m2v, S, brows(m.b_ov, S), mv(l, 2, 1), mv(l, 6, 2), RAD_NONE, cuv, + brows(m.b_hv, S), brows(m.a_hv.a.x, S)); + RAD_ISSUE_N(c, B.m2a, A, brows(m.b_oa, A), ma(l, 2, 1), ma(l, 6, 2), RAD_NONE, cua, + brows(m.b_ha, A), brows(m.a_ha.a.x, A)); + RAD_ISSUE_N(c, B.mtv, R, RAD_NONE, RAD_NONE, tab(m.b_mp, 0, 1, L * 2 * D, l * 2 * D, 2 * D), + RAD_NONE, cut, tv, brows(m.a_ctxv.a.x, R)); + RAD_ISSUE_N(c, B.mta, R, RAD_NONE, RAD_NONE, tab(m.b_mpa, 0, 1, L * 2 * Da, l * 2 * Da, 2 * Da), + RAD_NONE, cut, ta, brows(m.a_ctxa.a.x, R)); + for (int s = 0; s < 2; ++s) { + const bool vid = s == 0; + const Attn& At = vid ? B.tv : B.ta; + const Act& in = vid ? m.a_hv : m.a_ha; + const Act& ctx = vid ? m.a_ctxv : m.a_ctxa; + const Act& ao = vid ? m.a_aov : m.a_aoa; + const rad_buf bq = vid ? m.b_qv : m.b_qa, bkv = vid ? m.b_kvtv : m.b_kvta; + const rad_buf bg = vid ? m.b_gv : m.b_ga; + const int64_t n = vid ? S : A; + in.step(c, n); + ctx.step(c, R); + At.qkv.step(c, in, bq, n); + At.gate.step(c, in, bg, n); + At.kv.step(c, ctx, bkv, R); + attn_core(c, At, false, bq, bkv, bg, ao, n, R, vid ? cu1 : cua, cut, RAD_NONE, RAD_NONE); + ao.step(c, n); + At.out.step(c, ao, vid ? m.b_ov : m.b_oa, n); + } + if (!iso) { + /* ---- the cross-modal attentions: each stream gated by its text attention, normed for + * a2v and for v2a (both before either update), the two attentions, their gates */ + RAD_ISSUE_N(c, B.g2v, S, brows(m.b_ov, S), mv(l, 8, 1), cuv, brows(m.b_hv, S)); + RAD_ISSUE_N(c, B.g2a, A, brows(m.b_oa, A), ma(l, 8, 1), cua, brows(m.b_ha, A)); + RAD_ISSUE_N(c, B.mav, S, RAD_NONE, RAD_NONE, tab(m.b_mcv, 0, 1, L * 4 * D, l * 4 * D, 2 * D), + RAD_NONE, cu1, brows(m.b_hv, S), brows(m.a_nv.a.x, S)); + RAD_ISSUE_N(c, B.mvv, S, RAD_NONE, RAD_NONE, + tab(m.b_mcv, 0, 1, L * 4 * D, l * 4 * D + 2 * D, 2 * D), RAD_NONE, cu1, + brows(m.b_hv, S), brows(m.a_nv2.a.x, S)); + RAD_ISSUE_N(c, B.maa, A, RAD_NONE, RAD_NONE, + tab(m.b_mca, 0, 1, L * 4 * Da, l * 4 * Da, 2 * Da), RAD_NONE, cua, + brows(m.b_ha, A), brows(m.a_na.a.x, A)); + RAD_ISSUE_N(c, B.mva, A, RAD_NONE, RAD_NONE, + tab(m.b_mca, 0, 1, L * 4 * Da, l * 4 * Da + 2 * Da, 2 * Da), RAD_NONE, cua, + brows(m.b_ha, A), brows(m.a_na2.a.x, A)); + m.a_nv.step(c, S); + m.a_nv2.step(c, S); + m.a_na.step(c, A); + m.a_na2.step(c, A); + /* a2v: video queries over the soundtrack's keys, each on its time axis. */ + B.a2v.qkv.step(c, m.a_nv, m.b_qxv, S); + B.a2v.gate.step(c, m.a_nv, m.b_gxv, S); + B.a2v.kv.step(c, m.a_na, m.b_kvxa, A); + attn_core(c, B.a2v, false, m.b_qxv, m.b_kvxa, m.b_gxv, m.a_xv, S, A, cu1, cua, pvt, pa); + m.a_xv.step(c, S); + B.a2v.out.step(c, m.a_xv, m.b_ov, S); + /* v2a: the soundtrack's queries over the video's keys. */ + B.v2a.qkv.step(c, m.a_na2, m.b_qxa, A); + B.v2a.gate.step(c, m.a_na2, m.b_gxa, A); + B.v2a.kv.step(c, m.a_nv2, m.b_kvxv, S); + attn_core(c, B.v2a, false, m.b_qxa, m.b_kvxv, m.b_gxa, m.a_xa, A, S, cua, cu1, pa, pvt); + m.a_xa.step(c, A); + B.v2a.out.step(c, m.a_xa, m.b_oa, A); + RAD_ISSUE_N(c, B.gcv, S, brows(m.b_ov, S), tab(m.b_mcvg, 0, 1, L * D, l * D, D), cu1, + brows(m.b_hv, S)); + RAD_ISSUE_N(c, B.gca, A, brows(m.b_oa, A), tab(m.b_mcag, 0, 1, L * Da, l * Da, Da), cua, + brows(m.b_ha, A)); + RAD_ISSUE_N(c, B.m3v, S, RAD_NONE, RAD_NONE, mv(l, 3, 2), RAD_NONE, cuv, brows(m.b_hv, S), + brows(m.a_hv.a.x, S)); + RAD_ISSUE_N(c, B.m3a, A, RAD_NONE, RAD_NONE, ma(l, 3, 2), RAD_NONE, cua, brows(m.b_ha, A), + brows(m.a_ha.a.x, A)); + } else { + RAD_ISSUE_N(c, B.m3vg, S, brows(m.b_ov, S), mv(l, 8, 1), mv(l, 3, 2), RAD_NONE, cuv, + brows(m.b_hv, S), brows(m.a_hv.a.x, S)); + RAD_ISSUE_N(c, B.m3ag, A, brows(m.b_oa, A), ma(l, 8, 1), ma(l, 3, 2), RAD_NONE, cua, + brows(m.b_ha, A), brows(m.a_ha.a.x, A)); + } + /* ---- the feed-forwards, gated by gate_mlp in the next block's first norm */ + m.a_hv.step(c, S); + B.fv_up.step(c, m.a_hv, m.b_upv, S); + RAD_ISSUE_N(c, B.actv, S, brows(m.b_upv, S), brows(m.a_ffv.a.x, S)); + m.a_ffv.step(c, S); + B.fv_down.step(c, m.a_ffv, m.b_ov, S); + m.a_ha.step(c, A); + B.fa_up.step(c, m.a_ha, m.b_upa, A); + RAD_ISSUE_N(c, B.acta, A, brows(m.b_upa, A), brows(m.a_ffa.a.x, A)); + m.a_ffa.step(c, A); + B.fa_down.step(c, m.a_ffa, m.b_oa, A); + } + RAD_ISSUE_N(c, m.op_fnv, S, brows(m.b_ov, S), mv(L - 1, 5, 1), tab(m.b_fv, vr0, vn, 2 * D, 0, 2 * D), + RAD_NONE, cuv, brows(m.b_hv, S), brows(m.a_fv.a.x, S)); + RAD_ISSUE_N(c, m.op_fna, A, brows(m.b_oa, A), ma(L - 1, 5, 1), tab(m.b_fa, 0, 1, 2 * Da, 0, 2 * Da), + RAD_NONE, cua, brows(m.b_ha, A), brows(m.a_fa.a.x, A)); + m.pout_v.step(c, m.a_fv, m.b_vel_v[p], S); + m.pout_a.step(c, m.a_fa, m.b_vel_a[p], A); +} + +/* One denoising step: the first step's noise (and first frame), the step's tables, each + * evaluation the request's guidance needs, each modality's guided Euler step, the first frame + * restored. */ +static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + const RadVideoGeom& gm = V->geom; + const int64_t lane = V->lane, ppf = (int64_t)gm.lat_h * gm.lat_w; + const int64_t S = (int64_t)gm.lat_frames * ppf, A = gm.n_audio, L = m.nb, La = kMaxLanes; + const bool first = V->has_image != 0; + const RadOperand lane_d = praw(V->lane_d, RAD_I32, 1); + const RadOperand keep = brow_slice(m.b_vstate, lane * m.maxS, ppf, kC); + const RadOperand clean = brow_slice(m.b_first, lane * m.maxPpf, ppf, kC); + if (V->step == 0) { + RAD_ISSUE_N(c, m.op_rnd_v, S, praw(V->first_d, RAD_I32, 1), praw(V->seed, RAD_U32, 2), lane_d, + praw(V->lat_cu, RAD_I32, 2), brows(m.b_vstate, La * m.maxS)); + RAD_ISSUE_N(c, m.op_rnd_a, A, praw(V->first_d, RAD_I32, 1), praw(V->seed + 2, RAD_U32, 2), + lane_d, praw(V->lat_cu + 2, RAD_I32, 2), brows(m.b_astate, La * m.maxA)); + if (first) RAD_ISSUE_N(c, m.op_keep_first, ppf, clean, keep); + } + + /* ---- the step's tables: {0, sigma} through the eight modulation MLPs (the video's both + * rows, the rest sigma's), then each block's rows */ + RAD_ISSUE_N(c, m.op_tin0, 1, view(c, m.b_tin, RAD_F32, 1, 2)); + RAD_ISSUE_N(c, m.op_tin1, 1, praw2(V->sched + 1, RAD_F32, 1, 1), view(c, m.b_tin, RAD_F32, 1, 1, 1)); + RAD_ISSUE_N(c, m.op_tsin, 2, praw(rad_buf_ptr(c, m.b_tin), RAD_F32, 2), brows(m.b_tsin, 2)); + ada_step(c, m.ad_v, m.b_tsin, 0, 2); + for (const Ada* a : { &m.ad_a, &m.ad_p, &m.ad_pa, &m.ad_cv, &m.ad_cvg, &m.ad_ca, &m.ad_cag }) + ada_step(c, *a, m.b_tsin, 1, 1); + const int64_t D = m.D, Da = m.Da; + auto temb = [&](const Ada& a, int64_t r0, int64_t n) { + return brow_slice(a.temb, r0, n, a.k * a.d); + }; + for (int64_t l = 0; l < L; ++l) { + const DitBlock& B = m.dit[(size_t)l]; + RAD_ISSUE_N(c, B.op_tv, 2, temb(m.ad_v, 0, 2), RAD_W(B.t_v), + tab(m.b_mv, 0, 2, L * 9 * D, l * 9 * D, 9 * D)); + RAD_ISSUE_N(c, B.op_ta, 1, temb(m.ad_a, 1, 1), RAD_W(B.t_a), + tab(m.b_ma, 0, 1, L * 9 * Da, l * 9 * Da, 9 * Da)); + RAD_ISSUE_N(c, B.op_tp, 1, temb(m.ad_p, 1, 1), RAD_W(B.t_p), + tab(m.b_mp, 0, 1, L * 2 * D, l * 2 * D, 2 * D)); + RAD_ISSUE_N(c, B.op_tpa, 1, temb(m.ad_pa, 1, 1), RAD_W(B.t_pa), + tab(m.b_mpa, 0, 1, L * 2 * Da, l * 2 * Da, 2 * Da)); + RAD_ISSUE_N(c, B.op_tcv, 1, temb(m.ad_cv, 1, 1), RAD_W(B.t_cv), + tab(m.b_mcv, 0, 1, L * 4 * D, l * 4 * D, 4 * D)); + RAD_ISSUE_N(c, B.op_tcvg, 1, temb(m.ad_cvg, 1, 1), RAD_W(B.t_cvg), + tab(m.b_mcvg, 0, 1, L * D, l * D, D)); + RAD_ISSUE_N(c, B.op_tca, 1, temb(m.ad_ca, 1, 1), RAD_W(B.t_ca), + tab(m.b_mca, 0, 1, L * 4 * Da, l * 4 * Da, 4 * Da)); + RAD_ISSUE_N(c, B.op_tcag, 1, temb(m.ad_cag, 1, 1), RAD_W(B.t_cag), + tab(m.b_mcag, 0, 1, L * Da, l * Da, Da)); + } + RAD_ISSUE_N(c, m.op_fv, 2, brows(m.ad_v.emb, 2), RAD_W(m.w_fv), brows(m.b_fv, 2)); + RAD_ISSUE_N(c, m.op_fa, 1, brow_slice(m.ad_a.emb, 1, 1, Da), RAD_W(m.w_fa), brows(m.b_fa, 1)); + + /* ---- the evaluations: a term is on for either modality, each modality weighs its own */ + const float* gs = V->guidance_h; + const bool cfg = gs[kGsV] != 1.0f || gs[kGsA] != 1.0f; + const bool stg = gs[kStgV] != 0.0f || gs[kStgA] != 0.0f; + const bool iso = gs[kMsV] != 1.0f || gs[kMsA] != 1.0f; + dit_eval(c, V, m, kPassCond, 0, false, false); + if (cfg) dit_eval(c, V, m, kPassUncond, 1, false, false); + if (stg) dit_eval(c, V, m, kPassStg, 0, true, false); + if (iso) dit_eval(c, V, m, kPassIso, 0, false, true); + auto vel = [&](const rad_buf* v, int p, bool on, int64_t n) { + return on ? brows(v[p], n) : RAD_NONE; + }; + RAD_ISSUE_N(c, m.op_gv, S, vel(m.b_vel_v, kPassCond, true, S), vel(m.b_vel_v, kPassUncond, cfg, S), + vel(m.b_vel_v, kPassStg, stg, S), vel(m.b_vel_v, kPassIso, iso, S), + praw(V->guidance, RAD_F32, 4), praw(V->sched + 1, RAD_F32, 2), RAD_B(m.b_gst), + brow_slice(m.b_vstate, lane * m.maxS, S, kC)); + RAD_ISSUE_N(c, m.op_ga, A, vel(m.b_vel_a, kPassCond, true, A), vel(m.b_vel_a, kPassUncond, cfg, A), + vel(m.b_vel_a, kPassStg, stg, A), vel(m.b_vel_a, kPassIso, iso, A), + praw(V->guidance + 4, RAD_F32, 4), praw(V->sched + 4, RAD_F32, 2), RAD_B(m.b_gst), + brow_slice(m.b_astate, lane * m.maxA, A, kAudioC)); + if (first) RAD_ISSUE_N(c, m.op_keep_first, ppf, clean, keep); +} + +/* A vocoder over `rows0` input rows: each stage's sequence bounds, conv_in, the stages, the last + * activation and conv_out. */ +static void voc_step(RadCtx* c, const Voc& V, const RadVideoGenBatch* B, int64_t rows0) { + const RadOperand gd = praw(B->geom_d, RAD_I32, RAD_VGEOM_N); + auto conv = [&](const VConv& k, rad_buf x, rad_buf res, rad_buf y, int64_t R, rad_buf cu) { + RAD_ISSUE_N(c, k.op, R, brows(x, R), RAD_W(k.w), brows(cu, 2), res ? brows(res, R) : RAD_NONE, + brows(y, R), k.b ? RAD_W(k.b) : RAD_NONE); + }; + auto act = [&](const VAct& a, rad_buf x, rad_buf y, int64_t R, rad_buf cu) { + RAD_ISSUE_N(c, a.op, R, brows(x, R), RAD_W(a.alpha), RAD_W(a.beta), RAD_W(a.up), RAD_W(a.down), + brows(cu, 2), brows(y, R)); + }; + RAD_ISSUE_N(c, V.op_cu0, 2, gd, brows(V.cu[0], 2)); + conv(V.cin, V.in_buf, 0, V.avg[0], rows0, V.cu[0]); + int64_t rows = rows0; + for (size_t s = 0; s < V.st.size(); ++s) { + const VStage& St = V.st[s]; + const int64_t R = rows * St.rate; + RAD_ISSUE_N(c, St.op_cu, 2, gd, brows(V.cu[s + 1], 2)); + RAD_ISSUE_N(c, St.up.op, rows, brows(V.avg[s], rows), RAD_W(St.up.w), RAD_W(St.up.b), + brows(V.cu[s], 2), brows(V.h[s + 1], R)); + for (int j = 0; j < 3; ++j) + for (int d = 0; d < 3; ++d) { + const VUnit& U = St.u[j][d]; + const rad_buf x = d == 0 ? V.h[s + 1] : V.amp[j][s + 1]; + act(U.a1, x, V.t1[s + 1], R, V.cu[s + 1]); + conv(U.c1, V.t1[s + 1], 0, V.t2[s + 1], R, V.cu[s + 1]); + act(U.a2, V.t2[s + 1], V.t1[s + 1], R, V.cu[s + 1]); + conv(U.c2, V.t1[s + 1], x, V.amp[j][s + 1], R, V.cu[s + 1]); + } + RAD_ISSUE_N(c, St.op_sum, R, brows(V.amp[0][s + 1], R), brows(V.amp[1][s + 1], R), + brows(V.avg[s + 1], R)); + RAD_ISSUE_N(c, St.op_avg, R, brows(V.avg[s + 1], R), brows(V.amp[2][s + 1], R), + brows(V.avg[s + 1], R)); + rows = R; + } + const size_t ns = V.st.size(); + act(V.act, V.avg[ns], V.t1[ns], rows, V.cu[ns]); + conv(V.cout, V.t1[ns], 0, V.wav, rows, V.cu[ns]); +} + +/* The soundtrack, once after the last step. */ +static void step_audio(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + const int64_t A = V->geom.n_audio, lane = V->lane, Tm = mel_frames(A); + RAD_ISSUE_N(c, m.op_aden, A, brow_slice(m.b_astate, lane * m.maxA, A, kAudioC), RAD_W(m.w_amean), + RAD_W(m.w_astd), brows(m.b_aden, A)); + RAD_ISSUE_N(c, m.op_acast, A, brows(m.b_aden, A), brows(m.b_alat, A)); + RAD_ISSUE_N(c, m.op_aunpack, A, brows(m.b_alat, A), + praw(V->geom_d + RAD_VGEOM_AUDIO_VOL, RAD_I32, 3), + brows(m.b_aimg, A * kLatMel)); + int64_t H = A, W = kLatMel; + RAD_ISSUE_N(c, m.op_acin, H * W, view(c, m.b_aimg, RAD_BF16, H, W * kLatCh), RAD_W(m.w_acin), + RAD_W(m.b_acin), view(c, m.b_aa, RAD_BF16, H, W * m.aC0)); + for (const ARes& Rb : m.amid) ares_step(c, Rb, H, W, m.b_aa, m.b_ab, m.b_ac, m.b_as); + for (int lev = 2; lev >= 0; --lev) { + for (const ARes& Rb : m.aup[(size_t)(2 - lev)]) + ares_step(c, Rb, H, W, m.b_aa, m.b_ab, m.b_ac, m.b_as); + if (lev == 0) break; + const int64_t co = m.alev_c[(size_t)lev]; + const VConv& U = m.aups[(size_t)(2 - lev)]; + /* The nearest x2 upsample read by the conv, then the first time row dropped. */ + RAD_ISSUE_N(c, U.op, 4 * H * W, view(c, m.b_aa, RAD_BF16, H, W * co), RAD_W(U.w), RAD_W(U.b), + view(c, m.b_ab, RAD_BF16, 2 * H, 2 * W * co)); + const int64_t px = (2 * H - 1) * 2 * W; + RAD_ISSUE_N(c, m.aups_cp[(size_t)(2 - lev)], px, + view(c, m.b_ab, RAD_BF16, px, co, 2 * W * co), view(c, m.b_aa, RAD_BF16, px, co)); + H = 2 * H - 1; + W *= 2; + } + const int64_t C0 = m.alev_c[0]; + RAD_ISSUE_N(c, m.op_anout, H * W, view(c, m.b_aa, RAD_BF16, H * W, C0), + view(c, m.b_ab, RAD_BF16, H * W, C0)); + for (int ch = 0; ch < 2; ++ch) + RAD_ISSUE_N(c, m.op_acout[ch], H * W, view(c, m.b_ab, RAD_BF16, H, W * C0), RAD_W(m.w_acout[ch]), + RAD_W(m.b_acout[ch]), bcol(m.b_amel16, ch * kMel, kMel, Tm)); + RAD_ISSUE_N(c, m.op_amel, Tm, brows(m.b_amel16, Tm), brows(m.b_amel, Tm)); + voc_step(c, m.voc, V, Tm); + const int64_t Sw = Tm * kMelHop; + RAD_ISSUE_N(c, m.op_stft, Sw / 80, brows(m.voc.wav, Sw), RAD_W(m.w_basis), RAD_W(m.w_melb), + brows(m.b_bmel16, Sw / 80)); + RAD_ISSUE_N(c, m.op_bmel, Sw / 80, brows(m.b_bmel16, Sw / 80), brows(m.b_bmel, Sw / 80)); + voc_step(c, m.bwe, V, Sw / 80); + RAD_ISSUE_N(c, m.op_bwe, 3 * Sw, brows(m.voc.wav, Sw), brows(m.bwe.wav, 3 * Sw), + brows(m.b_audio, 3 * Sw)); + const int64_t tail = V->n_samples - 3 * Sw; + if (tail > 0) + RAD_ISSUE_N(c, m.op_tail, tail, brow_slice(m.b_audio, 3 * Sw, tail, kAudioCh)); +} + +/* One chunk of frames: chunk 0 decodes the whole video into the lane's frame store first; every + * chunk turns its frames into bytes. */ +/* The decoder over one tile's latent (b_vtlat: F x h x w voxels, `tg` that volume on the device) + * to its pixel patches at `out`. */ +static void vae_decode(RadCtx* c, const Model& m, int64_t F, int64_t h, int64_t w, + const RadOperand& tg, const RadOperand& out) { + const int64_t S = F * h * w; + RAD_ISSUE_N(c, m.op_vcin, S, brows(m.b_vtlat, S), RAD_W(m.w_vcin), RAD_W(m.b_vcin), tg, RAD_NONE, + view(c, m.b_va, RAD_BF16, S, m.vC0)); + for (const VRes& Rb : m.vmid) vres_step(c, Rb, S, tg, m.b_va, m.b_vb, m.b_vc); + int64_t T = F, Hh = h, Ww = w; + RadOperand gin = tg; + for (const VUp& U : m.vup) { + const int64_t vin = T * Hh * Ww; + RAD_ISSUE_N(c, U.op_geom, 3, tg, brows(U.geom, 3)); + RAD_ISSUE_N(c, U.op_conv, vin, view(c, m.b_va, RAD_BF16, vin, U.cin), RAD_W(U.w), RAD_W(U.b), + gin, RAD_NONE, view(c, m.b_vb, RAD_BF16, vin, U.conv_out)); + T = T * U.st - (U.st - 1); + Hh *= U.sh; + Ww *= U.sw; + const int64_t vout = T * Hh * Ww; + RAD_ISSUE_N(c, U.op_d2s, vin, view(c, m.b_vb, RAD_BF16, vin, U.conv_out), gin, + view(c, m.b_va, RAD_BF16, vout, U.cout)); + gin = brows(U.geom, 3); + for (const VRes& Rb : U.res) vres_step(c, Rb, vout, gin, m.b_va, m.b_vb, m.b_vc); + } + const int64_t vout = T * Hh * Ww, C = m.vup.back().cout; + RAD_ISSUE_N(c, m.op_vnout, vout, view(c, m.b_va, RAD_BF16, vout, C), + view(c, m.b_vb, RAD_BF16, vout, C)); + RAD_ISSUE_N(c, m.op_vcout, vout, view(c, m.b_vb, RAD_BF16, vout, C), RAD_W(m.w_vcout), + RAD_W(m.b_vcout), gin, RAD_NONE, out); +} + +/* One diffusion-decoder block over V voxels of residual `xb` (a C-wide view), the volume `geom` + * on the device and its positions already in b_dpos. */ +static void dd_block_step(RadCtx* c, const Model& m, const DdBlock& B, int64_t V, rad_buf xb, + const RadOperand& geom, bool diff) { + const int64_t C = B.C; + const RadOperand X = view(c, xb, RAD_BF16, V, C), N = view(c, m.b_dn, RAD_BF16, V, C); + const rad_buf qkv = m.b_dqkv[B.slot], gu = m.b_dg[B.slot]; + if (diff) { + RAD_ISSUE_N(c, B.op_ctx, V, view(c, m.b_dctx, RAD_BF16, V, C), RAD_W(B.w_ctx), RAD_W(B.b_ctx), + X, X); + RAD_ISSUE_N(c, B.op_mod, 1, brows(m.b_dmod, 1), RAD_W(B.w_sst), brows(m.b_dbmod, 1)); + RAD_ISSUE_N(c, B.op_n1, V, RAD_NONE, RAD_NONE, bcol(m.b_dbmod, 0, 2 * C, 1), RAD_W(B.w_n1), + brows(m.b_ddcu, 2), X, N); + } else { + RAD_ISSUE_N(c, B.op_n1, V, X, RAD_W(B.w_n1), N); + } + const int64_t gw = C / (int64_t)B.op_qkvh.size(); + for (size_t g = 0; g < B.op_qkvh.size(); ++g) { + RAD_ISSUE_N(c, B.op_qkvh[g], V, N, RAD_W(B.w_qkvh[g]), RAD_W(B.b_qkvh[g]), RAD_NONE, + brows(qkv, V)); + RAD_ISSUE_N(c, B.op_rope, V, brows(qkv, V), bcol(m.b_dpos, 0, V, 3), RAD_W(B.w_nq), + RAD_W(B.w_nk)); + RAD_ISSUE_N(c, B.op_attn, V, bcol(qkv, 0, gw, V), bcol(qkv, gw, gw, V), bcol(qkv, 2 * gw, gw, V), + geom, diff ? bcol(m.b_dao, (int64_t)g * gw, gw, V) : N); + } + RAD_ISSUE_N(c, B.op_o, V, diff ? view(c, m.b_dao, RAD_BF16, V, C) : N, RAD_W(B.w_o), RAD_W(B.b_o), + X, X); + if (diff) + RAD_ISSUE_N(c, B.op_n2, V, RAD_NONE, RAD_NONE, bcol(m.b_dbmod, 2 * C, 2 * C, 1), RAD_W(B.w_n2), + brows(m.b_ddcu, 2), X, N); + else + RAD_ISSUE_N(c, B.op_n2, V, X, RAD_W(B.w_n2), N); + for (int64_t r0 = 0; r0 < V; r0 += B.chunk) { + const int64_t n = std::min(B.chunk, V - r0); + const RadOperand Nr = view(c, m.b_dn, RAD_BF16, n, C, r0 * C); + RAD_ISSUE_N(c, B.op_gu, n, Nr, RAD_W(B.w_gu), brows(gu, n)); + RAD_ISSUE_N(c, B.op_act, n, brows(gu, n), view(c, m.b_da, RAD_BF16, n, B.ff)); + RAD_ISSUE_N(c, B.op_down, n, view(c, m.b_da, RAD_BF16, n, B.ff), RAD_W(B.w_down), + view(c, m.b_dmo, RAD_BF16, n, C)); + const RadOperand Xr = view(c, xb, RAD_BF16, n, C, r0 * C); + RAD_ISSUE_N(c, B.op_add2, n, Xr, view(c, m.b_dmo, RAD_BF16, n, C), Xr); + } +} + +/* The diffusion decoder over the lane's latent (b_vlat, cast and denormalised) into the tile store + * (chunk 0 of a request that named it); the chunks then stitch from the store with op_dst. */ +static void step_ddec(RadCtx* c, const RadVideoGenBatch* V, const Model& m) { + const RadVideoGeom& gm = V->geom; + const int64_t h = gm.lat_h, w = gm.lat_w, F = gm.lat_frames, A = h * w, S = F * A; + const RadOperand gd = praw(V->geom_d, RAD_I32, RAD_VGEOM_N); + /* The latent and its last frame twice more. */ + RAD_ISSUE_N(c, m.op_dpad, S, brows(m.b_vlat, S), view(c, m.b_dz, RAD_BF16, S, kC)); + for (int64_t g = 0; g < kDdGhost; ++g) + RAD_ISSUE_N(c, m.op_dpad, A, view(c, m.b_vlat, RAD_BF16, A, kC, (F - 1) * A * kC), + view(c, m.b_dz, RAD_BF16, A, kC, (S + g * A) * kC)); + for (const DdStage& St : m.dst) RAD_ISSUE_N(c, St.op_geom, 3, gd, brows(St.geom, 3)); + RAD_ISSUE_N(c, m.op_dtgeom, 3, gd, brows(m.b_dtg, 3)); + RAD_ISSUE_N(c, m.op_dgrid, kDdMaxTiles, brows(m.b_dtg, 3), brows(m.b_dgrid, kDdMaxTiles)); + RAD_ISSUE_N(c, m.op_dtin, 1, brows(m.b_dtin, 1)); + RAD_ISSUE_N(c, m.op_dtsin, 1, brows(m.b_dtin, 1), brows(m.b_dtsin, 1)); + RAD_ISSUE_N(c, m.op_dt1, 1, brows(m.b_dtsin, 1), RAD_W(m.dw_t1), RAD_W(m.db_t1), RAD_NONE, + brows(m.b_dth, 1)); + RAD_ISSUE_N(c, m.op_dts, 1, brows(m.b_dth, 1), brows(m.b_dths, 1)); + RAD_ISSUE_N(c, m.op_dt2, 1, brows(m.b_dths, 1), RAD_W(m.dw_t2), RAD_W(m.db_t2), RAD_NONE, + brows(m.b_dtemb, 1)); + RAD_ISSUE_N(c, m.op_das, 1, brows(m.b_dtemb, 1), brows(m.b_dtes, 1)); + RAD_ISSUE_N(c, m.op_dad, 1, brows(m.b_dtes, 1), RAD_W(m.dw_ad), RAD_W(m.db_ad), RAD_NONE, + brows(m.b_dmod, 1)); + RAD_ISSUE_N(c, m.op_ddcu, 2, brows(m.b_ddcu, 2)); + RAD_ISSUE_N(c, m.op_dsig, 1, brows(m.b_dsig, 1)); + + /* ---- stages 0..2 over the whole latent into the feature volume */ + int64_t T = F + kDdGhost, Hh = h, Ww = w; + const int64_t V0 = T * Hh * Ww; + RAD_ISSUE_N(c, m.op_dcin, V0, view(c, m.b_dz, RAD_BF16, V0, kC), RAD_W(m.dw_cin), RAD_W(m.db_cin), + RAD_NONE, view(c, m.b_dx, RAD_BF16, V0, 2048)); + for (int s = 0; s < 3; ++s) { + const DdStage& St = m.dst[(size_t)s]; + const int64_t Vs = T * Hh * Ww; + const RadOperand g = brows(St.geom, 3); + RAD_ISSUE_N(c, St.op_pos, Vs, g, bcol(m.b_dpos, 0, Vs, 3)); + for (const DdBlock& B : St.blk) dd_block_step(c, m, B, Vs, m.b_dx, g, false); + const int64_t P = St.st * St.sh * St.sw * St.cout; + const rad_buf scratch = m.b_dqkv[s]; + RAD_ISSUE_N(c, St.op_proj, Vs, view(c, m.b_dx, RAD_BF16, Vs, St.C), RAD_W(St.w_up), + RAD_W(St.b_up), RAD_NONE, view(c, scratch, RAD_BF16, Vs, P)); + T = T * St.st - (St.st - 1); + Hh *= St.sh; + Ww *= St.sw; + const rad_buf dest = s < 2 ? m.b_dx : m.b_dfeat; + RAD_ISSUE_N(c, St.op_d2s, Vs, view(c, scratch, RAD_BF16, Vs, P), g, + view(c, dest, RAD_BF16, T * Hh * Ww, St.cout)); + } + const int64_t V3 = T * Hh * Ww; + + /* ---- per tile: stage 3, then the diffusion step into the store */ + const DdStage& S3 = m.dst[3]; + const std::vector tl = dd_tiles(4 * F - 3, Hh, Ww); + const int32_t* rows = (const int32_t*)rad_buf_ptr(c, m.b_dgrid); + int64_t off = 0; + for (size_t k = 0; k < tl.size() && k < (size_t)kDdMaxTiles; ++k) { + const DdTile& t = tl[k]; + const int64_t V4 = t.t * t.h * t.w; + const RadOperand tg = praw(rows + 8 * k, RAD_I32, 3); + RAD_ISSUE_N(c, m.op_dcrop, V4, view(c, m.b_dfeat, RAD_BF16, V3, 512), brows(S3.geom, 3), + praw(rows + 8 * k, RAD_I32, 6), view(c, m.b_d4, RAD_BF16, V4, 512)); + RAD_ISSUE_N(c, S3.op_pos, V4, tg, bcol(m.b_dpos, 0, V4, 3)); + for (const DdBlock& B : S3.blk) dd_block_step(c, m, B, V4, m.b_d4, tg, false); + const int64_t P = S3.st * S3.sh * S3.sw * S3.cout; + RAD_ISSUE_N(c, S3.op_proj, V4, view(c, m.b_d4, RAD_BF16, V4, 512), RAD_W(S3.w_up), + RAD_W(S3.b_up), RAD_NONE, view(c, m.b_dqkv[2], RAD_BF16, V4, P)); + const int64_t drop = t.origin ? 1 : 0, Fc = 2 * t.t - drop; + RAD_ISSUE_N(c, t.origin ? S3.op_d2s : S3.op_d2s_keep, V4, + view(c, m.b_dqkv[2], RAD_BF16, V4, P), tg, + view(c, m.b_dctx, RAD_BF16, Fc * 4 * t.h * t.w, 256)); + const int64_t F5 = Fc - (t.trailing ? 2 * kDdGhostCells : 0), V5 = F5 * 4 * t.h * t.w; + RAD_ISSUE_N(c, m.op_dg5[(t.origin ? 2 : 0) + (t.trailing ? 1 : 0)], 3, tg, brows(m.b_dg5, 3)); + const RadOperand g5 = brows(m.b_dg5, 3); + RAD_ISSUE_N(c, m.op_dpos5, V5, g5, bcol(m.b_dpos, 0, V5, 3)); + RAD_ISSUE_N(c, m.op_dz, V5, brows(m.b_dxt, V5)); + RAD_ISSUE_N(c, m.op_dnoise[k], V5, brows(m.b_dsig, 1), praw(V->seed, RAD_U32, 2), + brows(m.b_dxt, V5)); + RAD_ISSUE_N(c, m.op_dxcast, V5, brows(m.b_dxt, V5), brows(m.b_dxb, V5)); + RAD_ISSUE_N(c, m.op_dxin, V5, brows(m.b_dxb, V5), RAD_W(m.dw_xin), RAD_W(m.db_xin), RAD_NONE, + view(c, m.b_ddh, RAD_BF16, V5, 256)); + for (const DdBlock& B : m.dblk) dd_block_step(c, m, B, V5, m.b_ddh, g5, true); + RAD_ISSUE_N(c, m.op_dnout, V5, view(c, m.b_ddh, RAD_BF16, V5, 256), RAD_W(m.dw_nout), + view(c, m.b_dn, RAD_BF16, V5, 256)); + RAD_ISSUE_N(c, m.op_ddout, V5, view(c, m.b_dn, RAD_BF16, V5, 256), RAD_W(m.dw_cout), + RAD_W(m.db_cout), RAD_NONE, view(c, m.b_vtiles, RAD_BF16, V5, kPixC, off * kPixC)); + off += V5; + } +} + +/* Chunk 0 decodes the whole video into the lane's tile store, a tile at a time (the boxes made on + * the device by tile_grid, their sizes and store offsets known here); every chunk stitches its + * frames to bytes. */ +static void step_video(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + const RadVideoGeom& gm = V->geom; + const int64_t lane = V->lane, h = gm.lat_h, w = gm.lat_w, F = gm.lat_frames, S = F * h * w; + const int64_t Fo = m.vAt * F + m.vBt, sc = m.vAhw; + const bool tiled = vae_tiled(h, w); + const std::vector tl = vae_tiles(h, w); + int64_t store = 0; + for (const VaeTile& t : tl) store += Fo * t.h * sc * t.w * sc; + const RadOperand gd = praw(V->geom_d, RAD_I32, RAD_VGEOM_N); + const bool diffusion = V->decoder == 1 && m.ddec; + if (V->chunk == 0) { + RAD_ISSUE_N(c, m.op_vlat, S, brow_slice(m.b_vstate, lane * m.maxS, S, kC), brows(m.b_vlat, S)); + RAD_ISSUE_N(c, m.op_vden, S, brows(m.b_vlat, S), RAD_W(m.vd_mean), RAD_W(m.vd_std), + brows(m.b_vlat, S)); + } + if (V->chunk == 0 && diffusion) step_ddec(c, V, m); + if (V->chunk == 0 && !diffusion) { + const RadOperand g0 = praw(V->geom_d, RAD_I32, 3); + RAD_ISSUE_N(c, tiled ? m.op_vgrid : m.op_vgrid1, m.maxTiles, g0, brows(m.b_vgrid, m.maxTiles)); + const int32_t* rows = (const int32_t*)rad_buf_ptr(c, m.b_vgrid); + int64_t off = 0; + for (size_t k = 0; k < tl.size(); ++k) { + const int64_t tv = F * tl[k].h * tl[k].w, n = Fo * tl[k].h * sc * tl[k].w * sc; + const RadOperand tg = praw(rows + 8 * k, RAD_I32, 3); + RAD_ISSUE_N(c, m.op_vcrop, tv, brows(m.b_vlat, S), g0, praw(rows + 8 * k, RAD_I32, 6), + brows(m.b_vtlat, tv)); + vae_decode(c, m, F, tl[k].h, tl[k].w, tg, + view(c, m.b_vtiles, RAD_BF16, n, kPixC, off * kPixC)); + off += n; + } + } + const int64_t R = (int64_t)V->n_frames_out * h * kScale, Wpx = w * kScale; + RAD_ISSUE_N(c, m.op_vf0, 1, gd, brows(m.b_vf0, 1)); + if (diffusion) { + int64_t drows = 0; + for (const DdTile& t : dd_tiles(4 * F - 3, 4 * h, 4 * w)) + drows += (2 * (t.t - (t.trailing ? kDdGhostCells : 0)) - (t.origin ? 1 : 0)) * 4 * t.h * t.w; + RAD_ISSUE_N(c, m.op_dtgeom, 3, gd, brows(m.b_dtg, 3)); + RAD_ISSUE_N(c, m.op_dst, R, brows(m.b_vtiles, drows), brows(m.b_dtg, 3), brows(m.b_vf0, 1), + view(c, m.b_frames, RAD_U8, R, Wpx * 3)); + return; + } + RAD_ISSUE_N(c, tiled ? m.op_vst : m.op_vst1, R, brows(m.b_vtiles, store), + praw(V->geom_d, RAD_I32, 3), brows(m.b_vf0, 1), view(c, m.b_frames, RAD_U8, R, Wpx * 3)); +} + +/* The latent upscale: the clean small latent through the upsampler to the full size, both latents + * re-noised to the second stage's first sigma with streams of their own, a first frame kept + * clean. */ +static void step_upscale(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + const RadVideoGeom& s = V->geom_from; + const RadVideoGeom& d = V->geom; + const int64_t lane = V->lane, F = d.lat_frames, C = m.uC, hs = s.lat_h, ws = s.lat_w; + const int64_t ppf = (int64_t)d.lat_h * d.lat_w, vs = F * hs * ws, vd = (int64_t)F * ppf; + const RadOperand gsrc = praw(V->geom_d + RAD_VGEOM_UP_SRC, RAD_I32, 3); + const RadOperand gdst = praw(V->geom_d + RAD_VGEOM_UP_DST, RAD_I32, 3); + const RadOperand st = RAD_B(m.b_ust); + const RadOperand lat = brow_slice(m.b_vstate, lane * m.maxS, vs, kC); + RAD_ISSUE_N(c, m.op_uden, vs, lat, RAD_W(m.vd_mean), RAD_W(m.vd_std), brows(m.b_uden, vs)); + RAD_ISSUE_N(c, m.op_ucast, vs, brows(m.b_uden, vs), brows(m.b_uin, vs)); + auto x = [&](rad_buf bf, int64_t v) { return view(c, bf, RAD_BF16, v, C); }; + RAD_ISSUE_N(c, m.op_ucin, vs, brows(m.b_uin, vs), RAD_W(m.u_cinw), RAD_W(m.u_cinb), gsrc, RAD_NONE, + x(m.b_ua, vs)); + RAD_ISSUE_N(c, m.op_unin, vs, x(m.b_ua, vs), RAD_W(m.u_ninw), RAD_W(m.u_ninb), RAD_NONE, st, + x(m.b_ua, vs)); + auto blocks = [&](const std::vector& list, int64_t v, const RadOperand& g) { + for (const URes& U : list) { + RAD_ISSUE_N(c, U.op_c1, v, x(m.b_ua, v), RAD_W(U.c1w), RAD_W(U.c1b), g, RAD_NONE, + x(m.b_ub, v)); + RAD_ISSUE_N(c, U.op_n1, v, x(m.b_ub, v), RAD_W(U.n1w), RAD_W(U.n1b), RAD_NONE, st, + x(m.b_ub, v)); + RAD_ISSUE_N(c, U.op_c2, v, x(m.b_ub, v), RAD_W(U.c2w), RAD_W(U.c2b), g, RAD_NONE, + x(m.b_uc, v)); + RAD_ISSUE_N(c, U.op_n2, v, x(m.b_uc, v), RAD_W(U.n2w), RAD_W(U.n2b), RAD_NONE, st, + x(m.b_uc, v)); + RAD_ISSUE_N(c, U.op_add, v, x(m.b_uc, v), x(m.b_ua, v), x(m.b_ua, v)); + RAD_ISSUE_N(c, U.op_act, v, x(m.b_ua, v), x(m.b_ua, v)); + } + }; + blocks(m.u_pre, vs, gsrc); + /* Each frame's Conv2d to 4 C channels, then the pixel shuffle over the volume. */ + const int64_t fr = hs * ws; + for (int64_t f = 0; f < F; ++f) + RAD_ISSUE_N(c, m.op_uup, fr, view(c, m.b_ua, RAD_BF16, hs, ws * C, f * fr * C), RAD_W(m.u_upw), + RAD_W(m.u_upb), view(c, m.b_ub, RAD_BF16, hs, ws * 4 * C, f * fr * 4 * C)); + RAD_ISSUE_N(c, m.op_ud2s, vs, view(c, m.b_ub, RAD_BF16, vs, 4 * C), gsrc, x(m.b_ua, vd)); + blocks(m.u_post, vd, gdst); + RAD_ISSUE_N(c, m.op_ucout, vd, x(m.b_ua, vd), RAD_W(m.u_coutw), RAD_W(m.u_coutb), gdst, RAD_NONE, + brows(m.b_uout, vd)); + RAD_ISSUE_N(c, m.op_unorm, vd, brows(m.b_uout, vd), RAD_W(m.vd_mean), RAD_W(m.vd_std), + brows(m.b_uout, vd)); + const RadOperand full = brow_slice(m.b_vstate, lane * m.maxS, vd, kC); + RAD_ISSUE_N(c, m.op_uf32, vd, brows(m.b_uout, vd), full); + const bool first = V->has_image != 0; + const RadOperand keep = brow_slice(m.b_vstate, lane * m.maxS, ppf, kC); + const RadOperand clean = brow_slice(m.b_first, lane * m.maxPpf, ppf, kC); + if (first) RAD_ISSUE_N(c, m.op_ufirst, ppf, keep, clean); + RAD_ISSUE_N(c, m.op_urnv, vd, praw(V->sched + 1, RAD_F32, 1), praw(V->seed, RAD_U32, 2), full); + RAD_ISSUE_N(c, m.op_urna, d.n_audio, praw(V->sched + 4, RAD_F32, 1), praw(V->seed + 2, RAD_U32, 2), + brow_slice(m.b_astate, lane * m.maxA, d.n_audio, kAudioC)); + if (first) RAD_ISSUE_N(c, m.op_ukeep, ppf, clean, keep); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (!batch->gen || !batch->vgen_b) { + rad_step_fail(c, "ltx2 is a video generator and runs its generator passes only"); + return; + } + switch (batch->gen) { + case RAD_GEN_PASS_VCOND: step_cond(c, batch, m); return; + case RAD_GEN_PASS_VSTEP: step_dit(c, batch, m); return; + case RAD_GEN_PASS_ADECODE: step_audio(c, batch, m); return; + case RAD_GEN_PASS_VDECODE: step_video(c, batch, m); return; + case RAD_GEN_PASS_VUPSCALE: + if (!m.ups) { + rad_step_fail(c, "ltx2: an upscale pass, and this container has no latent upsampler"); + return; + } + step_upscale(c, batch, m); + return; + default: + rad_step_fail(c, "ltx2: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +/* The rows of the largest pass: a step of the longest video at the largest size. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->gen_rows = std::max(max_step_rows(), 2 * (int64_t)kTextRows); + out->gen_video = 1; + return RAD_OK; +} + +} /* namespace ltx2 */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(ltx2) +RAD_ARCH_PLUGIN(ltx2, "ltx2", "", "0.1.0", + "LTX-2.5 (t2va, i2va): a Gemma 4 text encoder and connectors, the duration head, a " + "22B dual-stream audio-video diffusion transformer with four-way guidance, the " + "causal 3D video VAE (tiled past the default canvas) and the diffusion decoder, the " + "audio VAE with a BigVGAN vocoder and bandwidth extension, the x2 latent upsampler; " + "bf16 or block-fp8 linears") + +extern "C" int64_t rad_arch_video_positions(int which, const RadVideoGeom* g, float* pos, + int64_t cap) { + if (!g || g->n_text != ltx2::kTextRows) return RAD_E_INVAL; + if (which == RAD_VPOS_STEP) return ltx2::positions(g, pos, cap); + if (which == RAD_VPOS_DECODE) return 1; + return RAD_E_INVAL; +} +#endif diff --git a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp index 97f6ed5e..d30c4b58 100644 --- a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp +++ b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp @@ -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; } diff --git a/arch/qwenimage21/qwenimage21.cpp b/arch/qwenimage21/qwenimage21.cpp index ebce7b1b..70b558b5 100644 --- a/arch/qwenimage21/qwenimage21.cpp +++ b/arch/qwenimage21/qwenimage21.cpp @@ -47,6 +47,7 @@ #include #include #include +#include #include #include @@ -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 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 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 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> 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 { diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index d3bf0fa8..236f2c4c 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -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; } diff --git a/core/config.cpp b/core/config.cpp index c3eeb23e..56c2f91a 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -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)" }, diff --git a/core/engine.cpp b/core/engine.cpp index c2625599..1b15d259 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -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()); } diff --git a/core/engine_probe.cpp b/core/engine_probe.cpp index bba87b21..1d7861ee 100644 --- a/core/engine_probe.cpp +++ b/core/engine_probe.cpp @@ -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"); diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index aa81c61f..800c549d 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -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()); + else if (e.is_number()) *s += fmt("%.17g", e.get()); + else if (e.is_string()) *s += e.get(); + else if (e.is_boolean()) *s += e.get() ? "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()); 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()); - else if (e.is_number()) s += fmt("%.17g", e.get()); - else if (e.is_string()) s += e.get(); - else if (e.is_boolean()) s += e.get() ? "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& 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& 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 srcs; diff --git a/core/gen/driver.cpp b/core/gen/driver.cpp index 500194b9..c4d09ab0 100644 --- a/core/gen/driver.cpp +++ b/core/gen/driver.cpp @@ -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& 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 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(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(ri, R_SRC); G.rope = dptr(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(R_LANE); G.flags = dptr(ri, R_FLAGS); G.seed = dptr(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(R_TOK); int32_t* pos = hptr(R_POS); int32_t* rope = hptr(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& bt = kv_->block_table(c.seq, kv_group_); - int32_t* slot = hptr(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 no_bt; + const std::vector& bt = joint() ? no_bt : kv_->block_table(c.seq, kv_group_); + if (joint()) { + std::memcpy(hptr(R_ROPEF), c.lay.rope_f.data(), (size_t)(4 * P) * 4); + reg_[R_ROPEF].used = 4 * P * 4; + int32_t* vcu = hptr(R_VCU); + vcu[0] = 0; + vcu[1] = (int32_t)T_valid; + reg_[R_VCU].used = 2 * 4; + } else { + int32_t* slot = hptr(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(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(R_USED)[0] = (int32_t)P; + reg_[R_USED].used = 4; } - reg_[R_SLOT].used = P * 4; - int32_t* btab = hptr(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(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{}; + /* The joint layout's conditioning goes to every lane of the request. */ + host_lanes_ = inp || joint() ? j.lanes : std::vector{}; /* The lanes on the device too: an op copies the inpainting latent and mask into each. */ if (!host_lanes_.empty()) { std::memcpy(hptr(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(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(ri, R_VCU); + G.rope = nullptr; + G.rope_f = dptr(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& 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(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(max_q, (int32_t)rows); max_ctx = std::max(max_ctx, (int32_t)e.j->cond[e.branch].lay.rows); - pitch = std::max(pitch, (int64_t)kv_->block_table(e.j->cond[e.branch].seq, kv_group_).size()); + if (!joint()) + pitch = std::max(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(R_SRC); + int32_t* icu = hptr(R_ICU); + int32_t* irows = hptr(R_IROWS); + int32_t* mcu = hptr(R_MCU); + float* ropef = hptr(R_ROPEF); + int64_t img = 0; + if (joint()) icu[0] = 0; int32_t* cu = hptr(R_CU); int32_t* pos = hptr(R_POS); int32_t* tok = hptr(R_TOK); @@ -731,9 +831,37 @@ const RadBatch* Driver::build_denoise(const std::vector& 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& 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& 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& 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(R_MROWS); + int32_t* msrc = hptr(R_MSRC); + int32_t* mccu = hptr(R_MCCU); + float* mrope = hptr(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& take, int step G.inpaint = 0; G.n_lane = 0; G.lane_h = nullptr; - G.rope = dptr(ri, R_GROPE); + G.rope = joint() ? nullptr : dptr(ri, R_GROPE); G.lane_dh = hptr(R_LANE); + if (joint()) { + G.src = dptr(ri, R_SRC); + G.n_img = n_img; + G.img_cu = dptr(ri, R_ICU); + G.img_rows = dptr(ri, R_IROWS); + G.mode_cu = dptr(ri, R_MCU); + G.rope_f = dptr(ri, R_ROPEF); + G.slot_mapping = nullptr; + G.mode_rows = dptr(ri, R_MROWS); + G.mode_src = dptr(ri, R_MSRC); + G.mode_ccu = dptr(ri, R_MCCU); + G.n_mode_h = host_nmode_; + G.mode_rope_f = dptr(ri, R_MROPE); + } } pass_.kind = RAD_GEN_PASS_DENOISE; return &out_[0]; diff --git a/core/gen/driver.h b/core/gen/driver.h index 79c51fff..6bd715d6 100644 --- a/core/gen/driver.h +++ b/core/gen/driver.h @@ -75,6 +75,7 @@ private: bool have_kv = false; bool encoded = false; std::vector rope_img; /* [3, image tokens]: the image's rows at this sequence */ + std::vector 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 T* hptr(int r) const { return reinterpret_cast(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& 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 host_bidi_, host_px_, host_lanes_; + int64_t host_nmode_[3] = { 0, 0, 0 }; mutable std::mutex mu_; std::deque> jobs_; /* arrival order */ diff --git a/core/gen/gen.cpp b/core/gen/gen.cpp index 8116f29f..89e7eb2b 100644 --- a/core/gen/gen.cpp +++ b/core/gen/gen.cpp @@ -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>& 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 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>& ref_hw, Layout* out, std::string* why) { diff --git a/core/gen/gen.h b/core/gen/gen.h index 9a7d2980..6ad9af96 100644 --- a/core/gen/gen.h +++ b/core/gen/gen.h @@ -129,6 +129,11 @@ struct Layout { std::vector seg; /* [n_seg + 1] */ std::vector 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 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>& 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 */ diff --git a/core/gen/video.h b/core/gen/video.h index efd4928b..eb0daf14 100644 --- a/core/gen/video.h +++ b/core/gen/video.h @@ -10,6 +10,7 @@ #include "rad_core.h" #include +#include #include #include #include @@ -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 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 rgb; }; @@ -49,7 +51,8 @@ public: std::atomic 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 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 image; + /* The decoder (RadVideoGenDecl::decoders) by its index; 0 the model's default. */ + int32_t decoder = 0; std::shared_ptr 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 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 */ diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp index 08f28d25..e702188c 100644 --- a/core/gen/video_driver.cpp +++ b/core/gen/video_driver.cpp @@ -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 #include @@ -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 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 flow_sigmas(const RadVideoGenDecl& d, int32_t n, int64_t tokens) { + std::vector 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(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED)); frames_host_ = static_cast(rad_dev_alloc(frames_bytes_, RAD_MEM_HOST_PINNED)); audio_host_ = static_cast(rad_dev_alloc(audio_bytes_, RAD_MEM_HOST_PINNED)); - if (!host_ || !frames_host_ || !audio_host_) { + duration_host_ = static_cast(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(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(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(d.min_chunks, std::min(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(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 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 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 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(); - 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(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 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(R_LANE) = j.lane; *hptr(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(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(ri, R_UP); + V.guidance_h = j.guidance; + V.guidance = dptr(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(R_TOK); int32_t* pos = hptr(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(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& img = j.req->image; + if (!img.empty()) { + uint16_t* px = hptr(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(R_TV); float* ta = hptr(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((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; diff --git a/core/gen/video_driver.h b/core/gen/video_driver.h index c1dd0da6..2962d229 100644 --- a/core/gen/video_driver.h +++ b/core/gen/video_driver.h @@ -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 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 T* hptr(int r) const { return reinterpret_cast(host_ + reg_[r].off); } template 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 rungs_; /* decl_.rungs points here */ + std::vector refine_rungs_; /* decl_.refine_rungs */ + std::string default_negative_; + std::vector decoder_names_; /* RadVideoGenDecl::decoders */ + std::vector 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 rb_; std::vector out_; /* one per rank */ diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index 179e9e86..820e1abb 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -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; diff --git a/core/mm/imaging.cpp b/core/mm/imaging.cpp index 585e6438..fb8e2943 100644 --- a/core/mm/imaging.cpp +++ b/core/mm/imaging.cpp @@ -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 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]; diff --git a/core/mm/imaging.h b/core/mm/imaging.h index 637f0e13..5457ace6 100644 --- a/core/mm/imaging.h +++ b/core/mm/imaging.h @@ -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); diff --git a/core/mm/media.cpp b/core/mm/media.cpp index 7ba705cd..8eb1e048 100644 --- a/core/mm/media.cpp +++ b/core/mm/media.cpp @@ -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*, 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 */ diff --git a/core/mm/media.h b/core/mm/media.h index 8473accb..27ef41c6 100644 --- a/core/mm/media.h +++ b/core/mm/media.h @@ -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* 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 */ diff --git a/core/rad_core.h b/core/rad_core.h index a0dab54a..c552cf73 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -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 sigmas; } gen_str; bool is_generator() const { return generator.layout != 0; } @@ -392,6 +393,11 @@ public: struct VideoGenStrings { std::string name, tmpl; std::vector rungs; /* RadVideoGenDecl::rungs; the declaration's pointer is null */ + std::vector refine_rungs; + std::string default_negative; + /* RadVideoGenDecl::decoders, one name each, and their largest frames (0: max_area). */ + std::vector decoders; + std::vector 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 */ diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp index abc5443f..da0d20ce 100644 --- a/core/runtime/ctx.cpp +++ b/core/runtime/ctx.cpp @@ -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; } diff --git a/core/runtime/ctx.h b/core/runtime/ctx.h index 9ef3a898..66daed98 100644 --- a/core/runtime/ctx.h +++ b/core/runtime/ctx.h @@ -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_; } diff --git a/core/sched/metrics.h b/core/sched/metrics.h index ce0218ed..801cec72 100644 --- a/core/sched/metrics.h +++ b/core/sched/metrics.h @@ -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 */ diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index ffb88f74..b2fac3e8 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -1599,7 +1599,10 @@ const RadBatch* Scheduler::step() { /* ------------------------------------------------------------------ media */ bool Scheduler::prefill_continues() const { std::lock_guard 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(); diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index 803aab0e..06aa8711 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -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 */ diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 68ef685b..eb52ea51 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -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; diff --git a/core/server/iface.h b/core/server/iface.h index ac1d9968..e492463a 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -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 decoders; + std::vector decoder_max_area; }; class IVideoGen { diff --git a/core/server/images.cpp b/core/server/images.cpp index 8d953c5f..f8c888ab 100644 --- a/core/server/images.cpp +++ b/core/server/images.cpp @@ -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 on_white(const std::vector& 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(); - 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(); + 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(); std::vector> 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(1, (int32_t)(f.w * k)); + rh = std::max(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 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& 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 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 rgb = on_white(px, im.w, im.h); s = mm::encode_image(rgb.data(), im.w, im.h, 3, fmt, comp, &file, why); } else { diff --git a/core/server/oai.cpp b/core/server/oai.cpp index 692368e4..85477067 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include 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>* 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 "__": 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 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 __)"); + 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)); diff --git a/core/server/oai.h b/core/server/oai.h index 4ea77023..ffbf5538 100644 --- a/core/server/oai.h +++ b/core/server/oai.h @@ -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 ("__") to its namespace and name, which a function_call item reports + * apart. Empty for the other shapes. */ + std::map> 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 "__", 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>* 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. */ diff --git a/core/server/server.cpp b/core/server/server.cpp index d7719961..d72dc82d 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -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 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 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 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> 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); diff --git a/core/server/server.h b/core/server/server.h index 12360f1f..f1cded21 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -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 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 speech_sessions_{0}; std::atomic 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 diff --git a/core/server/videos.cpp b/core/server/videos.cpp index 94f48633..b1de899f 100644 --- a/core/server/videos.cpp +++ b/core/server/videos.cpp @@ -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 #include #include +#include #include #include #include @@ -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 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().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(); - 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(); + else if (v.is_object() && v.contains("image_url") && v["image_url"].is_string()) + u = v["image_url"].get(); + 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(); + 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() != "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() != 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() == "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 r = std::make_unique(); 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 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(); + 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* 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 j) { std::lock_guard 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 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; diff --git a/core/text/chat.cpp b/core/text/chat.cpp index 2986dc5e..076b3820 100644 --- a/core/text/chat.cpp +++ b/core/text/chat.cpp @@ -10,6 +10,7 @@ #include #include +#include #include 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(); + } 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(); + } + } 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 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); diff --git a/core/util/rad_util.cpp b/core/util/rad_util.cpp index 76fbdf8b..bef28516 100644 --- a/core/util/rad_util.cpp +++ b/core/util/rad_util.cpp @@ -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" : ""; diff --git a/data/recipes/flux-3-klein-fp8.recipe b/data/recipes/flux-3-klein-fp8.recipe new file mode 100644 index 00000000..a44c6cfc --- /dev/null +++ b/data/recipes/flux-3-klein-fp8.recipe @@ -0,0 +1,24 @@ +# flux-3-klein-fp8.recipe -- FLUX.3 [klein] (or its base) with block-scaled fp8 linears. +# +# rad-convert --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 diff --git a/data/recipes/krea-2-bf16.recipe b/data/recipes/krea-2-bf16.recipe new file mode 100644 index 00000000..a6657048 --- /dev/null +++ b/data/recipes/krea-2-bf16.recipe @@ -0,0 +1,23 @@ +# krea-2-bf16.recipe -- Krea 2 (Raw or Turbo) at bf16. +# +# rad-convert --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 diff --git a/data/recipes/krea-2-fp8.recipe b/data/recipes/krea-2-fp8.recipe new file mode 100644 index 00000000..330219e4 --- /dev/null +++ b/data/recipes/krea-2-fp8.recipe @@ -0,0 +1,41 @@ +# krea-2-fp8.recipe -- Krea 2 (Raw or Turbo) with block-scaled fp8 linears. +# +# rad-convert --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 diff --git a/data/recipes/ltx-2.5-bf16.recipe b/data/recipes/ltx-2.5-bf16.recipe new file mode 100644 index 00000000..27eb7ba2 --- /dev/null +++ b/data/recipes/ltx-2.5-bf16.recipe @@ -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 --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 diff --git a/data/recipes/ltx-2.5-fp8.recipe b/data/recipes/ltx-2.5-fp8.recipe new file mode 100644 index 00000000..74d96867 --- /dev/null +++ b/data/recipes/ltx-2.5-fp8.recipe @@ -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 --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 diff --git a/deploy/compose/flux-3-klein.yaml b/deploy/compose/flux-3-klein.yaml new file mode 100644 index 00000000..b3214063 --- /dev/null +++ b/deploy/compose/flux-3-klein.yaml @@ -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 diff --git a/deploy/compose/krea-2-raw.yaml b/deploy/compose/krea-2-raw.yaml new file mode 100644 index 00000000..f65e554a --- /dev/null +++ b/deploy/compose/krea-2-raw.yaml @@ -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 diff --git a/deploy/compose/krea-2-turbo.yaml b/deploy/compose/krea-2-turbo.yaml new file mode 100644 index 00000000..87b6f3cc --- /dev/null +++ b/deploy/compose/krea-2-turbo.yaml @@ -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 diff --git a/deploy/compose/ltx-2.5.yaml b/deploy/compose/ltx-2.5.yaml new file mode 100644 index 00000000..0c737922 --- /dev/null +++ b/deploy/compose/ltx-2.5.yaml @@ -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 diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index bda1b0ce..dadd297e 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -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 "{prompt}" (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). diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 9df15ae7..99f58bb1 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -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`. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index d3b45689..cad2fee6 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -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 `` 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 +`__`: 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) | diff --git a/docs/OPS.md b/docs/OPS.md index 2fe30b51..94348275 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -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 diff --git a/libavx/CMakeLists.txt b/libavx/CMakeLists.txt index 10e80c3a..3da5c89b 100644 --- a/libavx/CMakeLists.txt +++ b/libavx/CMakeLists.txt @@ -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 ) diff --git a/libavx/avx_attn.cpp b/libavx/avx_attn.cpp index 6ac77d3b..1441048b 100644 --- a/libavx/avx_attn.cpp +++ b/libavx/avx_attn.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(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(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; +} diff --git a/libavx/avx_audio.cpp b/libavx/avx_audio.cpp index a25e7582..99e16e1a 100644 --- a/libavx/avx_audio.cpp +++ b/libavx/avx_audio.cpp @@ -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) { diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index 39f51551..67460da9 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -359,6 +359,17 @@ std::vector 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 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 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 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 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 * diff --git a/libavx/avx_gen.cpp b/libavx/avx_gen.cpp index 608e1df2..f49025db 100644 --- a/libavx/avx_gen.cpp +++ b/libavx/avx_gen.cpp @@ -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 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 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; +} diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 2081c01c..e5b14941 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -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) \ diff --git a/libavx/avx_ltx.cpp b/libavx/avx_ltx.cpp new file mode 100644 index 00000000..6bc35149 --- /dev/null +++ b/libavx/avx_ltx.cpp @@ -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 +#include +#include +#include + +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* 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 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 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 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& 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 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 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(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; +} diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 3d70387a..602ac0c6 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -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 diff --git a/libavx/avx_video.cpp b/libavx/avx_video.cpp index 431fe8c1..9aebb8fe 100644 --- a/libavx/avx_video.cpp +++ b/libavx/avx_video.cpp @@ -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 wbuf, pbuf; static thread_local std::vector 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(std::max(tz, 0), T - 1); + else if (tpad == 2) tz = std::max(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; diff --git a/libquant/lq_gptq.cpp b/libquant/lq_gptq.cpp index af4ce4bf..81edadd3 100644 --- a/libquant/lq_gptq.cpp +++ b/libquant/lq_gptq.cpp @@ -136,16 +136,14 @@ bool chol_upper_loop(std::vector& 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& a, int64_t k) { #ifdef RAD_LQ_LAPACK @@ -168,7 +166,7 @@ bool chol_upper(std::vector& 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(); } diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 351dca26..e8ccd9ad 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -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. diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 141b1b85..aa4c8509 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -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); diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 1f348c96..7a76627a 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -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")) { diff --git a/libr4d/r4d_attn_dense_bf16.hip b/libr4d/r4d_attn_dense_bf16.hip index 6ef0329e..25799f63 100644 --- a/libr4d/r4d_attn_dense_bf16.hip +++ b/libr4d/r4d_attn_dense_bf16.hip @@ -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 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), 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(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; } diff --git a/libr4d/r4d_attn_gen.hip b/libr4d/r4d_attn_gen.hip index 025043fd..6599bf9b 100644 --- a/libr4d/r4d_attn_gen.hip +++ b/libr4d/r4d_attn_gen.hip @@ -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 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), 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); } diff --git a/libr4d/r4d_attn_paged_gqa8.hip b/libr4d/r4d_attn_paged_gqa8.hip index 15eb6c03..ab6bbb27 100644 --- a/libr4d/r4d_attn_paged_gqa8.hip +++ b/libr4d/r4d_attn_paged_gqa8.hip @@ -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 +template /* 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), \ + 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 diff --git a/libr4d/r4d_attn_paged_h256_gqa12.hip b/libr4d/r4d_attn_paged_h256_gqa12.hip index 971a915c..f589e125 100644 --- a/libr4d/r4d_attn_paged_h256_gqa12.hip +++ b/libr4d/r4d_attn_paged_h256_gqa12.hip @@ -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" diff --git a/libr4d/r4d_attn_paged_h256_gqa6_bs4.hip b/libr4d/r4d_attn_paged_h256_gqa6_bs4.hip index 6330c1bd..2394aad6 100644 --- a/libr4d/r4d_attn_paged_h256_gqa6_bs4.hip +++ b/libr4d/r4d_attn_paged_h256_gqa6_bs4.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" diff --git a/libr4d/r4d_audio.hip b/libr4d/r4d_audio.hip index 8bf20db2..1cf06249 100644 --- a/libr4d/r4d_audio.hip +++ b/libr4d/r4d_audio.hip @@ -16,6 +16,7 @@ #include "rad_philox.h" #include +#include #include 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); diff --git a/libr4d/r4d_fp8_f32scale.hip b/libr4d/r4d_fp8_f32scale.hip index fe947940..b961814d 100644 --- a/libr4d/r4d_fp8_f32scale.hip +++ b/libr4d/r4d_fp8_f32scale.hip @@ -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 #include "r4d_args.h" #include "r4d_emit.h" @@ -8,108 +9,75 @@ #include "r4d_fp8_wmma.h" #include "r4d_launch.h" #include -#include #include -#include #include 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 -__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 @@ -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 @@ -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(x.data) | reinterpret_cast(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), 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), \ 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, 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, 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); } diff --git a/libr4d/r4d_gen.hip b/libr4d/r4d_gen.hip index 73cbfd21..97a4cfde 100644 --- a/libr4d/r4d_gen.hip +++ b/libr4d/r4d_gen.hip @@ -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 +__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 __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 __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 +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), 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(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) \ diff --git a/libr4d/r4d_glm.hip b/libr4d/r4d_glm.hip index b8324b27..6cd8560c 100644 --- a/libr4d/r4d_glm.hip +++ b/libr4d/r4d_glm.hip @@ -5,9 +5,6 @@ #include "r4d_moe_sort.h" #include #include -#include -#include -#include 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 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(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, diff --git a/libr4d/r4d_kda.hip b/libr4d/r4d_kda.hip index fdbcd799..baba52f2 100644 --- a/libr4d/r4d_kda.hip +++ b/libr4d/r4d_kda.hip @@ -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 #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 -__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 __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(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(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 +/* 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 __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, dim3(32, (unsigned)H, seqs), dim3(128), - 0, j.state, j.idx, j.cu, j.accepted, j.init, static_cast(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(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(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(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), 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(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), 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(j)); } } extern "C" int r4d_rad_kda_update(const RadArgs* a, RadStream stream) { return body(a, stream); } diff --git a/libr4d/r4d_ltx.hip b/libr4d/r4d_ltx.hip new file mode 100644 index 00000000..9633beab --- /dev/null +++ b/libr4d/r4d_ltx.hip @@ -0,0 +1,1091 @@ +// R4D -- LTX-2's ops (docs/OPS.md, "LTX-2"): its rotary over fractional coordinates, the per-head +// attention gate and the guided sampler step. +// +// Each kernel rounds where its libref function does (libref/ref_ltx.cpp). The rotary's angles take +// the device's sincosf, within two units in the last place of libref's correctly rounded cos and +// sin; the guided step's deviations are f64 block sums in a fixed order, so it is deterministic. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_gdn_wmma.h" + +#include +#include +#include +#include + +namespace { + +constexpr int kT = 256; + +__device__ __forceinline__ float bfr(float v) { return bf2f(f32_to_bf16(v)); } + +// A value stored to an operand of dtype `bf`: bf16 when set, else f32. +__device__ __forceinline__ float ldx(const void* p, size_t i, bool bf) { + return bf ? bf2f(((const uint16_t*)p)[i]) : ((const float*)p)[i]; +} +__device__ __forceinline__ void stx(void* p, size_t i, float v, bool bf) { + if (bf) ((uint16_t*)p)[i] = f32_to_bf16(v); + else ((float*)p)[i] = v; +} + +// ---------------------------------------------------------------------------- rope_split +// One workgroup a (head, run of kRopeRows rows): the head's half-width pairs across the threads, +// their frequency and axis worked out once into LDS (f64 pow, as libref), then the rows. +constexpr int kRopeRows = 64; +constexpr int kMaxDims = 4; + +__global__ __launch_bounds__(kT) void rope_split_kernel( + void* __restrict__ x, const void* __restrict__ pos, int rows, int nh, int hd, int head0, + int nd, int steps, int pad, double theta, float m0, float m1, float m2, float m3, long long x_ld, + long long p_ld, long long p_cs, bool xbf, bool pint) { + __shared__ float freq[256]; + __shared__ int axis[256]; + const int half = hd / 2, h = blockIdx.y, r0 = blockIdx.x * kRopeRows; + if ((int)threadIdx.x < half) { + const int p = (head0 + h) * half + (int)threadIdx.x; + if (p < pad) { + axis[threadIdx.x] = -1; + freq[threadIdx.x] = 0.0f; + } else { + const int j = p - pad, k = j / nd; + axis[threadIdx.x] = j % nd; + double l = 0.0; + if (steps > 1) { + const double st = 1.0 / (double)(steps - 1); + l = k < steps / 2 ? st * (double)k : 1.0 - st * (double)(steps - 1 - k); + } + freq[threadIdx.x] = (float)(pow(theta, l) * M_PI / 2.0); + } + } + __syncthreads(); + const float mx[kMaxDims] = { m0, m1, m2, m3 }; + const int per = kT / half; // rows a pass of the workgroup covers + const int i = (int)threadIdx.x % half, rr = (int)threadIdx.x / half; + if (rr >= per) return; + const int d = axis[i]; + if (d < 0) return; // cos 1, sin 0: the value as it is + const float f = freq[i]; + for (int r = r0 + rr; r < min(r0 + kRopeRows, rows); r += per) { + const long long pi = (long long)d * p_cs + (long long)r * p_ld; + const float c0 = pint ? (float)((const int*)pos)[pi] : ((const float*)pos)[pi]; + const float g = c0 / mx[d]; + const float ang = (2.0f * g - 1.0f) * f; + float s, c; + sincosf(ang, &s, &c); + const size_t o1 = (size_t)r * x_ld + (size_t)h * hd + i, o2 = o1 + half; + const float x1 = ldx(x, o1, xbf), x2 = ldx(x, o2, xbf); + const float a1 = x1 * c, b1 = x2 * s, a2 = x2 * c, b2 = x1 * s; + stx(x, o1, a1 - b1, xbf); + stx(x, o2, a2 + b2, xbf); + } +} + +// ---------------------------------------------------------------------------- head_gate +// x = rd(x rd(2 rd(sigmoid(g)))): a thread an element. +__global__ __launch_bounds__(kT) void head_gate_kernel( + void* __restrict__ x, const uint16_t* __restrict__ g, long long total, int width, int hd, + long long x_ld, long long g_ld, bool xbf) { + const long long e = (long long)blockIdx.x * kT + threadIdx.x; + if (e >= total) return; + const long long r = e / width; + const int col = (int)(e % width), h = col / hd; + const float sg = bfr(1.0f / (1.0f + expf(-bf2f(g[r * g_ld + h])))); + const float gate = xbf ? bfr(2.0f * sg) : 2.0f * sg; + const size_t o = (size_t)r * x_ld + col; + stx(x, o, ldx(x, o, xbf) * gate, xbf); +} + +// ---------------------------------------------------------------------------- ltx_guide +// Two launches. The first, when the rescale is on (read off `scales` on the device), sums x0_c, +// x0_c^2, g and g^2 in f64 a workgroup a part into `stats`; the second reduces the parts (each +// workgroup the same sums in the same order), then recomputes g from the passes, rescales it, and +// takes the Euler step in place. +constexpr int kGuideParts = 1024; + +struct GuideIn { + const void* vc; const void* vu; const void* vs; const void* vm; + long long lc, lu, ls, lm; // row pitches + bool bc, bu, bs, bm; // bf16 +}; + +__device__ __forceinline__ float guide_g(const GuideIn& v, long long r, int c, float x, float sig, + float cu, float stg, float cm, bool uu, bool us, bool um, + float* x0c) { + const float xc = x - ldx(v.vc, (size_t)(r * v.lc + c), v.bc) * sig; + float g = xc; + if (uu) g = g + cu * (xc - (x - ldx(v.vu, (size_t)(r * v.lu + c), v.bu) * sig)); + if (us) g = g + stg * (xc - (x - ldx(v.vs, (size_t)(r * v.ls + c), v.bs) * sig)); + if (um) g = g + cm * (xc - (x - ldx(v.vm, (size_t)(r * v.lm + c), v.bm) * sig)); + *x0c = xc; + return g; +} + +__global__ __launch_bounds__(kT) void ltx_guide_sum_kernel( + GuideIn v, const float* __restrict__ x, const float* __restrict__ sc, + const float* __restrict__ sh, double* __restrict__ parts, long long rows, int n, long long x_ld) { + __shared__ double red[4][kT]; + const float gs = sc[0], stg = sc[1], ms = sc[2], rr = sc[3], sig = sh[0]; + const bool uu = v.vu && gs != 1.0f, us = v.vs && stg != 0.0f, um = v.vm && ms != 1.0f; + double a[4] = { 0, 0, 0, 0 }; + if (rr > 0.0f) { + const long long total = rows * n; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < total; + e += (long long)gridDim.x * kT) { + const long long r = e / n; + const int c = (int)(e % n); + float xc; + const float g = guide_g(v, r, c, x[r * x_ld + c], sig, gs - 1.0f, stg, ms - 1.0f, uu, us, + um, &xc); + a[0] += xc; + a[1] += (double)xc * xc; + a[2] += g; + a[3] += (double)g * g; + } + } + for (int k = 0; k < 4; ++k) red[k][threadIdx.x] = a[k]; + __syncthreads(); + for (int s = kT / 2; s > 0; s >>= 1) { + if ((int)threadIdx.x < s) + for (int k = 0; k < 4; ++k) red[k][threadIdx.x] += red[k][threadIdx.x + s]; + __syncthreads(); + } + if (threadIdx.x < 4) parts[(size_t)blockIdx.x * 4 + threadIdx.x] = red[threadIdx.x][0]; +} + +__global__ __launch_bounds__(kT) void ltx_guide_step_kernel( + GuideIn v, float* __restrict__ x, const float* __restrict__ sc, const float* __restrict__ sh, + const double* __restrict__ parts, int n_parts, long long rows, int n, long long x_ld) { + __shared__ double red[4][kT]; + __shared__ float fac_s; + const float gs = sc[0], stg = sc[1], ms = sc[2], rr = sc[3], sig = sh[0], sn = sh[1]; + const bool uu = v.vu && gs != 1.0f, us = v.vs && stg != 0.0f, um = v.vm && ms != 1.0f; + float fac = 1.0f; + if (rr > 0.0f) { + double a[4] = { 0, 0, 0, 0 }; + for (int p = threadIdx.x; p < n_parts; p += kT) + for (int k = 0; k < 4; ++k) a[k] += parts[(size_t)p * 4 + k]; + for (int k = 0; k < 4; ++k) red[k][threadIdx.x] = a[k]; + __syncthreads(); + for (int s = kT / 2; s > 0; s >>= 1) { + if ((int)threadIdx.x < s) + for (int k = 0; k < 4; ++k) red[k][threadIdx.x] += red[k][threadIdx.x + s]; + __syncthreads(); + } + if (threadIdx.x == 0) { + const double N = (double)(rows * n), dof = N > 1.0 ? N - 1.0 : 1.0; + const double vc = (red[1][0] - red[0][0] * red[0][0] / N) / dof; + const double vg = (red[3][0] - red[2][0] * red[2][0] / N) / dof; + fac_s = (float)sqrt(vc > 0.0 ? vc : 0.0) / (float)sqrt(vg > 0.0 ? vg : 0.0); + } + __syncthreads(); + fac = fac_s; + } + const float kept = (float)(1.0 - (double)rr), dt = sn - sig; + const long long total = rows * n; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < total; + e += (long long)gridDim.x * kT) { + const long long r = e / n; + const int c = (int)(e % n); + float* xp = x + r * x_ld + c; + const float xv = *xp; + float xc; + float g = guide_g(v, r, c, xv, sig, gs - 1.0f, stg, ms - 1.0f, uu, us, um, &xc); + if (rr > 0.0f) g = rr * (g * fac) + kept * g; + const float vel = (xv - g) / sig; + *xp = xv + dt * vel; + } +} + +// ---------------------------------------------------------------------------- pixel_norm +// A wave a row, eight rows a workgroup: the lanes' strided sums of rd(x^2) reduced by the wave +// (a different f32 order from libref's ascending one), then the row scaled. `ileave` L sends +// row t L + l to columns c L + l of y's row t. +__device__ __forceinline__ float rdx(float v, bool bf) { return bf ? bfr(v) : v; } + +__global__ __launch_bounds__(kT) void pixel_norm_kernel( + const void* __restrict__ x, void* __restrict__ y, long long rows, int n, int L, float eps, + float mult, long long x_ld, long long y_ld, bool xbf, bool ybf, bool divf, bool silu) { + const long long r = (long long)blockIdx.x * (kT / 32) + (threadIdx.x >> 5); + if (r >= rows) return; + const int lane = threadIdx.x & 31; + const size_t xb = (size_t)r * x_ld; + float ss = 0.0f; + for (int i = lane; i < n; i += 32) { + const float v = ldx(x, xb + i, xbf); + ss += rdx(v * v, ybf); + } + for (int o = 16; o > 0; o >>= 1) ss += __shfl_xor(ss, o, 32); + const float v = rdx(rdx(ss / (float)n, ybf) + eps, ybf); + const float s = divf ? rdx(sqrtf(v), ybf) : rdx(1.0f / sqrtf(v), ybf); + const size_t yb = (size_t)(r / L) * y_ld + (size_t)(r % L); + for (int i = lane; i < n; i += 32) { + const float xv = ldx(x, xb + i, xbf); + float z = rdx(divf ? xv / s : xv * s, ybf); + if (silu) z = rdx(z / (1.0f + expf(-z)), ybf); + if (mult != 1.0f) z = rdx(z * mult, ybf); + stx(y, yb + (size_t)i * L, z, ybf); + } +} + +// ---------------------------------------------------------------------------- d2s3d / s2d3d +// Copies over voxel rows, a thread an output value; the volume is read off `geom` on the device, +// and rows past it (or past the `rows` the output holds) are left alone. +__global__ __launch_bounds__(kT) void d2s3d_kernel( + const void* __restrict__ x, void* __restrict__ y, const int* __restrict__ geom, long long rows, + int C, int st, int sh, int sw, int drop, long long x_ld, long long y_ld, bool xbf, bool ybf) { + const int T = geom[0], H = geom[1], W = geom[2]; + if (T <= 0 || H <= 0 || W <= 0) return; + const long long Ho = (long long)H * sh, Wo = (long long)W * sw; + const long long To = (long long)T * st - drop; + const long long n = min(rows, To * Ho * Wo) * C; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < n; + e += (long long)gridDim.x * kT) { + const long long r = e / C; + const int c = (int)(e % C); + const long long tt = r / (Ho * Wo) + drop, ii = (r / Wo) % Ho, jj = r % Wo; + const long long t = tt / st, i = ii / sh, j = jj / sw; + const int aa = (int)(tt % st), b = (int)(ii % sh), d = (int)(jj % sw); + const long long xr = (t * H + i) * W + j; + stx(y, (size_t)(r * y_ld + c), + ldx(x, (size_t)(xr * x_ld + ((c * st + aa) * sh + b) * sw + d), xbf), ybf); + } +} + +__global__ __launch_bounds__(kT) void s2d3d_kernel( + const void* __restrict__ x, void* __restrict__ y, const int* __restrict__ geom, long long rows, + int C, int st, int sh, int sw, int tpre, int grp, int Co, long long x_ld, long long y_ld, + bool xbf, bool ybf, bool mean, bool add) { + const int T = geom[0], H = geom[1], W = geom[2]; + if (T <= 0 || H <= 0 || W <= 0 || (T + tpre) % st || H % sh || W % sw) return; + const long long Ho = H / sh, Wo = W / sw, To = (T + tpre) / st; + const long long n = min(rows, To * Ho * Wo) * Co; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < n; + e += (long long)gridDim.x * kT) { + const long long r = e / Co; + const int o = (int)(e % Co); + const long long t = r / (Ho * Wo), i = (r / Wo) % Ho, j = r % Wo; + auto val = [&](int q) { + const int d = q % sw, b = (q / sw) % sh, aa = (q / (sw * sh)) % st; + const int c = q / (sw * sh * st); + const long long v = t * st + aa, tr = v < tpre ? v : v - tpre; + return ldx(x, (size_t)(((tr * H + i * sh + b) * W + j * sw + d) * x_ld + c), xbf); + }; + float v; + if (!mean) { + v = val(o); + } else { + float s = 0.0f; + for (int q = o * grp; q < (o + 1) * grp; ++q) s += val(q); + v = rdx(s / (float)grp, ybf); + } + const size_t oy = (size_t)(r * y_ld + o); + stx(y, oy, add ? ldx(y, oy, ybf) + rdx(v, ybf) : v, ybf); + } +} + +// ---------------------------------------------------------------------------- pix_patch / patch_pix8 +__device__ __forceinline__ int patch_col(int c, int ph, int pw, int p, bool wh) { + return c * p * p + (wh ? pw * p + ph : ph * p + pw); +} + +// A thread an image value. +__global__ __launch_bounds__(kT) void pix_patch_kernel( + const void* __restrict__ x, void* __restrict__ y, int H, int W, int C, int p, bool wh, + long long x_ld, long long y_ld, bool xbf, bool ybf) { + const long long n = (long long)H * W * C; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < n; + e += (long long)gridDim.x * kT) { + const int c = (int)(e % C); + const long long px = e / C; + const int yy = (int)(px / W), xx = (int)(px % W); + stx(y, (size_t)((yy / p) * y_ld + (long long)(xx / p) * C * p * p + + patch_col(c, yy % p, xx % p, p, wh)), + ldx(x, (size_t)(yy * x_ld + (long long)xx * C + c), xbf), ybf); + } +} + +// A thread an output byte. +__global__ __launch_bounds__(kT) void patch_pix8_kernel( + const void* __restrict__ x, uint8_t* __restrict__ y, long long R, int w, int C, int p, bool wh, + long long x_ld, long long y_ld, bool xbf) { + const long long Wp = (long long)w * p * C, n = R * p * Wp; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < n; + e += (long long)gridDim.x * kT) { + const long long yy = e / Wp; + const int rem = (int)(e % Wp), xx = rem / C, c = rem % C; + const float v = ldx(x, (size_t)((yy / p) * x_ld + (long long)(xx / p) * C * p * p + + patch_col(c, (int)(yy % p), xx % p, p, wh)), xbf); + const float cl = fminf(fmaxf(v, -1.0f), 1.0f); + const float u = fminf(fmaxf(rdx(rdx(cl / 2.0f, xbf) + 0.5f, xbf), 0.0f), 1.0f); + y[yy * y_ld + xx * C + c] = (uint8_t)rintf(u * 255.0f); + } +} + +// ---------------------------------------------------------------------------- attn_na3d +// 3-D neighborhood attention (libref/ref_attn.cpp states it): a thread a (query, head), its query +// in registers, the window's keys streamed from memory -- neighbouring queries share all but a +// slice of their windows, so the caches serve most reads -- in libref's two passes, the maximum +// and then the exponentials' sum and the weighted values. +template +__global__ __launch_bounds__(kT) void attn_na3d_kernel( + const void* __restrict__ q, const void* __restrict__ k, const void* __restrict__ v, + const int* __restrict__ geom, void* __restrict__ o, long long rows, int kt, int kh, int kw, + float scale, long long q_ld, long long k_ld, long long v_ld, long long o_ld, bool qbf, bool kbf, + bool vbf, bool obf) { + const int h = blockIdx.y; + const long long r = (long long)blockIdx.x * kT + threadIdx.x; + const int T = geom[0], H = geom[1], W = geom[2]; + if (T <= 0 || H <= 0 || W <= 0 || r >= min(rows, (long long)T * H * W)) return; + const int nt = min(kt, T), nh = min(kh, H), nw = min(kw, W); + const int t = (int)(r / ((long long)H * W)), i = (int)((r / W) % H), j = (int)(r % W); + const int t0 = min(max(t - nt / 2, 0), T - nt), i0 = min(max(i - nh / 2, 0), H - nh); + const int j0 = min(max(j - nw / 2, 0), W - nw); + float qv[HD]; + for (int d = 0; d < HD; ++d) qv[d] = ldx(q, (size_t)(r * q_ld + h * HD + d), qbf); + auto score = [&](long long key) { + float dot = 0.0f; + const size_t kb = (size_t)(key * k_ld + h * HD); + for (int d = 0; d < HD; ++d) dot = __fadd_rn(dot, __fmul_rn(qv[d], ldx(k, kb + d, kbf))); + return dot * scale; + }; + float mx = -INFINITY; + for (int a1 = t0; a1 < t0 + nt; ++a1) + for (int b1 = i0; b1 < i0 + nh; ++b1) { + const long long base = ((long long)a1 * H + b1) * W; + for (int c1 = j0; c1 < j0 + nw; ++c1) mx = fmaxf(mx, score(base + c1)); + } + float acc[HD]; + for (int d = 0; d < HD; ++d) acc[d] = 0.0f; + float sum = 0.0f; + for (int a1 = t0; a1 < t0 + nt; ++a1) + for (int b1 = i0; b1 < i0 + nh; ++b1) { + const long long base = ((long long)a1 * H + b1) * W; + for (int c1 = j0; c1 < j0 + nw; ++c1) { + const float w = expf(score(base + c1) - mx); + sum += w; + const size_t vb = (size_t)((base + c1) * v_ld + h * HD); + for (int d = 0; d < HD; ++d) acc[d] = fmaf(w, ldx(v, vb + d, vbf), acc[d]); + } + } + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; + for (int d = 0; d < HD; ++d) stx(o, (size_t)(r * o_ld + h * HD + d), acc[d] * inv, obf); +} + +// The same over bf16 operands, each row read 8 values at a time (16-byte loads: the rows sit at +// multiples of 8 values and the heads at multiples of 64). +__device__ __forceinline__ void bf16x8(const uint16_t* __restrict__ p, float* f) { + const uint4 u = *(const uint4*)p; + const uint32_t w[4] = { u.x, u.y, u.z, u.w }; + for (int i = 0; i < 4; ++i) { + f[2 * i] = __uint_as_float(w[i] << 16); + f[2 * i + 1] = __uint_as_float(w[i] & 0xffff0000u); + } +} + +template +__global__ __launch_bounds__(kT) void attn_na3d_bf16_kernel( + const uint16_t* __restrict__ q, const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, + const int* __restrict__ geom, uint16_t* __restrict__ o, long long rows, int kt, int kh, int kw, + float scale, long long q_ld, long long k_ld, long long v_ld, long long o_ld) { + const int h = blockIdx.y; + const long long r = (long long)blockIdx.x * kT + threadIdx.x; + const int T = geom[0], H = geom[1], W = geom[2]; + if (T <= 0 || H <= 0 || W <= 0 || r >= min(rows, (long long)T * H * W)) return; + const int nt = min(kt, T), nh = min(kh, H), nw = min(kw, W); + const int t = (int)(r / ((long long)H * W)), i = (int)((r / W) % H), j = (int)(r % W); + const int t0 = min(max(t - nt / 2, 0), T - nt), i0 = min(max(i - nh / 2, 0), H - nh); + const int j0 = min(max(j - nw / 2, 0), W - nw); + float qv[HD]; + for (int d = 0; d < HD; d += 8) bf16x8(q + r * q_ld + h * HD + d, qv + d); + auto score = [&](long long key) { + const uint16_t* kr = k + key * k_ld + h * HD; + float dot = 0.0f; + for (int d = 0; d < HD; d += 8) { + float kk[8]; + bf16x8(kr + d, kk); + for (int e = 0; e < 8; ++e) dot = fmaf(qv[d + e], kk[e], dot); + } + return dot * scale; + }; + float mx = -INFINITY; + for (int a1 = t0; a1 < t0 + nt; ++a1) + for (int b1 = i0; b1 < i0 + nh; ++b1) { + const long long base = ((long long)a1 * H + b1) * W; + for (int c1 = j0; c1 < j0 + nw; ++c1) mx = fmaxf(mx, score(base + c1)); + } + float acc[HD]; + for (int d = 0; d < HD; ++d) acc[d] = 0.0f; + float sum = 0.0f; + for (int a1 = t0; a1 < t0 + nt; ++a1) + for (int b1 = i0; b1 < i0 + nh; ++b1) { + const long long base = ((long long)a1 * H + b1) * W; + for (int c1 = j0; c1 < j0 + nw; ++c1) { + const float w = expf(score(base + c1) - mx); + sum += w; + const uint16_t* vr = v + (base + c1) * v_ld + h * HD; + for (int d = 0; d < HD; d += 8) { + float vv[8]; + bf16x8(vr + d, vv); + for (int e = 0; e < 8; ++e) acc[d + e] = fmaf(w, vv[e], acc[d + e]); + } + } + } + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; + for (int d = 0; d < HD; ++d) o[r * o_ld + h * HD + d] = f32_to_bf16(acc[d] * inv); +} + +// ---------------------------------------------------------------------------- vol_index +// A thread a voxel's three coordinates. +__global__ __launch_bounds__(kT) void vol_index_kernel(const int* __restrict__ geom, + int* __restrict__ y, long long n, + long long y_ld) { + const int T = geom[0], H = geom[1], W = geom[2]; + if (T <= 0 || H <= 0 || W <= 0) return; + const long long m1 = min(n, (long long)T * H * W); + for (long long m = (long long)blockIdx.x * kT + threadIdx.x; m < m1; + m += (long long)gridDim.x * kT) { + y[m] = (int)(m / ((long long)H * W)); + y[y_ld + m] = (int)((m / W) % H); + y[2 * y_ld + m] = (int)(m % W); + } +} + +// ---------------------------------------------------------------------------- tile_grid / tile_crop / tile_stitch +// diffusers' tiled decodes (libref/ref_ltx.cpp states the cuts and the blends): the boxes, a +// tile's voxels out of a volume, the tiles blended to bytes. The volumes are read off the device. +struct TileCutD { + int tile, stride, least; + bool intervals; + __device__ int count(int L) const { + if (intervals && L <= tile) return 1; + int n = (L + stride - 1) / stride; + while (intervals && n > 1 && L - (n - 1) * stride < least) --n; + return n; + } + __device__ int len(int L, int k) const { + return k == count(L) - 1 ? L - k * stride : min(tile, L - k * stride); + } +}; + +// A thread a row of the box table. +__global__ __launch_bounds__(kT) void tile_grid_kernel(const int* __restrict__ geom, + int* __restrict__ y, int n, TileCutD cs, + TileCutD ct, int tail) { + const int k = blockIdx.x * kT + threadIdx.x; + if (k >= n) return; + const int T = geom[0], H = geom[1], W = geom[2]; + int row[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + if (T > 0 && H > 0 && W > 0) { + const int nt = ct.count(T), ni = cs.count(H), nj = cs.count(W), count = nt * ni * nj; + if (k < count) { + const int kt = k / (ni * nj), i = (k / nj) % ni, j = k % nj; + row[0] = ct.len(T, kt) + (kt == nt - 1 ? tail : 0); + row[1] = cs.len(H, i); + row[2] = cs.len(W, j); + row[3] = kt * ct.stride; + row[4] = i * cs.stride; + row[5] = j * cs.stride; + row[6] = k; + row[7] = count; + } + } + for (int e = 0; e < 8; ++e) y[(long long)k * 8 + e] = row[e]; +} + +// A thread an output value; rows past the box's voxels (or the `rows` y holds) are left alone. +__global__ __launch_bounds__(kT) void tile_crop_kernel( + const void* __restrict__ x, void* __restrict__ y, const int* __restrict__ geom, + const int* __restrict__ box, long long rows, int C, long long x_ld, long long y_ld, bool xbf, + bool ybf) { + const int T = geom[0], H = geom[1], W = geom[2]; + const int t = box[0], h = box[1], w = box[2], t0 = box[3], y0 = box[4], x0 = box[5]; + if (t <= 0 || h <= 0 || w <= 0 || t0 < 0 || y0 < 0 || x0 < 0 || t0 + t > T || y0 + h > H || + x0 + w > W) + return; + const long long n = min(rows, (long long)t * h * w) * C; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < n; + e += (long long)gridDim.x * kT) { + const long long r = e / C; + const int c = (int)(e % C); + const long long f = r / ((long long)h * w), i = (r / w) % h, j = r % w; + const long long xr = ((t0 + f) * H + y0 + i) * W + x0 + j; + stx(y, (size_t)(r * y_ld + c), ldx(x, (size_t)(xr * x_ld + c), xbf), ybf); + } +} + +// The tile store's layout: time bands of every tile back to back. +struct TileStoreD { + TileCutD cs, ct; + int T, H, W, sc, st; + __device__ int frames(int kt) const { return st * ct.len(T, kt) - (kt == 0 ? st - 1 : 0); } + __device__ long long offset(int kt, int i, int j) const { + const int nj = cs.count(W), ni = cs.count(H); + long long hsum = 0, wsum = 0, left = 0, above = 0, before = 0; + for (int q = 0; q < nj; ++q) { + const int b = cs.len(W, q); + wsum += b; + if (q < j) left += b; + } + for (int q = 0; q < ni; ++q) { + const int b = cs.len(H, q); + hsum += b; + if (q < i) above += b; + } + for (int q = 0; q < kt; ++q) before += frames(q); + return (long long)sc * sc * + (before * hsum * wsum + (long long)frames(kt) * (above * wsum + (long long)cs.len(H, i) * left)); + } +}; + +// A thread an output byte: up to eight tiles' values, the blends in libref's order and roundings. +__global__ __launch_bounds__(kT) void tile_stitch_kernel( + const void* __restrict__ x, uint8_t* __restrict__ y, const int* __restrict__ geom, + const int* __restrict__ first, long long y_rows, long long y_cols, TileCutD cs, TileCutD ct, + int sc, int st, int p, int C, bool wh, long long x_ld, long long y_ld, bool xbf) { + const int T = geom[0], H = geom[1], W = geom[2], f0 = first[0]; + const long long Hpx = (long long)H * sc * p, Wpx = (long long)W * sc * p; + if (T <= 0 || H <= 0 || W <= 0 || y_cols != Wpx * C || y_rows % Hpx) return; + const long long nf = y_rows / Hpx; + if (f0 < 0 || f0 + nf > (long long)st * T - (st - 1)) return; + const TileStoreD ts{ cs, ct, T, H, W, sc, st }; + const int nt = ct.count(T), ni = cs.count(H), nj = cs.count(W); + const long long s = (long long)cs.stride * sc * p, E = (long long)(cs.tile - cs.stride) * sc * p; + const long long Et = (long long)(ct.tile - ct.stride) * st, band = (long long)ct.stride * st; + const long long n = y_rows * y_cols; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < n; + e += (long long)gridDim.x * kT) { + const long long r = e / y_cols; + const int rem = (int)(e % y_cols), Xp = rem / C, c = rem % C; + const long long nfr = f0 + r / Hpx, Yp = r % Hpx; + const int kt = (int)min((nfr + st - 1) / band, (long long)nt - 1); + const int f = (int)(nfr - (kt == 0 ? 0 : kt * band - (st - 1))); + auto R = [&](int bk, int ti, int tj, int fr, int yy, int xx) { + const long long wp = (long long)cs.len(W, tj) * sc, hp = (long long)cs.len(H, ti) * sc; + const long long row = ts.offset(bk, ti, tj) + ((long long)fr * hp + yy / p) * wp + xx / p; + return ldx(x, (size_t)(row * x_ld + patch_col(c, yy % p, xx % p, p, wh)), xbf); + }; + auto mix = [&](float va, float vb, int k, int ext) { + const float wa = (float)(1.0 - (double)k / (double)ext); + const float wb = (float)((double)k / (double)ext); + return rdx(rdx(__fmul_rn(va, wa), xbf) + rdx(__fmul_rn(vb, wb), xbf), xbf); + }; + const int i = (int)min(Yp / s, (long long)ni - 1), j = (int)min((long long)Xp / s, (long long)nj - 1); + const int ly = (int)(Yp - i * s), lx = (int)(Xp - j * s); + const int ha = i > 0 ? cs.len(H, i - 1) * sc * p : 0; + const int ev = i > 0 ? (int)min(min((long long)ha, (long long)cs.len(H, i) * sc * p), E) : 0; + const int wl = j > 0 ? cs.len(W, j - 1) * sc * p : 0; + const int eh = j > 0 ? (int)min(min((long long)wl, (long long)cs.len(W, j) * sc * p), E) : 0; + const bool vb = i > 0 && ly < ev, hb = j > 0 && lx < eh; + auto S = [&](int bk, int fr) { + float V = R(bk, i, j, fr, ly, lx); + if (vb) { + const int ya = ha - ev + ly; + float A = R(bk, i - 1, j, fr, ya, lx); + if (hb) A = mix(R(bk, i - 1, j - 1, fr, ya, wl - eh + lx), A, lx, eh); + V = mix(A, V, ly, ev); + } + if (hb) { + float L = R(bk, i, j - 1, fr, ly, wl - eh + lx); + if (vb) L = mix(R(bk, i - 1, j - 1, fr, ha - ev + ly, wl - eh + lx), L, ly, ev); + V = mix(L, V, lx, eh); + } + return V; + }; + float v = S(kt, f); + if (kt > 0) { + const int et = (int)min(min((long long)ts.frames(kt - 1), (long long)ts.frames(kt)), Et); + if (f < et) v = mix(S(kt - 1, ts.frames(kt - 1) - et + f), v, f, et); + } + const float cl = fminf(fmaxf(v, -1.0f), 1.0f); + const float u = fminf(fmaxf(rdx(rdx(cl / 2.0f, xbf) + 0.5f, xbf), 0.0f), 1.0f); + y[r * y_ld + (long long)Xp * C + c] = (uint8_t)rintf(u * 255.0f); + } +} + +// ---------------------------------------------------------------------------- stft_logmel +// A workgroup a (frame, channel): the frame's samples into LDS, a thread a frequency bin's real +// and imaginary sums (ascending, as libref), the magnitudes into LDS, then a thread a mel bin. +constexpr int kStftMaxN = 4096; + +__global__ __launch_bounds__(kT) void stft_logmel_kernel( + const void* __restrict__ x, const void* __restrict__ basis, const void* __restrict__ melb, + void* __restrict__ y, int frames, int ch, int hop, int nfft, int nm, long long x_ld, + long long y_ld, bool xbf, bool bbf, bool mbf, bool ybf) { + __shared__ float sx[kStftMaxN]; + __shared__ float mag[kStftMaxN / 2 + 1]; + const int t = blockIdx.x, h = blockIdx.y, F = nfft / 2 + 1, pad = nfft - hop; + for (int j = threadIdx.x; j < nfft; j += kT) { + const long long s = (long long)t * hop + j - pad; + sx[j] = s < 0 ? 0.0f : ldx(x, (size_t)(s * x_ld + h), xbf); + } + __syncthreads(); + for (int k = threadIdx.x; k < F; k += kT) { + float re = 0.0f, im = 0.0f; + const size_t br = (size_t)k * nfft, bi = (size_t)(F + k) * nfft; + for (int j = 0; j < nfft; ++j) { + re += ldx(basis, br + j, bbf) * sx[j]; + im += ldx(basis, bi + j, bbf) * sx[j]; + } + re = rdx(re, ybf); + im = rdx(im, ybf); + mag[k] = rdx(sqrtf(rdx(rdx(re * re, ybf) + rdx(im * im, ybf), ybf)), ybf); + } + __syncthreads(); + const float fl = rdx(1e-5f, ybf); + for (int m = threadIdx.x; m < nm; m += kT) { + float s = 0.0f; + for (int k = 0; k < F; ++k) s += ldx(melb, (size_t)m * F + k, mbf) * mag[k]; + stx(y, (size_t)((long long)t * y_ld + (long long)h * nm + m), logf(fmaxf(rdx(s, ybf), fl)), + ybf); + } +} + +// ---------------------------------------------------------------------------- bwe_up +// A thread an output value; the resampler's taps are worked out on the host as libref does and +// passed by value. +// Taps for ratios up to 4 (2 w r + 1 = 57): the filter is passed by value, and the backend's +// kernel-argument slot is 768 bytes. +constexpr int kBweTaps = 64; +struct BweTaps { float f[kBweTaps]; }; + +__global__ __launch_bounds__(kT) void bwe_up_kernel( + const void* __restrict__ x, const void* __restrict__ res, void* __restrict__ y, BweTaps f, + long long S, long long O, int ch, int r, int w, int K, long long x_ld, long long r_ld, + long long y_ld, bool xbf, bool rbf, bool ybf) { + const long long n = O * ch; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < n; + e += (long long)gridDim.x * kT) { + const long long o = e / ch; + const int h = (int)(e % ch); + const long long u = o + 2ll * w * r; + float acc = 0.0f; + for (int k = (int)(u % r); k < K; k += r) { + const long long i = (u - k) / r; + const long long s = min(max(i - w, 0ll), S - 1); + acc += f.f[k] * ldx(x, (size_t)(s * x_ld + h), xbf); + } + const float up = rdx((float)r * rdx(acc, xbf), xbf); + const float v = rdx(ldx(res, (size_t)(o * r_ld + h), rbf) + up, xbf); + stx(y, (size_t)(o * y_ld + h), fminf(fmaxf(v, -1.0f), 1.0f), ybf); + } +} + +inline int st_of(hipError_t e) { return e == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } +inline bool is_bf16(const RadTensor* t) { return t && t->dtype == RAD_BF16; } +inline bool is_f32(const RadTensor* t) { return t && t->dtype == RAD_F32; } +inline bool is_bf_or_f32(const RadTensor* t) { return is_bf16(t) || is_f32(t); } + +int parse_floats(const char* s, float* out, int max) { + int n = 0; + while (s && *s) { + char* end = nullptr; + const double v = std::strtod(s, &end); + if (end == s) break; + if (n == max) return max + 1; + out[n++] = (float)v; + s = end; + } + return n; +} + +} // namespace + +// ============================================================== the plugin ABI entry points + +extern "C" int r4d_rad_rope_split(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *p = r4d_opt(a, 1); + if (!x || !p) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || !(p->dtype == RAD_F32 || p->dtype == RAD_I32)) + return R4D_NO(RAD_E_DTYPE); + const long long nh = r4d_geti_or(a, "n_head", 0), hd = r4d_geti_or(a, "head_dim", 0); + const long long dim = r4d_geti_or(a, "dim", 0), nd = r4d_geti_or(a, "n_dims", 0); + const long long h0 = r4d_geti_or(a, "head0", 0); + float mx[kMaxDims] = { 1, 1, 1, 1 }; + if (nh <= 0 || hd <= 0 || (hd & 1) || hd / 2 > 256 || (kT % (hd / 2)) || nd <= 0 || + nd > kMaxDims || dim < (h0 + nh) * hd || + parse_floats(r4d_gets(a, "max"), mx, kMaxDims) != (int)nd) + return R4D_NO(RAD_E_SHAPE); + long long rows = 0; + const long long xl = r4d_rows_pitch(x, nh * hd, &rows); + if (xl < 0) return R4D_NO(RAD_E_STRIDE); + if (rows <= 0) return R4D_NO(RAD_E_SHAPE); + // positions [n_dims, M] at its strides, or [M]. + long long pl = 1, pc = 0; + if (p->rank >= 2) { + pc = p->stride[0]; + pl = p->stride[1]; + if (p->shape[0] < nd || p->shape[1] < rows) return R4D_NO(RAD_E_SHAPE); + } else { + pl = p->rank ? p->stride[0] : 1; + if (nd != 1 || r4d_numel(p) < rows) return R4D_NO(RAD_E_SHAPE); + } + const long long P2 = dim / 2, steps = P2 / nd, pad = P2 - steps * nd; + dim3 grid((unsigned)((rows + kRopeRows - 1) / kRopeRows), (unsigned)nh); + hipLaunchKernelGGL(rope_split_kernel, grid, dim3(kT), 0, (hipStream_t)s, x->data, p->data, + (int)rows, (int)nh, (int)hd, (int)h0, (int)nd, (int)steps, (int)pad, + r4d_getf(a, "theta", 10000.0), mx[0], mx[1], mx[2], mx[3], xl, pl, pc, + is_bf16(x), p->dtype == RAD_I32); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_head_gate(const RadArgs* a, RadStream s) { + const RadTensor *g = r4d_opt(a, 0), *x = r4d_opt(a, 1); + if (!g || !x) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(g) || !is_bf_or_f32(x)) return R4D_NO(RAD_E_DTYPE); + const long long nh = r4d_geti_or(a, "n_head", 0), hd = r4d_geti_or(a, "head_dim", 0); + if (nh <= 0 || hd <= 0) return R4D_NO(RAD_E_SHAPE); + long long rows = 0, rg = 0; + const long long xl = r4d_rows_pitch(x, nh * hd, &rows), gl = r4d_rows_pitch(g, nh, &rg); + if (xl < 0 || gl < 0) return R4D_NO(RAD_E_STRIDE); + if (rows <= 0 || rg < rows) return R4D_NO(RAD_E_SHAPE); + const long long total = rows * nh * hd; + hipLaunchKernelGGL(head_gate_kernel, dim3((unsigned)((total + kT - 1) / kT)), dim3(kT), 0, + (hipStream_t)s, x->data, (const uint16_t*)g->data, total, (int)(nh * hd), + (int)hd, xl, gl, is_bf16(x)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_ltx_guide(const RadArgs* a, RadStream s) { + const RadTensor *vc = r4d_opt(a, 0), *vu = r4d_opt(a, 1), *vs = r4d_opt(a, 2); + const RadTensor *vm = r4d_opt(a, 3), *sc = r4d_opt(a, 4), *sh = r4d_opt(a, 5); + const RadTensor *st = r4d_opt(a, 6), *x = r4d_opt(a, 7); + if (!vc || !sc || !sh || !st || !x) return R4D_NO(RAD_E_INVAL); + if (!is_f32(x) || !is_f32(sc) || !is_f32(sh) || !is_f32(st)) return R4D_NO(RAD_E_DTYPE); + for (const RadTensor* v : { vc, vu, vs, vm }) + if (v && !is_bf_or_f32(v)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + long long rows = 0; + const long long xl = r4d_rows_pitch(x, n, &rows); + if (xl < 0) return R4D_NO(RAD_E_STRIDE); + if (n <= 0 || rows <= 0 || r4d_numel(sc) < 4 || r4d_numel(sh) < 2 || + r4d_numel(st) < 2 * 4 * kGuideParts || !r4d_contig(sc) || !r4d_contig(sh) || + ((uintptr_t)st->data & 7)) + return R4D_NO(RAD_E_SHAPE); + GuideIn in{}; + const RadTensor* vv[4] = { vc, vu, vs, vm }; + const void** dst[4] = { &in.vc, &in.vu, &in.vs, &in.vm }; + long long* ld[4] = { &in.lc, &in.lu, &in.ls, &in.lm }; + bool* bf[4] = { &in.bc, &in.bu, &in.bs, &in.bm }; + for (int i = 0; i < 4; ++i) { + *dst[i] = nullptr; + if (!vv[i]) continue; + long long rv = 0; + const long long l = r4d_rows_pitch(vv[i], n, &rv); + if (l < 0) return R4D_NO(RAD_E_STRIDE); + if (rv < rows) return R4D_NO(RAD_E_SHAPE); + *dst[i] = vv[i]->data; + *ld[i] = l; + *bf[i] = is_bf16(vv[i]); + } + const long long total = rows * n; + const int parts = (int)std::min(kGuideParts, (total + kT - 1) / kT); + double* pd = (double*)st->data; + hipLaunchKernelGGL(ltx_guide_sum_kernel, dim3((unsigned)parts), dim3(kT), 0, (hipStream_t)s, + in, (const float*)x->data, (const float*)sc->data, (const float*)sh->data, + pd, rows, (int)n, xl); + hipLaunchKernelGGL(ltx_guide_step_kernel, dim3((unsigned)parts), dim3(kT), 0, (hipStream_t)s, + in, (float*)x->data, (const float*)sc->data, (const float*)sh->data, pd, + parts, rows, (int)n, xl); + return st_of(hipGetLastError()); +} + +namespace { + +// Workgroups for a grid-stride loop over n values. +inline unsigned grid_for(long long n) { + return (unsigned)std::max(1ll, std::min((n + kT - 1) / kT, 1ll << 20)); +} + +// A dense 2-D operand: its rows, columns and row pitch, or false. +inline bool dense2(const RadTensor* t, long long* rows, long long* cols, long long* ld) { + if (!t || t->rank != 2 || t->stride[1] != 1 || t->shape[0] <= 0 || t->shape[1] <= 0) + return false; + *rows = t->shape[0]; + *cols = t->shape[1]; + *ld = t->stride[0]; + return true; +} + +// `order`: wh (the default, LTX-2's) or hw; -1 for anything else. +inline int patch_order(const RadArgs* a) { + const char* o = r4d_gets(a, "order"); + if (!o || !*o || !std::strcmp(o, "wh")) return 1; + return std::strcmp(o, "hw") ? -1 : 0; +} + +} // namespace + +extern "C" int r4d_rad_pixel_norm(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_bf_or_f32(x) || !is_bf_or_f32(y)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), L = r4d_geti_or(a, "ileave", 1); + const char *form = r4d_gets(a, "form"), *act = r4d_gets(a, "act"); + const bool divf = form && !std::strcmp(form, "div"); + const bool silu = act && !std::strcmp(act, "silu"); + if ((form && *form && !divf && std::strcmp(form, "rsqrt")) || + (act && *act && !silu && std::strcmp(act, "none"))) + return R4D_NO(RAD_E_INVAL); + if (n <= 0 || L <= 0) return R4D_NO(RAD_E_SHAPE); + long long ry = 0, rx = 0; + const long long yl = r4d_rows_pitch(y, n * L, &ry), xl = r4d_rows_pitch(x, n, &rx); + if (yl < 0 || xl < 0) return R4D_NO(RAD_E_STRIDE); + const long long rows = ry * L; + if (rows <= 0 || rx < rows) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(pixel_norm_kernel, dim3((unsigned)((rows + kT / 32 - 1) / (kT / 32))), + dim3(kT), 0, (hipStream_t)s, x->data, y->data, rows, (int)n, (int)L, + (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "mult", 1.0), xl, yl, + is_bf16(x), is_bf16(y), divf, silu); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_d2s3d(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *g = r4d_opt(a, 1), *y = r4d_opt(a, 2); + if (!x || !g || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || !is_bf_or_f32(y) || g->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + const long long C = r4d_geti_or(a, "C", 0), st = r4d_geti_or(a, "st", 1); + const long long sh = r4d_geti_or(a, "sh", 1), sw = r4d_geti_or(a, "sw", 1); + const long long drop = r4d_geti_or(a, "drop", st - 1); + if (C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || drop < 0 || drop >= st || r4d_numel(g) < 3 || + !r4d_contig(g)) + return R4D_NO(RAD_E_SHAPE); + long long rx = 0, ry = 0; + const long long xl = r4d_rows_pitch(x, C * st * sh * sw, &rx), yl = r4d_rows_pitch(y, C, &ry); + if (xl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE); + if (rx <= 0 || ry <= 0) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(d2s3d_kernel, dim3(grid_for(ry * C)), dim3(kT), 0, (hipStream_t)s, x->data, + y->data, (const int*)g->data, ry, (int)C, (int)st, (int)sh, (int)sw, (int)drop, + xl, yl, is_bf16(x), is_bf16(y)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_s2d3d(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *g = r4d_opt(a, 1), *y = r4d_opt(a, 2); + if (!x || !g || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || !is_bf_or_f32(y) || g->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + const long long C = r4d_geti_or(a, "C", 0), st = r4d_geti_or(a, "st", 1); + const long long sh = r4d_geti_or(a, "sh", 1), sw = r4d_geti_or(a, "sw", 1); + const long long tpre = r4d_geti_or(a, "tpre", 0), grp = r4d_geti_or(a, "group", 1); + const char* mode = r4d_gets(a, "mode"); + const bool mean = mode && !std::strcmp(mode, "mean"); + if (mode && *mode && !mean && std::strcmp(mode, "copy")) return R4D_NO(RAD_E_INVAL); + const long long P = C * st * sh * sw; + if (C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || tpre < 0 || grp <= 0 || (mean && P % grp) || + r4d_numel(g) < 3 || !r4d_contig(g)) + return R4D_NO(RAD_E_SHAPE); + const long long Co = mean ? P / grp : P; + long long rx = 0, ry = 0; + const long long xl = r4d_rows_pitch(x, C, &rx), yl = r4d_rows_pitch(y, Co, &ry); + if (xl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE); + if (rx <= 0 || ry <= 0) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(s2d3d_kernel, dim3(grid_for(ry * Co)), dim3(kT), 0, (hipStream_t)s, x->data, + y->data, (const int*)g->data, ry, (int)C, (int)st, (int)sh, (int)sw, + (int)tpre, (int)grp, (int)Co, xl, yl, is_bf16(x), is_bf16(y), mean, + r4d_geti_or(a, "add", 0) != 0); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_pix_patch(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_bf_or_f32(x) || !is_bf_or_f32(y)) return R4D_NO(RAD_E_DTYPE); + const long long p = r4d_geti_or(a, "p", 0), C = r4d_geti_or(a, "C", 0); + const int wh = patch_order(a); + if (wh < 0) return R4D_NO(RAD_E_INVAL); + long long H = 0, WC = 0, xl = 0, Ry = 0, Cy = 0, yl = 0; + if (!dense2(x, &H, &WC, &xl) || !dense2(y, &Ry, &Cy, &yl)) return R4D_NO(RAD_E_SHAPE); + if (p <= 0 || C <= 0 || WC % C) return R4D_NO(RAD_E_SHAPE); + const long long W = WC / C; + if (H % p || W % p || Ry != H / p || Cy != (W / p) * C * p * p) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(pix_patch_kernel, dim3(grid_for(H * W * C)), dim3(kT), 0, (hipStream_t)s, + x->data, y->data, (int)H, (int)W, (int)C, (int)p, wh == 1, xl, yl, + is_bf16(x), is_bf16(y)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_patch_pix8(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_bf_or_f32(x) || y->dtype != RAD_U8) return R4D_NO(RAD_E_DTYPE); + const long long p = r4d_geti_or(a, "p", 0), C = r4d_geti_or(a, "C", 0); + const int wh = patch_order(a); + if (wh < 0) return R4D_NO(RAD_E_INVAL); + long long R = 0, Cx = 0, xl = 0, Ry = 0, Cy = 0, yl = 0; + if (!dense2(x, &R, &Cx, &xl) || !dense2(y, &Ry, &Cy, &yl)) return R4D_NO(RAD_E_SHAPE); + if (p <= 0 || C <= 0 || Cx % (C * p * p)) return R4D_NO(RAD_E_SHAPE); + const long long w = Cx / (C * p * p); + if (Ry != R * p || Cy != w * p * C) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(patch_pix8_kernel, dim3(grid_for(Ry * Cy)), dim3(kT), 0, (hipStream_t)s, + x->data, (uint8_t*)y->data, R, (int)w, (int)C, (int)p, wh == 1, xl, yl, + is_bf16(x)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_attn_na3d(const RadArgs* a, RadStream s) { + const RadTensor *q = r4d_opt(a, 0), *k = r4d_opt(a, 1), *v = r4d_opt(a, 2), *g = r4d_opt(a, 3); + const RadTensor* o = r4d_opt(a, 4); + if (!q || !k || !v || !g || !o) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(q) || !is_bf_or_f32(k) || !is_bf_or_f32(v) || !is_bf_or_f32(o) || + g->dtype != RAD_I32) + return R4D_NO(RAD_E_DTYPE); + const long long hd = r4d_geti_or(a, "head_dim", 0), kt = r4d_geti_or(a, "kt", 0); + const long long kh = r4d_geti_or(a, "kh", 0), kw = r4d_geti_or(a, "kw", 0); + if (hd != 64 || kt <= 0 || kh <= 0 || kw <= 0 || r4d_numel(g) < 3 || !r4d_contig(g) || + q->rank != 2 || q->shape[1] % hd) + return R4D_NO(RAD_E_SHAPE); + const long long heads = q->shape[1] / hd, D = heads * hd; + long long rq = 0, rk = 0, rv = 0, ro = 0; + const long long ql = r4d_rows_pitch(q, D, &rq), kl = r4d_rows_pitch(k, D, &rk); + const long long vl = r4d_rows_pitch(v, D, &rv), ol = r4d_rows_pitch(o, D, &ro); + if (ql < 0 || kl < 0 || vl < 0 || ol < 0) return R4D_NO(RAD_E_STRIDE); + if (rq <= 0 || rk < rq || rv < rq || ro < rq) return R4D_NO(RAD_E_SHAPE); + const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)hd)); + const dim3 grid((unsigned)((rq + kT - 1) / kT), (unsigned)heads); + if (is_bf16(q) && is_bf16(k) && is_bf16(v) && is_bf16(o) && ql % 8 == 0 && kl % 8 == 0 && + vl % 8 == 0 && ((uintptr_t)q->data | (uintptr_t)k->data | (uintptr_t)v->data) % 16 == 0) { + hipLaunchKernelGGL(attn_na3d_bf16_kernel<64>, grid, dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)q->data, (const uint16_t*)k->data, + (const uint16_t*)v->data, (const int*)g->data, (uint16_t*)o->data, rq, + (int)kt, (int)kh, (int)kw, scale, ql, kl, vl, ol); + return st_of(hipGetLastError()); + } + hipLaunchKernelGGL(attn_na3d_kernel<64>, grid, dim3(kT), 0, (hipStream_t)s, q->data, k->data, + v->data, (const int*)g->data, o->data, rq, (int)kt, (int)kh, (int)kw, scale, + ql, kl, vl, ol, is_bf16(q), is_bf16(k), is_bf16(v), is_bf16(o)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_vol_index(const RadArgs* a, RadStream s) { + const RadTensor *g = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!g || !y) return R4D_NO(RAD_E_INVAL); + if (g->dtype != RAD_I32 || y->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + if (r4d_numel(g) < 3 || !r4d_contig(g) || y->rank != 2 || y->shape[0] != 3 || + y->shape[1] <= 0 || y->stride[1] != 1) + return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(vol_index_kernel, dim3(grid_for(y->shape[1])), dim3(kT), 0, (hipStream_t)s, + (const int*)g->data, (int*)y->data, (long long)y->shape[1], + (long long)y->stride[0]); + return st_of(hipGetLastError()); +} + +// The cuts a tile op's parameters name (libref's tile_cuts); false when one is out of range. +static bool tile_cuts_d(const RadArgs* a, TileCutD* s, TileCutD* t) { + const char* rs = r4d_gets(a, "rule"); + const char* rule = rs ? rs : "stride"; + const bool iv = std::strcmp(rule, "intervals") == 0; + if (!iv && std::strcmp(rule, "stride") != 0) return false; + *s = TileCutD{ (int)r4d_geti_or(a, "tile", 0), (int)r4d_geti_or(a, "stride", 0), + (int)r4d_geti_or(a, "min", 1), iv }; + *t = TileCutD{ (int)r4d_geti_or(a, "tile_t", 1 << 30), (int)r4d_geti_or(a, "stride_t", 1 << 30), + (int)r4d_geti_or(a, "min_t", 1), iv }; + return s->tile > 0 && s->stride > 0 && s->stride <= s->tile && s->least > 0 && t->tile > 0 && + t->stride > 0 && t->stride <= t->tile && t->least > 0; +} + +extern "C" int r4d_rad_tile_grid(const RadArgs* a, RadStream s) { + const RadTensor *g = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!g || !y) return R4D_NO(RAD_E_INVAL); + if (g->dtype != RAD_I32 || y->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + TileCutD cs, ct; + const long long n = r4d_numel(y) / 8, tail = r4d_geti_or(a, "tail", 0); + if (!tile_cuts_d(a, &cs, &ct) || tail < 0 || n <= 0 || r4d_numel(g) < 3 || !r4d_contig(g) || + !r4d_contig(y)) + return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(tile_grid_kernel, dim3((unsigned)((n + kT - 1) / kT)), dim3(kT), 0, + (hipStream_t)s, (const int*)g->data, (int*)y->data, (int)n, cs, ct, (int)tail); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_tile_crop(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *g = r4d_opt(a, 1), *b = r4d_opt(a, 2), *y = r4d_opt(a, 3); + if (!x || !g || !b || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || !is_bf_or_f32(y) || g->dtype != RAD_I32 || b->dtype != RAD_I32) + return R4D_NO(RAD_E_DTYPE); + const long long C = r4d_geti_or(a, "C", 0); + if (C <= 0 || r4d_numel(g) < 3 || r4d_numel(b) < 6 || !r4d_contig(g) || !r4d_contig(b)) + return R4D_NO(RAD_E_SHAPE); + long long rx = 0, ry = 0; + const long long xl = r4d_rows_pitch(x, C, &rx), yl = r4d_rows_pitch(y, C, &ry); + if (xl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE); + if (rx <= 0 || ry <= 0) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(tile_crop_kernel, dim3(grid_for(ry * C)), dim3(kT), 0, (hipStream_t)s, + x->data, y->data, (const int*)g->data, (const int*)b->data, ry, (int)C, xl, + yl, is_bf16(x), is_bf16(y)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_tile_stitch(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *g = r4d_opt(a, 1), *f = r4d_opt(a, 2), *y = r4d_opt(a, 3); + if (!x || !g || !f || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || g->dtype != RAD_I32 || f->dtype != RAD_I32 || y->dtype != RAD_U8) + return R4D_NO(RAD_E_DTYPE); + TileCutD cs, ct; + const long long sc = r4d_geti_or(a, "scale", 0), st = r4d_geti_or(a, "scale_t", 1); + const long long p = r4d_geti_or(a, "p", 0), C = r4d_geti_or(a, "C", 0); + const int wh = patch_order(a); + if (wh < 0) return R4D_NO(RAD_E_INVAL); + if (!tile_cuts_d(a, &cs, &ct) || sc <= 0 || st <= 0 || p <= 0 || C <= 0 || + r4d_numel(g) < 3 || r4d_numel(f) < 1 || !r4d_contig(g) || !r4d_contig(f)) + return R4D_NO(RAD_E_SHAPE); + long long rx = 0, Cx = 0, xl = 0, ry = 0, Cy = 0, yl = 0; + if (!dense2(x, &rx, &Cx, &xl) || !dense2(y, &ry, &Cy, &yl)) return R4D_NO(RAD_E_SHAPE); + if (Cx != C * p * p || ry <= 0 || Cy <= 0) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(tile_stitch_kernel, dim3(grid_for(ry * Cy)), dim3(kT), 0, (hipStream_t)s, + x->data, (uint8_t*)y->data, (const int*)g->data, (const int*)f->data, ry, Cy, + cs, ct, (int)sc, (int)st, (int)p, (int)C, wh == 1, xl, yl, is_bf16(x)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_stft_logmel(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *b = r4d_opt(a, 1), *m = r4d_opt(a, 2), *y = r4d_opt(a, 3); + if (!x || !b || !m || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || !is_bf_or_f32(b) || !is_bf_or_f32(m) || !is_bf_or_f32(y)) + return R4D_NO(RAD_E_DTYPE); + const long long hop = r4d_geti_or(a, "hop", 0), nfft = r4d_geti_or(a, "nfft", 0); + const long long nm = r4d_geti_or(a, "n_mel", 0), ch = r4d_geti_or(a, "ch", 0); + if (hop <= 0 || nfft < hop || nfft > kStftMaxN || nm <= 0 || ch <= 0) + return R4D_NO(RAD_E_SHAPE); + const long long F = nfft / 2 + 1; + long long S = 0, frames = 0; + const long long xl = r4d_rows_pitch(x, ch, &S), yl = r4d_rows_pitch(y, ch * nm, &frames); + if (xl < 0 || yl < 0 || !r4d_contig(b) || !r4d_contig(m)) return R4D_NO(RAD_E_STRIDE); + if (S <= 0 || frames <= 0 || frames * hop > S || frames > INT32_MAX || + r4d_numel(b) < 2 * F * nfft || r4d_numel(m) < nm * F) + return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(stft_logmel_kernel, dim3((unsigned)frames, (unsigned)ch), dim3(kT), 0, + (hipStream_t)s, x->data, b->data, m->data, y->data, (int)frames, (int)ch, + (int)hop, (int)nfft, (int)nm, xl, yl, is_bf16(x), is_bf16(b), is_bf16(m), + is_bf16(y)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_bwe_up(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *rz = r4d_opt(a, 1), *y = r4d_opt(a, 2); + if (!x || !rz || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || !is_bf_or_f32(rz) || !is_bf_or_f32(y)) return R4D_NO(RAD_E_DTYPE); + const long long r = r4d_geti_or(a, "ratio", 0), ch = r4d_geti_or(a, "ch", 0); + const int w = (int)std::ceil(6.0 / 0.99); + const long long K = 2ll * w * r + 1; + if (r <= 0 || ch <= 0 || K > kBweTaps) return R4D_NO(RAD_E_SHAPE); + long long S = 0, O = 0, Rr = 0; + const long long xl = r4d_rows_pitch(x, ch, &S), yl = r4d_rows_pitch(y, ch, &O); + const long long rl = r4d_rows_pitch(rz, ch, &Rr); + if (xl < 0 || yl < 0 || rl < 0) return R4D_NO(RAD_E_STRIDE); + if (S <= 0 || O <= 0 || O > S * r || Rr < O) return R4D_NO(RAD_E_SHAPE); + // libref's taps: f32 arithmetic as torch builds the filter, rounded to x's dtype. + BweTaps f{}; + for (long long n = 0; n < K; ++n) { + const float u = ((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(uc * (float)M_PI / 6.0f / 2.0f); + const float pu = (float)M_PI * u; + const float sinc = u == 0.0f ? 1.0f : std::sin(pu) / pu; + const float v = sinc * (cw * cw) * 0.99f / (float)r; + f.f[n] = is_bf16(x) ? rad_bf16_to_f32(rad_f32_to_bf16(v)) : v; + } + hipLaunchKernelGGL(bwe_up_kernel, dim3(grid_for(O * ch)), dim3(kT), 0, (hipStream_t)s, + x->data, rz->data, y->data, f, S, O, (int)ch, (int)r, w, (int)K, xl, rl, yl, + is_bf16(x), is_bf16(rz), is_bf16(y)); + return st_of(hipGetLastError()); +} diff --git a/libr4d/r4d_mhc.hip b/libr4d/r4d_mhc.hip index 53a2b8ea..a92d039f 100644 --- a/libr4d/r4d_mhc.hip +++ b/libr4d/r4d_mhc.hip @@ -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 -__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 __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 +// 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 -__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 __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 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), 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), - 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), 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 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), 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), 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), 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), 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, diff --git a/libr4d/r4d_mla.hip b/libr4d/r4d_mla.hip index 710c1a35..58f93126 100644 --- a/libr4d/r4d_mla.hip +++ b/libr4d/r4d_mla.hip @@ -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 __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], diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index aa48c382..084a76e6 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -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 +__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, 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, 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 */ diff --git a/libr4d/r4d_moe_mxfp4.hip b/libr4d/r4d_moe_mxfp4.hip index ad22b3b5..4217fd53 100644 --- a/libr4d/r4d_moe_mxfp4.hip +++ b/libr4d/r4d_moe_mxfp4.hip @@ -10,14 +10,14 @@ #include "r4d_mxfp4.h" #include #include -#include +#include 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 +/* 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 +/* 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(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(bb + r * 136 + d) = mx_codes8(packed); + *reinterpret_cast(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 __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(aa + arow * P + ad) = ra; #pragma unroll for (int t = 0; t < 4; ++t) - *reinterpret_cast(bb + wcol * P + 2 * wd + 8 * t) = mx_codes8(rw[t]); + *reinterpret_cast(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 + * 16-byte rows instead of a lane's 2-byte column stores. */ +template 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 +template __global__ __launch_bounds__(256) - R4D_WAVES((MxP64::Waves)) void moe_mxfp4_p64_kernel( + R4D_WAVES((MxP64::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; + using G = MxP64; 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(aa + b * BM * PA + arow * PA + (a0 + i * TPA) * 16) = - ra[i]; - if (tid < BM * KB) sa[b * SAK * BM + tid] = rsa; + *reinterpret_cast(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(bb + b * BN * PB + wcol * PB + (w0c + i * TPW) * 32 + - 8 * t) = mx_codes8(rw[i][t]); + *reinterpret_cast(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(ab, wave_row * 16, ka + group * 32, lane); - const auto fa1 = r4d_fp8::frag(ab, wave_row * 16, ka + group * 32 + 16, lane); + const auto fa0 = r4d_fp8::frag(aa, wave_row * 16, ka + group * 32, lane); + const auto fa1 = r4d_fp8::frag(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(bp, colw + t * 16, kb * 128 + group * 32, lane), + fa0, r4d_fp8::frag(bb, colw + t * 16, kb * 128 + group * 32, lane), r4d_fp8::acc_zero()); raw = r4d_fp8::mma( fa1, - r4d_fp8::frag(bp, colw + t * 16, kb * 128 + group * 32 + 16, lane), + r4d_fp8::frag(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 +template __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(bb + c * P + 2 * d + 8 * t) = mx_codes8(q[t]); + *reinterpret_cast(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 +template __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(bb + c * P + 2 * d + 8 * t) = - mx_codes8(R.w[i][t]); + *reinterpret_cast(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(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), \ - 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), \ - 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), 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); } diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 7db0f3a9..6b74b26f 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -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); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index a4d7038a..4cd29805 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -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 */ diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 3844acbd..1e7e0e69 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -944,11 +944,12 @@ static void attn_oracle_one(const uint16_t* qh, const uint8_t* kv, int kv_is_fp8 * compare the bf16 output against the oracle above. A negative control corrupts part of the * reference and requires the comparison to fail. */ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_dim, int64_t gqa, - int64_t q_len, const char* kv_dtype, int window, int64_t ctx = 64) { + int64_t q_len, const char* kv_dtype, int window, int64_t ctx = 64, + int64_t bs = 16) { if (!sel(name)) return; const RadKernelInfo* r = find(pl, name); if (!r) { ok(name, false, "row absent"); return; } - const int64_t seqs = 1, kv_heads = 2, bs = 16; + const int64_t seqs = 1, kv_heads = 2; const int64_t q_heads = kv_heads * gqa; const int64_t max_blocks = (ctx + bs - 1) / bs; /* a ctx past a whole block: a partial last one */ const int64_t total_q = seqs * q_len; @@ -2671,9 +2672,12 @@ static void rowtopk_shard_case(const Plugin& pl) { * zero scale group and a scale of 1. The E4M3 cache is random bytes except NaN codes, the bf16 one * random finite values, and the descales are not 1. * - * `i8` runs both at int8 codes (the operand an int8 out projection reads), with the same claim. */ -static void attn_gq_fold_case(const Plugin& pl, int64_t S, bool bf16, bool i8 = false) { - const std::string kvs = bf16 ? "bf16kv" : "fp8kv"; + * `i8` runs both at int8 codes (the operand an int8 out projection reads), with the same claim. + * `kvq` 1 or 2 runs them over an fp8_v4 or k6_v4 cache instead of the E4M3 one: random codes with + * finite f16 group scales. */ +static void attn_gq_fold_case(const Plugin& pl, int64_t S, bool bf16, bool i8 = false, + int kvq = 0) { + const std::string kvs = bf16 ? "bf16kv" : kvq == 1 ? "fp8v4" : kvq == 2 ? "k6v4" : "fp8kv"; const std::string fold = "attn_decode_gq_h256_gqa12_" + kvs; const std::string pair = "attn_decode_h256_gqa12_" + kvs; if (!sel(fold.c_str())) return; @@ -2701,7 +2705,10 @@ static void attn_gq_fold_case(const Plugin& pl, int64_t S, bool bf16, bool i8 = std::vector hq((size_t)(S * nq * hd)), hqg((size_t)(S * nq * 2 * hd)); for (auto& x : hq) x = h_to_bf16(rnd(2.0f)); for (auto& x : hqg) x = h_to_bf16(rnd(6.0f)); - const size_t cbytes = (size_t)(nb * nkv * bs * 2 * hd) * (bf16 ? 2 : 1); + /* A token's row in a page: 2 * head_dim elements, or the v4 layouts' 25 / 22 * head_dim / 16 + * bytes (RadBuildCtx::kv_quant). */ + const int64_t rowb = kvq == 2 ? 22 * hd / 16 : kvq == 1 ? 25 * hd / 16 : 2 * hd; + const size_t cbytes = (size_t)(nb * nkv * bs * rowb) * (bf16 ? 2 : 1); std::vector hc(cbytes); if (bf16) { for (size_t i = 0; i + 1 < cbytes; i += 2) { @@ -2713,6 +2720,18 @@ static void attn_gq_fold_case(const Plugin& pl, int64_t S, bool bf16, bool i8 = x = (uint8_t)(rnd(128.0f) + 128.0f); if ((x & 0x7f) == 0x7f) x ^= 1; /* E4M3's NaN codes */ } + /* The group scales: K's (k6_v4) and V's, finite and positive. */ + const int64_t vs = kvq == 2 ? hd * 21 / 16 : hd * 3 / 2, ks = hd * 5 / 4; + if (kvq) + for (size_t r0 = 0; r0 < cbytes; r0 += (size_t)rowb) + for (int64_t g = 0; g < hd / 32; ++g) { + const _Float16 v = (_Float16)(0.03125f * (1.0f + (rnd(1.0f) + 1.0f) * 2.0f)); + std::memcpy(&hc[r0 + (size_t)(vs + g * 2)], &v, 2); + if (kvq == 2) { + const _Float16 k = (_Float16)(0.0078125f * (1.0f + (rnd(1.0f) + 1.0f) * 2.0f)); + std::memcpy(&hc[r0 + (size_t)(ks + g * 2)], &k, 2); + } + } } std::vector hds((size_t)(S * nkv)); for (auto& x : hds) x = 0.75f + 0.5f * (rnd(1.0f) + 1.0f) * 0.5f; @@ -2741,7 +2760,7 @@ static void attn_gq_fold_case(const Plugin& pl, int64_t S, bool bf16, bool i8 = auto attn_ops = [&](void* out) { return std::vector{ T(d_q, RAD_BF16, { S, nq, hd }), - T(d_c, bf16 ? RAD_BF16 : RAD_F8E4M3, { nb, nkv, bs, 2 * hd }), + T(d_c, bf16 ? RAD_BF16 : RAD_F8E4M3, { nb, nkv, bs, rowb }), TI32({ S, maxb }, table), TI32({ S }, used), T(d_kd, RAD_F32, { S, nkv }), @@ -2752,7 +2771,7 @@ static void attn_gq_fold_case(const Plugin& pl, int64_t S, bool bf16, bool i8 = std::vector pa = { PI("q_len", 1), PI("head_dim", hd), PI("gqa", nq / nkv), PI("block_size", bs), PI("causal", 1), PI("window", 0), PS("q_dtype", "bf16"), - PS("kv_dtype", bf16 ? "bf16" : "fp8_e4m3"), + PS("kv_dtype", bf16 ? "bf16" : kvq == 1 ? "fp8_v4" : kvq == 2 ? "k6_v4" : "fp8_e4m3"), PI("n_head", nq), PI("max_seqs", S), PI("max_ctx", maxb * bs), }; @@ -6807,6 +6826,1186 @@ void snake_aa_cases(const Plugin& pl) { } /* namespace vid */ +/* ================================================================== the joint image generators + * Krea 2's and FLUX.3's ops: table_add, mix_rows, chan_stats, attn_cross, rms_mod's zero-centred + * and LayerNorm forms, timestep_embed's bf16 roundings and the wide attention at 384 and 512, each + * against the host's arithmetic in libref's order. */ +namespace g3 { + +using namespace au; + +/* y[r, l n + c] = x[r, c] + t[l, c]: exact, x at a wider pitch, y a column slice. */ +void table_add_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "table_add_bf16"); + if (!r) { ok("table_add_bf16", false, "row absent"); return; } + const int64_t M = 3, n = 6144 * 6, L = 1, xld = n + 64, yld = 28 * n; + std::vector x = randv((size_t)(M * xld), 1.0f), t = randv((size_t)(L * n), 0.5f); + for (float& v : x) v = bfr(v); + for (float& v : t) v = bfr(v); + RadTensor tx = T(up_bf16(x), RAD_BF16, { M, n }); + tx.stride[0] = xld; + void* dy = dalloc((size_t)(M * yld) * 2); + RadTensor ty = T((char*)dy + 5 * n * 2, RAD_BF16, { M, L * n }); + ty.stride[0] = yld; + const int rc = launch(r, { tx, T(up_bf16(t), RAD_BF16, { L, n }), ty }, + { PI("M", M), PI("n", n), PI("L", L), PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok("table_add_bf16", false, "rc " + std::to_string(rc)); return; } + const std::vector all = down_bf16(dy, (size_t)(M * yld)); + int64_t bad = 0; + for (int64_t row = 0; row < M; ++row) + for (int64_t c = 0; c < n; ++c) + bad += all[(size_t)(row * yld + 5 * n + c)] != bfr(x[(size_t)(row * xld + c)] + t[(size_t)c]); + ok("table_add_bf16 one block's table into its columns, exact", bad == 0, + fmt("%lld values differ", (long long)bad)); +} + +/* y[r, c] = sum_i w[i] x[r k + i, c], twelve taps of 2560. */ +void mix_rows_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "mix_rows_bf16"); + if (!r) { ok("mix_rows_bf16", false, "row absent"); return; } + const int64_t M = 37, n = 2560, k = 12; + std::vector x = randv((size_t)(M * k * n), 1.0f), w = randv((size_t)k, 0.3f); + for (float& v : x) v = bfr(v); + for (float& v : w) v = bfr(v); + void* dy = dalloc((size_t)(M * n) * 2); + const int rc = launch(r, { T(up_bf16(x), RAD_BF16, { M * k, n }), T(up_bf16(w), RAD_BF16, { k }), + T(dy, RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PI("k", k), PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok("mix_rows_bf16", false, "rc " + std::to_string(rc)); return; } + std::vector want((size_t)(M * n)); + for (int64_t row = 0; row < M; ++row) + for (int64_t c = 0; c < n; ++c) { + float acc = 0.0f; + for (int64_t i = 0; i < k; ++i) acc += w[(size_t)i] * x[(size_t)((row * k + i) * n + c)]; + want[(size_t)(row * n + c)] = bfr(acc); + } + check("mix_rows_bf16 twelve taps", down_bf16(dy, want.size()), want, 8e-3); +} + +/* Both modes, a deviation and a variance (FLUX's BatchNorm, eps 1e-4). */ +void chan_stats_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "chan_stats_bf16"); + if (!r) { ok("chan_stats_bf16", false, "row absent"); return; } + const int64_t M = 33, n = 128; + for (const bool norm : { false, true }) + for (const int var : { 0, 1 }) { + std::vector x = randv((size_t)(M * n), 2.0f), mu = randv((size_t)n, 0.5f); + std::vector sv((size_t)n); + for (int64_t c = 0; c < n; ++c) sv[(size_t)c] = bfr(0.3f + 0.02f * (float)c); + for (float& v : x) v = bfr(v); + for (float& v : mu) v = bfr(v); + void* dy = dalloc((size_t)(M * n) * 2); + const int rc = launch(r, { T(up_bf16(x), RAD_BF16, { M, n }), + T(up_bf16(mu), RAD_BF16, { n }), + T(up_bf16(sv), RAD_BF16, { n }), T(dy, RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PS("mode", norm ? "norm" : "denorm"), + PI("var", var), PF("eps", 1e-4), PS("dtype", "bf16") }); + const std::string nm = fmt("chan_stats_bf16 %s var %d", norm ? "norm" : "denorm", var); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(M * n)); + for (int64_t row = 0; row < M; ++row) + for (int64_t c = 0; c < n; ++c) { + const float sd = var ? bfr(std::sqrt(sv[(size_t)c] + 1e-4f)) : sv[(size_t)c]; + const float xv = x[(size_t)(row * n + c)]; + want[(size_t)(row * n + c)] = norm ? bfr(bfr(xv - mu[(size_t)c]) / sd) + : bfr(bfr(xv * sd) + mu[(size_t)c]); + } + check(nm, down_bf16(dy, want.size()), want, 8e-3); + } +} + +/* The f32 form over bf16 and f32 statistics: exact against the host's f32 steps. */ +void chan_stats_f32_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "chan_stats_f32"); + if (!r) { ok("chan_stats_f32", false, "row absent"); return; } + const int64_t M = 19, n = 128; + for (const bool wf32 : { false, true }) + for (const bool norm : { false, true }) + for (const int var : { 0, 1 }) { + std::vector x = randv((size_t)(M * n), 2.0f), mu = randv((size_t)n, 0.5f); + std::vector sv((size_t)n); + for (int64_t c = 0; c < n; ++c) sv[(size_t)c] = 0.3f + 0.0137f * (float)c; + if (!wf32) { + for (float& v : mu) v = bfr(v); + for (float& v : sv) v = bfr(v); + } + void* dy = dalloc((size_t)(M * n) * 4); + const uint32_t wd = wf32 ? RAD_F32 : RAD_BF16; + const int rc = launch(r, { T(up_f32(x), RAD_F32, { M, n }), + T(wf32 ? up_f32(mu) : up_bf16(mu), wd, { n }), + T(wf32 ? up_f32(sv) : up_bf16(sv), wd, { n }), + T(dy, RAD_F32, { M, n }) }, + { PI("M", M), PI("n", n), PS("mode", norm ? "norm" : "denorm"), + PI("var", var), PF("eps", 1e-4), PS("dtype", "f32") }); + const std::string nm = fmt("chan_stats_f32 %s stats %s var %d", norm ? "norm" : "denorm", + wf32 ? "f32" : "bf16", var); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(M * n)); + for (int64_t row = 0; row < M; ++row) + for (int64_t c = 0; c < n; ++c) { + volatile float e = sv[(size_t)c] + 1e-4f; + const float sd = var ? std::sqrt((float)e) : sv[(size_t)c]; + const float xv = x[(size_t)(row * n + c)]; + volatile float t = norm ? xv - mu[(size_t)c] : xv * sd; + want[(size_t)(row * n + c)] = norm ? (float)t / sd : (float)t + mu[(size_t)c]; + } + /* f32 against f32 (rel() would round the answer to bf16 first): each error over + * the size of the terms it came from, |x s| + |mean| or |x - mean| / s, since a + * result near zero is a cancellation. The device's square root may sit an ulp from + * the host's. */ + const std::vector got = down_f32(dy, want.size()); + double worst = 0; + for (int64_t row = 0; row < M; ++row) + for (int64_t c = 0; c < n; ++c) { + const size_t e = (size_t)(row * n + c); + const double sd = var ? std::sqrt((double)sv[(size_t)c] + 1e-4) : sv[(size_t)c]; + const double xv = x[e], m = mu[(size_t)c]; + const double size = norm ? (std::fabs(xv) + std::fabs(m)) / sd + : std::fabs(xv * sd) + std::fabs(m); + worst = std::max(worst, std::fabs((double)got[e] - want[e]) / + std::max(1e-30, size)); + } + ok(fmt("%s (max error over the terms %.3g, bound 5e-7)", nm.c_str(), worst).c_str(), + worst <= 5e-7); + } +} + +/* Host attention over q rows [q0, q1) against key rows [k0, k1), causal on relative indices. */ +static void host_attn(const std::vector& q, const std::vector& k, + const std::vector& v, int64_t qld, int64_t kld, int64_t nh, + int64_t nkv, int64_t hd, int64_t q0, int64_t q1, int64_t k0, int64_t k1, + bool causal, std::vector* out) { + const float sc = 1.0f / std::sqrt((float)hd); + for (int64_t i = q0; i < q1; ++i) + for (int64_t h = 0; h < nh; ++h) { + const int64_t kh = h / (nh / nkv); + const int64_t je = causal ? std::min(k1, k0 + (i - q0) + 1) : k1; + std::vector s; + double mx = -1e30; + for (int64_t j = k0; j < je; ++j) { + double d = 0; + for (int64_t t = 0; t < hd; ++t) + d += (double)q[(size_t)(i * qld + h * hd + t)] * k[(size_t)(j * kld + kh * hd + t)]; + s.push_back(d * sc); + mx = std::max(mx, s.back()); + } + double sum = 0; + for (double& e : s) { e = std::exp(e - mx); sum += e; } + for (int64_t t = 0; t < hd; ++t) { + double a = 0; + for (int64_t j = k0; j < je; ++j) + a += s[(size_t)(j - k0)] * v[(size_t)(j * kld + kh * hd + t)]; + (*out)[(size_t)(i * nh * hd + h * hd + t)] = s.empty() ? 0.0f : (float)(a / sum); + } + } +} + +/* Two entries, queries and keys of different counts, at gqa 1 and 4, causal and not. */ +void attn_cross_cases(const Plugin& pl, int64_t hd) { + const std::string row = fmt("attn_cross_h%lld_bf16", (long long)hd); + const RadKernelInfo* r = find(pl, row.c_str()); + if (!r) { ok(row.c_str(), false, "row absent"); return; } + for (const int64_t gqa : { 1, 4 }) + for (const int causal : { 0, 1 }) { + const int64_t nkv = 2, nh = nkv * gqa, Q = 150, K = 211; + const std::vector cuq = { 0, 70, 150 }, cuk = { 0, 123, 211 }; + std::vector q = randv((size_t)(Q * nh * hd), 1.0f); + std::vector k = randv((size_t)(K * nkv * hd), 1.0f), v = randv((size_t)(K * nkv * hd), 1.0f); + for (float& x : q) x = bfr(x); + for (float& x : k) x = bfr(x); + for (float& x : v) x = bfr(x); + void* dout = dalloc((size_t)(Q * nh * hd) * 2); + const int rc = launch(r, { T(up_bf16(q), RAD_BF16, { Q, nh * hd }), + T(up_bf16(k), RAD_BF16, { K, nkv * hd }), + T(up_bf16(v), RAD_BF16, { K, nkv * hd }), + T(up_i32(cuq), RAD_I32, { 3 }), T(up_i32(cuk), RAD_I32, { 3 }), + T(dout, RAD_BF16, { Q, nh * hd }) }, + { PI("M", Q), PI("head_dim", hd), PI("gqa", gqa), + PI("causal", causal), PS("dtype", "bf16") }); + const std::string nm = fmt("%s gqa %lld causal %d", row.c_str(), (long long)gqa, causal); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(Q * nh * hd)); + for (int e = 0; e < 2; ++e) + host_attn(q, k, v, nh * hd, nkv * hd, nh, nkv, hd, cuq[(size_t)e], cuq[(size_t)e + 1], + cuk[(size_t)e], cuk[(size_t)e + 1], causal != 0, &want); + check(nm, down_bf16(dout, want.size()), want, 2e-2); + } +} + +/* attn_dense at the grouped h256 and h512 rows, causal and not, over two segments: a text + * encoder's prompt (Gemma 4's sliding and global layers). */ +void attn_dense_gqa_cases(const Plugin& pl) { + for (const int64_t hd : { 256, 512 }) + for (const int64_t gqa : { 2, 4, 8, 16 }) { + /* 16 query heads a KV head run on the gqa-8 row, two workgroups a KV head. */ + const std::string row = fmt("attn_dense_h%lld_gqa%lld_bf16", (long long)hd, + (long long)std::min(gqa, 8)); + const RadKernelInfo* r = find(pl, row.c_str()); + if (!r) { ok(row.c_str(), false, "row absent"); continue; } + for (const int causal : { 0, 1 }) { + const int64_t nkv = 2, nh = nkv * gqa, total = 173; + const std::vector cu = { 0, 101, 173 }; + std::vector q = randv((size_t)(total * nh * hd), 1.0f); + std::vector k = randv((size_t)(total * nkv * hd), 1.0f); + std::vector v = randv((size_t)(total * nkv * hd), 1.0f); + for (float& x : q) x = bfr(x); + for (float& x : k) x = bfr(x); + for (float& x : v) x = bfr(x); + void* dout = dalloc((size_t)(total * nh * hd) * 2); + const int rc = launch(r, { T(up_bf16(q), RAD_BF16, { total, nh * hd }), + T(up_bf16(k), RAD_BF16, { total, nkv * hd }), + T(up_bf16(v), RAD_BF16, { total, nkv * hd }), + T(up_i32(cu), RAD_I32, { 3 }), + T(dout, RAD_BF16, { total, nh * hd }) }, + { PI("M", total), PI("head_dim", hd), PI("gqa", gqa), + PI("causal", causal), PS("dtype", "bf16"), + PI("max_seqlen", 101) }); + const std::string nm = fmt("%s gqa %lld causal %d", row.c_str(), (long long)gqa, + causal); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(total * nh * hd)); + for (int e = 0; e < 2; ++e) + host_attn(q, k, v, nh * hd, nkv * hd, nh, nkv, hd, cu[(size_t)e], + cu[(size_t)e + 1], cu[(size_t)e], cu[(size_t)e + 1], causal != 0, &want); + check(nm, down_bf16(dout, want.size()), want, 2e-2); + } + } +} + +/* One wide head over every pixel, 384 and 512. */ +void attn_wide_cases(const Plugin& pl) { + for (const int64_t hd : { 384, 512 }) { + const std::string row = fmt("attn_dense_h%lld_bf16", (long long)hd); + const RadKernelInfo* r = find(pl, row.c_str()); + if (!r) { ok(row.c_str(), false, "row absent"); continue; } + const int64_t N = 300; + const std::vector cu = { 0, (int32_t)N }; + std::vector qkv = randv((size_t)(N * 3 * hd), 1.0f); + for (float& x : qkv) x = bfr(x); + void* d = up_bf16(qkv); + auto col = [&](int c) { + RadTensor t = T((char*)d + c * hd * 2, RAD_BF16, { N, hd }); + t.stride[0] = 3 * hd; + return t; + }; + void* dout = dalloc((size_t)(N * hd) * 2); + const int rc = launch(r, { col(0), col(1), col(2), T(up_i32(cu), RAD_I32, { 2 }), + T(dout, RAD_BF16, { N, hd }) }, + { PI("M", N), PI("head_dim", hd), PI("gqa", 1), PI("causal", 0), + PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok(row.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector q((size_t)(N * hd)), k((size_t)(N * hd)), v((size_t)(N * hd)); + for (int64_t i = 0; i < N; ++i) + for (int64_t t = 0; t < hd; ++t) { + q[(size_t)(i * hd + t)] = qkv[(size_t)(i * 3 * hd + t)]; + k[(size_t)(i * hd + t)] = qkv[(size_t)(i * 3 * hd + hd + t)]; + v[(size_t)(i * hd + t)] = qkv[(size_t)(i * 3 * hd + 2 * hd + t)]; + } + std::vector want((size_t)(N * hd)); + host_attn(q, k, v, hd, hd, 1, 1, hd, 0, N, 0, N, false, &want); + check(row + " one head over 300 rows", down_bf16(dout, want.size()), want, 2e-2); + } +} + +/* rms_mod's zero-centred gain rounded once (Krea 2) and its gainless LayerNorm (FLUX), gated + * and not, plain and quantised. */ +void rms_mod_forms(const Plugin& pl) { + for (const bool quant : { false, true }) { + const char* name = quant ? "rms_mod_quant_fp8_bf16" : "rms_mod_bf16"; + const RadKernelInfo* r = find(pl, name); + if (!r) { ok(name, false, "row absent"); continue; } + const int64_t n = 3072, M = 7, segs = 3, pitch = 3 * n; + const std::vector cu = { 0, 2, 5, 7 }; + for (const bool layer : { false, true }) + for (const int gated : { 0, 1 }) { + std::vector x = randv((size_t)(M * n), 2.0f), y = randv((size_t)(M * n), 1.0f); + std::vector tab = randv((size_t)(segs * pitch), 0.5f), w = randv((size_t)n, 0.1f); + for (float& v : x) v = bfr(v + 0.7f); + for (float& v : y) v = bfr(v); + for (float& v : tab) v = bfr(v); + for (float& v : w) v = bfr(v); + void* dx = up_bf16(x); + void* dtab = up_bf16(tab); + RadTensor tg = T(dtab, RAD_BF16, { segs, n }); + tg.stride[0] = pitch; + RadTensor ts2 = T((char*)dtab + n * 2, RAD_BF16, { segs, 2 * n }); + ts2.stride[0] = pitch; + RadTensor ty = T(up_bf16(y), RAD_BF16, { M, n }); + if (!gated) { absent(ty); absent(tg); } + RadTensor tw = T(up_bf16(w), RAD_BF16, { n }); + if (layer) absent(tw); + void* dz = dalloc((size_t)(M * n) * 2); + void* dq = dalloc((size_t)(M * n)); + void* dqs = dalloc((size_t)(M * n / 128) * 4); + std::vector args = { ty, tg, ts2, tw, T(up_i32(cu), RAD_I32, { 4 }), + T(dx, RAD_BF16, { M, n }) }; + std::vector ps = { PI("M", M), PI("n", n), PF("eps", 1e-6), + PI("gated", gated), PS("dtype", "bf16") }; + if (layer) ps.push_back(PS("norm", "layer")); + else { ps.push_back(PF("wadd", 1.0)); ps.push_back(PI("norm_once", 1)); } + if (quant) { + args.push_back(T(dq, RAD_F8E4M3, { M, n })); + args.push_back(T(dqs, RAD_F32, { M, n / 128 })); + ps.push_back(PI("group", 128)); + } + args.push_back(T(dz, RAD_BF16, { M, n })); + const std::string nm = fmt("%s %s gated %d", name, layer ? "layer" : "zero-centred", + gated); + const int rc = launch(r, args, ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(M * n)); + for (int64_t row = 0; row < M; ++row) { + const int64_t e = seq_of(cu, row); + float* xv = x.data() + row * n; + if (gated) + for (int64_t i = 0; i < n; ++i) + xv[i] = bfr(xv[i] + bfr(tab[(size_t)(e * pitch + i)] * y[(size_t)(row * n + i)])); + float mu = 0.0f; + if (layer) { + for (int64_t i = 0; i < n; ++i) mu += xv[i]; + mu /= (float)n; + } + float ss = 0.0f; + for (int64_t i = 0; i < n; ++i) ss += (xv[i] - mu) * (xv[i] - mu); + const float rs = 1.0f / std::sqrt(ss / (float)n + 1e-6f); + for (int64_t i = 0; i < n; ++i) { + const float vv = xv[i] - mu; + const float n2 = layer ? bfr(vv * rs) : bfr(vv * rs * (w[(size_t)i] + 1.0f)); + const float sc = bfr(1.0f + tab[(size_t)(e * pitch + 2 * n + i)]); + want[(size_t)(row * n + i)] = bfr(bfr(n2 * sc) + tab[(size_t)(e * pitch + n + i)]); + } + } + check(nm + " norm", down_bf16(dz, want.size()), want, 4e-3); + if (quant) { + std::vector qb((size_t)(M * n)); + st_memcpy(qb.data(), dq, qb.size(), hipMemcpyDeviceToHost); + const std::vector qs = down_f32(dqs, (size_t)(M * n / 128)); + std::vector deq((size_t)(M * n)); + for (size_t i = 0; i < deq.size(); ++i) deq[i] = rad_fp8e4m3_to_f32(qb[i]) * qs[i / 128]; + check(nm + " codes", deq, want, 4e-2); + } + } + } +} + +/* timestep_embed's round 2 (1000 bf16(t)) and 3 (bf16(1000 bf16(t))): the angle from each. */ +void timestep_round_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "timestep_embed_bf16"); + if (!r) { ok("timestep_embed_bf16", false, "row absent"); return; } + const std::vector t = { 0.9876543f, 0.5f, 0.0123457f }; + for (const int round : { 2, 3 }) { + void* dy = dalloc((size_t)(3 * 256) * 2); + const int rc = launch(r, { T(up_f32(t), RAD_F32, { 3 }), T(dy, RAD_BF16, { 3, 256 }) }, + { PI("M", 3), PI("n", 256), PF("scale", 1000.0), + PF("max_period", 10000.0), PI("round", round), + PS("dtype", "bf16") }); + const std::string nm = fmt("timestep_embed_bf16 round %d", round); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want(3 * 256); + for (int m = 0; m < 3; ++m) { + const float tt = round == 3 ? bfr(1000.0f * bfr(t[(size_t)m])) : 1000.0f * bfr(t[(size_t)m]); + for (int i = 0; i < 128; ++i) { + const float f = std::exp(-std::log(10000.0f) * (float)i / 128.0f); + want[(size_t)(m * 256 + i)] = bfr(std::cos(tt * f)); + want[(size_t)(m * 256 + 128 + i)] = bfr(std::sin(tt * f)); + } + } + check(nm, down_bf16(dy, want.size()), want, 2e-2); + } +} + +} /* namespace g3 */ + +/* ================================================================== LTX-2 + * rope_split, head_gate and ltx_guide against the host's arithmetic in libref's order: the rotary's + * device sincosf within a few bf16 steps, the gate exact, the guided step's f64 deviations. */ +namespace ltx { + +using namespace au; + +static double lin01(int64_t i, int64_t steps) { + if (steps <= 1) return 0.0; + const double st = 1.0 / (double)(steps - 1); + return i < steps / 2 ? st * (double)i : 1.0 - st * (double)(steps - 1 - i); +} + +/* The video's 3-axis rotary over a rank's second and third heads of 4096 (two pairs padded), and + * a 1-axis one over 2048, each over a column slice of a fused [q | k | v] row. */ +void rope_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "rope_split"); + if (!r) { ok("rope_split", false, "row absent"); return; } + struct Case { int64_t nh, hd, dim, nd, h0; const char* mx; }; + for (const Case cs : { Case{ 2, 128, 4096, 3, 1, "20 2048 2048" }, + Case{ 32, 64, 2048, 1, 0, "20" } }) { + const int64_t M = 77, w = cs.nh * cs.hd, ld = 3 * w + 8; + std::vector x = randv((size_t)(M * ld), 1.0f); + for (float& v : x) v = bfr(v); + std::vector pos((size_t)(cs.nd * M)); + for (int64_t d = 0; d < cs.nd; ++d) + for (int64_t i = 0; i < M; ++i) + pos[(size_t)(d * M + i)] = d == 0 ? (float)i / 24.0f : (float)(32 * (i % 9) + 16); + void* dx = up_bf16(x); + RadTensor tx = T((char*)dx + w * 2, RAD_BF16, { M, w }); + tx.stride[0] = ld; + const int rc = launch(r, { tx, T(up_f32(pos), RAD_F32, { cs.nd, M }) }, + { PI("M", M), PI("n_head", cs.nh), PI("head_dim", cs.hd), + PI("dim", cs.dim), PI("n_dims", cs.nd), PF("theta", 10000.0), + PS("max", cs.mx), PI("head0", cs.h0), PS("dtype", "bf16") }); + const std::string nm = fmt("rope_split %lld axes over %lld", (long long)cs.nd, + (long long)cs.dim); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + float mx[3] = { 20.0f, 2048.0f, 2048.0f }; + const int64_t P2 = cs.dim / 2, steps = P2 / cs.nd, pad = P2 - steps * cs.nd, half = cs.hd / 2; + std::vector want((size_t)(M * w)), got((size_t)(M * w)); + const std::vector all = down_bf16(dx, (size_t)(M * ld)); + for (int64_t i = 0; i < M; ++i) + for (int64_t c = 0; c < w; ++c) { + want[(size_t)(i * w + c)] = x[(size_t)(i * ld + w + c)]; + got[(size_t)(i * w + c)] = all[(size_t)(i * ld + w + c)]; + } + for (int64_t i = 0; i < M; ++i) + for (int64_t h = 0; h < cs.nh; ++h) + for (int64_t k = 0; k < half; ++k) { + const int64_t p = (cs.h0 + h) * half + k; + if (p < pad) continue; + const int64_t j = p - pad, d = j % cs.nd, f = j / cs.nd; + const float fr = (float)(std::pow(10000.0, lin01(f, steps)) * M_PI / 2.0); + const float g = pos[(size_t)(d * M + i)] / mx[d]; + const float ang = (2.0f * g - 1.0f) * fr; + const float co = (float)std::cos((double)ang), si = (float)std::sin((double)ang); + const float x1 = x[(size_t)(i * ld + w + h * cs.hd + k)]; + const float x2 = x[(size_t)(i * ld + w + h * cs.hd + half + k)]; + want[(size_t)(i * w + h * cs.hd + k)] = bfr(x1 * co - x2 * si); + want[(size_t)(i * w + h * cs.hd + half + k)] = bfr(x2 * co + x1 * si); + } + check(nm, got, want, 4e-3); + /* The columns either side of the slice are untouched. */ + int64_t moved = 0; + for (int64_t i = 0; i < M; ++i) + for (int64_t c = 0; c < w; ++c) moved += all[(size_t)(i * ld + c)] != x[(size_t)(i * ld + c)]; + ok(fmt("%s leaves the neighbouring columns", nm.c_str()).c_str(), moved == 0); + } +} + +void gate_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "head_gate"); + if (!r) { ok("head_gate", false, "row absent"); return; } + const int64_t M = 53, nh = 32, hd = 128, gld = nh + 3; + std::vector x = randv((size_t)(M * nh * hd), 2.0f), g = randv((size_t)(M * gld), 3.0f); + for (float& v : x) v = bfr(v); + for (float& v : g) v = bfr(v); + void* dx = up_bf16(x); + RadTensor tg = T(up_bf16(g), RAD_BF16, { M, nh }); + tg.stride[0] = gld; + const int rc = launch(r, { tg, T(dx, RAD_BF16, { M, nh * hd }) }, + { PI("M", M), PI("n_head", nh), PI("head_dim", hd), PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok("head_gate", false, "rc " + std::to_string(rc)); return; } + std::vector want((size_t)(M * nh * hd)); + for (int64_t i = 0; i < M; ++i) + for (int64_t c = 0; c < nh * hd; ++c) { + const float sg = bfr(1.0f / (1.0f + std::exp(-g[(size_t)(i * gld + c / hd)]))); + want[(size_t)(i * nh * hd + c)] = bfr(x[(size_t)(i * nh * hd + c)] * bfr(2.0f * sg)); + } + const std::vector got = down_bf16(dx, want.size()); + ok("head_gate 32 heads of 128, logits at a wider pitch", + differ(got, want) <= (int64_t)(want.size() / 1000), fmt("%lld differ", (long long)differ(got, want))); +} + +/* Every pass bound with the rescale on, then CFG alone: x after one step against the host's f64 + * deviations. */ +void guide_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "ltx_guide"); + if (!r) { ok("ltx_guide", false, "row absent"); return; } + const int64_t M = 3000, n = 128; + for (const bool full : { true, false }) { + std::vector x = randv((size_t)(M * n), 1.0f); + std::vector> v(4); + for (auto& e : v) { + e = randv((size_t)(M * n), 1.0f); + for (float& q : e) q = bfr(q); + } + const std::vector sc = full ? std::vector{ 3.0f, 1.0f, 3.0f, 0.7f } + : std::vector{ 7.0f, 0.0f, 1.0f, 0.0f }; + const std::vector sh = { 0.909375f, 0.725f }; + void* dx = up_f32(x); + void* st = dalloc((size_t)8200 * 4); + const int rc = launch(r, { T(up_bf16(v[0]), RAD_BF16, { M, n }), + T(up_bf16(v[1]), RAD_BF16, { M, n }), + full ? T(up_bf16(v[2]), RAD_BF16, { M, n }) : RadTensor{}, + full ? T(up_bf16(v[3]), RAD_BF16, { M, n }) : RadTensor{}, + T(up_f32(sc), RAD_F32, { 4 }), T(up_f32(sh), RAD_F32, { 2 }), + T(st, RAD_F32, { 8200 }), T(dx, RAD_F32, { M, n }) }, + { PI("M", M), PI("n", n), PS("dtype", "bf16") }); + const std::string nm = full ? "ltx_guide every pass, rescaled" : "ltx_guide CFG alone"; + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + const float sig = sh[0], dt = sh[1] - sh[0]; + std::vector x0c((size_t)(M * n)), g((size_t)(M * n)), want((size_t)(M * n)); + for (size_t e = 0; e < want.size(); ++e) { + const float xc = x[e] - v[0][e] * sig; + float gv = xc; + gv = gv + (sc[0] - 1.0f) * (xc - (x[e] - v[1][e] * sig)); + if (full) gv = gv + sc[1] * (xc - (x[e] - v[2][e] * sig)); + if (full) gv = gv + (sc[2] - 1.0f) * (xc - (x[e] - v[3][e] * sig)); + x0c[e] = xc; + g[e] = gv; + } + float fac = 1.0f; + if (sc[3] > 0.0f) { + auto sd = [&](const std::vector& a) { + double m = 0.0, q = 0.0; + for (float e : a) m += e; + m /= (double)a.size(); + for (float e : a) q += ((double)e - m) * ((double)e - m); + return (float)std::sqrt(q / (double)(a.size() - 1)); + }; + fac = sd(x0c) / sd(g); + } + const float kept = (float)(1.0 - (double)sc[3]); + for (size_t e = 0; e < want.size(); ++e) { + float gv = g[e]; + if (sc[3] > 0.0f) gv = sc[3] * (gv * fac) + kept * gv; + want[e] = x[e] + dt * ((x[e] - gv) / sig); + } + /* An f32 latent: compared in f32 (check() holds a bf16 answer). */ + const std::vector got = down_f32(dx, want.size()); + double e = 0.0, w2 = 0.0; + for (size_t i = 0; i < want.size(); ++i) { + e += ((double)got[i] - want[i]) * ((double)got[i] - want[i]); + w2 += (double)want[i] * want[i]; + } + const double rl = std::sqrt(e / w2); + ok(fmt("%s (rel_l2 %.3g, bound 1e-6)", nm.c_str(), rl).c_str(), rl <= 1e-6); + } +} + + +/* ---- LTX-2's VAE, audio VAE and vocoder ops, each against a host port of its libref function + * (libref/ref_ltx.cpp). Copies are compared bit for bit; sums the kernel orders differently to a + * relative L2. */ + +/* The div form with SiLU (the VAE's norm) at bf16, and the rsqrt form interleaving 4 layers and + * scaled (the connectors') at f32 in and bf16 out. */ +void pixel_norm_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "pixel_norm"); + if (!r) { ok("pixel_norm", false, "row absent"); return; } + struct Case { int64_t rows, n, L; bool div, silu, xf32; float eps, mult; }; + for (const Case c : { Case{ 333, 512, 1, true, true, false, 1e-8f, 1.0f }, + Case{ 4 * 37, 96, 4, false, false, true, 1e-6f, 2.75f } }) { + std::vector x = randv((size_t)(c.rows * c.n), 2.0f); + void* dx = c.xf32 ? up_f32(x) : up_bf16(x); + void* dy = dalloc((size_t)(c.rows * c.n) * 2); + std::vector ps = { PI("M", c.rows / c.L), PI("n", c.n), PF("eps", c.eps), + PS("form", c.div ? "div" : "rsqrt"), PS("dtype", "bf16") }; + if (c.silu) ps.push_back(PS("act", "silu")); + if (c.L > 1) ps.push_back(PI("ileave", c.L)); + if (c.mult != 1.0f) ps.push_back(PF("mult", c.mult)); + const int rc = launch(r, { T(dx, c.xf32 ? RAD_F32 : RAD_BF16, { c.rows, c.n }), + T(dy, RAD_BF16, { c.rows / c.L, c.n * c.L }) }, + ps); + const std::string nm = fmt("pixel_norm %s%s over %lld, %lld layers interleaved", + c.div ? "div" : "rsqrt", c.silu ? " silu" : "", (long long)c.n, + (long long)c.L); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(c.rows * c.n)); + for (int64_t q = 0; q < c.rows; ++q) { + float ss = 0.0f; + for (int64_t i = 0; i < c.n; ++i) { + const float v = x[(size_t)(q * c.n + i)]; + ss += bfr(v * v); + } + const float v = bfr(bfr(ss / (float)c.n) + c.eps); + const float s = c.div ? bfr(std::sqrt(v)) : bfr(1.0f / std::sqrt(v)); + for (int64_t i = 0; i < c.n; ++i) { + const float xv = x[(size_t)(q * c.n + i)]; + float z = bfr(c.div ? xv / s : xv * s); + if (c.silu) z = bfr(z / (1.0f + std::exp(-z))); + if (c.mult != 1.0f) z = bfr(z * c.mult); + want[(size_t)((q / c.L) * c.n * c.L + i * c.L + q % c.L)] = z; + } + } + check(nm, down_bf16(dy, want.size()), want, 4e-3); + } +} + +/* The upsampler's 2 x 2 x 2 and 1 x 2 x 2 depth to space; the downsampler's space to depth, copy + * with a frame prepended, and the residual's group mean added into y. */ +void resample_cases(const Plugin& pl) { + const RadKernelInfo* rd = find(pl, "d2s3d"); + const RadKernelInfo* rs = find(pl, "s2d3d"); + if (!rd || !rs) { ok("d2s3d / s2d3d", false, "row absent"); return; } + struct D { int64_t st, drop; }; + for (const D dd : { D{ 2, 1 }, D{ 1, 0 }, D{ 2, 0 } }) { + const int64_t st = dd.st, drop = dd.drop; + const int64_t T0 = 3, H = 5, W = 7, C = 24, P = st * 4; + const int64_t To = T0 * st - drop, M = To * H * 2 * W * 2; + std::vector x = randv((size_t)(T0 * H * W * C * P), 1.0f); + void* dx = up_bf16(x); + void* dy = dalloc((size_t)((M + 5) * C) * 2); + const int rc = launch(rd, { T(dx, RAD_BF16, { T0 * H * W, C * P }), + TI32({ 3 }, { (int32_t)T0, (int32_t)H, (int32_t)W }), + T(dy, RAD_BF16, { M + 5, C }) }, + { PI("M", M), PI("C", C), PI("st", st), PI("sh", 2), PI("sw", 2), + PI("drop", drop), PS("dtype", "bf16") }); + const std::string nm = fmt("d2s3d %lld x 2 x 2, %lld dropped", (long long)st, (long long)drop); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(M * C)); + const int64_t Ho = H * 2, Wo = W * 2; + for (int64_t q = 0; q < M; ++q) { + const int64_t tt = q / (Ho * Wo) + drop, ii = (q / Wo) % Ho, jj = q % Wo; + const int64_t t = tt / st, aa = tt % st, i = ii / 2, b = ii % 2, j = jj / 2, d = jj % 2; + for (int64_t c = 0; c < C; ++c) + want[(size_t)(q * C + c)] = + x[(size_t)(((t * H + i) * W + j) * C * P + ((c * st + aa) * 2 + b) * 2 + d)]; + } + const std::vector got = down_bf16(dy, want.size()); + ok(nm.c_str(), differ(got, want) == 0, fmt("%lld differ", (long long)differ(got, want))); + } + struct S { int64_t tpre, group; bool mean, add; }; + for (const S c : { S{ 1, 1, false, false }, S{ 1, 4, true, true } }) { + const int64_t T0 = 5, H = 6, W = 4, C = 16, P = C * 8, Co = c.mean ? P / c.group : P; + const int64_t To = (T0 + c.tpre) / 2, M = To * (H / 2) * (W / 2); + std::vector x = randv((size_t)(T0 * H * W * C), 1.0f), y0 = randv((size_t)(M * Co), 1.0f); + void* dx = up_bf16(x); + void* dy = up_bf16(y0); + std::vector ps = { PI("M", T0 * H * W), PI("C", C), PI("st", 2), PI("sh", 2), + PI("sw", 2), PI("tpre", c.tpre), PI("group", c.group), + PS("mode", c.mean ? "mean" : "copy"), PI("add", c.add), + PS("dtype", "bf16") }; + const int rc = launch(rs, { T(dx, RAD_BF16, { T0 * H * W, C }), + TI32({ 3 }, { (int32_t)T0, (int32_t)H, (int32_t)W }), + T(dy, RAD_BF16, { M, Co }) }, + ps); + const std::string nm = fmt("s2d3d %s, a frame prepended%s", c.mean ? "group mean" : "copy", + c.add ? ", added" : ""); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(M * Co)); + const int64_t Ho = H / 2, Wo = W / 2; + for (int64_t q = 0; q < M; ++q) { + const int64_t t = q / (Ho * Wo), i = (q / Wo) % Ho, j = q % Wo; + auto val = [&](int64_t p) { + const int64_t d = p % 2, b = (p / 2) % 2, aa = (p / 4) % 2, cc = p / 8; + const int64_t v = t * 2 + aa, tr = v < c.tpre ? v : v - c.tpre; + return x[(size_t)(((tr * H + i * 2 + b) * W + j * 2 + d) * C + cc)]; + }; + for (int64_t o = 0; o < Co; ++o) { + float v; + if (!c.mean) { + v = val(o); + } else { + float s = 0.0f; + for (int64_t p = o * c.group; p < (o + 1) * c.group; ++p) s += val(p); + v = bfr(s / (float)c.group); + } + want[(size_t)(q * Co + o)] = c.add ? bfr(y0[(size_t)(q * Co + o)] + v) : v; + } + } + const std::vector got = down_bf16(dy, want.size()); + ok(nm.c_str(), differ(got, want) == 0, fmt("%lld differ", (long long)differ(got, want))); + } +} + +/* An RGB image to 4 x 4 patches and back to bytes, both orders. */ +void patch_cases(const Plugin& pl) { + const RadKernelInfo* rp = find(pl, "pix_patch"); + const RadKernelInfo* r8 = find(pl, "patch_pix8"); + if (!rp || !r8) { ok("pix_patch / patch_pix8", false, "row absent"); return; } + for (const bool wh : { true, false }) { + const int64_t H = 24, W = 40, C = 3, p = 4, w = W / p, cols = w * C * p * p; + std::vector x = randv((size_t)(H * W * C), 1.2f); + void* dx = up_bf16(x); + void* dy = dalloc((size_t)(H / p * cols) * 2); + const std::vector ps = { PI("M", H / p), PI("p", p), PI("C", C), + PS("order", wh ? "wh" : "hw"), PS("dtype", "bf16") }; + int rc = launch(rp, { T(dx, RAD_BF16, { H, W * C }), T(dy, RAD_BF16, { H / p, cols }) }, ps); + const char* ord = wh ? "wh" : "hw"; + if (rc != RAD_OK) { ok(fmt("pix_patch %s", ord).c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(H / p * cols)); + auto col = [&](int64_t c, int64_t ph, int64_t pw) { + return c * p * p + (wh ? pw * p + ph : ph * p + pw); + }; + for (int64_t yy = 0; yy < H; ++yy) + for (int64_t xx = 0; xx < W; ++xx) + for (int64_t c = 0; c < C; ++c) + want[(size_t)((yy / p) * cols + (xx / p) * C * p * p + col(c, yy % p, xx % p))] = + x[(size_t)((yy * W + xx) * C + c)]; + const std::vector got = down_bf16(dy, want.size()); + ok(fmt("pix_patch %s", ord).c_str(), differ(got, want) == 0, + fmt("%lld differ", (long long)differ(got, want))); + void* d8 = dalloc((size_t)(H * W * C)); + RadTensor t8 = T(d8, RAD_U8, { H, W * C }); + rc = launch(r8, { T(dy, RAD_BF16, { H / p, cols }), t8 }, ps); + if (rc != RAD_OK) { ok(fmt("patch_pix8 %s", ord).c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector g8((size_t)(H * W * C)), w8(g8.size()); + st_memcpy(g8.data(), d8, g8.size(), hipMemcpyDeviceToHost); + for (size_t e = 0; e < w8.size(); ++e) { + const float cl = std::min(std::max(x[e], -1.0f), 1.0f); + const float u = std::min(std::max(bfr(bfr(cl / 2.0f) + 0.5f), 0.0f), 1.0f); + w8[e] = (uint8_t)std::nearbyint(u * 255.0f); + } + ok(fmt("patch_pix8 %s is pix_patch's inverse in bytes", ord).c_str(), differ(g8, w8) == 0, + fmt("%lld differ", (long long)differ(g8, w8))); + } +} + +/* diffusers' tiled decodes. The boxes of a 29 x 33 grid at tile 16, stride 14 (bands of 16, 15 + * and 1 rows, 16, 16 and 5 columns) and of the diffusion decoder's 61 x 68 x 100 grid under + * `intervals` (two time bands, the last 8 tail cells longer; one row band; a 12-column remnant + * merged); a 2 x 4 x 3 box out of a volume; and tiles stitched to bytes against a host + * transcription of the in-place blends (libref/ref_ltx.cpp): five frames over a 9 x 10 grid at + * tile 4, stride 3, and 9 cells of 2 frames in two time bands at tile 6, stride 4, rule + * `intervals`, its spatial remnant merged. */ +struct HostCut { + int64_t tile, stride, min; + bool iv; + int64_t count(int64_t L) const { + if (iv && L <= tile) return 1; + int64_t n = (L + stride - 1) / stride; + while (iv && 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); + } +}; + +/* Neighborhood attention against a host transcription: two heads of 64 over a 6 x 9 x 13 volume + * with the decoder's 3 x 5 x 5 window, and with its 11 x 11 x 11 one, which the 6 frames clamp. */ +void na3d_cases(const Plugin& pl) { + const RadKernelInfo* rn = find(pl, "attn_na3d_h64"); + if (!rn) { ok("attn_na3d", false, "row absent"); return; } + struct K { int64_t kt, kh, kw; }; + for (const K w : { K{ 3, 5, 5 }, K{ 11, 11, 11 } }) { + const int64_t T0 = 6, H = 9, W = 13, V = T0 * H * W, hd = 64, nhd = 2, D = nhd * hd; + std::vector q = randv((size_t)(V * D), 1.0f), k = randv((size_t)(V * D), 1.0f), + v = randv((size_t)(V * D), 1.0f); + for (auto* x : { &q, &k, &v }) + for (auto& e : *x) e = bfr(e); + void* dq = up_bf16(q); + void* dk = up_bf16(k); + void* dv = up_bf16(v); + void* dout = dalloc((size_t)(V * D) * 2); + const int rc = launch(rn, { T(dq, RAD_BF16, { V, D }), T(dk, RAD_BF16, { V, D }), + T(dv, RAD_BF16, { V, D }), + TI32({ 3 }, { (int32_t)T0, (int32_t)H, (int32_t)W }), + T(dout, RAD_BF16, { V, D }) }, + { PI("M", V), PI("head_dim", hd), PI("kt", w.kt), PI("kh", w.kh), + PI("kw", w.kw), PS("dtype", "bf16") }); + const std::string nm = fmt("attn_na3d %lld x %lld x %lld over 6 x 9 x 13", (long long)w.kt, + (long long)w.kh, (long long)w.kw); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + const int64_t nt = std::min(w.kt, T0), nh = std::min(w.kh, H), nw = std::min(w.kw, W); + auto start = [](int64_t c, int64_t n, int64_t L) { + return std::min(std::max(c - n / 2, 0), L - n); + }; + std::vector want((size_t)(V * D)); + for (int64_t r = 0; r < V; ++r) + for (int64_t h = 0; h < nhd; ++h) { + const int64_t t = r / (H * W), i = (r / W) % H, j = r % W; + const int64_t t0 = start(t, nt, T0), i0 = start(i, nh, H), j0 = start(j, nw, W); + std::vector sc; + std::vector keys; + double mx = -1e300; + 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; + double d = 0; + for (int64_t e = 0; e < hd; ++e) + d += (double)q[(size_t)(r * D + h * hd + e)] * k[(size_t)(key * D + h * hd + e)]; + d /= 8.0; + sc.push_back(d); + keys.push_back(key); + mx = std::max(mx, d); + } + double sum = 0; + for (double& x : sc) { x = std::exp(x - mx); sum += x; } + for (int64_t e = 0; e < hd; ++e) { + double acc = 0; + for (size_t n = 0; n < keys.size(); ++n) acc += sc[n] * v[(size_t)(keys[n] * D + h * hd + e)]; + want[(size_t)(r * D + h * hd + e)] = (float)(acc / sum); + } + } + check(nm.c_str(), down_bf16(dout, want.size()), want, 8e-3); + } +} + +/* A 3 x 4 x 5 volume's voxel coordinates. */ +void vol_index_cases(const Plugin& pl) { + const RadKernelInfo* rv = find(pl, "vol_index"); + if (!rv) { ok("vol_index", false, "row absent"); return; } + const int64_t T0 = 3, H = 4, W = 5, n = T0 * H * W + 4; + void* dy = dalloc((size_t)(3 * n) * 4); + const int rcode = launch(rv, { TI32({ 3 }, { (int32_t)T0, (int32_t)H, (int32_t)W }), + T(dy, RAD_I32, { 3, n }) }, + { PI("M", n) }); + if (rcode != RAD_OK) { ok("vol_index 3 x 4 x 5", false, "rc " + std::to_string(rcode)); return; } + std::vector got((size_t)(3 * n)); + st_memcpy(got.data(), dy, got.size() * 4, hipMemcpyDeviceToHost); + int64_t bad = 0; + for (int64_t m = 0; m < T0 * H * W; ++m) + bad += got[(size_t)m] != m / (H * W) || got[(size_t)(n + m)] != (m / W) % H || + got[(size_t)(2 * n + m)] != m % W; + ok("vol_index 3 x 4 x 5", bad == 0, fmt("%lld differ", (long long)bad)); +} + +void tile_cases(const Plugin& pl) { + const RadKernelInfo* rg = find(pl, "tile_grid"); + const RadKernelInfo* rc = find(pl, "tile_crop"); + const RadKernelInfo* rs = find(pl, "tile_stitch"); + if (!rg || !rc || !rs) { ok("tile_grid / tile_crop / tile_stitch", false, "row absent"); return; } + struct G { int32_t T, H, W; std::vector ps; HostCut cs, ct; int64_t tail, n; const char* nm; }; + const std::vector grids = { + { 3, 29, 33, { PI("M", 12), PI("tile", 16), PI("stride", 14) }, + { 16, 14, 1, false }, { 1 << 30, 1 << 30, 1, false }, 0, 12, "tile_grid 29 x 33" }, + { 61, 68, 100, { PI("M", 4), PI("tile", 96), PI("stride", 88), PS("rule", "intervals"), + PI("min", 13), PI("tile_t", 40), PI("stride_t", 28), PI("min_t", 6), + PI("tail", 8) }, + { 96, 88, 13, true }, { 40, 28, 6, true }, 8, 4, "tile_grid intervals 61 x 68 x 100" }, + }; + for (const G& g : grids) { + void* dy = dalloc((size_t)(g.n * 8) * 4); + const int rcode = launch(rg, { TI32({ 3 }, { g.T, g.H, g.W }), T(dy, RAD_I32, { g.n, 8 }) }, + g.ps); + if (rcode != RAD_OK) { ok(g.nm, false, "rc " + std::to_string(rcode)); continue; } + std::vector got((size_t)(g.n * 8)), want((size_t)(g.n * 8), 0); + st_memcpy(got.data(), dy, got.size() * 4, hipMemcpyDeviceToHost); + const int64_t nt = g.ct.count(g.T), ni = g.cs.count(g.H), nj = g.cs.count(g.W); + const int64_t count = nt * ni * nj; + for (int64_t k = 0; k < std::min(count, g.n); ++k) { + const int64_t kt = k / (ni * nj), i = (k / nj) % ni, j = k % nj; + const int64_t v[8] = { g.ct.len(g.T, kt) + (kt == nt - 1 ? g.tail : 0), g.cs.len(g.H, i), + g.cs.len(g.W, j), kt * g.ct.stride, i * g.cs.stride, + j * g.cs.stride, k, count }; + for (int e = 0; e < 8; ++e) want[(size_t)(k * 8 + e)] = (int32_t)v[e]; + } + ok(g.nm, got == want, "rows differ"); + } + { + const int64_t T0 = 5, H = 7, W = 9, C = 6, t = 2, h = 4, w = 3, t0 = 2, y0 = 2, x0 = 5; + std::vector x = randv((size_t)(T0 * H * W * C), 1.0f); + void* dx = up_bf16(x); + void* dy = dalloc((size_t)((t * h * w + 3) * C) * 2); + const int rcode = launch(rc, { T(dx, RAD_BF16, { T0 * H * W, C }), + TI32({ 3 }, { (int32_t)T0, (int32_t)H, (int32_t)W }), + TI32({ 6 }, { (int32_t)t, (int32_t)h, (int32_t)w, (int32_t)t0, + (int32_t)y0, (int32_t)x0 }), + T(dy, RAD_BF16, { t * h * w + 3, C }) }, + { PI("M", t * h * w + 3), PI("C", C), PS("dtype", "bf16") }); + if (rcode != RAD_OK) { + ok("tile_crop 2 x 4 x 3 at (2, 2, 5)", false, "rc " + std::to_string(rcode)); + } else { + std::vector want((size_t)(t * h * w * C)); + for (int64_t r = 0; r < t * h * w; ++r) { + const int64_t f = r / (h * w), i = (r / w) % h, j = r % w; + for (int64_t c = 0; c < C; ++c) + want[(size_t)(r * C + c)] = + x[(size_t)((((t0 + f) * H + y0 + i) * W + x0 + j) * C + c)]; + } + const std::vector got = down_bf16(dy, want.size()); + ok("tile_crop 2 x 4 x 3 at (2, 2, 5)", differ(got, want) == 0, + fmt("%lld differ", (long long)differ(got, want))); + } + } + struct S { int64_t T, H, W; HostCut cs, ct; int64_t sc, st, f0, nf; bool wh; const char* rule; }; + const std::vector stitches = { + { 5, 9, 10, { 4, 3, 1, false }, { 1 << 30, 1 << 30, 1, false }, 2, 1, 1, 3, true, "stride" }, + { 5, 9, 10, { 4, 3, 1, false }, { 1 << 30, 1 << 30, 1, false }, 2, 1, 1, 3, false, "stride" }, + { 9, 7, 13, { 6, 4, 4, true }, { 6, 4, 2, true }, 2, 2, 0, 17, true, "intervals" }, + }; + for (const S& k : stitches) { + const int64_t p = 2, C = 3, P = C * p * p; + const int64_t nt = k.ct.count(k.T), ni = k.cs.count(k.H), nj = k.cs.count(k.W); + int64_t hs = 0, ws = 0; + for (int64_t i = 0; i < ni; ++i) hs += k.cs.len(k.H, i); + for (int64_t j = 0; j < nj; ++j) ws += k.cs.len(k.W, j); + auto frames = [&](int64_t kt) { return k.st * k.ct.len(k.T, kt) - (kt == 0 ? k.st - 1 : 0); }; + int64_t ftot = 0; + for (int64_t kt = 0; kt < nt; ++kt) ftot += frames(kt); + const int64_t rows = ftot * k.sc * k.sc * hs * ws; + std::vector x = randv((size_t)(rows * P), 1.3f); + for (auto& v : x) v = bfr(v); + auto offset = [&](int64_t kt, int64_t i, int64_t j) { + int64_t before = 0, left = 0, above = 0; + for (int64_t q = 0; q < kt; ++q) before += frames(q); + for (int64_t q = 0; q < j; ++q) left += k.cs.len(k.W, q); + for (int64_t q = 0; q < i; ++q) above += k.cs.len(k.H, q); + return k.sc * k.sc * (before * hs * ws + frames(kt) * (above * ws + k.cs.len(k.H, i) * left)); + }; + 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 = k.cs.len(k.W, j) * k.sc, hp = k.cs.len(k.H, i) * k.sc; + const int64_t row = offset(kt, i, j) + (f * hp + yy / p) * wp + xx / p; + const int64_t col = c * p * p + (k.wh ? (xx % p) * p + yy % p : (yy % p) * p + xx % p); + return x[(size_t)(row * P + col)]; + }; + auto mix = [&](float va, float vb, int64_t q, int64_t e) { + const float wa = (float)(1.0 - (double)q / (double)e), wb = (float)((double)q / (double)e); + return bfr(bfr(va * wa) + bfr(vb * wb)); + }; + const int64_t Hpx = k.H * k.sc * p, Wpx = k.W * k.sc * p, s = k.cs.stride * k.sc * p; + const int64_t E = (k.cs.tile - k.cs.stride) * k.sc * p, Et = (k.ct.tile - k.ct.stride) * k.st; + const int64_t band = k.ct.stride * k.st; + auto Sv = [&](int64_t kt, int64_t f, int64_t Yp, int64_t Xp, int64_t c) { + const int64_t i = std::min(Yp / s, ni - 1), ly = Yp - i * s; + const int64_t j = std::min(Xp / s, nj - 1), lx = Xp - j * s; + const int64_t ha = i > 0 ? k.cs.len(k.H, i - 1) * k.sc * p : 0; + const int64_t ev = i > 0 ? std::min(std::min(ha, k.cs.len(k.H, i) * k.sc * p), E) : 0; + const int64_t wl = j > 0 ? k.cs.len(k.W, j - 1) * k.sc * p : 0; + const int64_t eh = j > 0 ? std::min(std::min(wl, k.cs.len(k.W, j) * k.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) { + float A = R(kt, i - 1, j, f, ha - ev + ly, lx, c); + if (hb) A = mix(R(kt, i - 1, j - 1, f, ha - ev + ly, 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; + }; + std::vector want((size_t)(k.nf * Hpx * Wpx * C)); + for (int64_t r = 0; r < k.nf * Hpx; ++r) { + const int64_t n = k.f0 + r / Hpx, Yp = r % Hpx; + const int64_t kt = std::min((n + k.st - 1) / band, nt - 1); + const int64_t f = n - (kt == 0 ? 0 : kt * band - (k.st - 1)); + const int64_t et = kt > 0 ? std::min(std::min(frames(kt - 1), frames(kt)), Et) : 0; + for (int64_t Xp = 0; Xp < Wpx; ++Xp) + for (int64_t c = 0; c < C; ++c) { + float v = Sv(kt, f, Yp, Xp, c); + if (kt > 0 && f < et) v = mix(Sv(kt - 1, frames(kt - 1) - et + f, Yp, Xp, c), v, f, et); + const float cl = std::min(std::max(v, -1.0f), 1.0f); + const float u = std::min(std::max(bfr(bfr(cl / 2.0f) + 0.5f), 0.0f), 1.0f); + want[(size_t)((r * Wpx + Xp) * C + c)] = (uint8_t)std::nearbyint(u * 255.0f); + } + } + void* dx = up_bf16(x); + void* dy = dalloc(want.size()); + std::vector ps = { PI("M", k.nf * Hpx), PI("tile", k.cs.tile), PI("stride", k.cs.stride), + PS("rule", k.rule), PI("min", k.cs.min), PI("scale", k.sc), + PI("scale_t", k.st), PI("p", p), PI("C", C), + PS("order", k.wh ? "wh" : "hw"), PS("dtype", "bf16") }; + if (nt > 1 || k.ct.tile < (1 << 30)) { + ps.push_back(PI("tile_t", k.ct.tile)); + ps.push_back(PI("stride_t", k.ct.stride)); + ps.push_back(PI("min_t", k.ct.min)); + } + const int rcode = launch(rs, { T(dx, RAD_BF16, { rows, P }), + TI32({ 3 }, { (int32_t)k.T, (int32_t)k.H, (int32_t)k.W }), + TI32({ 1 }, { (int32_t)k.f0 }), + T(dy, RAD_U8, { k.nf * Hpx, Wpx * C }) }, + ps); + const std::string nm = fmt("tile_stitch %s %lld x %lld x %lld %s, frames %lld..%lld", k.rule, + (long long)k.T, (long long)k.H, (long long)k.W, k.wh ? "wh" : "hw", + (long long)k.f0, (long long)(k.f0 + k.nf - 1)); + if (rcode != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rcode)); continue; } + std::vector got(want.size()); + st_memcpy(got.data(), dy, got.size(), hipMemcpyDeviceToHost); + ok(nm.c_str(), differ(got, want) == 0, fmt("%lld differ", (long long)differ(got, want))); + } +} + +/* The extender's MelSTFT shape (512-point DFT, hop 128, 64 mel bins) over two channels, bf16. */ +void stft_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "stft_logmel"); + if (!r) { ok("stft_logmel", false, "row absent"); return; } + const int64_t nfft = 512, hop = 128, nm = 64, ch = 2, F = nfft / 2 + 1, S = 37 * hop; + const int64_t frames = S / hop; + std::vector x = randv((size_t)(S * ch), 0.5f); + std::vector basis((size_t)(2 * F * nfft)), mel((size_t)(nm * F)); + for (int64_t k = 0; k < F; ++k) + for (int64_t j = 0; j < nfft; ++j) { + const double wnd = 0.5 - 0.5 * std::cos(2.0 * M_PI * (double)j / (double)nfft); + const double ang = -2.0 * M_PI * (double)(k * j) / (double)nfft; + basis[(size_t)(k * nfft + j)] = (float)(wnd * std::cos(ang)); + basis[(size_t)((F + k) * nfft + j)] = (float)(wnd * std::sin(ang)); + } + for (float& v : mel) v = std::fabs(rnd()) * 0.05f; + void* dx = up_bf16(x); + void* db = up_bf16(basis); + void* dm = up_bf16(mel); + void* dy = dalloc((size_t)(frames * ch * nm) * 2); + const int rc = launch(r, { T(dx, RAD_BF16, { S, ch }), T(db, RAD_BF16, { 2 * F, 1, nfft }), + T(dm, RAD_BF16, { nm, F }), T(dy, RAD_BF16, { frames, ch * nm }) }, + { PI("M", frames), PI("hop", hop), PI("nfft", nfft), PI("n_mel", nm), + PI("ch", ch), PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok("stft_logmel", false, "rc " + std::to_string(rc)); return; } + std::vector want((size_t)(frames * ch * nm)); + for (int64_t t = 0; t < frames; ++t) + for (int64_t h = 0; h < ch; ++h) { + std::vector 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 - (nfft - hop); + if (s < 0) continue; + re += basis[(size_t)(k * nfft + j)] * x[(size_t)(s * ch + h)]; + im += basis[(size_t)((F + k) * nfft + j)] * x[(size_t)(s * ch + h)]; + } + re = bfr(re); + im = bfr(im); + mag[(size_t)k] = bfr(std::sqrt(bfr(bfr(re * re) + bfr(im * im)))); + } + for (int64_t m = 0; m < nm; ++m) { + float s = 0.0f; + for (int64_t k = 0; k < F; ++k) s += mel[(size_t)(m * F + k)] * mag[(size_t)k]; + want[(size_t)(t * ch * nm + h * nm + m)] = std::log(std::max(bfr(s), bfr(1e-5f))); + } + } + check("stft_logmel 512-point, hop 128, 64 mel bins, 2 channels", down_bf16(dy, want.size()), + want, 5e-3); +} + +/* A decoder's volume at a scale and a constant, off a device geometry. */ +void int_affine_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "int_affine"); + if (!r) { ok("int_affine", false, "row absent"); return; } + RadTensor x = TI32({ 4 }, { 21, 16, 24, 30 }); + void* dy = dalloc(5 * 4); + const int rc = launch(r, { x, T(dy, RAD_I32, { 5 }) }, + { PI("M", 5), PS("src", "0 1 2 -1 3"), PS("mul", "8 2 2 0 4"), + PS("add", "-7 0 0 1 -3") }); + if (rc != RAD_OK) { ok("int_affine", false, "rc " + std::to_string(rc)); return; } + const std::vector got = down_i32(dy, 5); + ok("int_affine (8 F - 7, 2 h, 2 w, 1, 4 n - 3)", + got == std::vector({ 161, 32, 48, 1, 117 })); +} + +/* 16 kHz to 48 kHz over two channels, f32 out as the vocoder's waveform. */ +void bwe_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "bwe_up"); + if (!r) { ok("bwe_up", false, "row absent"); return; } + const int64_t S = 400, ch = 2, ratio = 3, O = S * ratio; + std::vector x = randv((size_t)(S * ch), 0.8f), res = randv((size_t)(O * ch), 0.5f); + void* dx = up_bf16(x); + void* dr = up_bf16(res); + void* dy = dalloc((size_t)(O * ch) * 4); + const int rc = launch(r, { T(dx, RAD_BF16, { S, ch }), T(dr, RAD_BF16, { O, ch }), + T(dy, RAD_F32, { O, ch }) }, + { PI("M", O), PI("ratio", ratio), PI("ch", ch), PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok("bwe_up", false, "rc " + std::to_string(rc)); return; } + const int64_t w = (int64_t)std::ceil(6.0 / 0.99), K = 2 * w * ratio + 1; + std::vector f((size_t)K); + for (int64_t n = 0; n < K; ++n) { + const float u = ((float)n / (float)ratio - (float)w) * 0.99f; + const float uc = std::min(std::max(u, -6.0f), 6.0f); + const float cw = std::cos(uc * (float)M_PI / 6.0f / 2.0f); + const float pu = (float)M_PI * u; + const float sinc = u == 0.0f ? 1.0f : std::sin(pu) / pu; + f[(size_t)n] = bfr(sinc * (cw * cw) * 0.99f / (float)ratio); + } + std::vector want((size_t)(O * ch)); + for (int64_t o = 0; o < O; ++o) + for (int64_t h = 0; h < ch; ++h) { + const int64_t u = o + 2 * w * ratio; + float acc = 0.0f; + for (int64_t k = u % ratio; k < K; k += ratio) { + const int64_t s = std::min(std::max((u - k) / ratio - w, 0), S - 1); + acc += f[(size_t)k] * x[(size_t)(s * ch + h)]; + } + const float up = bfr((float)ratio * bfr(acc)); + const float v = bfr(res[(size_t)(o * ch + h)] + up); + want[(size_t)(o * ch + h)] = std::min(std::max(v, -1.0f), 1.0f); + } + check("bwe_up 3x over 2 channels, f32 out", down_f32(dy, want.size()), want, 4e-3); +} + +/* conv2d_nhwc's three paddings (same, down, causal) on the implicit GEMM, and causal on the direct + * kernel (the audio VAE's 2-channel input). */ +void conv2d_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "conv2d_nhwc_bf16"); + if (!r) { ok("conv2d_nhwc_bf16", false, "row absent"); return; } + struct Case { const char* pad; int64_t cin, cout, k, stride, H, W; }; + for (const Case c : { Case{ "same", 64, 96, 3, 1, 9, 13 }, Case{ "down", 32, 64, 3, 2, 10, 14 }, + Case{ "causal", 64, 128, 3, 1, 11, 8 }, + Case{ "causal", 2, 32, 3, 1, 12, 16 } }) { + const bool down = !std::strcmp(c.pad, "down"), causal = !std::strcmp(c.pad, "causal"); + const int64_t pt = down ? 0 : causal ? c.k - 1 : c.k / 2, pb = down ? 1 : causal ? 0 : c.k / 2; + const int64_t pl0 = down ? 0 : c.k / 2, pr = down ? 1 : c.k / 2; + const int64_t Ho = (c.H + pt + pb - c.k) / c.stride + 1, Wo = (c.W + pl0 + pr - c.k) / c.stride + 1; + const int64_t K = c.cin * c.k * c.k; + std::vector x = randv((size_t)(c.H * c.W * c.cin), 1.0f); + std::vector w = randv((size_t)(c.cout * K), 1.5f / std::sqrt((float)K)); + std::vector b = randv((size_t)c.cout, 0.3f); + for (float& e : w) e = bfr(e); + const std::vector ps = { PI("M", Ho), PI("cin", c.cin), PI("cout", c.cout), + PI("k", c.k), PI("stride", c.stride), PS("pad", c.pad), + PI("up", 1), PS("dtype", "bf16") }; + const std::string nm = fmt("conv2d_nhwc_bf16 pad %s, %lld -> %lld, stride %lld", c.pad, + (long long)c.cin, (long long)c.cout, (long long)c.stride); + void* dw = stored_weight(r, ps, w, c.cout, K, nm.c_str()); + void* dx = up_bf16(x); + void* db = up_bf16(b); + void* dy = dalloc((size_t)(Ho * Wo * c.cout) * 2); + const int rc = launch(r, { T(dx, RAD_BF16, { c.H, c.W * c.cin }), T(dw, RAD_BF16, { c.cout, K }), + T(db, RAD_BF16, { c.cout }), T(dy, RAD_BF16, { Ho, Wo * c.cout }) }, + ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(Ho * Wo * c.cout)); + for (int64_t oy = 0; oy < Ho; ++oy) + for (int64_t ox = 0; ox < Wo; ++ox) + for (int64_t o = 0; o < c.cout; ++o) { + double acc = 0.0; + for (int64_t kh = 0; kh < c.k; ++kh) + for (int64_t kw = 0; kw < c.k; ++kw) { + const int64_t iy = oy * c.stride + kh - pt, ix = ox * c.stride + kw - pl0; + if (iy < 0 || iy >= c.H || ix < 0 || ix >= c.W) continue; + for (int64_t ci = 0; ci < c.cin; ++ci) + acc += (double)w[(size_t)(((o * c.cin + ci) * c.k + kh) * c.k + kw)] * + x[(size_t)((iy * c.W + ix) * c.cin + ci)]; + } + want[(size_t)((oy * Wo + ox) * c.cout + o)] = bfr((float)acc + b[(size_t)o]); + } + check(nm, down_bf16(dy, want.size()), want, 5e-3); + } + /* One output channel into the second half of wider rows (an audio decoder's conv_out writing + * a channel's mel bins into its own columns): the slice right, the other half untouched. */ + { + const int64_t cin = 128, H = 9, W = 16, k = 3, K = cin * k * k, P = 2 * W; + std::vector x = randv((size_t)(H * W * cin), 1.0f); + std::vector w = randv((size_t)K, 1.5f / std::sqrt((float)K)), b = { 0.25f }; + for (float& e : w) e = bfr(e); + const std::vector ps = { PI("M", H), PI("cin", cin), PI("cout", 1), PI("k", k), + PI("stride", 1), PS("pad", "causal"), PI("up", 1), + PS("dtype", "bf16") }; + const char* nm = "conv2d_nhwc_bf16 causal 128 -> 1 into a column slice"; + void* dw = stored_weight(r, ps, w, 1, K, nm); + std::vector pre((size_t)(H * P), -7.5f); + void* dy = up_bf16(pre); + RadTensor ty = T((uint16_t*)dy + W, RAD_BF16, { H, W }); + ty.stride[0] = P; + const int rc = launch(r, { T(up_bf16(x), RAD_BF16, { H, W * cin }), T(dw, RAD_BF16, { 1, K }), + T(up_bf16(b), RAD_BF16, { 1 }), ty }, + ps); + if (rc != RAD_OK) ok(nm, false, "rc " + std::to_string(rc)); + else { + const std::vector got = down_bf16(dy, (size_t)(H * P)); + std::vector want((size_t)(H * W)), sl((size_t)(H * W)); + bool kept = true; + for (int64_t oy = 0; oy < H; ++oy) + for (int64_t ox = 0; ox < W; ++ox) { + double acc = 0.0; + for (int64_t kh = 0; kh < k; ++kh) + for (int64_t kw = 0; kw < k; ++kw) { + const int64_t iy = oy + kh - (k - 1), ix = ox + kw - k / 2; + if (iy < 0 || ix < 0 || ix >= W) continue; + for (int64_t ci = 0; ci < cin; ++ci) + acc += (double)w[(size_t)((ci * k + kh) * k + kw)] * + x[(size_t)((iy * W + ix) * cin + ci)]; + } + want[(size_t)(oy * W + ox)] = bfr((float)acc + b[0]); + sl[(size_t)(oy * W + ox)] = got[(size_t)(oy * P + W + ox)]; + kept = kept && got[(size_t)(oy * P + ox)] == -7.5f; + } + check(nm, sl, want, 5e-3); + ok("conv2d_nhwc_bf16 leaves the columns outside the slice alone", kept); + } + } +} + +} /* namespace ltx */ + /* ---- a video latent upscaler's ops, at MiniMax-H3's shapes --------------------------------------- * * The upscaler runs a 37-frame clip at its 42 x 24 latent (the source) and at 84 x 48 (the @@ -6886,14 +8085,18 @@ std::vector conv_rows(const Vol& v, int64_t M, int64_t want) { /* libref's conv3d_ndhwc at output row r: the products (exact in f32) summed in f64, rounded to f32, * the bias added in f32 and rounded; with a residual, that plus the residual, rounded. `wt` is the - * weight tap-major, as the row stores it. */ + * weight tap-major, as the row stores it. `v` is the input's volume; `tpad` 1 replicates the edge + * frames, 2 is causal with `tpre` more first frames in front. */ void conv3d_row(const std::vector& x, int64_t cin, const std::vector& wt, const std::vector& b, const float* res, const Vol& v, int64_t cout, - int64_t r, float* out) { + int64_t r, float* out, int tpad = 0, int64_t tpre = 0) { const int64_t HW = v.H * v.W, t = r / HW, y = (r / v.W) % v.H, xx = r % v.W; std::vector acc((size_t)cout, 0.0); for (int64_t tap = 0; tap < 27; ++tap) { - const int64_t nt = t + tap / 9 - 1, ny = y + (tap / 3) % 3 - 1, nx = xx + tap % 3 - 1; + int64_t nt = t + tap / 9 - 1; + if (tpad == 1) nt = std::min(std::max(nt, 0), v.T - 1); + else if (tpad == 2) nt = std::max(nt - 1 - tpre, 0); + const int64_t ny = y + (tap / 3) % 3 - 1, nx = xx + tap % 3 - 1; if (nt < 0 || nt >= v.T || ny < 0 || ny >= v.H || nx < 0 || nx >= v.W) continue; const float* xr = &x[(size_t)((nt * HW + ny * v.W + nx) * cin)]; for (int64_t o = 0; o < cout; ++o) { @@ -6919,18 +8122,23 @@ struct ConvCase { int64_t xpad, ypad, yextra; /* pitch padding, output rows past the volume */ int64_t mshort; /* the M parameter this short of T H W: the volume's rows are written */ int64_t sample; /* rows checked besides the faces; 0 every row */ + int tpad = 0; /* 0 zero, 1 replicate, 2 causal frame padding */ + int64_t tpre = 0; /* causal: more first frames in front, as many more output frames */ }; void conv3d_case(const RadKernelInfo* r, const ConvCase& c) { const Vol& v = c.v; - const int64_t vol = v.T * v.H * v.W, M = vol, K = 27 * c.cin; + const Vol vo{ v.T + c.tpre, v.H, v.W }; + const int64_t vol = v.T * v.H * v.W, M = vo.T * v.H * v.W, K = 27 * c.cin; const int64_t ldx = c.cin + c.xpad, ldy = c.cout + c.ypad, yrows = M + c.yextra; - const std::string nm = fmt("conv3d_ndhwc_bf16 %s: %lld -> %lld at %lld x %lld, %lld frames%s%s%s", + static const char* const kTpad[] = { "", ", replicate", ", causal" }; + const std::string nm = fmt("conv3d_ndhwc_bf16 %s: %lld -> %lld at %lld x %lld, %lld frames%s%s%s%s", c.what, (long long)c.cin, (long long)c.cout, (long long)v.H, (long long)v.W, (long long)v.T, c.res == 2 ? ", res in place" : c.res ? ", res" : "", c.bf32 ? ", f32 bias" : "", - c.xpad || c.ypad || c.yextra || c.mshort ? ", pitched" : ""); + c.xpad || c.ypad || c.yextra || c.mshort ? ", pitched" : "", + kTpad[c.tpad]); g_seed = 0xc03dull + (uint64_t)(c.cin * 131 + c.cout * 7 + v.T); std::vector x = randv((size_t)(vol * c.cin), 1.0f); std::vector w = randv((size_t)(c.cout * K), 1.5f / std::sqrt((float)K)); @@ -6945,6 +8153,8 @@ void conv3d_case(const RadKernelInfo* r, const ConvCase& c) { wt[(size_t)((o * 27 + t) * c.cin + ci)] = w[(size_t)((o * c.cin + ci) * 27 + t)]; std::vector ps = { PI("M", M - c.mshort), PI("cin", c.cin), PI("cout", c.cout), PI("k", 3), PI("kt", 3), PS("dtype", "bf16") }; + if (c.tpad) ps.push_back(PS("tpad", c.tpad == 1 ? "replicate" : "causal")); + if (c.tpre) ps.push_back(PI("tpre", c.tpre)); void* dw = stored_weight(r, ps, w, c.cout, K, nm.c_str()); void* dx = up_rows(x, vol, c.cin, ldx, vol); std::vector bb = b; @@ -6969,7 +8179,7 @@ void conv3d_case(const RadKernelInfo* r, const ConvCase& c) { const std::vector yb = down_u16(dy, (size_t)(yrows * ldy)); std::vector rows; if (c.sample) { - rows = conv_rows(v, M, c.sample); + rows = conv_rows(vo, M, c.sample); } else { for (int64_t i = 0; i < M; ++i) rows.push_back(i); } @@ -6977,7 +8187,7 @@ void conv3d_case(const RadKernelInfo* r, const ConvCase& c) { par_for((int64_t)rows.size(), [&](int64_t i) { const int64_t rr = rows[(size_t)i]; conv3d_row(x, c.cin, wt, b, c.res ? &res[(size_t)(rr * c.cout)] : nullptr, v, c.cout, rr, - &want[(size_t)i * c.cout]); + &want[(size_t)i * c.cout], c.tpad, c.tpre); for (int64_t o = 0; o < c.cout; ++o) got[(size_t)i * c.cout + o] = h_bf16(yb[(size_t)(rr * ldy + o)]); }); @@ -7005,6 +8215,12 @@ void conv3d_cases(const Plugin& pl) { ConvCase{ "one frame", Vol{ 1, 9, 13 }, 16, 24, 2, true, 0, 8, 2, 0, 0 }, ConvCase{ "one row", Vol{ 4, 1, 21 }, 8, 8, 0, false, 8, 0, 0, 0, 0 }, ConvCase{ "two tiles a tap", Vol{ 2, 11, 6 }, 128, 136, 2, false, 0, 0, 7, 0, 0 }, + /* LTX-2's VAE: the decoder's replicated frames, the encoder's causal ones (its + * 48-channel patchified input off the 64-channel tile), and the temporal + * downsampler's first frame prepended once more. */ + ConvCase{ "replicate", Vol{ 4, 6, 10 }, 128, 128, 2, false, 0, 0, 3, 0, 0, 1, 0 }, + ConvCase{ "causal", Vol{ 5, 7, 9 }, 48, 128, 0, false, 8, 0, 0, 0, 0, 2, 0 }, + ConvCase{ "causal, one more frame", Vol{ 3, 6, 6 }, 64, 64, 1, true, 0, 8, 4, 0, 0, 2, 1 }, }) conv3d_case(r, c); /* A 15 s clip at the target size: 411264 rows, the largest volume the model runs. */ @@ -7083,6 +8299,13 @@ void group_norm_cases(const Plugin& pl) { G{ "f32 in, bf16 out", 101, 512, 32, true, false, false, 0, false, false, -3.0f, 16 }, G{ "one row", 1, 512, 32, false, false, false, 1, true, false, 0.0f, 0 }, G{ "64 channels", 1000, 64, 8, false, true, false, 0, true, false, 0.0f, 8 }, + /* Groups of 4 channels (four-channel chunks): the FLUX.2 VAE's 128 channels in 32 + * groups at a 256 x 256 image, bf16 with SiLU, then f32 rows over a large mean. */ + G{ "4 channels a group", 256 * 256, 128, 32, false, false, false, 0, true, false, 0.0f, 0 }, + /* Groups of 2 channels (two-channel chunks): a 64-wide latent upsampler in 32 groups. */ + G{ "2 channels a group", 48 * 8 * 8, 64, 32, false, false, false, 0, true, false, 0.0f, 0 }, + G{ "2 channels a group, f32 rows", 777, 64, 32, true, true, true, 2, false, false, 5.0f, 8 }, + G{ "4 channels a group, f32", 777, 128, 32, true, true, true, 2, false, false, 20.0f, 8 }, }) { const int64_t M = g.M, n = g.n, ld = n + g.pad, rows = M + 2; const std::string nm = fmt("group_norm %s: %lld x %lld in %lld groups", g.what, @@ -12030,12 +13253,13 @@ static void mla_check(const Plugin& pl, int64_t rows, int64_t heads, int64_t blo st_memcpy(right, (char*)scratch + 128 + need, 128, hipMemcpyDeviceToHost); for (int i = 0; i < 128; ++i) guards = guards && left[i] == 0xa5 && right[i] == 0xa5; } - const char* pairing = std::getenv("RADIANCE_MLA_PAIR"); + /* Paired tiles walk the union of both tables up to 520 entries (kUnionBlocks), past it the + * tables position by position. */ + const bool positional = std::strstr(name, "matrix") && heads % 16 && blocks > 520; ok(fmt("MLA M=%lld heads=%lld blocks=%lld%s%s%s split/unsplit, max error %.8g", (long long)rows, (long long)heads, (long long)blocks, fill == MlaFill::topk ? fmt(" topk:%lld", (long long)swaps).c_str() : "", - form ? fmt(" pinned form %d", form).c_str() : "", - pairing && std::strstr(name, "matrix") ? fmt(" pairing %s", pairing).c_str() : "", + form ? fmt(" pinned form %d", form).c_str() : "", positional ? " positional pairing" : "", max_error) .c_str(), matches); @@ -12169,8 +13393,7 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads, PI("blocks", blocks), PI("block_size", bs), PF("scale", 0.0625), PS("dtype", "bf16") }; std::vector base, rule; - auto run = [&](const char* name, int form, const char* label, bool positional = false) { - ScopedEnv pairing("RADIANCE_MLA_PAIR", positional ? "pos" : nullptr); + auto run = [&](const char* name, int form, const char* label) { const RadKernelInfo* r = find(pl, name); if (!r) { std::printf(" %-34s row absent\n", label); @@ -12235,28 +13458,15 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads, ulp = std::max(ulp, std::abs(ord(got[i]) - ord(base[i]))); abs_err = std::max(abs_err, std::fabs(x - y)); } - /* The two key loads stage the same values: their outputs must agree to the bit. The - * pairings walk request r of a pair in the same order (equal at one split) and r+1 in - * another. */ - std::string same = + /* The two key loads stage the same values: their outputs must agree to the bit. */ + const std::string same = form == 1 && !rule.empty() ? (rule == got ? ", bit-identical to form 0" : ", DIFFERS from form 0") : ""; - if (positional && !rule.empty()) { - size_t differ[2] = { 0, 0 }; - float apart = 0; - for (size_t i = 0; i < got.size(); ++i) - if (got[i] != rule[i]) { - ++differ[(i / (size_t)(heads * D)) % 2]; - apart = std::max(apart, std::fabs(h_bf16(got[i]) - h_bf16(rule[i]))); - } - same = fmt(", vs union %zu/%zu values differ (r/r+1), max abs %.3g", differ[0], - differ[1], apart); - } std::snprintf(diff, sizeof diff, "%smax %d ulp, max abs %.3g%s", finite ? "" : "NONFINITE ", ulp, abs_err, same.c_str()); } - if (form == 0 && !positional) rule = got; + if (form == 0) rule = got; std::printf(" %-34s %10.2f us %7.2f TFLOP/s %s\n", label, us, flops / (us * 1e6), diff); if (form >= 0 && pl.mla_stats) { /* One more launch with the conflict counters on, outside the timing. */ @@ -12276,10 +13486,13 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads, std::printf(" mla_attn_matrix_bf16 serves heads a multiple of 8 only\n"); return; } - if (heads % 16) { + /* Tables of up to 520 entries (kUnionBlocks) pair by their union, wider ones by position. */ + if (heads % 16 && blocks <= 520) { run("mla_attn_matrix_bf16", 0, "matrix paired, union, vector load"); run("mla_attn_matrix_bf16", 1, "matrix paired, union, element load"); - run("mla_attn_matrix_bf16", 0, "matrix paired, positional, vector", true); + } else if (heads % 16) { + run("mla_attn_matrix_bf16", 0, "matrix paired, positional, vector"); + run("mla_attn_matrix_bf16", 1, "matrix paired, positional, element"); } else { run("mla_attn_matrix_bf16", 0, "matrix 16 heads, vector load"); run("mla_attn_matrix_bf16", 1, "matrix 16 heads, element load"); @@ -12449,41 +13662,6 @@ static void kda_check(const Plugin& pl, const char* mode, bool cold, int accepte dlclose(ref); } -/* Saves the given switches on construction and restores them on destruction; pin() sets each - * to its value or, for nullptr, back to what the caller had. */ -struct EnvPins { - std::vector names; - std::vector saved; - std::vector had; - explicit EnvPins(std::initializer_list n) : names(n) { - for (const char* k : names) { - const char* v = std::getenv(k); - had.push_back(v != nullptr); - saved.push_back(v ? v : ""); - } - } - void pin(std::initializer_list values) { - size_t i = 0; - for (const char* v : values) { - if (v) - setenv(names[i], v, 1); - else if (had[i]) - setenv(names[i], saved[i].c_str(), 1); - else - unsetenv(names[i]); - ++i; - } - } - ~EnvPins() { - for (size_t i = 0; i < names.size(); ++i) { - if (had[i]) - setenv(names[i], saved[i].c_str(), 1); - else - unsetenv(names[i]); - } - } -}; - /* One launch, then a 200 ms warm-up and `iters` timed launches (st_time_us: --cold gives the * median of flushed launches). -1 when the row refuses the arguments. */ static double form_us(const RadKernelInfo* r, RadArgs* a, int iters) { @@ -12510,15 +13688,16 @@ static std::vector fetch_bytes(const void* d, size_t bytes) { return v; } -/* kda_update at GLM's TP8 shape (eight heads, 128 x 128 state per head), every form held byte for - * byte to the one-row kernel on shuffle sums (RADIANCE_KDA_FORM=old) over the output and the - * whole state buffer, the slots no sequence names included: prefill of M tokens as one sequence - * per candidate and as three anchored sequences (one cold, one unseated), and the verify step of - * eight sequences with up to six candidates, per candidate and anchored, the anchored one after a - * replay of the accepted prefix. `iters` below zero compares only, as a case. */ -static void kda_forms(const Plugin& pl, int64_t M, int iters) { +/* kda_update at GLM's TP8 shape (eight heads, 128 x 128 state per head): prefill of M tokens as + * one sequence per candidate and as three anchored sequences (one cold, one unseated), and the + * verify step of eight sequences with up to six candidates, per candidate and anchored, the + * anchored one after a replay of the accepted prefix. Timed, or with `iters` below zero held to + * libref over the output and the whole state buffer, the slots no sequence names included, as a + * case: the lane reductions sum in another order than libref's loops, so f32 state within + * 2e-5 + 2e-5 |x| and bf16 output within one rounding step. */ +static void kda_perf(const Plugin& pl, int64_t M, int iters) { const bool check = iters < 0; - if (iters == 0) iters = 50; + if (iters <= 0) iters = 50; if (M < 1 || M > 65535) { std::printf("--perfkda: 1 <= M <= 65535\n"); return; @@ -12528,6 +13707,23 @@ static void kda_forms(const Plugin& pl, int64_t M, int iters) { std::printf("--perfkda: row kda_update_k128_v128_bf16 absent\n"); return; } + const RadKernelInfo* oracle = nullptr; + void* ref = nullptr; + if (check && g_plugin) { + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + auto count = ref ? (int (*)(void))dlsym(ref, "rad_kernel_count") : nullptr; + auto at = ref ? (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at") : nullptr; + if (count && at) + for (int i = 0; i < count() && !oracle; ++i) + if (!std::strcmp(at(i)->op, "kda_update")) oracle = at(i); + } + if (check && !oracle) { + ok("KDA at GLM's TP8 shape", false, "reference operation unavailable"); + if (ref) dlclose(ref); + return; + } const int64_t H = 8, D = 128, slots = 64, tokens = std::max(M, 48); const size_t state_floats = (size_t)(slots * H * D * D); std::vector state0(state_floats), alog((size_t)H), bias((size_t)(H * D)); @@ -12628,20 +13824,6 @@ static void kda_forms(const Plugin& pl, int64_t M, int iters) { cases.push_back(c); } - EnvPins env({ "RADIANCE_KDA_FORM", "RADIANCE_KDA_ROWS", "RADIANCE_KDA_PREFETCH" }); - struct Form { - const char* what; - const char* form; - const char* rows; - const char* prefetch; - }; - const Form forms[] = { { "rule", nullptr, nullptr, nullptr }, - { "1 row a wave", "new", "1", "1" }, - { "2 rows a wave", "new", "2", "1" }, - { "4 rows a wave", "new", "4", "1" }, - { "1 row a wave, no prefetch", "new", "1", "0" }, - { "2 rows a wave, no prefetch", "new", "2", "0" }, - { "4 rows a wave, no prefetch", "new", "4", "0" } }; if (!check) std::printf("kda_update at GLM's TP8 shape (8 heads, 128 x 128), %s, %d launches\n", g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() @@ -12691,54 +13873,65 @@ static void kda_forms(const Plugin& pl, int64_t M, int iters) { a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; - auto run = [&]() { - st_memcpy(d_state, start.data(), state_bytes, hipMemcpyHostToDevice); - st_memset(d_out, 0xff, out_bytes); - if (row->launch(&a, nullptr) != RAD_OK || st_stream_sync(nullptr) != hipSuccess) - return false; - return true; - }; - auto outputs = [&]() { - std::vector o = fetch_bytes(d_out, out_bytes); - const std::vector s = fetch_bytes(d_state, state_bytes); - o.insert(o.end(), s.begin(), s.end()); - return o; - }; - env.pin({ "old", nullptr, nullptr }); - const bool ref_ok = run(); - const std::vector ref = outputs(); - if (check) - ok(fmt("KDA %s: old form served", c.what.c_str()).c_str(), ref_ok); - else - std::printf(" %s\n %-34s %8.1f us\n", c.what.c_str(), "old", - ref_ok ? form_us(row, &a, iters) : -1.0); - for (const Form& f : forms) { - env.pin({ f.form, f.rows, f.prefetch }); - const bool served = run(); - const bool same = served && outputs() == ref; - if (check) { - ok(fmt("KDA %s, %s: byte-identical to the old form", c.what.c_str(), f.what) - .c_str(), - ref_ok && same, served ? "" : "not served"); - continue; + st_memcpy(d_state, start.data(), state_bytes, hipMemcpyHostToDevice); + st_memset(d_out, 0xff, out_bytes); + if (check) { + std::vector want_out((size_t)(tokens * H * D), 0xffff); + std::vector want_state = start; + void* const host[13] = { in[0].data(), in[1].data(), in[2].data(), + in[3].data(), in[4].data(), alog.data(), + bias.data(), want_state.data(), c.idx.data(), + c.cu.data(), c.accepted.data(), c.init.data(), + want_out.data() }; + std::vector ht = t; + for (int i = 0; i < 13; ++i) ht[(size_t)i].data = host[i]; + RadArgs ha = a; + ha.t = ht.data(); + const bool served = oracle->launch(&ha, nullptr) == RAD_OK && + row->launch(&a, nullptr) == RAD_OK && + st_stream_sync(nullptr) == hipSuccess; + std::vector got_out(want_out.size()); + std::vector got_state(state_floats); + st_memcpy(got_out.data(), d_out, out_bytes, hipMemcpyDeviceToHost); + st_memcpy(got_state.data(), d_state, state_bytes, hipMemcpyDeviceToHost); + size_t bad = 0; + for (size_t i = 0; i < got_out.size(); ++i) { + if (got_out[i] == want_out[i]) continue; + const float x = h_bf16(got_out[i]), y = h_bf16(want_out[i]); + if (!std::isfinite(x) || !std::isfinite(y) || + std::fabs(x - y) > 0.008f + 0.008f * std::fabs(y)) { + if (bad < 4) std::printf(" out[%zu]: %.6g, libref %.6g\n", i, x, y); + ++bad; + } } - const double us = served ? form_us(row, &a, iters) : -1.0; - if (us < 0) - std::printf(" %-34s not served\n", f.what); - else - std::printf(" %-34s %8.1f us%s\n", f.what, us, - same ? " = old" : " DIFFERS from old"); + for (size_t i = 0; i < got_state.size(); ++i) { + if (got_state[i] == want_state[i]) continue; + if (!std::isfinite(got_state[i]) || + std::fabs(got_state[i] - want_state[i]) > 2e-5f + 2e-5f * std::fabs(want_state[i])) { + if (bad < 4) + std::printf(" state[%zu] (slot %zu): %.9g, libref %.9g, start %.9g\n", i, + i / (size_t)(H * D * D), got_state[i], want_state[i], start[i]); + ++bad; + } + } + ok(fmt("KDA %s: output and whole state at libref's (%zu outside)", c.what.c_str(), bad) + .c_str(), + served && !bad, served ? "" : "not served"); + continue; } + const double us = form_us(row, &a, iters); + if (us < 0) + std::printf(" %-44s not served\n", c.what.c_str()); + else + std::printf(" %-44s %8.1f us\n", c.what.c_str(), us); } + if (ref) dlclose(ref); } -/* mla_project at GLM's TP8 shape (eight heads, head_dim 256, latent 512) in both modes, every row - * form held byte for byte to the one-row kernels on shuffle sums (RADIANCE_MLA_PROJECT=old) over - * the whole pitched output, so a store past a row or into the pitch shows. M not a multiple of the - * rows a group checks the tail. `iters` below zero compares only, as a case. */ -static void project_forms(const Plugin& pl, int64_t M, int iters) { - const bool check = iters < 0; - if (iters == 0) iters = 100; +/* mla_project at GLM's TP8 shape (eight heads, head_dim 256, latent 512) in both modes, on pitched + * tensors, timed. mla_project_check holds the row to libref. */ +static void project_perf(const Plugin& pl, int64_t M, int iters) { + if (iters <= 0) iters = 100; if (M < 1 || M > 65535) { std::printf("--perfproject: 1 <= M <= 65535\n"); return; @@ -12758,14 +13951,11 @@ static void project_forms(const Plugin& pl, int64_t M, int iters) { return; } st_memcpy(d_w, w.data(), w.size() * 2, hipMemcpyHostToDevice); - EnvPins env({ "RADIANCE_MLA_PROJECT" }); - if (!check) - std::printf( - "mla_project at GLM's TP8 shape (8 heads, 256 <-> 512), M=%lld, %s, %d launches\n", - (long long)M, - g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() - : "warm (back to back, mean)", - iters); + std::printf("mla_project at GLM's TP8 shape (8 heads, 256 <-> 512), M=%lld, %s, %d launches\n", + (long long)M, + g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() + : "warm (back to back, mean)", + iters); for (const char* mode : { "absorb", "expand" }) { const bool absorb = !std::strcmp(mode, "absorb"); const int64_t xd = absorb ? 256 : 512, yd = absorb ? 512 : 256; @@ -12797,38 +13987,12 @@ static void project_forms(const Plugin& pl, int64_t M, int iters) { a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; - const size_t y_bytes = (size_t)(M * yr * 2); - auto run = [&]() { - st_memset(d_y, 0xa5, y_bytes); - return row->launch(&a, nullptr) == RAD_OK && st_stream_sync(nullptr) == hipSuccess; - }; - env.pin({ "old" }); - const bool ref_ok = run(); - const std::vector ref = fetch_bytes(d_y, y_bytes); - if (check) - ok(fmt("MLA project %s M=%lld: old form served", mode, (long long)M).c_str(), ref_ok); + st_memset(d_y, 0xa5, (size_t)(M * yr * 2)); + const double us = form_us(row, &a, iters); + if (us < 0) + std::printf(" %-8s not served\n", mode); else - std::printf(" %s\n %-20s %8.1f us\n", mode, "old", - ref_ok ? form_us(row, &a, iters) : -1.0); - for (const char* f : { (const char*)nullptr, "1", "2", "4", "8" }) { - env.pin({ f }); - const bool served = run(); - const bool same = served && fetch_bytes(d_y, y_bytes) == ref; - const std::string what = f ? fmt("%s rows a group", f) : std::string("rule"); - if (check) { - ok(fmt("MLA project %s M=%lld, %s: byte-identical to the old form", mode, - (long long)M, what.c_str()) - .c_str(), - ref_ok && same, served ? "" : "not served"); - continue; - } - const double us = served ? form_us(row, &a, iters) : -1.0; - if (us < 0) - std::printf(" %-20s not served\n", what.c_str()); - else - std::printf(" %-20s %8.1f us%s\n", what.c_str(), us, - same ? " = old" : " DIFFERS from old"); - } + std::printf(" %-8s %8.1f us\n", mode, us); } } @@ -12939,7 +14103,7 @@ static void mx_experts_check(const Plugin& pl, int M, int parts, bool pooled, co } ok("MXFP4 expert storage allocation", memory_ok); if (!memory_ok) { - for (void* p : pinned) hipHostFree(p); + for (void* p : pinned) hip_ck(hipHostFree(p), "hipHostFree", __LINE__); dlclose(ref); return; } @@ -13009,27 +14173,9 @@ static void mx_experts_check(const Plugin& pl, int M, int parts, bool pooled, co 0.004f + 0.008f * std::fabs(want)); } } - const char* lut = std::getenv("RADIANCE_MXFP4_LUT"); - const char* pipe = std::getenv("RADIANCE_MXFP4_PREFILL_PIPE"); - auto env_or = [](const char* n, const char* d) { - const char* v = std::getenv(n); - return v ? v : d; - }; - const char* p64 = std::getenv("RADIANCE_MXFP4_PREFILL_P64"); - const std::string p64s = - !p64 ? std::string("rule") - : p64[0] == '1' - ? fmt("BM%s BN%s K%s x%s out%s db%s", env_or("RADIANCE_MXFP4_PREFILL_P64_BM", "rule"), - env_or("RADIANCE_MXFP4_PREFILL_P64_BN", "rule"), - env_or("RADIANCE_MXFP4_PREFILL_P64_STAGE_K", "rule"), - env_or("RADIANCE_MXFP4_PREFILL_P64_COLTILES", "4"), - env_or("RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", "rule"), - env_or("RADIANCE_MXFP4_PREFILL_P64_DB", "0")) - : std::string("off"); - ok(fmt("MXFP4 M=%d N=%d K=%d parts=%d pooled=%d %s exceptional=%d holes=%d lut=%s pipe=%s " - "p64=%s, pointer tables and dropped slots", - M, OUT, NK, parts, pooled, order, exceptional, holes, lut ? lut : "rule", - pipe ? pipe : "rule", p64s.c_str()) + ok(fmt("MXFP4 M=%d N=%d K=%d parts=%d pooled=%d %s exceptional=%d holes=%d experts=%d top=%d, " + "pointer tables and dropped slots", + M, OUT, NK, parts, pooled, order, exceptional, holes, NE, top) .c_str(), match); ok("MXFP4 grouped output red zones and pitch", guards); @@ -13047,7 +14193,7 @@ static void mx_experts_check(const Plugin& pl, int M, int parts, bool pooled, co ok("MXFP4 layout rejects a different scale group", row->layout(ps.data(), (int)ps.size(), 2, &enc, &selection, &plane, 1, &layout) == RAD_E_DTYPE); - for (void* p : pinned) hipHostFree(p); + for (void* p : pinned) hip_ck(hipHostFree(p), "hipHostFree", __LINE__); dlclose(ref); } @@ -13062,12 +14208,10 @@ static void mx_experts_check(const Plugin& pl, int M, int parts, bool pooled, co * the touched experts are the real traffic. Warm, a touched set under 64 MiB is cache-resident * after the first launch; --cold is the engine's case. * - * Forms are chosen by the RADIANCE_MXFP4_* environment, read at every launch. Their rule is - * mirrored here only to name the form and count the expert slices it streams: a (job, expert) - * pair reads the whole slice across the column blocks, so row groups re-read an expert once per - * group its run spans, and the expert-major decode form once per 16 of its rows. Every form must - * match the bytes of a pinned reference ("old": the TP8 prefill form with its stage prefetch from - * 512 routed rows, below that the rule), since each keeps one accumulation order per element. */ + * The form is the launcher's rule, mirrored here only to name it and count the expert slices it + * streams: a (job, expert) pair reads the whole slice across the column blocks, so row groups + * re-read an expert once per group its run spans, the expert-major decode form once per 16 of its + * rows, and the P64 and GLM prefill forms once per job. */ static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_t top_k, bool f8 = false, const char* skew = nullptr) { if (iters <= 0) iters = 100; @@ -13177,125 +14321,8 @@ static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_ : "warm (back to back, mean)", iters); - constexpr int kEnvs = 22; - static const char* const kEnvMx[kEnvs] = { "RADIANCE_MXFP4_DECODE_EXPERTS", - "RADIANCE_MXFP4_ALIGNED_JOBS", - "RADIANCE_MXFP4_PREFILL_N32", - "RADIANCE_MXFP4_PREFILL_M32", - "RADIANCE_MXFP4_PREFILL_N64", - "RADIANCE_MXFP4_PREFILL_CACHE_ROWS", - "RADIANCE_MXFP4_EXPERTS_STAGE_K", - "RADIANCE_MXFP4_EXPERTS_COLTILES", - "RADIANCE_MXFP4_LUT", - "RADIANCE_MXFP4_PREFILL_PIPE", - "RADIANCE_MXFP4_PREFILL_P64", - "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", - "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN", - "RADIANCE_MXFP4_PREFILL_P64_BM", - "RADIANCE_MXFP4_PREFILL_P64_BN", - "RADIANCE_MXFP4_PREFILL_P64_STAGE_K", - "RADIANCE_MXFP4_PREFILL_P64_COLTILES", - "RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", - "RADIANCE_MXFP4_PREFILL_P64_T_BM64", - "RADIANCE_MXFP4_PREFILL_P64_T_BN128", - "RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", - "RADIANCE_MXFP4_PREFILL_P64_DB" }; - /* The F32-scale row has no prefill forms; its slots 1..5 and 8..21 name the MXFP4 switches, - * which it does not read. */ - static const char* const kEnvF8[kEnvs] = { "RADIANCE_FP8F32_DECODE_EXPERTS", - "RADIANCE_MXFP4_ALIGNED_JOBS", - "RADIANCE_MXFP4_PREFILL_N32", - "RADIANCE_MXFP4_PREFILL_M32", - "RADIANCE_MXFP4_PREFILL_N64", - "RADIANCE_MXFP4_PREFILL_CACHE_ROWS", - "RADIANCE_FP8F32_EXPERTS_STAGE_K", - "RADIANCE_FP8F32_EXPERTS_COLTILES", - "RADIANCE_MXFP4_LUT", - "RADIANCE_MXFP4_PREFILL_PIPE", - "RADIANCE_MXFP4_PREFILL_P64", - "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", - "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN", - "RADIANCE_MXFP4_PREFILL_P64_BM", - "RADIANCE_MXFP4_PREFILL_P64_BN", - "RADIANCE_MXFP4_PREFILL_P64_STAGE_K", - "RADIANCE_MXFP4_PREFILL_P64_COLTILES", - "RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", - "RADIANCE_MXFP4_PREFILL_P64_T_BM64", - "RADIANCE_MXFP4_PREFILL_P64_T_BN128", - "RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", - "RADIANCE_MXFP4_PREFILL_P64_DB" }; - const char* const* const kEnv = f8 ? kEnvF8 : kEnvMx; - std::string saved[kEnvs]; - bool had[kEnvs]; - for (int i = 0; i < kEnvs; ++i) { - const char* v = std::getenv(kEnv[i]); - had[i] = v != nullptr; - if (v) saved[i] = v; - } - auto restore = [&]() { - for (int i = 0; i < kEnvs; ++i) { - if (had[i]) - setenv(kEnv[i], saved[i].c_str(), 1); - else - unsetenv(kEnv[i]); - } - }; - auto on = [](const char* n, bool dflt) { - const char* v = std::getenv(n); - return v ? v[0] == '1' : dflt; - }; - /* body()'s glm_prefill: the default of the prefill switches at GLM's projections. */ + /* body()'s glm_prefill: the measured GLM slices, at which the prefill forms serve. */ const bool glm = !f8 && E == 288 && top_k == 8; - auto num = [](const char* n, long dflt) { - const char* v = std::getenv(n); - return v && *v ? std::strtol(v, nullptr, 10) : dflt; - }; - /* env nullptr: the environment as given. Expert-major forms pin stage and column tiles; the - * prefill forms exist only from 512 routed rows. `lut` 0 or 1 pins the weight decode, `pipe` - * the TP8 prefill form's stage prefetch (-1: as given); the arithmetic decode without the - * prefetch is the bytewise reference of the others. `bm` > 0 pins the P64 form below its row - * bound at BM, BN, stage, column tiles (down only), LDS output and double buffer (gate_up - * only); every other pinned form pins P64 off. */ - struct Form { - const char* env; - int stage, tiles, lut, pipe = -1, bm = 0, bn = 0, sk = 0, ct = 0, out = 0, db = 0; - }; - std::vector
forms = { { nullptr, 0, 0, -1 }, { "100000", 256, 1, -1 }, - { "100000", 256, 4, -1 }, { "100000", 128, 1, -1 }, - { "100000", 128, 4, -1 }, { "000000", 0, 0, -1 } }; - if (!f8) - for (int lut : { 0, 1 }) { - forms.push_back({ "100000", 256, 1, lut }); - forms.push_back({ "100000", 128, 4, lut }); - } - if (Tr >= 512 && !f8) { - for (const char* f : { "010000", "001000", "011000", "011100", "011110", "011111" }) - forms.push_back({ f, 0, 0, -1 }); - for (int pipe : { 0, 1 }) - for (int lut : { 0, 1 }) forms.push_back({ "011111", 0, 0, lut, pipe }); - } - const Form old = Tr >= 512 && !f8 ? Form{ "011111", 0, 0, 1, 1 } : Form{ nullptr, 0, 0, -1 }; - auto apply = [&](const Form& F) { - restore(); - if (!F.env) return; - for (int i = 0; i < 6; ++i) setenv(kEnv[i], F.env[i] == '1' ? "1" : "0", 1); - const int pinned[2] = { F.stage, F.tiles }; - for (int i = 0; i < 2; ++i) { - if (F.stage) - setenv(kEnv[6 + i], std::to_string(pinned[i]).c_str(), 1); - else - unsetenv(kEnv[6 + i]); - } - const int pinned2[2] = { F.lut, F.pipe }; - for (int i = 8; i < 10; ++i) - if (pinned2[i - 8] >= 0) setenv(kEnv[i], pinned2[i - 8] ? "1" : "0", 1); - setenv(kEnv[10], F.bm ? "1" : "0", 1); - if (F.bm) { - const int v[7] = { 0, 0, F.bm, F.bn, F.sk, F.ct, F.out }; - for (int i = 0; i < 7; ++i) setenv(kEnv[11 + i], std::to_string(v[i]).c_str(), 1); - setenv(kEnv[21], F.db ? "1" : "0", 1); - } - }; struct Proj { const char* name; @@ -13315,28 +14342,6 @@ static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_ P.name, (long long)N, (long long)K, (long long)P.parts, P.srt ? "sorted" : "token", slice / 1048576.0, touched * slice / 1048576.0, E * slice / 1048576.0); - /* P64 over BM x BN x stage; at down's K (A resident) also over column tiles, and the LDS - * output at the default. */ - std::vector pf = forms; - if (Tr >= 512 && !f8) { - for (int bm : { 32, 64 }) - for (int bn : { 64, 128 }) - for (int sk2 : { 128, 256 }) - for (int ct : { 1, 4 }) { - if (ct == 1 && K > 256) continue; - pf.push_back({ "000000", 0, 0, -1, -1, bm, bn, sk2, ct, 0 }); - } - pf.push_back({ "000000", 0, 0, -1, -1, 64, 128, 128, 4, 1 }); - /* The double buffer where two stages fit in LDS (streamed A, gate_up). */ - if (K > 256) { - for (int bm : { 32, 64 }) - for (int bn : { 64, 128 }) - pf.push_back({ "000000", 0, 0, -1, -1, bm, bn, 128, 4, 0, 1 }); - pf.push_back({ "000000", 0, 0, -1, -1, 32, 64, 256, 4, 0, 1 }); - pf.push_back({ "000000", 0, 0, -1, -1, 64, 128, 128, 4, 1, 1 }); - } - } - std::vector av((size_t)(Ma * K)); for (size_t i = 0; i < av.size(); ++i) av[i] = rad_f32_to_fp8e4m3((float)((int)(st_mix32((uint32_t)i) % 33) - 16) / 4); @@ -13428,74 +14433,36 @@ static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_ a.world_size = 1; const double flop = 2.0 * (double)Tr * (double)N * (double)K; const size_t ybytes = (size_t)(Tr * N) * 2; - std::vector reference(ybytes), got(ybytes); - apply(old); - st_memset(d_y, 0xff, ybytes); - bool have_old = r->launch(&a, nullptr) == RAD_OK && st_stream_sync(nullptr) == hipSuccess; - if (have_old) st_memcpy(reference.data(), d_y, ybytes, hipMemcpyDeviceToHost); - std::printf(" old: %s\n", - !have_old ? "not served, no byte comparison" - : old.env ? "TP8 prefill form, stage prefetch and table decode pinned" - : "the rule"); - for (size_t f = 0; f < pf.size(); ++f) { - apply(pf[f]); - const long max_t = f8 ? num("RADIANCE_FP8F32_DECODE_EXPERTS_MAX_T", -1) - : num(P.srt ? "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_DOWN" - : "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_GATE_UP", - glm ? (P.srt ? 6143 : 768) : 511); - const char* forced = std::getenv(kEnv[0]); - const bool pwide = K > 256 ? Tr >= num(kEnv[19], 24576) : Tr >= num(kEnv[20], 24576); - const long dbm = pwide || (K > 256 && Tr >= num(kEnv[18], 12288)) ? 64 : 32; - const long dbn = pwide ? 128 : 64; - const long dsk = K > 256 && !pwide ? 256 : 128; - const long pbm = num(kEnv[13], dbm) == 32 ? 32 : 64, - pbn = num(kEnv[14], dbn) == 64 ? 64 : 128; - const long psk = num(kEnv[15], dsk) == 256 ? 256 : 128; - const bool p64 = !f8 && on(kEnv[10], glm) && !(forced && forced[0] == '1') && - Tr >= num(P.srt ? kEnv[12] : kEnv[11], P.srt ? 5760 : 769) && - (Tr + pbm - 1) / pbm + E <= 65535; - const bool expert = !p64 && on(kEnv[0], max_t < 0 || Tr <= max_t); - const long esk = num(kEnv[6], K <= 256 ? 128 : 256) == 128 ? 128 : 256; - const long et = num(kEnv[7], K <= 256 || (f8 && Tr < 128) ? 4 : 1) == 4 ? 4 : 1; - const bool aligned = !p64 && !expert && !f8 && on(kEnv[1], glm) && Tr >= 512; - const bool wide = !p64 && !expert && !f8 && on(kEnv[2], glm) && Tr >= 512; - const bool tall = wide && aligned && on(kEnv[3], glm), n64 = tall && on(kEnv[4], glm); - const bool cached = n64 && on(kEnv[5], glm), lut = f8 || p64 || on(kEnv[8], true); - const bool pipe = cached && on(kEnv[9], glm); - const long pct = K <= 256 && num(kEnv[16], 4) != 1 ? 4 : 1; - const bool pout = num(kEnv[17], pwide ? 1 : 0) == 1; - const bool pdb = - K > 256 && num(kEnv[21], 0) == 1 && (psk == 128 || (pbm == 32 && pbn == 64)); - const int64_t jr = p64 ? pbm : tall ? 32 : 16, tile = Tr < 32 ? 1 : Tr < 128 ? 4 : 16; + { + const bool pwide = Tr >= 24576; + const int64_t pbm = pwide || (K > 256 && Tr >= 12288) ? 64 : 32; + const bool p64 = + glm && Tr >= (P.srt ? 5760 : 769) && (Tr + pbm - 1) / pbm + E <= 65535; + const bool expert = !p64 && (f8 || Tr <= (glm ? (P.srt ? 6143 : 768) : 511)); + const bool pipe = !p64 && !expert && glm; + const int64_t jr = p64 ? pbm : pipe ? 32 : 16; int64_t streams = 0; - if (p64 || aligned || expert) + if (p64 || pipe || expert) for (int64_t e = 0; e < E; ++e) streams += (off[(size_t)(e + 1)] - off[(size_t)e] + jr - 1) / jr; else for (int64_t i = 0; i < Tr; ++i) - streams += i % tile == 0 || owner[(size_t)i] != owner[(size_t)(i - 1)]; + streams += i % 16 == 0 || owner[(size_t)i] != owner[(size_t)(i - 1)]; const std::string label = - std::string(pf[f].env ? "" : "rule: ") + - (p64 ? fmt("P64 BM%ld BN%ld K%ld", pbm, pbn, psk) + - (K <= 256 ? fmt(" x%ld, A resident", pct) : "") + - (pout ? ", LDS out" : "") + (pdb ? ", double buffer" : "") - : expert ? fmt("expert-major K%ld x%ld tiles", esk, et) - : std::string(n64 ? "M32N64" - : tall ? "M32N32" - : wide ? "M16N32" - : f8 ? "M16N64" - : "M16N16") + - (aligned ? " aligned jobs" - : fmt(" row groups of %lld", (long long)tile)) + - (cached ? ", cached rows" : "") + (pipe ? ", pipe" : "")) + - (lut ? "" : ", fp4x4"); + p64 ? fmt("P64 BM%lld BN%d K%d", (long long)pbm, pwide ? 128 : 64, + K > 256 && !pwide ? 256 : 128) + + (K <= 256 ? " x4, A resident" : "") + (pwide ? ", LDS out" : "") + : expert ? fmt("expert-major K%d x%d tiles", K <= 256 ? 128 : 256, + K <= 256 || (f8 && Tr < 128) ? 4 : 1) + : pipe ? std::string("GLM prefill form, jobs of 32 rows") + : std::string("row groups of 16"); st_memset(d_y, 0xff, ybytes); const int rc = r->launch(&a, nullptr); if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { std::printf(" %-46s rc=%d (not served)\n", label.c_str(), rc); + dfree_all(); continue; } - st_memcpy(got.data(), d_y, ybytes, hipMemcpyDeviceToHost); { hipEvent_t w0, w1; st_ev_create(&w0); @@ -13512,28 +14479,17 @@ static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_ st_ev_destroy(w1); } const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); - if (f == 0) { - rule_us += us; - rule_bytes += touched * slice; - } - std::string same; - if (have_old) { - int64_t diff = 0; - for (size_t i = 0; i < ybytes; i += 2) - diff += std::memcmp(&got[i], &reference[i], 2) != 0; - same = diff ? fmt(" %lld elements differ from old", (long long)diff) : " = old"; - } - std::printf( - " %-46s %9.1f us %7.1f GB/s touched %5.2fx streamed %6.1f TFLOP/s%s\n", - label.c_str(), us, touched * slice / (us * 1e3), - touched ? (double)streams / (double)touched : 0.0, flop / (us * 1e6), same.c_str()); + rule_us += us; + rule_bytes += touched * slice; + std::printf(" %-46s %9.1f us %7.1f GB/s touched %5.2fx streamed %6.1f TFLOP/s\n", + label.c_str(), us, touched * slice / (us * 1e3), + touched ? (double)streams / (double)touched : 0.0, flop / (us * 1e6)); } - restore(); dfree_all(); } if (rule_us > 0) - std::printf(" the rule's forms, gate_up + down: %.1f us a layer, %.1f GB/s touched\n", - rule_us, rule_bytes / (rule_us * 1e3)); + std::printf(" gate_up + down: %.1f us a layer, %.1f GB/s touched\n", rule_us, + rule_bytes / (rule_us * 1e3)); } /* The gated residual's read at int8 codes. The same inputs run with the codes plane as E4M3 and @@ -13832,10 +14788,9 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool /* mHC's chunk-split read, as tensor parallelism issues it: every rank's mhc_pre_partial over its * chunks, the partials joined row by row as the row-interleaved all_gather lays them out (here on * the host), then mhc_pre_finish. The result must be byte-identical to mhc_pre on the same inputs, - * under each of mhc_pre's kernel switches, since both run the same projection and finishing - * kernels; the partial matrix's padding slots must be zero. */ -static void mhc_split_check(const Plugin& pl, int64_t rows, int world, const char* env, - const char* value) { + * since both run the same projection and finishing kernels; the partial matrix's padding slots + * must be zero. */ +static void mhc_split_check(const Plugin& pl, int64_t rows, int world) { const RadKernelInfo* pre = find(pl, "mhc_pre_bf16"); const RadKernelInfo* part_row = find(pl, "mhc_pre_partial_bf16"); const RadKernelInfo* fin = find(pl, "mhc_pre_finish_bf16"); @@ -13843,9 +14798,6 @@ static void mhc_split_check(const Plugin& pl, int64_t rows, int world, const cha if (!pre || !part_row || !fin) { ok(nm, false, "row absent"); return; } const int64_t n = 4096, hc = 4, W = hc * n, mix = hc * (hc + 2), S = 28, total = 8; const int64_t mine = total / world, hp = W + 6, xp = n + 2; - const char* saved = env ? std::getenv(env) : nullptr; - const std::string keep = saved ? saved : ""; - if (env) setenv(env, value, 1); std::vector hv((size_t)(rows * hp)); for (size_t i = 0; i < hv.size(); ++i) @@ -13929,22 +14881,21 @@ static void mhc_split_check(const Plugin& pl, int64_t rows, int world, const cha good = good && launch(fin, split, fp); const Out got = fetch(sx, sp, sc); const bool same = good && got.x == want.x && got.p == want.p && got.c == want.c; - ok(fmt("%s at M=%lld over %d ranks%s%s%s: byte-identical to mhc_pre", nm, (long long)rows, - world, env ? ", " : "", env ? env : "", env ? (std::string("=") + value).c_str() : "") + ok(fmt("%s at M=%lld over %d ranks: byte-identical to mhc_pre", nm, (long long)rows, world) .c_str(), same, good ? (got.x != want.x ? "x differs" : got.p != want.p ? "post differs" : got.c != want.c ? "comb differs" : "") : "launch failed"); ok(fmt("%s at M=%lld over %d ranks: zero padding", nm, (long long)rows, world).c_str(), padded); - if (env) { if (saved) setenv(env, keep.c_str(), 1); else unsetenv(env); } } /* mhc_pre and mhc_post at GLM's shape (n 4096, four streams, 2048-column chunks, 20 Sinkhorn - * rounds), every form timed and compared byte for byte with the old dispatch - * (RADIANCE_MHC_FINISH=old, RADIANCE_MHC_PARTIAL_VEC=0, the per-output mhc_post). - * The whole op, its partials alone (all eight chunks, and the one chunk a rank computes at TP8) - * and its finish alone over those partials. GB/s counts h and x (and mhc_post's output); the - * mixing weights (1.5 MiB) stay in L2. `iters` below zero runs each form once and reports only - * the comparisons, as a case. */ + * rounds), timed on 16-byte rows, where the vector forms run (four-slot partials, the finish's + * 16-byte collapse, the eight-column mhc_post), and compared byte for byte with the same operands + * on a residual pitched by two elements, where the scalar forms run (one slot a thread, four rows + * and four coefficients a block from 32 rows, the per-output mhc_post). The whole op, its partials + * alone (all eight chunks, and the one chunk a rank computes at TP8) and its finish alone over + * those partials. GB/s counts h and x (and mhc_post's output); the mixing weights (1.5 MiB) stay + * in L2. `iters` below zero runs each form once and reports only the comparisons, as a case. */ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { const bool check = iters < 0; if (iters == 0) iters = 200; @@ -13955,29 +14906,14 @@ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { const RadKernelInfo* post = find(pl, "mhc_post_bf16"); if (!pre || !part || !fin || !post) { std::printf("--perfmhcpre: an mhc row is absent\n"); return; } const int64_t n = 4096, hc = 4, W = hc * n, mix = hc * (hc + 2), S = 28, total = 8; - static const char* const kEnv[5] = { "RADIANCE_MHC_FINISH", "RADIANCE_MHC_ROWS4_MIN", - "RADIANCE_MHC_POST_VEC", "RADIANCE_MHC_PARTIAL_VEC", - "RADIANCE_MHC_PARTIAL_ROWS" }; - std::string saved[5]; - bool had[5]; - for (int i = 0; i < 5; ++i) { - const char* v = std::getenv(kEnv[i]); - had[i] = v != nullptr; - if (v) saved[i] = v; - } - auto pin = [&](const char* finish, const char* rows4, const char* vec, - const char* pvec = nullptr, const char* prows = nullptr) { - const char* v[5] = { finish, rows4, vec, pvec, prows }; - for (int i = 0; i < 5; ++i) { - if (v[i]) setenv(kEnv[i], v[i], 1); - else if (had[i]) setenv(kEnv[i], saved[i].c_str(), 1); - else unsetenv(kEnv[i]); - } - }; + const int64_t pitched = W + 2; std::vector hv((size_t)(rows * W)), yv((size_t)(rows * n)); for (size_t i = 0; i < hv.size(); ++i) hv[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i * 3u + 11u) % 2001) - 1000) / 1000); + std::vector hpv((size_t)(rows * pitched), 0); + for (int64_t r = 0; r < rows; ++r) + std::memcpy(&hpv[(size_t)(r * pitched)], &hv[(size_t)(r * W)], (size_t)W * 2); for (size_t i = 0; i < yv.size(); ++i) yv[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i * 5u + 3u) % 2001) - 1000) / 500); std::vector fv((size_t)(mix * W)), sv = { 0.7f, 0.9f, 1.1f }, bv((size_t)mix); @@ -13985,6 +14921,7 @@ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { fv[i] = (float)((int)(st_mix32((uint32_t)i + 77u) % 2001) - 1000) / 100000; for (size_t i = 0; i < bv.size(); ++i) bv[i] = (float)((int)(i % 7) - 3) * 0.25f; void* d_h = dalloc(hv.size() * 2); + void* d_hp = dalloc(hpv.size() * 2); void* d_y = dalloc(yv.size() * 2); void* d_f = dalloc(fv.size() * 4); void* d_s = dalloc(12); @@ -13995,11 +14932,13 @@ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { void* d_part = dalloc((size_t)(rows * total * S * 4)); void* d_part1 = dalloc((size_t)(rows * S * 4)); void* d_out = dalloc((size_t)(rows * W * 2)); - if (!d_h || !d_y || !d_f || !d_s || !d_b || !d_x || !d_p || !d_c || !d_part || !d_part1 || !d_out) { + if (!d_h || !d_hp || !d_y || !d_f || !d_s || !d_b || !d_x || !d_p || !d_c || !d_part || !d_part1 || + !d_out) { std::printf("--perfmhcpre: alloc failed\n"); return; } st_memcpy(d_h, hv.data(), hv.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_hp, hpv.data(), hpv.size() * 2, hipMemcpyHostToDevice); st_memcpy(d_y, yv.data(), yv.size() * 2, hipMemcpyHostToDevice); st_memcpy(d_f, fv.data(), fv.size() * 4, hipMemcpyHostToDevice); st_memcpy(d_s, sv.data(), 12, hipMemcpyHostToDevice); @@ -14008,6 +14947,8 @@ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { ts = T(d_s, RAD_F32, { 3 }), tb = T(d_b, RAD_F32, { mix }), tx = T(d_x, RAD_BF16, { rows, n }), tp = T(d_p, RAD_F32, { rows, hc }), tc = T(d_c, RAD_F32, { rows, hc * hc }); + RadTensor thp = T(d_hp, RAD_BF16, { rows, W }); + thp.stride[0] = pitched; std::vector coef = { PI("M", rows), PI("n", n), PI("hc", hc), PI("iterations", 20), PF("eps", 1e-6), PF("hc_eps", 1e-6), PI("chunk", 2048), PS("dtype", "bf16") }; @@ -14021,6 +14962,8 @@ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { std::vector a_fin = { T(d_part, RAD_F32, { rows, total * S }), th, ts, tb, tx, tp, tc }; std::vector a_post = { T(d_y, RAD_BF16, { rows, n }), th, tp, tc, T(d_out, RAD_BF16, { rows, W }) }; + std::vector a_pre_p = a_pre, a_all_p = a_all, a_post_p = a_post; + a_pre_p[0] = a_all_p[0] = a_post_p[1] = thp; auto args = [](std::vector& t, std::vector& p) { RadArgs a{}; a.t = t.data(); a.n_t = (int)t.size(); a.p = p.data(); a.n_p = (int)p.size(); @@ -14028,7 +14971,8 @@ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { return a; }; RadArgs A_pre = args(a_pre, coef), A_all = args(a_all, p_all), A_one = args(a_one, p_one), - A_fin = args(a_fin, coef), A_post = args(a_post, coef); + A_fin = args(a_fin, coef), A_post = args(a_post, coef), A_pre_p = args(a_pre_p, coef), + A_all_p = args(a_all_p, p_all), A_post_p = args(a_post_p, coef); auto timed = [&](const RadKernelInfo* r, RadArgs* a) { if (r->launch(a, nullptr) != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return -1.0; if (check) return 0.0; @@ -14068,7 +15012,7 @@ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { auto line = [&](const char* what, double us, double bytes, const std::string& same) { if (check) { ok(fmt("%s at M=%lld%s", what, (long long)rows, - same.empty() ? " is served" : ": byte-identical to the old dispatch").c_str(), + same.empty() ? " is served" : ": byte-identical to the pitched rows").c_str(), us >= 0 && same.find("DIFFERS") == std::string::npos, us < 0 ? "not served" : ""); return; } @@ -14076,75 +15020,49 @@ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { std::printf(" %-44s %8.1f us %7.1f GB/s%s\n", what, us, bytes / (us * 1e3), same.c_str()); }; auto cmp = [](const std::vector& a, const std::vector& b) { - return a == b ? std::string(" = old") : std::string(" DIFFERS from old"); + return a == b ? std::string(" = pitched") : std::string(" DIFFERS from pitched"); }; - pin("old", nullptr, "0", "0"); - const double us_old = timed(pre, &A_pre); + const size_t x_bytes = (size_t)(rows * n * 2), part_bytes = (size_t)(rows * total * S * 4), + out_bytes = (size_t)(rows * W * 2); + const double us_pre_p = timed(pre, &A_pre_p); const std::vector ref = outputs(); - line("mhc_pre, old dispatch", us_old, hx, ""); - struct Pv { const char* what; const char* finish; const char* rows4; const char* pvec; - const char* prows; }; - for (const Pv& v : { Pv{ "mhc_pre, rule", nullptr, nullptr, nullptr, nullptr }, - Pv{ "mhc_pre, finish: scalar mix, wide read", "scalar", nullptr, nullptr, nullptr }, - Pv{ "mhc_pre, old partials (rows4 from 32)", nullptr, nullptr, "0", nullptr }, - Pv{ "mhc_pre, four-slot partials, 1 row a wave", nullptr, nullptr, "1", "1" }, - Pv{ "mhc_pre, four-slot partials, 2 rows a wave", nullptr, nullptr, "1", "2" }, - Pv{ "mhc_pre, four-slot partials, 4 rows a wave", nullptr, nullptr, "1", "4" } }) { - pin(v.finish, v.rows4, nullptr, v.pvec, v.prows); - st_memset(d_x, 0xff, (size_t)(rows * n * 2)); - const double us = timed(pre, &A_pre); - line(v.what, us, hx, us < 0 ? "" : cmp(outputs(), ref)); - } - pin(nullptr, nullptr, nullptr, "0"); - if (part->launch(&A_all, nullptr) == RAD_OK) st_stream_sync(nullptr); - const std::vector part_ref = fetch(d_part, (size_t)(rows * total * S * 4)); - for (const Pv& v : { Pv{ "mhc_pre_partial, 8 chunks, old", nullptr, nullptr, "0", nullptr }, - Pv{ "mhc_pre_partial, 8 chunks, rule", nullptr, nullptr, nullptr, nullptr }, - Pv{ "mhc_pre_partial, 8 chunks, four-slot x1", nullptr, nullptr, "1", "1" }, - Pv{ "mhc_pre_partial, 8 chunks, four-slot x2", nullptr, nullptr, "1", "2" }, - Pv{ "mhc_pre_partial, 8 chunks, four-slot x4", nullptr, nullptr, "1", "4" }, - Pv{ "mhc_pre_partial, 8 chunks, rows4 at every M", nullptr, "1", "0", nullptr }, - Pv{ "mhc_pre_partial, 8 chunks, scalar-row", nullptr, "1000000", "0", nullptr } }) { - pin(nullptr, v.rows4, nullptr, v.pvec, v.prows); - st_memset(d_part, 0xff, (size_t)(rows * total * S * 4)); - const double us = timed(part, &A_all); - const bool is_ref = v.pvec && !std::strcmp(v.pvec, "0") && !v.rows4; - line(v.what, us, (double)rows * W * 2, us < 0 || is_ref ? std::string() - : cmp(fetch(d_part, (size_t)(rows * total * S * 4)), part_ref)); - } - pin(nullptr, nullptr, nullptr); + line("mhc_pre, pitched rows", us_pre_p, hx, ""); + st_memset(d_x, 0xff, x_bytes); + const double us_pre = timed(pre, &A_pre); + line("mhc_pre", us_pre, hx, us_pre < 0 ? "" : cmp(outputs(), ref)); + + st_memset(d_part, 0xff, part_bytes); + const double us_all_p = timed(part, &A_all_p); + const std::vector part_ref = fetch(d_part, part_bytes); + line("mhc_pre_partial, 8 chunks, pitched rows", us_all_p, (double)rows * W * 2, ""); + st_memset(d_part, 0xff, part_bytes); + const double us_all = timed(part, &A_all); + line("mhc_pre_partial, 8 chunks", us_all, (double)rows * W * 2, + us_all < 0 ? "" : cmp(fetch(d_part, part_bytes), part_ref)); line("mhc_pre_partial, 1 chunk (a TP8 rank's)", timed(part, &A_one), (double)rows * W * 2 / 8, ""); + if (part->launch(&A_all, nullptr) == RAD_OK) st_stream_sync(nullptr); - for (const Pv& v : { Pv{ "mhc_pre_finish, old", "old", nullptr, nullptr, nullptr }, - Pv{ "mhc_pre_finish, rule", nullptr, nullptr, nullptr, nullptr }, - Pv{ "mhc_pre_finish, scalar mix, wide read", "scalar", nullptr, nullptr, nullptr } }) { - pin(v.finish, nullptr, nullptr); - st_memset(d_x, 0xff, (size_t)(rows * n * 2)); - const double us = timed(fin, &A_fin); - line(v.what, us, hx, us < 0 ? "" : cmp(outputs(), ref)); - } + st_memset(d_x, 0xff, x_bytes); + const double us_fin = timed(fin, &A_fin); + line("mhc_pre_finish", us_fin, hx, us_fin < 0 ? "" : cmp(outputs(), ref)); + const double post_bytes = (double)rows * (2 * W + n) * 2; - pin(nullptr, nullptr, "0"); - const double us_post_old = timed(post, &A_post); - const std::vector post_ref = fetch(d_out, (size_t)(rows * W * 2)); - line("mhc_post, old", us_post_old, post_bytes, ""); - pin(nullptr, nullptr, nullptr); - st_memset(d_out, 0xff, (size_t)(rows * W * 2)); + const double us_post_p = timed(post, &A_post_p); + const std::vector post_ref = fetch(d_out, out_bytes); + line("mhc_post, pitched rows", us_post_p, post_bytes, ""); + st_memset(d_out, 0xff, out_bytes); const double us_post = timed(post, &A_post); - line("mhc_post, rule", us_post, post_bytes, - us_post < 0 ? "" : cmp(fetch(d_out, (size_t)(rows * W * 2)), post_ref)); - for (int i = 0; i < 5; ++i) { - if (had[i]) setenv(kEnv[i], saved[i].c_str(), 1); - else unsetenv(kEnv[i]); - } + line("mhc_post", us_post, post_bytes, + us_post < 0 ? "" : cmp(fetch(d_out, out_bytes), post_ref)); } -/* router_sigmoid_topk's wave-per-row select against the serial scan (RADIANCE_ROUTER_SELECT=old), - * byte for byte over ids and weights with their pitches filled, so an overrun or a missed slot - * shows. Logits, bias and outputs are pitched, the bias strided. `ties` puts logits on steps of - * 1/2 and the bias on steps of 1/8, so many experts share a rank and the lower-index rule - * decides. `iters` below zero compares only, as a case; otherwise both are timed. */ +/* router_sigmoid_topk's wave-per-row select against libref's: the ids exactly and the weights to + * a relative 1e-5 (the card's expf and the host's may differ in the last place), with the pitches + * filled, so an overrun or a missed slot shows. Logits, bias and outputs are pitched, the bias + * strided. `ties` puts logits on steps of 1/2 and the bias on steps of 1/8, so many experts share + * a rank and the lower-index rule decides. `iters` below zero compares only, as a case; otherwise + * the select is timed. */ static void router_select(const Plugin& pl, int64_t rows, int64_t ne, int64_t k, int norm, bool ties, int iters) { const bool check = iters < 0; @@ -14180,45 +15098,70 @@ static void router_select(const Plugin& pl, int64_t rows, int64_t ne, int64_t k, RadArgs a{}; a.t = ts.data(); a.n_t = 4; a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; - const char* saved = std::getenv("RADIANCE_ROUTER_SELECT"); - const std::string keep = saved ? saved : ""; - auto run = [&](const char* form, std::vector* out, double* us) -> int { - if (form) setenv("RADIANCE_ROUTER_SELECT", form, 1); - else unsetenv("RADIANCE_ROUTER_SELECT"); - st_memset(d_i, 0xa5, (size_t)(rows * ip * 4)); - st_memset(d_w, 0xa5, (size_t)(rows * wp * 4)); - const int rc = r->launch(&a, nullptr); - if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return rc != RAD_OK ? rc : RAD_E_DEVICE; - out->resize((size_t)(rows * (ip + wp) * 4)); - st_memcpy(out->data(), d_i, (size_t)(rows * ip * 4), hipMemcpyDeviceToHost); - st_memcpy(out->data() + rows * ip * 4, d_w, (size_t)(rows * wp * 4), hipMemcpyDeviceToHost); - if (!check) *us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); - return (int)RAD_OK; - }; - std::vector old, got; - double us_old = 0, us_new = 0; - const int orc = run("old", &old, &us_old); - const int nrc = orc == RAD_OK ? run(nullptr, &got, &us_new) : orc; - if (saved) setenv("RADIANCE_ROUTER_SELECT", keep.c_str(), 1); - else unsetenv("RADIANCE_ROUTER_SELECT"); - const bool same = nrc == RAD_OK && got == old; - if (check) { - size_t first = 0; - if (nrc == RAD_OK && !same) while (first < got.size() && got[first] == old[first]) ++first; - ok(fmt("router_sigmoid_topk select at M=%lld n_expert=%lld top_k=%lld norm=%d%s: " - "byte-identical to the serial scan", (long long)rows, (long long)ne, (long long)k, - norm, ties ? ", tied ranks" : "").c_str(), same, - nrc != RAD_OK ? fmt("rc=%d", nrc) : same ? "" : fmt("first byte %zu", first)); + st_memset(d_i, 0xa5, (size_t)(rows * ip * 4)); + st_memset(d_w, 0xa5, (size_t)(rows * wp * 4)); + int rc = r->launch(&a, nullptr); + if (rc == RAD_OK && st_stream_sync(nullptr) != hipSuccess) rc = RAD_E_DEVICE; + if (!check) { + if (rc != RAD_OK) { std::printf("--perfrouter: launch failed (rc %d)\n", rc); return; } + const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); + std::printf("router_sigmoid_topk, M=%lld (n_expert %lld, top %lld, norm %d), %s, %d " + "launches\n", (long long)rows, (long long)ne, (long long)k, norm, + g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() + : "warm (back to back, mean)", iters); + std::printf(" %-28s %8.1f us\n", "wave per row", us); return; } - if (nrc != RAD_OK) { std::printf("--perfrouter: launch failed (rc %d)\n", nrc); return; } - std::printf("router_sigmoid_topk, M=%lld (n_expert %lld, top %lld, norm %d), %s, %d launches\n", - (long long)rows, (long long)ne, (long long)k, norm, - g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() - : "warm (back to back, mean)", iters); - std::printf(" %-28s %8.1f us\n", "serial scan (old)", us_old); - std::printf(" %-28s %8.1f us%s\n", "wave per row", us_new, - same ? " = old" : " DIFFERS from old"); + const std::string name = fmt("router_sigmoid_topk select at M=%lld n_expert=%lld top_k=%lld " + "norm=%d%s: libref's ids and weights", (long long)rows, + (long long)ne, (long long)k, norm, ties ? ", tied ranks" : ""); + if (rc != RAD_OK) { ok(name.c_str(), false, fmt("rc=%d", rc)); return; } + std::vector ids((size_t)(rows * ip)), want_ids((size_t)(rows * ip)); + std::vector wts((size_t)(rows * wp)), want_wts((size_t)(rows * wp)); + st_memcpy(ids.data(), d_i, ids.size() * 4, hipMemcpyDeviceToHost); + st_memcpy(wts.data(), d_w, wts.size() * 4, hipMemcpyDeviceToHost); + std::memset(want_ids.data(), 0xa5, want_ids.size() * 4); + std::memset(want_wts.data(), 0xa5, want_wts.size() * 4); + void* ref = nullptr; + if (g_plugin) { + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + } + const auto count = ref ? (int (*)())dlsym(ref, "rad_kernel_count") : nullptr; + const auto at = ref ? (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at") : nullptr; + const RadKernelInfo* oracle = nullptr; + for (int i = 0; count && at && i < count(); ++i) + if (!std::strcmp(at(i)->op, "router_sigmoid_topk")) oracle = at(i); + if (!oracle) { + ok(name.c_str(), false, "reference operation unavailable"); + if (ref) dlclose(ref); + return; + } + std::vector hs = ts; + hs[0].data = lg.data(); hs[1].data = bv.data(); + hs[2].data = want_ids.data(); hs[3].data = want_wts.data(); + RadArgs ha = a; + ha.t = hs.data(); + const int hrc = oracle->launch(&ha, nullptr); + dlclose(ref); + if (hrc != RAD_OK) { ok(name.c_str(), false, fmt("host oracle rc=%d", hrc)); return; } + int64_t bad = 0, first = -1; + for (int64_t row = 0; row < rows; ++row) { + for (int64_t c = 0; c < ip; ++c) { + const size_t i = (size_t)(row * ip + c); + if (ids[i] != want_ids[i] && !bad++) first = row; + } + for (int64_t c = 0; c < wp; ++c) { + const size_t i = (size_t)(row * wp + c); + const bool same = + c < k ? std::fabs(wts[i] - want_wts[i]) <= 1e-5f * std::fabs(want_wts[i]) + : std::memcmp(&wts[i], &want_wts[i], 4) == 0; + if (!same && !bad++) first = row; + } + } + ok(name.c_str(), bad == 0, bad ? fmt("%lld words differ, the first in row %lld", (long long)bad, + (long long)first) : ""); } /* ---- GLM's decode fusions of the MoE block (r4d_glm.hip), each against the separate launches it @@ -14557,11 +15500,12 @@ static void moefuse_perf(const Plugin& pl, int64_t rows, int iters) { moefuse_gather(pl, rows, false, iters); } -/* gemm_nt_f32 at every tile form (RADIANCE_F32_GEMM_TILE), each compared byte for byte with the - * one-wave-per-output legacy kernel. Rows are pitched and the output keeps a filled pitch, so an - * overrun or a missed tail shows as a byte difference. Timed, every form also prints its time, - * its GB/s on weight + input + output and its TFLOP/s; weights rotate over copies past the - * last-level cache, as in bf16_perf. */ +/* gemm_nt_f32 at the tile form its rule picks for M, compared byte for byte with the arithmetic + * every form keeps, written out on the host: lane l folds k = l, l+32, ... with fmaf, then the xor + * butterfly over 16, 8, 4, 2, 1. Rows are pitched and the output keeps a filled pitch, so an + * overrun or a missed tail shows as a byte difference. Timed, it also prints its time, its GB/s on + * weight + input + output and its TFLOP/s; weights rotate over copies past the last-level cache, + * as in bf16_perf. */ static void f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int iters, bool timed) { const RadKernelInfo* r = find(pl, "gemm_nt_f32_bf16"); if (!r) { ok("gemm_nt_f32_bf16 forms", false, "row absent"); return; } @@ -14576,17 +15520,15 @@ static void f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int ite void* d_w = dalloc(wbytes * (size_t)copies); void* d_y = dalloc(ybytes); if (!d_x || !d_w || !d_y) { ok("gemm_nt_f32_bf16 forms", false, "allocation failed"); return; } - { - std::vector x((size_t)M * (size_t)xp); - for (size_t i = 0; i < x.size(); ++i) - x[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i) % 2001) - 1000) / 1000); - st_memcpy(d_x, x.data(), x.size() * 2, hipMemcpyHostToDevice); - std::vector w((size_t)N * (size_t)K); - for (size_t i = 0; i < w.size(); ++i) - w[i] = (float)((int)(st_mix32((uint32_t)i + 0x51ed27u) % 2001) - 1000) / 8000; - for (int c = 0; c < copies; ++c) - st_memcpy((uint8_t*)d_w + (size_t)c * wbytes, w.data(), wbytes, hipMemcpyHostToDevice); - } + std::vector x((size_t)M * (size_t)xp); + for (size_t i = 0; i < x.size(); ++i) + x[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i) % 2001) - 1000) / 1000); + st_memcpy(d_x, x.data(), x.size() * 2, hipMemcpyHostToDevice); + std::vector w((size_t)N * (size_t)K); + for (size_t i = 0; i < w.size(); ++i) + w[i] = (float)((int)(st_mix32((uint32_t)i + 0x51ed27u) % 2001) - 1000) / 8000; + for (int c = 0; c < copies; ++c) + st_memcpy((uint8_t*)d_w + (size_t)c * wbytes, w.data(), wbytes, hipMemcpyHostToDevice); std::vector ts = { T(d_x, RAD_BF16, { M, K }), T(d_w, RAD_F32, { N, K }), T(d_y, RAD_F32, { M, N }), }; @@ -14596,70 +15538,57 @@ static void f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int ite std::memset(&a, 0, sizeof(a)); a.t = ts.data(); a.n_t = 3; a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; - const char* saved = std::getenv("RADIANCE_F32_GEMM_TILE"); - const std::string keep = saved ? saved : ""; - auto run = [&](const char* form, std::vector* out) -> int { - if (form) setenv("RADIANCE_F32_GEMM_TILE", form, 1); - else unsetenv("RADIANCE_F32_GEMM_TILE"); - std::vector fill(ybytes, 0xa5); - st_memcpy(d_y, fill.data(), ybytes, hipMemcpyHostToDevice); - ts[1].data = d_w; - const int rc = r->launch(&a, nullptr); - if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return rc != RAD_OK ? rc : RAD_E_DEVICE; - out->resize(ybytes); - st_memcpy(out->data(), d_y, ybytes, hipMemcpyDeviceToHost); - return (int)RAD_OK; - }; - static const char* kForms[] = { "1x1", "2x1", "4x1", "8x1", "4x2", "8x2", "4x4", "8x4", - "16x2", "16x4", nullptr }; - std::vector legacy, got; - const int lrc = run("legacy", &legacy); - ok(fmt("gemm_nt_f32 legacy form at M=%lld N=%lld K=%lld", (long long)M, (long long)N, - (long long)K).c_str(), lrc == RAD_OK); - if (lrc == RAD_OK) { - for (const char* const* f = kForms;; ++f) { - const char* form = *f; - const int rc = run(form, &got); - const bool same = rc == RAD_OK && got == legacy; - size_t first = 0; - if (rc == RAD_OK && !same) - while (first < got.size() && got[first] == legacy[first]) ++first; - ok(fmt("gemm_nt_f32 form %s at M=%lld N=%lld K=%lld: byte-identical to legacy", - form ? form : "default", (long long)M, (long long)N, (long long)K).c_str(), - same, rc != RAD_OK ? fmt("rc=%d", rc) : same ? "" : fmt("first byte %zu", first)); - if (!form) break; + std::vector fill(ybytes, 0xa5), got(ybytes); + st_memcpy(d_y, fill.data(), ybytes, hipMemcpyHostToDevice); + int rc = r->launch(&a, nullptr); + if (rc == RAD_OK && st_stream_sync(nullptr) != hipSuccess) rc = RAD_E_DEVICE; + if (rc == RAD_OK) st_memcpy(got.data(), d_y, ybytes, hipMemcpyDeviceToHost); + /* The arithmetic on the host, into a copy of the filled output. */ + std::vector want = fill; + for (int64_t row = 0; row < M; ++row) + for (int64_t c = 0; c < N; ++c) { + float lane[32]; + for (int l = 0; l < 32; ++l) { + float sum = 0; + for (int64_t j = l; j < K; j += 32) + sum = std::fmaf(h_bf16(x[(size_t)(row * xp + j)]), w[(size_t)(c * K + j)], sum); + lane[l] = sum; + } + for (int mask = 16; mask; mask >>= 1) { + float next[32]; + for (int l = 0; l < 32; ++l) next[l] = lane[l] + lane[l ^ mask]; + std::memcpy(lane, next, sizeof lane); + } + std::memcpy(&want[(size_t)(row * yp + c) * 4], &lane[0], 4); } - } - if (timed && lrc == RAD_OK) { + const bool same = rc == RAD_OK && got == want; + size_t first = 0; + if (rc == RAD_OK && !same) + while (first < got.size() && got[first] == want[first]) ++first; + ok(fmt("gemm_nt_f32 at M=%lld N=%lld K=%lld: byte-identical to the host arithmetic", + (long long)M, (long long)N, (long long)K).c_str(), + same, rc != RAD_OK ? fmt("rc=%d", rc) : same ? "" : fmt("first byte %zu", first)); + if (timed && rc == RAD_OK) { const double bytes = (double)wbytes + (double)M * K * 2 + (double)M * N * 4; const double flop = 2.0 * (double)M * (double)N * (double)K; std::printf("\ngemm_nt_f32 N=%lld K=%lld M=%lld %.2f MiB weight, %d copies, %d iters\n", (long long)N, (long long)K, (long long)M, (double)wbytes / (1 << 20), copies, iters); - static const char* kTimed[] = { "legacy", "1x1", "2x1", "4x1", "8x1", "4x2", "8x2", "4x4", - "8x4", "16x2", "16x4", nullptr }; - for (const char* const* f = kTimed;; ++f) { - const char* form = *f; - if (form) setenv("RADIANCE_F32_GEMM_TILE", form, 1); - else unsetenv("RADIANCE_F32_GEMM_TILE"); - const double us = st_time_us([&](int i) { - ts[1].data = (uint8_t*)d_w + (size_t)(i % copies) * wbytes; - r->launch(&a, nullptr); - }, iters, nullptr); - std::printf(" %-8s %9.1f us %7.1f GB/s %6.2f TFLOP/s\n", form ? form : "default", - us, bytes / (us * 1e3), flop / (us * 1e6)); - if (!form) break; - } + const double us = st_time_us([&](int i) { + ts[1].data = (uint8_t*)d_w + (size_t)(i % copies) * wbytes; + r->launch(&a, nullptr); + }, iters, nullptr); + std::printf(" %-8s %9.1f us %7.1f GB/s %6.2f TFLOP/s\n", "rule", us, + bytes / (us * 1e3), flop / (us * 1e6)); ts[1].data = d_w; } - if (saved) setenv("RADIANCE_F32_GEMM_TILE", keep.c_str(), 1); - else unsetenv("RADIANCE_F32_GEMM_TILE"); } -/* gemm_fp8a8_f32scale's dense forms (RADIANCE_FP8F32_FORM: decode at several R x S, rows) each - * compared byte for byte with the legacy 16x64 tile; the output keeps a filled pitch, so an - * overrun or a missed row shows. Timed, every form also prints its time and GB/s on the weight and its scale plane, the - * weight rotating over copies past the last-level cache. */ +/* gemm_fp8a8_f32scale's dense form at the shape (a decode form or a row tile, by the rule) + * compared byte for byte with the legacy 16x64 tile, which an activation pitch off 16 bytes takes; + * the output keeps a filled pitch, so an overrun or a missed row shows. Timed, it also prints its + * time and GB/s on the weight and its scale plane, the weight rotating over copies past the + * last-level cache. */ static void fp8f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int iters, bool timed) { const RadKernelInfo* r = find(pl, "gemm_fp8a8_f32scale"); if (!r) { ok("gemm_fp8a8_f32scale forms", false, "row absent"); return; } @@ -14671,11 +15600,12 @@ static void fp8f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int if (copies > 64) copies = 64; } void* d_a = dalloc((size_t)(M * K)); + void* d_al = dalloc((size_t)(M * (K + 8))); void* d_as = dalloc((size_t)(M * sk * 4)); void* d_w = dalloc(wb * (size_t)copies); void* d_s = dalloc(sb); void* d_y = dalloc(yb); - if (!d_a || !d_as || !d_w || !d_s || !d_y) { ok("gemm_fp8a8_f32scale forms", false, "allocation failed"); return; } + if (!d_a || !d_al || !d_as || !d_w || !d_s || !d_y) { ok("gemm_fp8a8_f32scale forms", false, "allocation failed"); return; } { std::vector a((size_t)(M * K)), w(wb); for (size_t i = 0; i < a.size(); ++i) @@ -14683,6 +15613,9 @@ static void fp8f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int for (size_t i = 0; i < w.size(); ++i) w[i] = rad_f32_to_fp8e4m3((float)((int)(st_mix32((uint32_t)i + 0x9e37u) % 2001) - 1000) / 500); st_memcpy(d_a, a.data(), a.size(), hipMemcpyHostToDevice); + /* The same rows at a pitch of K + 8 bytes. */ + st_memcpy2d(d_al, (size_t)(K + 8), a.data(), (size_t)K, (size_t)K, (size_t)M, + hipMemcpyHostToDevice); for (int c = 0; c < copies; ++c) st_memcpy((uint8_t*)d_w + (size_t)c * wb, w.data(), wb, hipMemcpyHostToDevice); std::vector as((size_t)(M * sk)), s(sb / 4); @@ -14703,18 +15636,16 @@ static void fp8f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int RadArgs a; std::memset(&a, 0, sizeof(a)); a.t = ts.data(); a.n_t = (int)ts.size(); a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; - const char* saved = std::getenv("RADIANCE_FP8F32_FORM"); - const std::string keep = saved ? saved : ""; - auto set = [](const char* form) { - if (form) setenv("RADIANCE_FP8F32_FORM", form, 1); - else unsetenv("RADIANCE_FP8F32_FORM"); - }; - auto run = [&](const char* form, std::vector* out) -> int { - set(form); + /* `legacy` reads the rows at the pitch off 16 bytes. */ + auto run = [&](bool legacy, std::vector* out) -> int { std::vector fill(yb, 0xa5); st_memcpy(d_y, fill.data(), yb, hipMemcpyHostToDevice); + ts[0].data = legacy ? d_al : d_a; + ts[0].stride[0] = legacy ? K + 8 : K; ts[2].data = d_w; const int rc = r->launch(&a, nullptr); + ts[0].data = d_a; + ts[0].stride[0] = K; if (rc != RAD_OK) return rc; if (st_stream_sync(nullptr) != hipSuccess) return (int)RAD_E_DEVICE; out->resize(yb); @@ -14722,47 +15653,30 @@ static void fp8f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int return (int)RAD_OK; }; std::vector legacy, got; - const int lrc = run("legacy", &legacy); + const int lrc = run(true, &legacy); ok(fmt("gemm_fp8a8_f32scale legacy form at M=%lld N=%lld K=%lld", (long long)M, (long long)N, (long long)K).c_str(), lrc == RAD_OK); - static const char* kForms[] = { "decode", "decode1x16", "decode2x16", "decode3x8", - "decode1x8x2", "decode1x8x4", "decode2x8x2", "decode3x8x2", - "decode2x4x4", "rows1", "rows4", nullptr }; + const int rc = lrc == RAD_OK ? run(false, &got) : lrc; if (lrc == RAD_OK) { - for (const char* const* f = kForms;; ++f) { - const int rc = run(*f, &got); - const bool same = rc == RAD_OK && got == legacy; - size_t first = 0; - if (rc == RAD_OK && !same) while (first < got.size() && got[first] == legacy[first]) ++first; - ok(fmt("gemm_fp8a8_f32scale form %s at M=%lld N=%lld K=%lld: byte-identical to legacy", - *f ? *f : "default", (long long)M, (long long)N, (long long)K).c_str(), - same, rc != RAD_OK ? fmt("rc=%d", rc) : same ? "" : fmt("first byte %zu", first)); - if (!*f) break; - } + const bool same = rc == RAD_OK && got == legacy; + size_t first = 0; + if (rc == RAD_OK && !same) while (first < got.size() && got[first] == legacy[first]) ++first; + ok(fmt("gemm_fp8a8_f32scale at M=%lld N=%lld K=%lld: byte-identical to legacy", + (long long)M, (long long)N, (long long)K).c_str(), + same, rc != RAD_OK ? fmt("rc=%d", rc) : same ? "" : fmt("first byte %zu", first)); } - if (timed && lrc == RAD_OK) { + if (timed && rc == RAD_OK) { const double bytes = (double)(wb + sb), flop = 2.0 * (double)M * (double)N * (double)K; std::printf("\ngemm_fp8a8_f32scale N=%lld K=%lld M=%lld %.2f MiB weight + scales, %d copies, " "%d iters\n", (long long)N, (long long)K, (long long)M, bytes / (1 << 20), copies, iters); - static const char* kTimed[] = { "legacy", "decode1x8", "decode1x16", "decode3x8", - "decode1x8x2", "decode1x16x2", "decode1x4x4", - "decode1x8x4", "decode2x8x2", "decode2x4x2", - "decode2x4x4", "decode3x8x2", "decode3x4x2", "rows1", - "rows2", nullptr }; - for (const char* const* f = kTimed;; ++f) { - set(*f); - const double us = st_time_us([&](int i) { - ts[2].data = (uint8_t*)d_w + (size_t)(i % copies) * wb; - r->launch(&a, nullptr); - }, iters, nullptr); - std::printf(" %-11s %9.1f us %7.1f GB/s %6.2f TFLOP/s\n", *f ? *f : "default", us, - bytes / (us * 1e3), flop / (us * 1e6)); - if (!*f) break; - } + const double us = st_time_us([&](int i) { + ts[2].data = (uint8_t*)d_w + (size_t)(i % copies) * wb; + r->launch(&a, nullptr); + }, iters, nullptr); + std::printf(" %-11s %9.1f us %7.1f GB/s %6.2f TFLOP/s\n", "rule", us, + bytes / (us * 1e3), flop / (us * 1e6)); ts[2].data = d_w; } - if (saved) setenv("RADIANCE_FP8F32_FORM", keep.c_str(), 1); - else unsetenv("RADIANCE_FP8F32_FORM"); } /* The block-quantised trunk GEMMs GLM's checkpoints resolve to, at one shape: E4M3 with F32 @@ -22093,6 +23007,20 @@ static void device_phase(const Plugin& pl) { attn_numeric_case(pl, "attn_prefill_h256_gqa6_k6v4", 256, 6, 100, "k6_v4", 0, 1024); attn_numeric_case(pl, "attn_decode_h256_gqa6_k6v4", 256, 6, 1, "k6_v4", 0, 1024); attn_numeric_case(pl, "attn_decode_h256_gqa6_k6v4", 256, 6, 4, "k6_v4", 0, 2048); + /* Flash-Next's QSA layers (#138): twelve queries per KV head over 4-token pages, and six at + * four ranks, each layout's prefill (a long history and a ragged last tile), decode, and the + * widest verify (q_len 5 at gqa 12, 10 at gqa 6). */ + for (const char* kv : { "fp8_v4", "k6_v4" }) { + const std::string t = kv[0] == 'f' ? "fp8v4" : "k6v4"; + const std::string p12 = "attn_prefill_h256_gqa12_" + t, d12 = "attn_decode_h256_gqa12_" + t; + const std::string p6 = "attn_prefill_h256_gqa6_bs4_" + t, d6 = "attn_decode_h256_gqa6_bs4_" + t; + attn_numeric_case(pl, p12.c_str(), 256, 12, 64, kv, 0, 1000, 4); + attn_numeric_case(pl, d12.c_str(), 256, 12, 1, kv, 0, 1000, 4); + attn_numeric_case(pl, d12.c_str(), 256, 12, 5, kv, 0, 2048, 4); + attn_numeric_case(pl, p6.c_str(), 256, 6, 64, kv, 0, 1000, 4); + attn_numeric_case(pl, d6.c_str(), 256, 6, 1, kv, 0, 1000, 4); + attn_numeric_case(pl, d6.c_str(), 256, 6, 10, kv, 0, 2048, 4); + } /* A ctx past a whole block (a partial last tile), and q_len 7: three waves, where the V * staging's unit count is not a multiple of the threads. */ for (const char* kv : { "fp8_v4", "k6_v4" }) { @@ -22120,6 +23048,11 @@ static void device_phase(const Plugin& pl) { attn_numeric_case(pl, "attn_decode_h128_gqa2_bf16kv", 128, 2, 24, "bf16", 0, 256); attn_gq_fold_case(pl, 3, false); attn_gq_fold_case(pl, 24, false); + /* And over the fp8_v4 and k6_v4 caches (Flash-Next's --kv-cache-dtype fp8_v4 / k6_v4). */ + for (int kvq : { 1, 2 }) { + attn_gq_fold_case(pl, 3, false, false, kvq); + attn_gq_fold_case(pl, 24, false, false, kvq); + } attn_gq_fold_case(pl, 3, true); attn_gq_fold_case(pl, 24, true); for (const bool bf16 : { false, true }) { @@ -22900,6 +23833,64 @@ static void device_phase(const Plugin& pl) { } } } + /* --- the f32 forms: a latent kept aside and put back, a zeroed f32 scratch --- */ + if (sel("cast_f32_f32")) { + const RadKernelInfo* r = find(pl, "cast_f32_f32"); + if (!r) ok("cast_f32_f32", false, "row absent"); + else { + const int64_t M = 6, n = 36, wide = 2 * n; + std::vector src((size_t)(M * n)); + for (int64_t i = 0; i < M * n; ++i) src[(size_t)i] = 0.37f * (float)((i * 29) % 83) - 9.1f; + void* d_src = dalloc((size_t)M * n * 4); + void* d_dst = dalloc((size_t)M * wide * 4); + std::vector pre((size_t)(M * wide), -7.5f); + st_memcpy(d_src, src.data(), (size_t)M * n * 4, hipMemcpyHostToDevice); + st_memcpy(d_dst, pre.data(), (size_t)M * wide * 4, hipMemcpyHostToDevice); + RadTensor ty = T(d_dst, RAD_F32, { M, n }); + ty.data = (void*)((float*)d_dst + n); + ty.stride[0] = wide; + std::vector ts = { T(d_src, RAD_F32, { M, n }), ty }; + std::vector ps = { PI("M", M), PI("n", n), PS("from", "f32"), PS("to", "f32") }; + run_case(r, ts, ps); + std::vector got((size_t)(M * wide)); + st_memcpy(got.data(), d_dst, (size_t)M * wide * 4, hipMemcpyDeviceToHost); + bool copied = true, spilled = false; + for (int64_t m = 0; m < M; ++m) + for (int64_t c = 0; c < wide; ++c) { + const float g = got[(size_t)(m * wide + c)]; + if (c >= n) copied = copied && std::memcmp(&g, &src[(size_t)(m * n + c - n)], 4) == 0; + else spilled = spilled || g != -7.5f; + } + ok("cast_f32_f32 copies into a column slice, byte for byte", copied); + ok("cast_f32_f32 leaves the columns outside the slice alone", !spilled); + } + } + if (sel("fill_f32")) { + const RadKernelInfo* r = find(pl, "fill_f32"); + if (!r) ok("fill_f32", false, "row absent"); + else { + const int64_t M = 5, n = 40, wide = 2 * n; + void* d = dalloc((size_t)M * wide * 4); + std::vector pre((size_t)(M * wide), -7.5f); + st_memcpy(d, pre.data(), (size_t)M * wide * 4, hipMemcpyHostToDevice); + RadTensor ty = T(d, RAD_F32, { M, n }); + ty.stride[0] = wide; + std::vector ts = { ty }; + std::vector ps = { PI("M", M), PI("n", n), PS("dtype", "f32"), PF("value", 1.37) }; + run_case(r, ts, ps); + std::vector got((size_t)(M * wide)); + st_memcpy(got.data(), d, (size_t)M * wide * 4, hipMemcpyDeviceToHost); + bool val = true, spilled = false; + for (int64_t m = 0; m < M; ++m) + for (int64_t c = 0; c < wide; ++c) { + const float g = got[(size_t)(m * wide + c)]; + if (c < n) val = val && g == 1.37f; + else spilled = spilled || g != -7.5f; + } + ok("fill_f32 writes the value exactly", val); + ok("fill_f32 leaves the columns past the pitch alone", !spilled); + } + } /* --- byte rows: the KV tier's transfer pair --- */ /* Pack and unpack a pool, the real layout in miniature: a "layer" is `rows` blocks of `n` * bytes, a session's blocks are scattered through it, and exactly those blocks must come back. @@ -23704,6 +24695,31 @@ static void device_phase(const Plugin& pl) { if (sel("resize_bilinear")) ups::resize_bilinear_cases(pl); if (sel("patch_fold_f32")) ups::patch_fold_cases(pl); if (sel("flow_renoise_f32")) ups::flow_renoise_cases(pl); + /* The joint image generators' ops. */ + if (sel("table_add_bf16")) g3::table_add_cases(pl); + if (sel("mix_rows_bf16")) g3::mix_rows_cases(pl); + if (sel("chan_stats_bf16")) g3::chan_stats_cases(pl); + if (sel("chan_stats_f32")) g3::chan_stats_f32_cases(pl); + if (sel("attn_cross_h128_bf16")) g3::attn_cross_cases(pl, 128); + if (sel("attn_cross_h64_bf16")) g3::attn_cross_cases(pl, 64); + if (sel("attn_dense_gqa")) g3::attn_dense_gqa_cases(pl); + if (sel("attn_dense_h384_bf16") || sel("attn_dense_h512_bf16")) g3::attn_wide_cases(pl); + if (sel("rms_mod_bf16") || sel("rms_mod_quant_fp8_bf16")) g3::rms_mod_forms(pl); + if (sel("timestep_embed_bf16")) g3::timestep_round_cases(pl); + /* LTX-2's. */ + if (sel("rope_split")) ltx::rope_cases(pl); + if (sel("head_gate")) ltx::gate_cases(pl); + if (sel("ltx_guide")) ltx::guide_cases(pl); + if (sel("pixel_norm")) ltx::pixel_norm_cases(pl); + if (sel("d2s3d") || sel("s2d3d")) ltx::resample_cases(pl); + if (sel("pix_patch") || sel("patch_pix8")) ltx::patch_cases(pl); + if (sel("tile_grid") || sel("tile_crop") || sel("tile_stitch")) ltx::tile_cases(pl); + if (sel("vol_index")) ltx::vol_index_cases(pl); + if (sel("attn_na3d")) ltx::na3d_cases(pl); + if (sel("stft_logmel")) ltx::stft_cases(pl); + if (sel("bwe_up")) ltx::bwe_cases(pl); + if (sel("conv2d_nhwc_bf16")) ltx::conv2d_cases(pl); + if (sel("int_affine")) ltx::int_affine_cases(pl); if (sel("vsa_select_h128_bf16")) vsa::select_cases(pl); if (sel("attn_vsa_h128_bf16")) vsa::attn_cases(pl); if (sel("quant_cols_fp8_bf16")) vsa::quant_cols_cases(pl); @@ -23797,37 +24813,14 @@ static void device_phase(const Plugin& pl) { fp8_f32scale_check(pl, true, 4, true, true, 288); fp8_f32scale_check(pl, true, 65, false); fp8_f32scale_check(pl, true, 65, true); - // The rule takes the expert-major form; pinned, the row tiles stay covered, and every - // stage and column-tile count meets several column tiles, a K of one stage and of - // several, and runs past sixteen rows. - const char* const pins[3] = { "RADIANCE_FP8F32_DECODE_EXPERTS", - "RADIANCE_FP8F32_EXPERTS_STAGE_K", - "RADIANCE_FP8F32_EXPERTS_COLTILES" }; - std::string kept[3]; - bool given[3]; - for (int i = 0; i < 3; ++i) { - const char* v = std::getenv(pins[i]); - given[i] = v; - if (v) kept[i] = v; - } - setenv(pins[0], "0", 1); + // The grouped row's three expert-major tilings, each over several column tiles and runs + // past sixteen rows: K 256 at 128 stages over four column tiles (above), a longer K at the + // 256 stage over four column tiles under 128 routed rows, and over one from there (top_k + // is 4 here). fp8_f32scale_check(pl, true, 17, true, true, 6, 512, 512); - fp8_f32scale_check(pl, true, 65, false); - setenv(pins[0], "1", 1); - for (const char* stage : { "128", "256" }) - for (const char* tiles : { "1", "4" }) { - setenv(pins[1], stage, 1); - setenv(pins[2], tiles, 1); - fp8_f32scale_check(pl, true, 17, true, true, 6, 512, 512); - fp8_f32scale_check(pl, true, 4, false, true, 288, 512, 384); - fp8_f32scale_check(pl, true, 65, false); - } - for (int i = 0; i < 3; ++i) { - if (given[i]) - setenv(pins[i], kept[i].c_str(), 1); - else - unsetenv(pins[i]); - } + fp8_f32scale_check(pl, true, 4, false, true, 288, 512, 384); + fp8_f32scale_check(pl, true, 65, true, true, 6, 512, 512); + fp8_f32scale_check(pl, true, 65, false, true, 288, 512, 384); } if (sel("moe_gemm_w4a8_mod4")) { @@ -23889,17 +24882,14 @@ static void device_phase(const Plugin& pl) { mhc_check(pl, nm, 33, 129, 8); } if (sel("mhc_pre_bf16") || sel("mhc_post_bf16")) { - /* Every finish and partial form and the vector mhc_post against the old dispatch, at the - * decode, verify and prefill row counts and on 16-byte rows, the vector paths' case. */ + /* The vector forms on 16-byte rows against the scalar forms on pitched rows, at the + * decode, verify and prefill row counts. */ for (int64_t rows : { 1, 6, 48, 128, 2048 }) mhcpre_perf(pl, rows, -1); } if (sel("mhc_pre_partial_bf16") || sel("mhc_pre_finish_bf16")) { for (int world : { 2, 4, 8 }) for (int64_t rows : { 1, 4, 31, 32, 33, 65, 130 }) - mhc_split_check(pl, rows, world, nullptr, nullptr); - for (const char* env : { "RADIANCE_MHC_PREFILL_COEFF4", "RADIANCE_MHC_PREFILL_ROWS4", - "RADIANCE_MHC_PREFILL_WARP" }) - for (int64_t rows : { 33, 130 }) mhc_split_check(pl, rows, 8, env, "0"); + mhc_split_check(pl, rows, world); } if (sel("swiglu_clamped_bf16")) { for (int64_t rows : { 1, 7, 33 }) @@ -23980,15 +24970,14 @@ static void device_phase(const Plugin& pl) { } if (sel("mla_project_bf16")) { for (const char* mode : { "absorb", "expand" }) { - for (int64_t rows : { 1, 2, 4, 33 }) + /* Every rows-a-group form (1, 2, 4, 8) and tails past the last full group. */ + for (int64_t rows : { 1, 2, 3, 4, 6, 33, 130 }) for (int64_t heads : { 8, 16 }) mla_project_check(pl, rows, heads, mode); mla_project_check(pl, 1, 1, mode); mla_project_check(pl, 1, 64, mode); for (int64_t rows : { 1, 4, 33 }) for (int64_t heads : { 8, 16 }) mla_project_check(pl, rows, heads, mode, true); } - /* Every row form against the one-row kernels, byte for byte, with tails at 3, 33 and 130. */ - for (int64_t rows : { 1, 3, 6, 33, 130 }) project_forms(pl, rows, -1); } if (sel("mla_attn_matrix_bf16")) { mla_check(pl, 7, 16, 17, "mla_attn_matrix_bf16"); @@ -24026,13 +25015,9 @@ static void device_phase(const Plugin& pl) { swaps); mla_check(pl, 33, 8, 513, "mla_attn_matrix_bf16", MlaFill::topk, "mla_attn_bf16", 0, 16); mla_check(pl, 4, 16, 65, "mla_attn_matrix_bf16", MlaFill::topk, nullptr, 0, 4); - { /* The positional pairing, kept for comparison; tables wider than the union's lists - * (kUnionBlocks, 520) take it too. */ - ScopedEnv positional("RADIANCE_MLA_PAIR", "pos"); - mla_check(pl, 33, 8, 17, "mla_attn_matrix_bf16", MlaFill::ragged, nullptr); - mla_check(pl, 7, 8, 513, "mla_attn_matrix_bf16", MlaFill::prefill, nullptr); - mla_check(pl, 7, 8, 65, "mla_attn_matrix_bf16", MlaFill::topk, nullptr, 0, 16); - } + /* Tables wider than the union's lists (kUnionBlocks, 520) take the positional pairing. */ + mla_check(pl, 33, 8, 521, "mla_attn_matrix_bf16", MlaFill::ragged, nullptr); + mla_check(pl, 7, 8, 521, "mla_attn_matrix_bf16", MlaFill::prefill, nullptr); mla_check(pl, 4, 8, 600, "mla_attn_matrix_bf16", MlaFill::topk, nullptr, 0, 16); /* The element-wise key load, the fallback for a cache the vectors cannot read. */ mla_check(pl, 33, 16, 17, "mla_attn_matrix_bf16", MlaFill::ragged, nullptr, 1); @@ -24048,8 +25033,8 @@ static void device_phase(const Plugin& pl) { kda_check(pl, mode, false, accepted, true); kda_check(pl, mode, true, accepted, true); } - /* Every form against the one-row shuffle-sum kernel, byte for byte, in all four modes. */ - for (int64_t M : { 1, 7, 48, 300 }) kda_forms(pl, M, -1); + /* GLM's TP8 shape against libref, in all four modes. */ + for (int64_t M : { 1, 7, 48, 300 }) kda_perf(pl, M, -1); } if (sel("moe_gemm_mxfp4a8")) { for (int m : { 1, 17, 65, 257 }) @@ -24067,151 +25052,32 @@ static void device_phase(const Plugin& pl) { for (int shape : { 1, 2, 3, 4 }) mx_experts_check(pl, 65, shape % 2 ? 2 : 1, true, "sorted", shape, false, 288, 8); mx_experts_check(pl, 1, 1, false, "token", 0, true); - // The rule takes the expert-major form at decode (at GLM's TP8 slices also above). Pinned, - // the row groups and the TP8 prefill form stay covered, and every expert-major stage and - // column-tile count meets narrow, parted and wide experts and runs of a hundred rows. - // Both weight decodes (RADIANCE_MXFP4_LUT) meet every form; dropped slots inside the runs - // and runs under 16 rows (288 experts) reach the TP8 prefill form at 65 and 257 tokens, - // with and without its stage prefetch (RADIANCE_MXFP4_PREFILL_PIPE). - constexpr int kPins = 10; - const char* const pins[kPins] = { - "RADIANCE_MXFP4_DECODE_EXPERTS", "RADIANCE_MXFP4_EXPERTS_STAGE_K", - "RADIANCE_MXFP4_EXPERTS_COLTILES", "RADIANCE_MXFP4_LUT", - "RADIANCE_MXFP4_ALIGNED_JOBS", "RADIANCE_MXFP4_PREFILL_N32", - "RADIANCE_MXFP4_PREFILL_M32", "RADIANCE_MXFP4_PREFILL_N64", - "RADIANCE_MXFP4_PREFILL_CACHE_ROWS", "RADIANCE_MXFP4_PREFILL_PIPE" - }; - std::string kept[kPins]; - bool given[kPins]; - for (int i = 0; i < kPins; ++i) { - const char* v = std::getenv(pins[i]); - given[i] = v; - if (v) kept[i] = v; - } - // P64 is the rule at GLM's TP8 slices from 769 rows; off here, so the forms above stay the - // ones these cases name, and pinned or by its rule further down. - constexpr int kP64 = 12; - const char* const p64[kP64] = { "RADIANCE_MXFP4_PREFILL_P64", - "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", - "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN", - "RADIANCE_MXFP4_PREFILL_P64_BM", - "RADIANCE_MXFP4_PREFILL_P64_BN", - "RADIANCE_MXFP4_PREFILL_P64_STAGE_K", - "RADIANCE_MXFP4_PREFILL_P64_COLTILES", - "RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", - "RADIANCE_MXFP4_PREFILL_P64_T_BM64", - "RADIANCE_MXFP4_PREFILL_P64_T_BN128", - "RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", - "RADIANCE_MXFP4_PREFILL_P64_DB" }; - std::string kept64[kP64]; - bool given64[kP64]; - for (int i = 0; i < kP64; ++i) { - const char* v = std::getenv(p64[i]); - given64[i] = v; - if (v) kept64[i] = v; - } - for (int i = 1; i < kP64; ++i) unsetenv(p64[i]); - setenv(p64[0], "0", 1); - for (const char* lut : { "0", "1" }) { - setenv(pins[3], lut, 1); - setenv(pins[0], "0", 1); - for (int shape : { 1, 2, 3, 4 }) - mx_experts_check(pl, 17, shape % 2 ? 2 : 1, false, "sorted", shape); - mx_experts_check(pl, 1, 1, false, "token", 0, true); - for (const char* pipe : { "0", "1" }) { - setenv(pins[9], pipe, 1); - for (int shape : { 3, 4 }) { - mx_experts_check(pl, 65, shape % 2 ? 2 : 1, true, "sorted", shape, false, 288, - 8); - for (int m : { 65, 257 }) - mx_experts_check(pl, m, shape % 2 ? 2 : 1, true, - shape == 4 ? "sorted" : "token", shape, false, 288, 8, - true); - } - // The TP8 prefill form outside GLM's slices: E8M0 codes 0 and 255, narrower and - // shorter odd experts, dropped slots. - for (int i = 4; i < 9; ++i) setenv(pins[i], "1", 1); - mx_experts_check(pl, 257, 2, false, "token", 0, true, 3, 2, true); - mx_experts_check(pl, 257, 1, true, "sorted", 0, false, 3, 2, true); - for (int i = 4; i < 9; ++i) unsetenv(pins[i]); - } - unsetenv(pins[9]); - setenv(pins[0], "1", 1); - for (const char* stage : { "128", "256" }) - for (const char* tiles : { "1", "4" }) { - setenv(pins[1], stage, 1); - setenv(pins[2], tiles, 1); - mx_experts_check(pl, 17, 1, false, "sorted", 2); - mx_experts_check(pl, 4, 2, true, "token", 3); - mx_experts_check(pl, 17, 2, false, "token"); - mx_experts_check(pl, 257, 2, true, "sorted"); - mx_experts_check(pl, 65, 1, false, "sorted", 4, false, 288, 8, true); - } - unsetenv(pins[1]); - unsetenv(pins[2]); - } - // The P64 form pinned below its row bounds: every BM x BN x stage at GLM's TP8 slices over - // 288 experts and 65 tokens (runs of about two rows, dropped slots), column tiles 1 and 4 - // with and without the LDS output at 257 tokens, and outside GLM's slices E8M0 codes 0 and - // 255 with narrower and shorter odd experts; then by its rule at 1024, 2048 and 4096 tokens - // (gate_up BM32 BN64 K256, BM64 BN64 K256 and BM64 BN128 K128 with the LDS output, down BM32 - // BN64 K128 x4 and BM64 BN128 K128 x4 with the LDS output). It always takes the table decode. - auto pin = [&](int bm, int bn, int sk, int ct, int out, int db = 0) { - const int v[8] = { 1, 0, 0, bm, bn, sk, ct, out }; - for (int i = 0; i < 8; ++i) setenv(p64[i], std::to_string(v[i]).c_str(), 1); - setenv(p64[11], db ? "1" : "0", 1); - }; - setenv(pins[0], "0", 1); - for (int bm : { 32, 64 }) - for (int bn : { 64, 128 }) - for (int sk : { 128, 256 }) { - pin(bm, bn, sk, 4, 0); - for (int shape : { 3, 4 }) - mx_experts_check(pl, 65, shape % 2 ? 2 : 1, true, - shape == 4 ? "sorted" : "token", shape, false, 288, 8, - true); - } - for (int out : { 0, 1 }) - for (int ct : { 1, 4 }) { - pin(64, 128, 128, ct, out); - for (int shape : { 3, 4 }) - mx_experts_check(pl, 257, shape % 2 ? 2 : 1, true, - shape == 4 ? "sorted" : "token", shape, false, 288, 8, true); - } - for (int out : { 0, 1 }) { - pin(64, 128, 128, 4, out); - mx_experts_check(pl, 257, 2, false, "token", 0, true, 3, 2, true); - mx_experts_check(pl, 257, 1, true, "sorted", 0, false, 3, 2, true); - } - // The double buffer at gate_up's slice wherever two stages fit, and with E8M0 codes 0 and - // 255 outside GLM's slices. - for (int bm : { 32, 64 }) - for (int bn : { 64, 128 }) { - pin(bm, bn, 128, 4, bm == 64 && bn == 128, 1); - mx_experts_check(pl, 257, 2, true, "token", 3, false, 288, 8, true); - } - pin(32, 64, 256, 4, 0, 1); - mx_experts_check(pl, 257, 2, true, "token", 3, false, 288, 8, true); + // The form follows the routed rows (top_k 2 away from GLM, 8 at its 288 experts). Away + // from GLM's slices the row groups from 512 rows: E8M0 codes 0 and 255, narrower and + // shorter odd experts, dropped slots. mx_experts_check(pl, 257, 2, false, "token", 0, true, 3, 2, true); - for (int i = 0; i < kP64; ++i) unsetenv(p64[i]); - unsetenv(pins[0]); - for (int m : { 1024, 2048 }) - for (int shape : { 3, 4 }) - mx_experts_check(pl, m, shape % 2 ? 2 : 1, true, shape == 4 ? "sorted" : "token", + mx_experts_check(pl, 257, 1, true, "sorted", 0, false, 3, 2, true); + // At GLM's TP4 slices the GLM prefill form from 512 rows, with dropped slots and runs under + // 16 rows, and with E8M0 codes 0 and 255. + for (int shape : { 1, 2 }) + for (int m : { 65, 257 }) { + mx_experts_check(pl, m, shape % 2 ? 2 : 1, true, shape == 2 ? "sorted" : "token", shape, false, 288, 8, true); - mx_experts_check(pl, 4096, 1, true, "sorted", 4, false, 288, 8, true); - for (int i = 0; i < kP64; ++i) { - if (given64[i]) - setenv(p64[i], kept64[i].c_str(), 1); - else - unsetenv(p64[i]); - } - for (int i = 0; i < kPins; ++i) { - if (given[i]) - setenv(pins[i], kept[i].c_str(), 1); - else - unsetenv(pins[i]); - } + mx_experts_check(pl, m, shape % 2 ? 2 : 1, false, shape == 2 ? "sorted" : "token", + shape, true, 288, 8); + } + // At GLM's TP8 slices the expert-major form to its bound (gate_up 768 rows, down below + // P64's 5760), then P64 by its rule: gate_up BM32 BN64 K256 from 769 rows, BM64 BN64 K256 + // from 12288 and BM64 BN128 K128 with the LDS output from 24576; down BM32 BN64 K128 x4 + // from 5760 rows and BM64 BN128 K128 x4 with the LDS output from 24576. + mx_experts_check(pl, 96, 2, true, "token", 3, false, 288, 8, true); + mx_experts_check(pl, 719, 1, true, "sorted", 4, false, 288, 8, true); + for (int m : { 97, 1024, 2048, 3072 }) + mx_experts_check(pl, m, 2, true, "token", 3, false, 288, 8, true); + for (int m : { 720, 1024, 2048, 4096 }) + mx_experts_check(pl, m, 1, true, "sorted", 4, false, 288, 8, true); + mx_experts_check(pl, 1024, 2, false, "token", 3, true, 288, 8); + mx_experts_check(pl, 1024, 1, false, "sorted", 4, true, 288, 8); } if (sel("hc_read_e4m3")) { @@ -24614,8 +25480,8 @@ static void usage(void) { " --perf N K M [iters]: time the fp8 decode GEMMs at one shape and print the\n" " weight bandwidth each reaches.\n" " --perfbf16 N K M [iters]: the bf16 skinny GEMM at every variant it has.\n" - " --perff32 N K M [iters]: gemm_nt_f32 at every tile form, each compared byte\n" - " for byte with the legacy kernel, with GB/s and TFLOP/s.\n" + " --perff32 N K M [iters]: gemm_nt_f32 at the tile form its rule picks, compared\n" + " byte for byte with the host arithmetic, with GB/s and TFLOP/s.\n" " --perfq N K M [iters]: the block-quantised trunk rows GLM resolves to: E4M3 with\n" " F32 block scales and the three OCP-MXFP4 rows, GB/s on weight + scales.\n" " --perfw8 N K M [iters]: the 8-bit trunk GEMMs -- block E4M3 W8A8 and the int8\n" @@ -24669,27 +25535,22 @@ static void usage(void) { " --perfmxf8 M [iters] [experts] [top_k] [skew]: the same at the FP8 experts with f32\n" " block scales (moe_gemm_fp8a8_f32scale, GLM's MTP layer).\n" " --perfmhcpre M [iters]: mhc_pre (whole, partials alone, finish alone) and\n" - " mhc_post at GLM's shape, every form against the old dispatch.\n" + " mhc_post at GLM's shape, 16-byte rows against pitched ones.\n" " --perfrouter M [iters]: router_sigmoid_topk at GLM's shape (288 experts, top 8),\n" - " the wave-per-row select against the serial scan.\n" + " the wave-per-row select timed.\n" " --perfmoefuse M [iters]: GLM's decode fusions of the MoE block at M token\n" " rows (288 experts, top 8, TP8 widths), each against the separate\n" " launches it replaces: time of both and a byte comparison of every\n" " output (`= old` or DIFFERS). The router fusion takes M <= 128.\n" " --perfkda M [iters]: kda_update at GLM's TP8 shape: prefill of M tokens (one\n" - " sequence, and three anchored) and the 8x6 verify step, every row and\n" - " prefetch form timed and compared byte for byte with the old kernel.\n" - " --perfproject M [iters]: mla_project at GLM's TP8 shape, both modes, every\n" - " rows-a-group form timed and compared byte for byte with the old kernels.\n" + " sequence, and three anchored) and the 8x6 verify step, timed.\n" + " --perfproject M [iters]: mla_project at GLM's TP8 shape, both modes, timed.\n" " --perfmx M [iters] [experts] [top_k] [skew]: the MXFP4 expert GEMM at GLM's\n" " TP8 slices (gate_up 512 x 4096, down 4096 x 256) over a routing of an\n" " M-token chunk (288 experts, top 8 by default; uniform, or `skew` a Gamma\n" " CV per expert as g1.0 or a Zipf exponent as z1.1): time, touched weight\n" - " bytes, GB/s and TFLOP/s per projection; the rule, the expert-major form\n" - " at each pinned stage and column-tile count, the row groups and from 512\n" - " routed rows every prefill form and the P64 raster (BM x BN x stage,\n" - " down also x column tiles), each compared with the bytes of the pinned\n" - " TP8 prefill form.\n" + " bytes, GB/s and TFLOP/s per projection of the form the rule picks, and\n" + " how often it streams each touched expert slice.\n" " --perfmla M blocks heads [iters] [fill]: MLA attention without the oracle, so\n" " a 2048-row prefill chunk at 2k/8k context fits (blocks 513/2049).\n" " The wave row and the matrix row at both key loads (paired tiles at\n" @@ -24778,7 +25639,7 @@ int main(int argc, char** argv) { perf_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != '-') perf_it = (int)std::strtol(argv[++i], nullptr, 0); } else if (!std::strcmp(argv[i], "--perff32")) { - /* gemm_nt_f32 at every tile form (see f32_forms). */ + /* gemm_nt_f32 at its rule's tile form (see f32_forms). */ if (i + 3 >= argc) { usage(); return 2; } perf_f32 = 1; perf_n = std::strtoll(argv[++i], nullptr, 0); @@ -24874,7 +25735,7 @@ int main(int argc, char** argv) { if (i + 1 < argc && argv[i + 1][0] != 0x2d) ar8_it = (int)std::strtol(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) ar8_dt = argv[++i]; } else if (!std::strcmp(argv[i], "--perfmhcpre")) { - /* mhc_pre and mhc_post at GLM's shape, every form, against the old dispatch. */ + /* mhc_pre and mhc_post at GLM's shape, 16-byte rows against pitched ones. */ if (i + 1 >= argc) { usage(); return 2; } mhc_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) mhc_it = (int)std::strtol(argv[++i], nullptr, 0); @@ -24887,7 +25748,7 @@ int main(int argc, char** argv) { mf_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) mf_it = (int)std::strtol(argv[++i], nullptr, 0); } else if (!std::strcmp(argv[i], "--perfkda") || !std::strcmp(argv[i], "--perfproject")) { - /* kda_update or mla_project at GLM's TP8 shape, every form, against the old kernel. */ + /* kda_update or mla_project at GLM's TP8 shape, timed. */ if (i + 1 >= argc) { usage(); return 2; } const bool kda = !std::strcmp(argv[i], "--perfkda"); (kda ? kda_m : proj_m) = std::strtoll(argv[++i], nullptr, 0); @@ -24895,7 +25756,7 @@ int main(int argc, char** argv) { (kda ? kda_it : proj_it) = (int)std::strtol(argv[++i], nullptr, 0); } else if (!std::strcmp(argv[i], "--perfmx") || !std::strcmp(argv[i], "--perfmxf8")) { mx_f8 = !std::strcmp(argv[i], "--perfmxf8"); - /* An expert GEMM at GLM's TP8 slices over an M-token chunk, every form: MXFP4, or with + /* An expert GEMM at GLM's TP8 slices over an M-token chunk: MXFP4, or with * --perfmxf8 the FP8 experts with f32 block scales. */ if (i + 1 >= argc) { usage(); return 2; } mx_m = std::strtoll(argv[++i], nullptr, 0); @@ -25058,8 +25919,8 @@ int main(int argc, char** argv) { if (kda_m || proj_m) { if (!load(&pl, path)) return 1; #ifdef RAD_HAVE_HIP - if (kda_m) kda_forms(pl, kda_m, kda_it); - if (proj_m) project_forms(pl, proj_m, proj_it); + if (kda_m) kda_perf(pl, kda_m, kda_it); + if (proj_m) project_perf(pl, proj_m, proj_it); dfree_all(); #else skip("kda_update and mla_project timing", "built without HIP"); diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 8caf64ae..880482b3 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -316,11 +316,11 @@ extern "C" int r4d_shape_cast(const RadParam* p, int n_p, int operand, const int64_t M = pi(p, n_p, "M"); const int64_t n = pi(p, n_p, "n"); - /* Three rows serve the op, bf16 -> bf16 (a strided row copy), bf16 -> f32 and bf16 -> f16, - * and the shims refuse any other pair, so another pair is declined here. */ + /* The rows serve bf16 -> bf16 and f32 -> f32 (strided row copies), bf16 -> f32, bf16 -> f16 + * and f32 -> bf16, and the shims refuse any other pair, so another pair is declined here. */ const uint32_t f = dt_par(p, n_p, "from"), t = dt_par(p, n_p, "to"); - if (f != (uint32_t)RAD_BF16 || - (t != (uint32_t)RAD_BF16 && t != (uint32_t)RAD_F32 && t != (uint32_t)RAD_F16)) + const uint32_t bf = (uint32_t)RAD_BF16, f32 = (uint32_t)RAD_F32, f16 = (uint32_t)RAD_F16; + if (!(f == bf && (t == bf || t == f32 || t == f16)) && !(f == f32 && (t == bf || t == f32))) return RAD_E_UNSUPPORTED; const RadOpdDesc l[] = { opd(f, M, n), opd(t, M, n) }; R4D_PICK(l); diff --git a/libr4d/r4d_upscaler.hip b/libr4d/r4d_upscaler.hip index 361dc46e..6e51b0ec 100644 --- a/libr4d/r4d_upscaler.hip +++ b/libr4d/r4d_upscaler.hip @@ -51,10 +51,49 @@ __device__ __forceinline__ void st8(float* p, const float* f) { *(float4*)p = make_float4(f[0], f[1], f[2], f[3]); *(float4*)(p + 4) = make_float4(f[4], f[5], f[6], f[7]); } -// Eight per-channel values of an f32 or bf16 vector, its dtype known only at run time. -__device__ __forceinline__ void ld8w(const void* p, bool f32, int c, float* f) { - if (f32) ld8((const float*)p + c, f); - else ld8((const uint16_t*)p + c, f); +// Four- and two-channel forms of the above, and a chunk of CW (8, 4 or 2) channels through them. +__device__ __forceinline__ void ld4(const uint16_t* p, float* f) { + const uint2 u = *(const uint2*)p; + f[0] = bf16w_lo(u.x); f[1] = bf16w_hi(u.x); f[2] = bf16w_lo(u.y); f[3] = bf16w_hi(u.y); +} +__device__ __forceinline__ void ld4(const float* p, float* f) { + const float4 a = *(const float4*)p; + f[0] = a.x; f[1] = a.y; f[2] = a.z; f[3] = a.w; +} +__device__ __forceinline__ void st4(uint16_t* p, const float* f) { + *(uint2*)p = make_uint2(bf16x2_rne(f[0], f[1]), bf16x2_rne(f[2], f[3])); +} +__device__ __forceinline__ void st4(float* p, const float* f) { + *(float4*)p = make_float4(f[0], f[1], f[2], f[3]); +} +__device__ __forceinline__ void ld2(const uint16_t* p, float* f) { + const uint32_t u = *(const uint32_t*)p; + f[0] = bf16w_lo(u); f[1] = bf16w_hi(u); +} +__device__ __forceinline__ void ld2(const float* p, float* f) { + const float2 a = *(const float2*)p; + f[0] = a.x; f[1] = a.y; +} +__device__ __forceinline__ void st2(uint16_t* p, const float* f) { + *(uint32_t*)p = bf16x2_rne(f[0], f[1]); +} +__device__ __forceinline__ void st2(float* p, const float* f) { + *(float2*)p = make_float2(f[0], f[1]); +} +template __device__ __forceinline__ void ldc(const T* p, float* f) { + if constexpr (CW == 8) ld8(p, f); + else if constexpr (CW == 4) ld4(p, f); + else ld2(p, f); +} +template __device__ __forceinline__ void stc(T* p, const float* f) { + if constexpr (CW == 8) st8(p, f); + else if constexpr (CW == 4) st4(p, f); + else st2(p, f); +} +// CW per-channel values of an f32 or bf16 vector, its dtype known only at run time. +template __device__ __forceinline__ void ldcw(const void* p, bool f32, int c, float* f) { + if (f32) ldc((const float*)p + c, f); + else ldc((const uint16_t*)p + c, f); } // The volume a request runs at: (T, H, W) and its row count, or false for a geometry the operands @@ -101,6 +140,11 @@ __device__ __forceinline__ bool volume_of(const int* geom, long long rows, int* // guarded load instead, its last tile running past K), so neither operand's addresses cost vector // arithmetic per tile. // +// `tpad` pads the frames other than with zeros (LTX-2's VAE): 1 replicate, the frame clamped into +// the volume; 2 causal, output frame t's tap dt reading frame max(t + dt - 1 - tpre, 0), so the +// output has tpre more frames than the input. A neighbour's frame is resolved when its offset is, +// once a tap. +// // Measured on the R9700 at 300 W, warm, against gemm_nt_bias at bf16 at the same M, N and K = 27 // cin: 512 -> 512 at 84 x 48 x 37 148 TFLOP/s (the GEMM 146), at 42 x 24 x 37 149 (145). The // select-and-pointer form of the gather this replaces ran 136 and 134: its loop issued twice the @@ -133,13 +177,13 @@ __device__ __forceinline__ unsigned short conv_finish(float acc, float bv, unsig /* `vec` (host-checked): y, res and the bias take 16-byte accesses at every eight-column boundary. * `xrows` bounds the volume the device geometry may name, `xbytes` is x's extent (at most kOob) - * and `Mcap` bounds the rows written. */ + * and `Mcap` bounds the rows written; `tpad` and `tpre` as above. */ template __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel( const unsigned short* __restrict__ X, const unsigned short* __restrict__ Wt, const void* __restrict__ bias, const unsigned short* R, unsigned short* C, const int* __restrict__ geom, unsigned ldx, unsigned ldr, unsigned ldc, int Mcap, int xrows, - unsigned xbytes, int cin, int N, unsigned vec) { + unsigned xbytes, int cin, int N, unsigned vec, int tpad, int tpre) { typedef r4d_u32x4 U4; __shared__ __attribute__((aligned(16))) unsigned char s_a[2][kCBM * kCPB]; @@ -147,7 +191,8 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel( long long vol; if (!volume_of(geom, xrows, &gT, &gH, &gW, &vol)) return; const int HW = gH * gW; - const int Mv = vol < (long long)Mcap ? (int)vol : Mcap; + const long long ovol = vol + (long long)tpre * HW; + const int Mv = ovol < (long long)Mcap ? (int)ovol : Mcap; const uint32_t tid = threadIdx.x, lane = tid & 31u; const uint32_t wave = __builtin_amdgcn_readfirstlane(tid >> 5); @@ -197,10 +242,14 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel( const int delta = dt * HW + dy * gW + dx; #pragma unroll for (uint32_t i = 0; i < kCSPT; ++i) { - const bool ok = tap < kTaps && (unsigned)(vt[i] + dt) < (unsigned)gT && + int ft = vt[i] + dt; + if (tpad == 1) ft = min(max(ft, 0), gT - 1); + else if (tpad == 2) ft = max(ft - 1 - tpre, 0); + const bool ok = tap < kTaps && vt[i] >= 0 && (unsigned)ft < (unsigned)gT && (unsigned)(vy[i] + dy) < (unsigned)gH && (unsigned)(vx[i] + dx) < (unsigned)gW; - off[i] = ok ? (uint32_t)(vm[i] + delta) * ldx * 2u + (C64 ? ch * 16u : 0u) : kOob; + const int src = tpad ? (ft * gH + vy[i] + dy) * gW + vx[i] + dx : vm[i] + delta; + off[i] = ok ? (uint32_t)src * ldx * 2u + (C64 ? ch * 16u : 0u) : kOob; } }; @@ -387,9 +436,9 @@ __device__ __forceinline__ void chan_merge(float& n, float& mean, float& m2, flo n = nab; } -/* `cpr_log`: log2 of the chunks a row (n / 8, a power of two dividing the block); `gs8` the chunks - * a group. */ -template +/* `cpr_log`: log2 of the chunks a row (n / CW, a power of two dividing the block); `gs8` the + * chunks a group. A chunk is CW channels: 8, or 4 for groups of 4 channels. */ +template __global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x, float* __restrict__ stats, int M, int groups, int cpr_log, int gs8, int ldx, int rpp) { @@ -401,16 +450,16 @@ __global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x, const int r0 = p * rpp, r1 = min(M, r0 + rpp); float cnt = 0.0f, s1 = 0.0f, s2 = 0.0f, shift = 0.0f; for (int r = r0 + slot; r < r1; r += slots) { - float v[8]; - ld8(x + (size_t)r * ldx + c * 8, v); + float v[CW]; + ldc(x + (size_t)r * ldx + c * CW, v); if (cnt == 0.0f) shift = v[0]; #pragma unroll - for (int j = 0; j < 8; ++j) { + for (int j = 0; j < CW; ++j) { const float d = v[j] - shift; s1 += d; s2 += d * d; } - cnt += 8.0f; + cnt += (float)CW; } float mean = 0.0f, m2 = 0.0f; if (cnt > 0.0f) { @@ -466,7 +515,7 @@ __global__ __launch_bounds__(kT) void gn_final_kernel(float* __restrict__ stats, /* `wf`, `bf`: the gain's and bias's dtype is f32; `modk` 0 no modulation, 1 a bf16 row, 2 an f32 * one. x and y may be the same memory: a thread reads its chunk before it writes it. */ -template +template __global__ __launch_bounds__(kT) void gn_apply_kernel( const TX* x, TY* y, const void* __restrict__ w, const void* __restrict__ b, const void* __restrict__ mod, const float* __restrict__ stats, int M, int n, int cpr_log, @@ -475,27 +524,27 @@ __global__ __launch_bounds__(kT) void gn_apply_kernel( const int tid = threadIdx.x; const int r = blockIdx.x * slots + (tid >> cpr_log); if (r >= M) return; - const int ck = tid & ((1 << cpr_log) - 1), c = ck * 8; + const int ck = tid & ((1 << cpr_log) - 1), c = ck * CW; const int g = ck / gs8; const float mean = stats[2 * g], rstd = stats[2 * g + 1]; - float v[8], wv[8], bv[8]; - ld8(x + (size_t)r * ldx + c, v); - ld8w(w, wf != 0, c, wv); - ld8w(b, bf != 0, c, bv); + float v[CW], wv[CW], bv[CW]; + ldc(x + (size_t)r * ldx + c, v); + ldcw(w, wf != 0, c, wv); + ldcw(b, bf != 0, c, bv); #pragma unroll - for (int j = 0; j < 8; ++j) v[j] = (v[j] - mean) * rstd * wv[j] + bv[j]; + for (int j = 0; j < CW; ++j) v[j] = (v[j] - mean) * rstd * wv[j] + bv[j]; if (modk) { - float sc[8], sf[8]; - ld8w(mod, modk == 2, c, sc); - ld8w(mod, modk == 2, n + c, sf); + float sc[CW], sf[CW]; + ldcw(mod, modk == 2, c, sc); + ldcw(mod, modk == 2, n + c, sf); #pragma unroll - for (int j = 0; j < 8; ++j) v[j] = v[j] * (1.0f + sc[j]) + sf[j]; + for (int j = 0; j < CW; ++j) v[j] = v[j] * (1.0f + sc[j]) + sf[j]; } if (silu) { #pragma unroll - for (int j = 0; j < 8; ++j) v[j] = v[j] / (1.0f + expf(-v[j])); + for (int j = 0; j < CW; ++j) v[j] = v[j] / (1.0f + expf(-v[j])); } - st8(y + (size_t)r * ldy + c, v); + stc(y + (size_t)r * ldy + c, v); } // ---------------------------------------------------------------------------- tconv_dw @@ -720,6 +769,15 @@ extern "C" int r4d_rad_conv3d_ndhwc(const RadArgs* a, RadStream stream) { if (r4d_numel(w) < cout * K || r4d_numel(b) < cout || r4d_numel(geom) < 3) return R4D_NO(RAD_E_SHAPE); if (!r4d_contig(w) || !r4d_contig(b) || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE); + const char* tp = r4d_gets(a, "tpad"); + int tpad = 0; + if (tp && *tp) { + if (!std::strcmp(tp, "replicate")) tpad = 1; + else if (!std::strcmp(tp, "causal")) tpad = 2; + else if (std::strcmp(tp, "zero")) return R4D_NO(RAD_E_INVAL); + } + const long long tpre = r4d_geti_or(a, "tpre", 0); + if (tpre < 0 || tpre > 64 || (tpre && tpad != 2)) return R4D_NO(RAD_E_INVAL); long long rx = 0, ldx = 0, ry = 0, rr = 0; if (!rows8(x, cin, &rx, &ldx) || !r4d_aligned(r4d_p(w), 16)) return R4D_NO(RAD_E_STRIDE); const long long ldy = r4d_rows_pitch(y, cout, &ry); @@ -747,7 +805,8 @@ extern "C" int r4d_rad_conv3d_ndhwc(const RadArgs* a, RadStream stream) { #define C3_L(C6, RS, BF) \ return R4D_EMIT(stream, (conv3d_kernel), grid, dim3(kCThreads), 0, Xp, Wp, Bp, Rp, \ Cp, (const int*)r4d_p(geom), (unsigned)ldx, (unsigned)ldr, (unsigned)ldy, \ - (int)Mcap, (int)rx, (unsigned)xbytes, (int)cin, (int)cout, vec) + (int)Mcap, (int)rx, (unsigned)xbytes, (int)cin, (int)cout, vec, tpad, \ + (int)tpre) #define C3_RES(C6, BF) do { if (res) C3_L(C6, true, BF); C3_L(C6, false, BF); } while (0) #define C3_BF(C6) do { if (bf32) C3_RES(C6, true); C3_RES(C6, false); } while (0) if (c64) C3_BF(true); @@ -774,12 +833,14 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) { if (!std::strcmp(act, "silu")) silu = 1; else if (std::strcmp(act, "none")) return R4D_NO(RAD_E_INVAL); } - /* A thread an 8-channel chunk inside one group, a row's chunks a power of two dividing the - * 256-thread block. */ - const int cpr_log = (n > 0 && !(n & 7)) ? log2_exact(n / 8) : -1; - if (cpr_log < 0 || n / 8 > kT || groups <= 0 || groups > kT || n % groups || - (n / groups) % 8) + /* A thread a chunk of CW channels inside one group (8; 4 for groups of 4 channels, the + * FLUX.2 VAE's 128 channels in 32 groups; 2 for groups of 2), a row's chunks a power of two + * dividing the 256-thread block. */ + if (groups <= 0 || groups > kT || n <= 0 || n % groups || (n / groups) % 2) return R4D_NO(RAD_E_SHAPE); + const int CW = (n / groups) % 8 == 0 ? 8 : (n / groups) % 4 == 0 ? 4 : 2; + const int cpr_log = log2_exact(n / CW); + if (cpr_log < 0 || n / CW > kT) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(w) < n || r4d_numel(b) < n || (mod && r4d_numel(mod) < 2 * n) || r4d_numel(st) < groups * (2 + 3 * kGnParts)) return R4D_NO(RAD_E_SHAPE); @@ -797,29 +858,36 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) { long long rpp = (M + kGnParts - 1) / kGnParts; rpp = (rpp + slots - 1) / slots * slots; const int parts = (int)((M + rpp - 1) / rpp); - const int gs8 = (int)(n / groups / 8); + const int gs8 = (int)(n / groups / CW); float* S = (float*)r4d_wp(st); const float eps = (float)r4d_getf(a, "eps", 1e-5); int rc; - if (is_f32(x)) - rc = R4D_EMIT(stream, gn_part_kernel, dim3((unsigned)parts), dim3(kT), 0, - (const float*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx, - (int)rpp); - else - rc = R4D_EMIT(stream, gn_part_kernel, dim3((unsigned)parts), dim3(kT), 0, - (const uint16_t*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx, - (int)rpp); +#define GN_P(TX, C4) \ + rc = R4D_EMIT(stream, (gn_part_kernel), dim3((unsigned)parts), dim3(kT), 0, \ + (const TX*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx, (int)rpp) + if (is_f32(x)) { + if (CW == 8) GN_P(float, 8); + else if (CW == 4) GN_P(float, 4); + else GN_P(float, 2); + } else { + if (CW == 8) GN_P(uint16_t, 8); + else if (CW == 4) GN_P(uint16_t, 4); + else GN_P(uint16_t, 2); + } +#undef GN_P if (rc != RAD_OK) return R4D_NO(rc); rc = R4D_EMIT(stream, gn_final_kernel, dim3((unsigned)groups), dim3(kT), 0, S, (int)groups, parts, eps); if (rc != RAD_OK) return R4D_NO(rc); const int modk = !mod ? 0 : is_f32(mod) ? 2 : 1; const dim3 grid((unsigned)((M + slots - 1) / slots)); -#define GN_A(TX, TY) \ - return R4D_EMIT(stream, (gn_apply_kernel), grid, dim3(kT), 0, (const TX*)r4d_p(x), \ +#define GN_A2(TX, TY, C4) \ + return R4D_EMIT(stream, (gn_apply_kernel), grid, dim3(kT), 0, (const TX*)r4d_p(x),\ (TY*)r4d_wp(y), r4d_p(w), r4d_p(b), r4d_p(mod), (const float*)S, (int)M, \ (int)n, cpr_log, gs8, (int)ldx, (int)ldy, (int)is_f32(w), (int)is_f32(b), \ modk, silu) +#define GN_A(TX, TY) \ + do { if (CW == 8) GN_A2(TX, TY, 8); if (CW == 4) GN_A2(TX, TY, 4); GN_A2(TX, TY, 2); } while (0) if (is_f32(x)) { if (is_f32(y)) GN_A(float, float); GN_A(float, uint16_t); @@ -827,6 +895,7 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) { if (is_f32(y)) GN_A(uint16_t, float); GN_A(uint16_t, uint16_t); #undef GN_A +#undef GN_A2 } /* ------------------------------------------------------------------ tconv_dw */ diff --git a/libr4d/r4d_video.hip b/libr4d/r4d_video.hip index c1134cc6..aebd18aa 100644 --- a/libr4d/r4d_video.hip +++ b/libr4d/r4d_video.hip @@ -82,7 +82,8 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel( const uint16_t* __restrict__ yd, const uint16_t* __restrict__ g, const uint16_t* __restrict__ s, const uint16_t* __restrict__ w, const int* __restrict__ cu, uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ qs, uint16_t* __restrict__ z, int n, int n_seq, - float eps, int y_ld, int g_ld, int s_ld, int x_ld, int q_ld, int qs_ld, int z_ld) { + float eps, int y_ld, int g_ld, int s_ld, int x_ld, int q_ld, int qs_ld, int z_ld, float wadd, + int once, int layer, int none) { __shared__ float sh[kT / 32]; const int r = blockIdx.x; const int e = seq_of(cu, n_seq, r); @@ -109,7 +110,32 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel( for (int j = 0; j < 8; ++j) { v[k][j] = f[j]; ss += f[j] * f[j]; } } } - const float rs = 1.0f / sqrtf(block_sum(ss, sh) / (float)n + eps); + /* A LayerNorm centres first: the mean's block sum, then the centred squares'. */ + float mu = 0.0f; + if (layer) { + float sm = 0.0f; + #pragma unroll + for (int k = 0; k < kRmChunks; ++k) { + const int i = ((int)threadIdx.x + k * kT) * 8; + if (i < n) { + #pragma unroll + for (int j = 0; j < 8; ++j) sm += v[k][j]; + } + } + mu = block_sum(sm, sh) / (float)n; + __syncthreads(); + ss = 0.0f; + #pragma unroll + for (int k = 0; k < kRmChunks; ++k) { + const int i = ((int)threadIdx.x + k * kT) * 8; + if (i < n) { + #pragma unroll + for (int j = 0; j < 8; ++j) { v[k][j] -= mu; ss += v[k][j] * v[k][j]; } + } + } + } + /* `none`: no norm (libref's n2 = x); the flag is the same for the whole workgroup. */ + const float rs = none ? 1.0f : 1.0f / sqrtf(block_sum(ss, sh) / (float)n + eps); const uint16_t* sr = s + (size_t)e * s_ld; #pragma unroll for (int k = 0; k < kRmChunks; ++k) { @@ -118,10 +144,11 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel( float shf[8], scf[8], wf[8], o[8]; ld8(sr + i, shf); ld8(sr + n + i, scf); - ld8(w + i, wf); + if (w) ld8(w + i, wf); #pragma unroll for (int j = 0; j < 8; ++j) { - const float n2 = bfr(bfr(v[k][j] * rs) * wf[j]); + const float n1 = once ? v[k][j] * rs : bfr(v[k][j] * rs); + const float n2 = w ? bfr(n1 * (wf[j] + wadd)) : bfr(v[k][j] * rs); o[j] = bfr(bfr(n2 * bfr(1.0f + scf[j])) + shf[j]); } if (z) st8(z + (size_t)r * z_ld + i, o); @@ -431,10 +458,10 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, bool quant) { const RadTensor* q = quant ? r4d_opt(a, 6) : nullptr; const RadTensor* qs = quant ? r4d_opt(a, 7) : nullptr; const RadTensor* z = r4d_opt(a, quant ? 8 : 6); - if (!sc || !w || !cu || !x || (quant ? (!q || !qs) : !z)) return R4D_NO(RAD_E_INVAL); + if (!sc || !cu || !x || (quant ? (!q || !qs) : !z)) return R4D_NO(RAD_E_INVAL); const bool gated = r4d_geti_or(a, "gated", 0) != 0; if (gated && (!y || !g)) return R4D_NO(RAD_E_INVAL); - if (!is_bf16(x) || !is_bf16(sc) || !is_bf16(w) || !is_i32(cu) || + if (!is_bf16(x) || !is_bf16(sc) || (w && !is_bf16(w)) || !is_i32(cu) || (gated && (!is_bf16(y) || !is_bf16(g))) || (z && !is_bf16(z)) || (quant && (q->dtype != RAD_F8E4M3 || qs->dtype != RAD_F32))) return R4D_NO(RAD_E_DTYPE); @@ -445,7 +472,7 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, bool quant) { long long rx = 0, xl = 0, ry = 0, yl = 0, rg = 0, gl = 0, rs = 0, sl = 0, rz = 0, zl = 0; long long rq = 0, rqs = 0, ql = 0, qsl = 0; if (!rows8(x, n, &rx, &xl) || !rows8(sc, 2 * n, &rs, &sl) || !r4d_contig(cu) || - !r4d_contig(w) || ((uintptr_t)w->data & 15) || + (w && (!r4d_contig(w) || ((uintptr_t)w->data & 15))) || (gated && (!rows8(y, n, &ry, &yl) || !rows8(g, n, &rg, &gl))) || (z && !rows8(z, n, &rz, &zl))) return R4D_NO(RAD_E_STRIDE); @@ -455,18 +482,26 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, bool quant) { if (ql < 0 || (ql & 7) || ((uintptr_t)q->data & 7) || qsl < 0) return R4D_NO(RAD_E_STRIDE); } const long long n_seq = r4d_numel(cu) - 1, rows = quant ? rq : rz; - if (rows <= 0 || n_seq <= 0 || rx < rows || rs < n_seq || r4d_numel(w) < n || + if (rows <= 0 || n_seq <= 0 || rx < rows || rs < n_seq || (w && r4d_numel(w) < n) || (quant && rqs < rows) || (gated && (ry < rows || rg < n_seq)) || (z && rz < rows)) return R4D_NO(RAD_E_SHAPE); const float eps = (float)r4d_getf(a, "eps", 1e-6); + const float wadd = (float)r4d_getf(a, "wadd", 0.0); + const int once = (int)r4d_geti_or(a, "norm_once", 0); + const char* nk = r4d_gets(a, "norm"); + const int layer = nk && !std::strcmp(nk, "layer"); + const int none = nk && !std::strcmp(nk, "none"); + if ((nk && !layer && !none && std::strcmp(nk, "rms")) || (none && w)) return R4D_NO(RAD_E_INVAL); #define R4D_RMQ(G, Q) \ hipLaunchKernelGGL((rms_mod_kernel), dim3((unsigned)rows), dim3(kT), 0, \ (hipStream_t)st, G ? (const uint16_t*)y->data : nullptr, \ G ? (const uint16_t*)g->data : nullptr, (const uint16_t*)sc->data, \ - (const uint16_t*)w->data, (const int*)cu->data, (uint16_t*)x->data, \ + w ? (const uint16_t*)w->data : nullptr, (const int*)cu->data, \ + (uint16_t*)x->data, \ Q ? (uint8_t*)q->data : nullptr, Q ? (float*)qs->data : nullptr, \ z ? (uint16_t*)z->data : nullptr, (int)n, (int)n_seq, eps, (int)yl, \ - (int)gl, (int)sl, (int)xl, (int)ql, (int)qsl, (int)zl) + (int)gl, (int)sl, (int)xl, (int)ql, (int)qsl, (int)zl, wadd, once, layer, \ + none) if (quant) { if (gated) R4D_RMQ(true, true); else R4D_RMQ(false, true); diff --git a/libref/ref_attn.cpp b/libref/ref_attn.cpp index b8fed97e..d5c0ccd4 100644 --- a/libref/ref_attn.cpp +++ b/libref/ref_attn.cpp @@ -353,6 +353,156 @@ int ref_attn_dense(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ attn_cross */ +/* attn_dense with each entry's keys a run of their own: entry `s`'s queries are rows + * [cu[s], cu[s+1]) of `q` and its keys and values rows [cu_k[s], cu_k[s+1]) of `k` and `v`. With + * `causal` a query sees key j of its run when j <= its own index in its entry, both counted from + * the start: a video's rows reading its prompt (cross attention), or a padded prompt's rows of which + * the padding sees only the prompt. A query that sees no key is zero. */ +int ref_attn_cross(const RadArgs* a, RadStream) { + if (!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 > REF_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 || cu_at(cu, n_seq) <= cu_at(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 (cu_at(cu, s + 1) < cu_at(cu, s) || cu_at(cuk, s + 1) < cu_at(cuk, s) || + cu_at(cu, s + 1) > total_q || cu_at(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)); + + REF_PAR_FOR(total_q * q_heads * head_dim * 64) + 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 = cu_at(cu, s), b1 = cu_at(cu, s + 1); + const int64_t k0 = cu_at(cuk, s), k1 = cu_at(cuk, s + 1); + 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(k1, k0 + (i - b0) + 1) : k1; + float mx = -INFINITY; + for (int64_t j = k0; j < jend; ++j) { + const int64_t kb = j * k_rs + kh * k_hs; + float dot = 0.0f; + for (int64_t d = 0; d < head_dim; ++d) + dot += ldt(q, qb + d * q_ds) * ldt(k, kb + d * k_ds); + dot *= scale; + if (dot > mx) mx = dot; + } + if (mx == -INFINITY) { + for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f); + continue; + } + float acc[REF_HD_MAX]; + for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f; + float sum = 0.0f; + for (int64_t j = k0; j < jend; ++j) { + const int64_t kb = j * k_rs + kh * k_hs, vb = j * v_rs + kh * v_hs; + float dot = 0.0f; + for (int64_t d = 0; d < head_dim; ++d) + dot += ldt(q, qb + d * q_ds) * ldt(k, kb + d * k_ds); + const float w = ref_exp(dot * scale - mx); + sum += w; + for (int64_t d = 0; d < head_dim; ++d) acc[d] += w * ldt(v, vb + d * v_ds); + } + const float inv = sum > 0.0f ? 1.0f / sum : 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: 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. A query attends the keys of a window `kt` x `kh` x `kw` (each extent at most its + * axis) centred on it and shifted inward at the border: along an axis of L and window n the + * window starts at clamp(c - n / 2, 0, L - n). 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 maximum, then the exponentials' sum), the output rounded to + * its dtype. Rows past T H W are not written. */ +int ref_attn_na3d(const RadArgs* a, RadStream) { + if (!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 > REF_HD_MAX) return RAD_E_UNSUPPORTED; + const int64_t heads = q->shape[1] / head_dim; + const int64_t T = cu_at(G, 0), H = cu_at(G, 1), W = cu_at(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(c - n / 2, 0), L - n); + }; + REF_PAR_FOR(N * heads * nt * nh * nw * head_dim) + 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); + const int64_t qb = r * q_rs + h * head_dim * q_ds, ob = r * o_rs + h * head_dim * o_ds; + auto score = [&](int64_t key) { + const int64_t kb = key * k_rs + h * head_dim * k_ds; + float dot = 0.0f; + for (int64_t d = 0; d < head_dim; ++d) dot += ldt(q, qb + d * q_ds) * ldt(k, kb + d * k_ds); + return dot * scale; + }; + float mx = -INFINITY; + 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) mx = std::max(mx, score((a1 * H + b1) * W + c1)); + float acc[REF_HD_MAX]; + for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f; + float sum = 0.0f; + 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 w = ref_exp(score(key) - mx); + sum += w; + const int64_t vb = key * v_rs + h * head_dim * v_ds; + for (int64_t d = 0; d < head_dim; ++d) acc[d] += w * ldt(v, vb + d * v_ds); + } + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; + for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ kv_store */ /* Writes this step's keys and values into the paged cache at `slot_mapping`. The cache is INOUT, * not OUT: only mapped slots are touched and every other slot must survive, which the buffer diff --git a/libref/ref_audio.cpp b/libref/ref_audio.cpp index c4d4357c..e7bb319a 100644 --- a/libref/ref_audio.cpp +++ b/libref/ref_audio.cpp @@ -16,6 +16,7 @@ #include #include +#include #include #include @@ -712,6 +713,39 @@ int ref_iota(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ int_affine */ +/* y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j], the three lists space-separated integers + * of one length: shapes and sequence bounds a model derives from a pass's device geometry (a + * decoder's volume at each of its scales). y holds at least the lists' length. */ +static int 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; +} + +int ref_int_affine(const RadArgs* a, RadStream) { + if (!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 = parse_ints(p_str(a, "src", ""), src, 16); + if (n <= 0 || parse_ints(p_str(a, "mul", ""), mul, 16) != n || + 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 : ld_int(x->dtype, x->data, offlin(x, src[j])); + st_int(y->dtype, y->data, offlin(y, j), v * mul[j] + add[j]); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ cu_repeat */ /* Sequence bounds of equal sequences: y[j] = j * len[0] * mult over y's elements. A pass's * lengths live on the device (a window's frames, the latents a vocoder decodes per channel group), diff --git a/libref/ref_gen.cpp b/libref/ref_gen.cpp index 4246cc3f..4c42ed12 100644 --- a/libref/ref_gen.cpp +++ b/libref/ref_gen.cpp @@ -168,7 +168,7 @@ int ref_ln_mod_quant_fp8(const RadArgs* a, RadStream) { static int rms_mod_check(const RadTensor* y, const RadTensor* g, const RadTensor* s, const RadTensor* w, const RadTensor* x, int64_t n, int64_t n_seq, int64_t rows, bool gated) { - 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(y, n) < rows || numel(g) < n_seq * n)) return RAD_E_SHAPE; @@ -184,10 +184,17 @@ static int rms_mod_check(const RadTensor* y, const RadTensor* g, const RadTensor * * The sum of squares is f32 in ascending order, read from the stored residual. `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). The residual rounds to x's dtype and the norm chain to `dt`. */ + * of the modulation table). The residual rounds to x's dtype and the norm chain to `dt`. + * + * `wadd` is added to the gain in f32 (a zero-centred norm's 1 + w), and with `once` the norm and + * its gain round together, n2 = bf16(x rsqrt(...) (w + wadd)), as an f32 RMS norm with a gain + * stores its output (Krea 2's). With `layer` the norm is a LayerNorm (FLUX's, which has no gain: + * `w` absent), and with `none` there is no norm and no gain, n2 = x (LTX-2's text keys and values, + * modulated as they are). */ static void rms_mod_row(const RadTensor* y, const RadTensor* g, const RadTensor* s, const RadTensor* w, const RadTensor* x, int64_t r, int64_t e, int64_t n, - float eps, bool gated, uint32_t dt, float* o) { + float eps, bool gated, uint32_t dt, float* o, float wadd = 0.0f, + bool once = false, bool layer = false, bool none = false) { const int64_t xb = rowoff(x, r, n), xs = laststride(x); if (gated) { const int64_t g_rs = row_stride(g, n), g_cs = laststride(g); @@ -197,13 +204,24 @@ static void rms_mod_row(const RadTensor* y, const RadTensor* g, const RadTensor* stt(x, xb + i * xs, ldt(x, xb + i * xs) + p); } } + /* RMS: x rsqrt(mean(x^2) + eps). Layer: (x - mean) rsqrt(var + eps), the biased variance of + * the centred values; both sums f32 in ascending order. */ + float mu = 0.0f; + if (layer) { + for (int64_t i = 0; i < n; ++i) mu += ldt(x, xb + i * xs); + mu /= (float)n; + } float ss = 0.0f; - for (int64_t i = 0; i < n; ++i) { const float v = ldt(x, xb + i * xs); ss += v * v; } + for (int64_t i = 0; i < n && !none; ++i) { const float v = ldt(x, xb + i * xs) - mu; ss += v * v; } const float rs = 1.0f / std::sqrt(ss / (float)n + eps); - const int64_t s_rs = row_stride(s, 2 * n), s_cs = laststride(s), ws = laststride(w); + const int64_t s_rs = row_stride(s, 2 * n), s_cs = laststride(s), ws = w ? laststride(w) : 0; for (int64_t i = 0; i < n; ++i) { - const float n1 = round_dt(dt, ldt(x, xb + i * xs) * rs); - const float n2 = round_dt(dt, n1 * ldt(w, i * ws)); + const float v = ldt(x, xb + i * xs) - mu; + /* With no gain the norm is rounded once, as a norm without a weight stores it. */ + const float n2 = none ? round_dt(dt, v) + : !w ? round_dt(dt, v * rs) + : once ? round_dt(dt, v * rs * (ldt(w, i * ws) + wadd)) + : round_dt(dt, round_dt(dt, v * rs) * (ldt(w, i * ws) + wadd)); const float sc = round_dt(dt, 1.0f + ldt(s, e * s_rs + (n + i) * s_cs)); const float m = round_dt(dt, n2 * sc); o[i] = round_dt(dt, m + ldt(s, e * s_rs + i * s_cs)); @@ -215,18 +233,24 @@ static void rms_mod_row(const RadTensor* y, const RadTensor* g, const RadTensor* * the norm chain rounds to z's dtype. */ int ref_rms_mod(const RadArgs* a, RadStream) { if (a->n_t < 7) return RAD_E_INVAL; - const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *w = &a->t[3]; + const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *w = t_in(a, 3); const RadTensor *cu = &a->t[4], *x = &a->t[5], *z = &a->t[6]; const int64_t n = p_int(a, "n", 0); 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) return RAD_E_INVAL; + if (none && t_in(a, 3)) return RAD_E_INVAL; if (n <= 0 || (gated && (!y || !g))) return RAD_E_SHAPE; const int64_t rows = rows_of(z, n), n_seq = numel(cu) - 1; RAD_REF_TRY(rms_mod_check(y, g, s, w, x, n, n_seq, rows, gated)); REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { std::vector o((size_t)n); - rms_mod_row(y, g, s, w, x, r, seq_of(cu, n_seq, r), n, eps, gated, z->dtype, o.data()); + rms_mod_row(y, g, s, w, x, r, seq_of(cu, n_seq, r), n, eps, gated, z->dtype, o.data(), wadd, once, layer, none); const int64_t zb = rowoff(z, r, n), zs = laststride(z); for (int64_t i = 0; i < n; ++i) stt(z, zb + i * zs, o[(size_t)i]); } @@ -238,11 +262,17 @@ int ref_rms_mod(const RadArgs* a, RadStream) { * bound. */ int ref_rms_mod_quant_fp8(const RadArgs* a, RadStream) { if (a->n_t < 9) return RAD_E_INVAL; - const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *w = &a->t[3]; + const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *w = t_in(a, 3); const RadTensor *cu = &a->t[4], *x = &a->t[5], *q = &a->t[6], *sc = &a->t[7], *z = t_in(a, 8); const int64_t n = p_int(a, "n", 0), grp = p_int(a, "group", 0); 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) return RAD_E_INVAL; + if (none && t_in(a, 3)) return RAD_E_INVAL; if (n <= 0 || grp <= 0 || n % grp || (gated && (!y || !g))) return RAD_E_SHAPE; const int64_t rows = rows_of(q, n), n_seq = numel(cu) - 1, ngrp = n / grp; RAD_REF_TRY(rms_mod_check(y, g, s, w, x, n, n_seq, rows, gated)); @@ -250,7 +280,7 @@ int ref_rms_mod_quant_fp8(const RadArgs* a, RadStream) { REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { std::vector o((size_t)n); - rms_mod_row(y, g, s, w, x, r, seq_of(cu, n_seq, r), n, eps, gated, RAD_BF16, o.data()); + rms_mod_row(y, g, s, w, x, r, seq_of(cu, n_seq, r), n, eps, gated, RAD_BF16, o.data(), wadd, once, layer, none); const int64_t zb = z ? rowoff(z, r, n) : 0, zs = z ? laststride(z) : 0; for (int64_t i = 0; z && i < n; ++i) stt(z, zb + i * zs, o[(size_t)i]); const int64_t qb = rowoff(q, r, n), qs = laststride(q); @@ -283,7 +313,8 @@ int ref_timestep_embed(const RadArgs* a, RadStream) { const float coef = (float)(-std::log(mp)); for (int64_t m = 0; m < rows; ++m) { const float tv = ldt(t, offlin(t, m)); - const float tt = round ? scale * rbf(rbf(tv * scale) / scale) : scale * tv; + const float tt = round == 3 ? rbf(scale * rbf(tv)) : round == 2 ? scale * rbf(tv) + : round ? scale * rbf(rbf(tv * scale) / scale) : scale * tv; const int64_t yb = rowoff(y, m, n), ys = laststride(y); for (int64_t i = 0; i < h; ++i) { const float f = ref_exp(coef * (float)i / (float)h); @@ -545,6 +576,8 @@ int ref_chan_affine(const RadArgs* a, RadStream) { * pad same k / 2 zeros on every side * pad down no zeros above and left, one below and right: ZeroPad2d((0, 1, 0, 1)) then the conv, * as a stride-2 downsample does + * pad causal k - 1 zeros above, none below, k / 2 a side across: a convolution causal along + * the rows (LTX-2's audio VAE, whose rows are time) * * f32 accumulation over (kh, kw, cin), the bias added, one rounding. */ int ref_conv2d_nhwc(const RadArgs* a, RadStream) { @@ -554,14 +587,16 @@ int ref_conv2d_nhwc(const RadArgs* a, RadStream) { const int64_t stride = p_int(a, "stride", 1), up = p_int(a, "up", 1); const char* pad = p_str(a, "pad", "same"); const bool down = pad && !std::strcmp(pad, "down"); + const bool causal = pad && !std::strcmp(pad, "causal"); if (cin <= 0 || cout <= 0 || k <= 0 || stride <= 0 || up <= 0) return RAD_E_SHAPE; if (x->rank != 2 || y->rank != 2 || x->shape[1] % cin || y->shape[1] % cout) return RAD_E_SHAPE; const int64_t Hin = x->shape[0], Win = x->shape[1] / cin; 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) + 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]; @@ -574,7 +609,7 @@ int ref_conv2d_nhwc(const RadArgs* a, RadStream) { const int64_t iy = oy * stride + kh - pt; if (iy < 0 || iy >= Hv) continue; for (int64_t kw = 0; kw < k; ++kw) { - const int64_t ix = ox * stride + kw - pt; + const int64_t ix = ox * stride + kw - pl; if (ix < 0 || ix >= Wv) continue; const int64_t xb = (iy / up) * xr + (ix / up) * cin; for (int64_t ci = 0; ci < cin; ++ci) @@ -895,3 +930,90 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) { } return RAD_OK; } + +/* ------------------------------------------------------------------ table_add */ +/* y[r, l n + c] = x[r, c] + t[l, c] for every row of `x` and every row l of the table: a shared + * modulation plus each block's own learned table (Krea 2's, LTX-2's), all blocks in one pass. The + * sum is f32, rounded once to y's dtype. `x` and `y` are read at their own row pitches. */ +int ref_table_add(const RadArgs* a, RadStream) { + if (!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; + const int64_t xs = laststride(X), ys = laststride(Y), ts = laststride(T); + REF_PAR_FOR(rows * L * n) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, L * n); + for (int64_t l = 0; l < L; ++l) + for (int64_t c = 0; c < n; ++c) + stt(Y, yb + (l * n + c) * ys, + ldt(X, xb + c * xs) + ldt(T, (l * n + c) * ts)); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ mix_rows */ +/* y[r, c] = sum_i w[i] x[r k + i, c], i < k: a Linear(k, 1) across k consecutive rows (Krea 2's + * text fusion folds twelve tapped layers of a token into one row). f32 sum in ascending i, rounded + * once to y's dtype. */ +int ref_mix_rows(const RadArgs* a, RadStream) { + if (!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; + const int64_t xs = laststride(X), ys = laststride(Y), ws = laststride(W); + REF_PAR_FOR(rows * n * k) + for (int64_t r = 0; r < rows; ++r) { + const int64_t yb = rowoff(Y, r, n); + for (int64_t c = 0; c < n; ++c) { + float acc = 0.0f; + for (int64_t i = 0; i < k; ++i) + acc += ldt(W, i * ws) * ldt(X, rowoff(X, r * k + i, n) + c * xs); + stt(Y, yb + c * ys, acc); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ chan_stats */ +/* A latent normalised or denormalised by per-channel statistics a VAE keeps as weights: `mean` and + * `s` [n], `s` a standard deviation, or with `var` 1 a variance (std = sqrt(s + eps), a BatchNorm's + * running statistics). Each statistic is rounded to y's dtype as the reference casts it, and + * every step is a tensor the reference stores: `denorm` y = rd(rd(x std) + mean), `norm` + * y = rd(rd(x - mean) / std). */ +int ref_chan_stats(const RadArgs* a, RadStream) { + if (!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 mu((size_t)n), sd((size_t)n); + for (int64_t c = 0; c < n; ++c) { + mu[(size_t)c] = round_dt(dt, ldt(Mn, c * laststride(Mn))); + const float v = ldt(Sd, c * laststride(Sd)); + sd[(size_t)c] = round_dt(dt, var ? std::sqrt(v + eps) : v); + } + const int64_t xs = laststride(X), ys = laststride(Y); + REF_PAR_FOR(rows * n) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, n); + for (int64_t c = 0; c < n; ++c) { + const float x = ldt(X, xb + c * xs); + const float y = norm ? round_dt(dt, round_dt(dt, x - mu[(size_t)c]) / sd[(size_t)c]) + : round_dt(dt, round_dt(dt, x * sd[(size_t)c]) + mu[(size_t)c]); + stt(Y, yb + c * ys, y); + } + } + return RAD_OK; +} diff --git a/libref/ref_ltx.cpp b/libref/ref_ltx.cpp new file mode 100644 index 00000000..b4aa348b --- /dev/null +++ b/libref/ref_ltx.cpp @@ -0,0 +1,722 @@ +/* ref_ltx.cpp -- LTX-2's ops (docs/OPS.md, "LTX-2"): its rotary over fractional coordinates, the + * per-head attention gate, and the sampler step that combines a step's guidance passes in the + * clean-estimate space. + * + * Every rounding follows the upstream model, which runs its transformer in bf16 and its rotary, + * guidance and sampler in f32 (diffusers' transformer_ltx2.py and pipeline_ltx2.py). + */ +#include "ref_common.h" +#include "ref_gemm.h" +#include "ref_ops.h" + +#include +#include +#include +#include + +using namespace ref; + +namespace { + +inline int64_t ldi(const RadTensor* t, int64_t i) { return ld_int(t->dtype, t->data, offlin(t, i)); } + +/* torch.linspace(0, 1, steps) in f64: the first half up from the start, the second down from the + * end, as torch computes it. */ +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_list_f32(const char* s, std::vector* 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(); +} + +/* Element (d, r) of a [C, M] operand at its own strides; an integer operand reads as its value. */ +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 */ +/* LTX-2's rotary (LTX2AudioVideoRotaryPosEmbed, "split"): over the full width `dim` of all heads, + * P = dim / 2 pairs, the first `pad` = P - steps n_dims of them unrotated and the rest the + * frequency ladder freq[k] = f32(theta^linspace(0, 1, steps)[k] pi / 2) (f64 before the cast), + * 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 becomes the angle a = f32(f32(2 f32(c / max[d])) - 1) + * freq[k]. Head h owns pairs [h hd/2, (h+1) hd/2) and rotates 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 this operand holds (a rank's share). `x` is + * [M, >= n_head head_dim] at its own row pitch; `positions` [n_dims, M], f32 or integer, at its own + * strides. */ +int ref_rope_split(const RadArgs* a, RadStream) { + if (!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 mx; + if (nh <= 0 || hd <= 0 || (hd & 1) || nd <= 0 || dim < (h0 + nh) * hd || + parse_list_f32(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 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); + REF_PAR_FOR(rows * nh * hd) + 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; /* cos 1, sin 0: the value as it is */ + 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); + const float a1 = x1 * c, b1 = x2 * s, a2 = x2 * c, b2 = x1 * s; + stt(X, o1, a1 - b1); + stt(X, o2, a2 + b2); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ head_gate */ +/* LTX-2's gated attention: each head's output times 2 sigmoid of its logit, + * x = rd(x rd(2 rd(sigmoid(g)))) (the sigmoid of the bf16 logit rounded, doubled exactly). `g` is + * [M, >= n_head], `x` [M, >= n_head head_dim], each at its own row pitch. */ +int ref_head_gate(const RadArgs* a, RadStream) { + if (!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); + REF_PAR_FOR(rows * nh * hd) + 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 = round_dt(G->dtype, 1.0f / (1.0f + std::exp(-lg))); + const float gate = round_dt(X->dtype, 2.0f * sg); + for (int64_t i = 0; i < hd; ++i) { + const int64_t o = xb + (h * hd + i) * xs; + stt(X, o, ldt(X, o) * gate); + } + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ ltx_guide */ +/* One LTX-2 sampler step over a modality's latent `x` (f32 [M, n]) from its guidance passes' + * velocities (each [M, n] at its own pitch, read as f32 as the pipeline upcasts them): + * + * x0_p = f32(x - f32(v_p sigma)) for every 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, f32 + * with rescale 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 (gs, ms 1; + * stg 0). 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 + * the implementation's scratch (libref leaves it untouched). */ +int ref_ltx_guide(const RadArgs* a, RadStream) { + if (a->n_t < 8) return RAD_E_INVAL; + const RadTensor *Vc = &a->t[0], *Vu = t_in(a, 1), *Vs = t_in(a, 2), *Vm = t_in(a, 3); + const RadTensor *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 float gs = ldt(Sc, 0), stg = ldt(Sc, laststride(Sc)), ms = ldt(Sc, 2 * laststride(Sc)); + const float rr = ldt(Sc, 3 * laststride(Sc)); + 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 x0c((size_t)N), g((size_t)N); + auto x0 = [&](const RadTensor* V, int64_t r, int64_t c, float x) { + return x - ldt(V, rowoff(V, r, n) + c * laststride(V)) * sig; + }; + REF_PAR_FOR(N) + 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 + cu * (xc - x0(Vu, r, c, x)); + if (use_s) v = v + stg * (xc - x0(Vs, r, c, x)); + if (use_m) v = v + 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, keep = 1.0f; + if (rr > 0.0f) { + auto stdev = [&](const std::vector& v) { + double m = 0.0; + for (float e : v) m += e; + m /= (double)N; + double ss = 0.0; + for (float e : v) ss += ((double)e - m) * ((double)e - m); + return (float)std::sqrt(ss / (double)(N > 1 ? N - 1 : 1)); + }; + fac = stdev(x0c) / stdev(g); + keep = (float)(1.0 - (double)rr); + } + const float dt = sig_n - sig; + REF_PAR_FOR(N) + 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 = rr * (v * fac) + keep * v; + const int64_t o = rowoff(X, r, n) + c * laststride(X); + const float x = ldt(X, o); + const float vel = (x - v) / sig; + stt(X, o, x + dt * vel); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ pixel_norm */ +/* An RMS norm over each row's n values as a model computes it in bf16 tensors, every step stored: + * + * m = rd(sum_i rd(x_i^2) / n) (f32 sum in ascending i) + * rsqrt form: z_i = rd(x_i rd(1 / sqrt(rd(m + eps)))) + * div form: z_i = rd(x_i / rd(sqrt(rd(m + eps)))) + * + * then with `act` silu z = rd(z / (1 + exp(-z))), and with `mult` z = rd(z mult) (the text + * connectors' scale to the DiT's width). rd is y's dtype. LTX-2's VAE PerChannelRMSNorm + * and audio PixelNorm are the div form; its text connectors' per-layer norm the rsqrt form, whose + * output `ileave` interleaves: row r = t L + l of x (L = ileave) goes to columns c L + l of y's row + * t, the layer index innermost as the reference flattens [C, L]. */ +int ref_pixel_norm(const RadArgs* a, RadStream) { + if (!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); + static const char* const kForms[] = { "rsqrt", "div" }; + static const char* const kActs[] = { "none", "silu" }; + const int form = p_enum(a, "form", kForms, 2, 0), act = p_enum(a, "act", kActs, 2, 0); + 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); + REF_PAR_FOR(rows * n) + 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 += round_dt(dt, v * v); + } + const float v = round_dt(dt, round_dt(dt, ss / (float)n) + eps); + const float s = form == 0 ? round_dt(dt, 1.0f / std::sqrt(v)) : round_dt(dt, std::sqrt(v)); + for (int64_t i = 0; i < n; ++i) { + const float x = ldt(X, xb + i * xs); + float z = round_dt(dt, form == 0 ? x * s : x / s); + if (act == 1) z = round_dt(dt, z / (1.0f + std::exp(-z))); + if (mult != 1.0f) z = round_dt(dt, z * mult); + stt(Y, yb + (i * L + l) * ys, z); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ d2s3d / s2d3d */ +/* LTX-2's video VAE resampling over voxel rows (row (t, i, j) of a T x H x W volume, channels + * innermost); `geom` is x's volume, i32 on the device. The packed channel of (c, a, b, d) is + * ((c st + a) sh + b) sw + d, a the frame offset, b the row's, d the column's. + * + * d2s3d, the upsampler's depth to space: y[(t st + a - drop, i sh + b, j sw + d), c] = x[(t, i, + * j), packed(c, a, b, d)], the first `drop` frames dropped (default st - 1, the causal mapping; + * T st - drop out). A copy. */ +int ref_d2s3d(const RadArgs* a, RadStream) { + if (!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 = ldi(G, 0), H = ldi(G, 1), W = ldi(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); + REF_PAR_FOR(To * Ho * Wo * C) + 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) + stt(Y, yb + c * ys, ldt(X, xb + (((c * st + aa) * sh + b) * sw + d) * xs)); + } + return RAD_OK; +} + +/* s2d3d, the downsampler's space to depth: the volume with `tpre` frames prepended (frames 0 .. + * tpre - 1 again, the reference's hs[:, :, :st-1]) cut into st x sh x sw boxes, each box's values + * a packed row. `mode` copy writes the packed row (C st sh sw channels); `mean` averages each run + * of `group` consecutive packed channels (f32 sum, divided, rounded once; the residual's mean). + * With `add` 1 the result is added into y, y = rd(y + v). */ +int ref_s2d3d(const RadArgs* a, RadStream) { + if (!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; + static const char* const kModes[] = { "copy", "mean" }; + const int mode = p_enum(a, "mode", kModes, 2, 0); + 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 = ldi(G, 0), H = ldi(G, 1), W = ldi(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; + REF_PAR_FOR(To * Ho * Wo * P) + 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) { /* packed channel q of this box */ + 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 = round_dt(dt, s / (float)grp); + } + const int64_t oy = yb + o * ys; + stt(Y, oy, add ? round_dt(dt, ldt(Y, oy)) + round_dt(dt, v) : v); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ pix_patch / patch_pix8 */ +/* LTX-2's patchifier, both ways, over dense 2-D operands whose shapes give the sizes. A patch of + * p x p pixels of C channels is one row of C p p values, channel c's offset (ph, pw) at + * c p p + pw p + ph with `order` wh (LTX-2's: the column offset outer) or c p p + ph p + pw with + * hw. + * + * pix_patch: an image x [H, W C] to patch rows y [H / p, (W / p) C p p]. A copy. */ +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); +} + +int ref_pix_patch(const RadArgs* a, RadStream) { + if (!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]; + REF_PAR_FOR(H * W * C) + for (int64_t y = 0; y < H; ++y) + for (int64_t x = 0; x < W; ++x) + for (int64_t c = 0; c < C; ++c) + stt(Y, (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; +} + +/* patch_pix8: patch rows x [R, w C p p] (R a frame's patch rows times its frames) to RGB bytes + * y [R p, w p C], each byte round(255 clamp(rd(rd(clamp(v, -1, 1) / 2) + 0.5), 0, 1)) with rd + * x's dtype, to_rgba8's rule. */ +int ref_patch_pix8(const RadArgs* a, RadStream) { + if (!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; + REF_PAR_FOR(R * p * w * p * C) + 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 = round_dt(dt, round_dt(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 */ +/* A volume's voxel coordinates, the rotary positions of attention over it: geom = (T, H, W), i32 + * on the device; 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). */ +int ref_vol_index(const RadArgs* a, RadStream) { + if (!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 = ldi(G, 0), H = ldi(G, 1), W = ldi(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(Y->dtype, Y->data, c * Y->stride[0] + m * Y->stride[1], v[c]); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ tile_grid / tile_crop / tile_stitch */ +/* A decoder run in tiles, as diffusers cuts and blends them: LTX-2's VAE (`tiled_decode`, rule + * `stride`) 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` one tile covers + * an axis of `tile` or fewer cells, and while more than one start is left and the last leaves fewer + * than `min` cells, that start is dropped. A tile but the last is min(tile, L - start) long; the + * last runs to L. Tiles are raster-ordered over (time band, row band, column band); without + * `tile_t` there is one time band of every frame. + * + * tile_grid: the boxes of the grid geom = (T, H, W), i32 on the device, into y i32 [M, 8], row k + * (t, h, w, t0, y0, x0, k, count); the last time band is `tail` cells longer than its cut (frames + * past T a decoder carries, which its crop takes and its output drops). Rows past the count are + * zero, tiles past M not written. A row's (t, h, w) is a decoder's volume operand and its first six + * entries tile_crop's box. */ +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); + } +}; + +static 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; +} + +int ref_tile_grid(const RadArgs* a, RadStream) { + if (!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 = ldi(G, 0), H = ldi(G, 1), W = ldi(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(Y->dtype, Y->data, offlin(Y, k * 8 + e), row[e]); + } + return RAD_OK; +} + +/* tile_crop: one tile's voxels out of a volume. x [>= T H W, C] is the volume (row (t, yy, xx) + * row-major), geom its (T, H, W); box = (t, h, w, t0, y0, x0), i32 on the device (a tile_grid + * row); y [t h w, C], y[(a, i, j)] = x[(t0 + a, y0 + i, x0 + j)]. A copy. */ +int ref_tile_crop(const RadArgs* a, RadStream) { + if (!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 = ldi(G, 0), H = ldi(G, 1), W = ldi(G, 2); + const int64_t t = ldi(B, 0), h = ldi(B, 1), w = ldi(B, 2); + const int64_t t0 = ldi(B, 3), y0 = ldi(B, 4), x0 = ldi(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); + REF_PAR_FOR(t * h * w * C) + 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) stt(Y, yb + c * ys, ldt(X, xb + c * xs)); + } + return RAD_OK; +} + +/* tile_stitch: decoded tiles to RGB bytes. geom = (T, H, W) is the grid the tiles cut (tail cells + * excluded); a cell is `scale` patches of p x p pixels a side and `scale_t` frames, the first cell + * of the video one frame (the causal mapping: T cells are scale_t T - scale_t + 1 frames). x is + * every tile's decoder output in tile order, back to back: tile (kt, i, j) with cells [t0, t1) in + * time is F = scale_t (t1 - t0), less scale_t - 1 when t0 is 0, frames of (h scale) x (w scale) + * rows of patches (pix_patch's columns, C p p a row). `first` is the first frame y holds, i32 [1]. + * + * A pixel (Y, X) of frame n is time band kt's whose kept frames hold n (a band but the last keeps + * stride_t scale_t frames, the first scale_t - 1 fewer), then tile (i, j) = (Y / s, X / s) of that + * band, s = stride scale p, the last band of an axis keeping the rest. With R a tile's decoded + * value, every product and sum rounded to x's dtype (rd) and mix(a, b, k, e) = + * rd(rd(a f32(1 - k / e)) + rd(b f32(k / e))) (the quotients in f64), a band's picture S is + * diffusers' in-place blend_v then blend_h of its tiles: + * + * ev = min(rows of tile (i-1, j), rows of tile (i, j), (tile - stride) scale p), eh likewise + * up(c) = R(i-1, c)[rows(i-1) - ev + ly, .] the tile above's bottom margin + * A = mix(up(j-1)[., cols(j-1) - eh + lx], up(j)[., lx], lx, eh) when j > 0, lx < eh, + * else up(j)[., lx] (it was blended with its own left) + * V = mix(A, R(i, j)[ly, lx], ly, ev) when i > 0 and ly < ev, else R(i, j)[ly, lx] + * L = mix(up(j-1)[., cols(j-1) - eh + lx], R(i, j-1)[ly, cols(j-1) - eh + lx], ly, ev) + * when i > 0 and ly < ev, else R(i, j-1)[ly, cols(j-1) - eh + lx] + * S = mix(L, V, lx, eh) when j > 0 and lx < eh, else V + * + * and across time blend_t: frame f of band kt, f < et = min(F of band kt-1, F of band kt, + * (tile_t - stride_t) scale_t), is mix(S_{kt-1}[F_{kt-1} - et + f], S_kt[f], f, et). The byte is + * patch_pix8's, round(255 clamp(rd(rd(clamp(v, -1, 1) / 2) + 0.5), 0, 1)). y is u8 + * [n (H scale p), (W scale p) C], frames first .. first + n - 1. A tile above, to the left or + * before is never short enough for its own blends to reach the margin read here (a tile not last + * on its axis spans more than `stride`), so these are the reference's values exactly. */ +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); + } + /* Tile (kt, i, j)'s first patch row. */ + 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); } +}; + +int ref_tile_stitch(const RadArgs* a, RadStream) { + if (!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 = ldi(G, 0), H = ldi(G, 1), W = ldi(G, 2), f0 = ldi(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 round_dt(dt, round_dt(dt, va * wa) + round_dt(dt, vb * wb)); + }; + /* Band kt's spatially stitched value at its frame f. */ + 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; + REF_PAR_FOR(nf * Hpx * Wpx * C) + 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 = round_dt(dt, round_dt(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 */ +/* LTX-2's bandwidth extender's input: each channel's causal log-mel spectrogram, as its MelSTFT + * computes it in the vocoder's dtype. x [S, ch] (time rows, a channel a column), `basis` + * [2F, 1, nfft] (the windowed DFT, real rows then imaginary), `mel` [n_mel, F]; frame t of channel + * h 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)))) + * + * sums f32 in ascending order, rd y's dtype. y is [S / hop, ch n_mel]. */ +int ref_stft_logmel(const RadArgs* a, RadStream) { + if (!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 = round_dt(dt, 1e-5f); + REF_PAR_FOR(frames * ch * 2 * F * nfft) + for (int64_t t = 0; t < frames; ++t) + for (int64_t h = 0; h < ch; ++h) { + std::vector 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 += ldt(B, k * nfft + j) * v; + im += ldt(B, (F + k) * nfft + j) * v; + } + re = round_dt(dt, re); + im = round_dt(dt, im); + mag[(size_t)k] = round_dt(dt, std::sqrt(round_dt(dt, round_dt(dt, re * re) + + round_dt(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 += ldt(Mb, m * F + k) * mag[(size_t)k]; + const float mel = std::max(round_dt(dt, s), floor_v); + stt(Y, yb + (h * nm + m) * ys, std::log(mel)); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ bwe_up */ +/* LTX-2's bandwidth extender's output: the low-rate waveform x [S, ch] raised `ratio` times by its + * Hann-windowed sinc resampler (UpSample1d, width ceil(6 / 0.99), its taps in x's dtype), added to + * the extender's residual `res` [S ratio, ch], clamped to [-1, 1]: + * + * f[n] = rd(sinc(u) cos^2(clamp(u, -6, 6) pi / 12) 0.99 / ratio), u = f32(n / ratio - w) 0.99 + * up[o] = rd(ratio rd(sum f[k] x[clamp(i - w, 0, S - 1)])), i ratio + k = o + 2 w ratio + * y[o] = clamp(rd(res[o] + up[o]), -1, 1) + * + * the filter's arithmetic f32 as torch builds it, rd x's dtype; y is f32 or x's dtype. */ +int ref_bwe_up(const RadArgs* a, RadStream) { + if (!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 f((size_t)K); + for (int64_t n = 0; n < K; ++n) { + const float u = ((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(uc * (float)M_PI / 6.0f / 2.0f); + const float pu = (float)M_PI * u; + const float sinc = u == 0.0f ? 1.0f : std::sin(pu) / pu; + f[(size_t)n] = round_dt(dt, sinc * (cw * cw) * 0.99f / (float)r); + } + const int64_t xs = laststride(X), rs = laststride(Rz), ys = laststride(Y); + REF_PAR_FOR(O * ch * K) + 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; /* the padded input's index */ + const int64_t s = std::min(std::max(i - w, 0), S - 1); + acc += f[(size_t)k] * ldt(X, rowoff(X, s, ch) + h * xs); + } + const float up = round_dt(dt, (float)r * round_dt(dt, acc)); + const float v = round_dt(dt, ldt(Rz, rowoff(Rz, o, ch) + h * rs) + up); + stt(Y, rowoff(Y, o, ch) + h * ys, std::min(std::max(v, -1.0f), 1.0f)); + } + return RAD_OK; +} diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 16c6e76c..3c72d4cc 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -144,6 +144,10 @@ int ref_logits_gemm (const RadArgs*, RadStream); /* ---- attention */ int ref_attn_paged (const RadArgs*, RadStream); int ref_attn_dense (const RadArgs*, RadStream); +int ref_attn_cross (const RadArgs*, RadStream); +int ref_table_add (const RadArgs*, RadStream); +int ref_mix_rows (const RadArgs*, RadStream); +int ref_chan_stats (const RadArgs*, RadStream); int ref_kv_store (const RadArgs*, RadStream); int ref_rope (const RadArgs*, RadStream); int ref_rope_table (const RadArgs*, RadStream); @@ -172,6 +176,24 @@ int ref_group_norm(const RadArgs*, RadStream); int ref_tconv_dw(const RadArgs*, RadStream); int ref_resize_bilinear(const RadArgs*, RadStream); int ref_flow_renoise(const RadArgs*, RadStream); +/* ref_ltx.cpp */ +int ref_rope_split(const RadArgs*, RadStream); +int ref_head_gate(const RadArgs*, RadStream); +int ref_ltx_guide(const RadArgs*, RadStream); +int ref_pixel_norm(const RadArgs*, RadStream); +int ref_d2s3d(const RadArgs*, RadStream); +int ref_s2d3d(const RadArgs*, RadStream); +int ref_pix_patch(const RadArgs*, RadStream); +int ref_patch_pix8(const RadArgs*, RadStream); +int ref_vol_index(const RadArgs*, RadStream); +int ref_attn_na3d(const RadArgs*, RadStream); +int ref_tile_grid(const RadArgs*, RadStream); +int ref_tile_crop(const RadArgs*, RadStream); +int ref_tile_stitch(const RadArgs*, RadStream); +int ref_stft_logmel(const RadArgs*, RadStream); +int ref_bwe_up(const RadArgs*, RadStream); +/* ltx_guide's scratch, in f32 values: the deviations' partial sums of a device implementation. */ +enum { kLtxGuideStats = 8200 }; /* ref_vsa.cpp */ int ref_vsa_select(const RadArgs*, RadStream); int ref_attn_vsa(const RadArgs*, RadStream); @@ -194,6 +216,7 @@ int ref_chan_split(const RadArgs*, RadStream); int ref_interleave2(const RadArgs*, RadStream); int ref_iota(const RadArgs*, RadStream); int ref_cu_repeat(const RadArgs*, RadStream); +int ref_int_affine(const RadArgs*, RadStream); int ref_chan_affine(const RadArgs*, RadStream); int ref_conv2d_nhwc(const RadArgs*, RadStream); int ref_l2norm_chan(const RadArgs*, RadStream); @@ -362,6 +385,10 @@ REF_SHAPE_FN(ref_logits_gemm); REF_SHAPE_FN(ref_attn_paged); REF_SHAPE_FN(ref_attn_dense); +REF_SHAPE_FN(ref_attn_cross); +REF_SHAPE_FN(ref_table_add); +REF_SHAPE_FN(ref_mix_rows); +REF_SHAPE_FN(ref_chan_stats); REF_SHAPE_FN(ref_kv_store); REF_SHAPE_FN(ref_rope); REF_SHAPE_FN(ref_rope_table); @@ -388,6 +415,21 @@ REF_SHAPE_FN(ref_group_norm); REF_SHAPE_FN(ref_tconv_dw); REF_SHAPE_FN(ref_resize_bilinear); REF_SHAPE_FN(ref_flow_renoise); +REF_SHAPE_FN(ref_rope_split); +REF_SHAPE_FN(ref_head_gate); +REF_SHAPE_FN(ref_ltx_guide); +REF_SHAPE_FN(ref_pixel_norm); +REF_SHAPE_FN(ref_d2s3d); +REF_SHAPE_FN(ref_s2d3d); +REF_SHAPE_FN(ref_pix_patch); +REF_SHAPE_FN(ref_patch_pix8); +REF_SHAPE_FN(ref_vol_index); +REF_SHAPE_FN(ref_attn_na3d); +REF_SHAPE_FN(ref_tile_grid); +REF_SHAPE_FN(ref_tile_crop); +REF_SHAPE_FN(ref_tile_stitch); +REF_SHAPE_FN(ref_stft_logmel); +REF_SHAPE_FN(ref_bwe_up); REF_SHAPE_FN(ref_vsa_select); REF_SHAPE_FN(ref_attn_vsa); REF_SHAPE_FN(ref_conv1d); @@ -408,6 +450,7 @@ REF_SHAPE_FN(ref_chan_split); REF_SHAPE_FN(ref_interleave2); REF_SHAPE_FN(ref_iota); REF_SHAPE_FN(ref_cu_repeat); +REF_SHAPE_FN(ref_int_affine); REF_SHAPE_FN(ref_chan_affine); REF_SHAPE_FN(ref_conv2d_nhwc); REF_SHAPE_FN(ref_l2norm_chan); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index abcf91fa..fbf5cbe3 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -367,6 +367,13 @@ static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_INT( 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") }; /* `k_scale` and `v_scale` are the descales an fp8 cache is read back with, so a store divides by * them; optional because a bf16 cache has none. */ @@ -693,6 +700,13 @@ static const RadOperandSpec oMerge[] = { OPD("gathered"), OPD("params"), 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") }; /* `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[] = { 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"), @@ -701,12 +715,14 @@ static const RadOperandSpec oLnModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), OPD( INOUT("x"), OUT("q"), OUT("scale"), OUT_O("z") }; /* `s` is [n_seq, >= 2n], [shift | scale] in each row. */ 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") }; /* `t`, `sigma` and `sigma_next` are one f32 value each. */ @@ -789,7 +805,8 @@ static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("se * (T, H, W) for conv3d_ndhwc and tconv_dw, (T, h, w, H, W) for resize_bilinear and (F, Hp, Wp) * for patch_fold, which shares 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") }; /* `mod` is one row [scale | shift]; `stats` the per-group mean and rstd, then scratch. */ @@ -805,6 +822,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 (ref_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 (ref_audio.cpp) */ 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"), @@ -864,6 +927,8 @@ static const RadParamSpec pIota[] = { P_INT("M"), P_INT("start"), P_INT("step"), P_INTO("period") }; static const RadOperandSpec oIota[] = { OUT("y") }; static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") }; +static const RadParamSpec pIntAffine[] = { P_INT("M"), P_STR("src"), P_STR("mul"), P_STR("add") }; +static const RadOperandSpec oIntAffine[] = { OPD("x"), OUT("y") }; static const RadOperandSpec oCuRepeat[] = { OPD("len"), OUT("y") }; /* ================================================================== the schema table */ @@ -948,6 +1013,16 @@ static const RadOpSchema kSchemas[] = { "rows; nothing else broadcasts. With `div`, y = rd(rd(a + b) / div), rd y's dtype: the last " "sum of a mean taken pairwise." }, { "mul", ARR(pMnD), ARR(oBinary), "y = a * b, with the same one broadcast rule as `add`." }, +{ "table_add", ARR(pTableAdd), ARR(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; `M` is y's rows." }, +{ "chan_stats", ARR(pChanStats), ARR(oChanStats), + "a latent through per-channel statistics held as weights: `denorm` y = rd(rd(x std) + mean), " + "`norm` y = rd(rd(x - mean) / std); std is `s`, or sqrt(s + eps) with `var` 1, each statistic " + "rounded to y's dtype." }, +{ "mix_rows", ARR(pMixRows), ARR(oMixRows), + "y[r, c] = sum_i w[i] x[r k + i, c], i < k: a Linear(k, 1) across k consecutive rows, f32 sum in " + "ascending i rounded once; `M` is y's rows." }, { "mul_weight", ARR(pMulWeight), ARR(oMulWeight), "y = x * w, `w` a WEIGHT of one element (a scalar for the whole output) or of one row " "(broadcast down the rows): a learned gain on an activation. f32 product, rounded once." }, @@ -1203,6 +1278,13 @@ static const RadOpSchema kSchemas[] = { "window, or i - j < window and j - i < window_right with `window_right`; 0 none. `block` cuts " "a segment into blocks of that many rows from its start, each attending within itself; 0 " "none." }, +{ "attn_cross", ARR(pAttnCross), ARR(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]); with `causal` a query sees key j of its run when j <= its own " + "index, both counted from their run's start. A query that sees no key is zero." }, +{ "attn_na3d", ARR(pAttnNa3d), ARR(oAttnNa3d), + "3-D neighborhood attention (NATTEN's na3d) over the voxels of geom = (T, H, W): a query sees the " + "kt x kh x kw window centred on it, shifted inward at the border, each extent at most its axis." }, { "kv_store", ARR(pKvStore), ARR(oKvStore), "Writes k and v into the paged cache at slot_mapping; a negative slot is skipped. The cache is " "INOUT rather than the OUT docs/OPS.md draws, because the op touches only the mapped slots." }, @@ -1572,6 +1654,53 @@ static const RadOpSchema kSchemas[] = { { "flow_renoise", ARR(pFlowRenoise), ARR(oFlowRenoise), "a clean latent re-noised to sigma s: x = f32(f32(f32(1 - s) x) + f32(s z)), z element " "k n + c of the normal stream (seed, `stream`) (abi/rad_philox.h)." }, +{ "rope_split", ARR(pRopeSplit), ARR(oRopeSplit), + "LTX-2's rotary over fractional coordinates: dim/2 pairs over all heads, the first `pad` " + "unrotated, then freq[k] = f32(theta^linspace(0,1,steps)[k] pi/2) with the n_dims coordinates " + "interleaved; angle f32(f32(2 f32(c / max)) - 1) freq; each head's halves rotated against each " + "other in f32, rounded to x's dtype. `head0` is the operand's first head." }, +{ "head_gate", ARR(pHeadGate), ARR(oHeadGate), + "x = rd(x rd(2 rd(sigmoid(g)))) per head: LTX-2's gated attention output." }, +{ "pixel_norm", ARR(pPixelNorm), ARR(oPixelNorm), + "an RMS norm over each row's n values as bf16 tensors compute it, every step rounded to y's " + "dtype: m = rd(sum rd(x^2) / n), then x rd(rsqrt(rd(m + eps))) (`form` rsqrt) or " + "x / rd(sqrt(rd(m + eps))) (div), optionally silu; `ileave` L writes x's row t L + l to " + "columns c L + l of y's row t." }, +{ "d2s3d", ARR(pD2s3d), ARR(oD2s3d), + "depth to space over voxel rows: packed channel ((c st + a) sh + b) sw + d of x's row (t, i, j) " + "to y's (t st + a - (st - 1), i sh + b, j sw + d), the first st - 1 frames dropped." }, +{ "s2d3d", ARR(pS2d3d), ARR(oS2d3d), + "space to depth over voxel rows, `tpre` leading frames prepended: each st x sh x sw box a packed " + "row (`mode` copy), or each run of `group` packed channels averaged (mean); `add` adds into y." }, +{ "pix_patch", ARR(pPixPatch), ARR(oPixPatch), + "an image [H, W C] to patch rows [H/p, (W/p) C p p], channel c's (ph, pw) at c p p + pw p + ph " + "(order wh) or c p p + ph p + pw (hw)." }, +{ "patch_pix8", ARR(pPixPatch), ARR(oPixPatch), + "patch rows [R, w C p p] to RGB bytes [R p, w p C] by to_rgba8's rule, pix_patch's channel " + "order." }, +{ "vol_index", ARR(pVolIndex), ARR(oVolIndex), + "a volume's voxel coordinates (t, i, j), component-major: attention's rotary positions." }, +{ "tile_grid", ARR(pTileGrid), ARR(oTileGrid), + "the tiles of a grid as diffusers cuts them (`rule` stride: tiled_decode's, a tile every " + "`stride` cells; intervals: _tile_intervals', a short last remnant merged), in space and " + "optionally time, one row (t, h, w, t0, y0, x0, k, count) a tile." }, +{ "tile_crop", ARR(pTileCrop), ARR(oTileCrop), + "one tile's voxels out of a volume: y[(a, i, j)] = x[(t0 + a, y0 + i, x0 + j)], box " + "(t, h, w, t0, y0, x0)." }, +{ "tile_stitch", ARR(pTileStitch), ARR(oTileStitch), + "decoded tiles to RGB bytes: diffusers' in-place blend_v then blend_h of each tile with the one " + "above and the one to its left, then blend_t of each time band with the one before, each kept to " + "its stride, then patch_pix8's bytes." }, +{ "stft_logmel", ARR(pStftMel), ARR(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: frames S / hop, columns h n_mel + m." }, +{ "bwe_up", ARR(pBweUp), ARR(oBweUp), + "y = clamp(rd(res + up(x)), -1, 1): x raised `ratio` times by a Hann-windowed sinc resampler " + "(width ceil(6 / 0.99), taps in x's dtype, edges replicated)." }, +{ "ltx_guide", ARR(pLtxGuide), ARR(oLtxGuide), + "LTX-2's sampler step: each pass's clean estimate x - v sigma, the guidance deltas (CFG, STG, " + "modality) added in f32, an optional rescale by the deviations' ratio, the velocity back and " + "an Euler step of x, all f32. `scales` f32[4] (gs, stg, ms, rescale), `sched` f32[2]." }, { "conv1d", ARR(pConv1d), ARR(oConv1d), "a 1-D convolution over the sequences `cu_seqlens` bounds, channels innermost: x [rows, cin], " "y [rows, cout], PyTorch's [cout, cin, k] weight and an optional bias, dilation `dil` and padding " @@ -1636,6 +1765,9 @@ static const RadOpSchema kSchemas[] = { "y[i] = start + i * step over y's elements, or start + (i % period) * step with `period`." }, { "cu_repeat", ARR(pCuRepeat), ARR(oCuRepeat), "bounds of equal sequences, y[j] = j * len[0] * mult over y's elements." }, +{ "int_affine", ARR(pIntAffine), ARR(oIntAffine), + "y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists: shapes and " + "bounds derived from a pass's device geometry." }, }; /* ================================================================== the kernel table */ @@ -1819,6 +1951,12 @@ SIMPLE("ref_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate SIMPLE("ref_act_mul", "act_mul", "elem", "act(a) * b over two operands", DT_FLOAT, ref_act_mul), SIMPLE("ref_mul_weight", "mul_weight", "elem", "x * a scalar or one-row weight", DT_FLOAT, ref_mul_weight), +SIMPLE("ref_table_add", "table_add", "elem", "a row plus each of L table rows", DT_FLOAT, + ref_table_add), +SIMPLE("ref_mix_rows", "mix_rows", "elem", "a weighted sum of k consecutive rows", DT_FLOAT, + ref_mix_rows), +SIMPLE("ref_chan_stats", "chan_stats", "elem", "per-channel statistics held as weights", + DT_FLOAT, ref_chan_stats), SIMPLE("ref_seg_mean", "seg_mean", "elem", "mean of each cu_seqlens segment's rows", DT_FLOAT, ref_seg_mean), SIMPLE("ref_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, then a multiplier", @@ -1942,6 +2080,11 @@ ROW("ref_attn_paged", "attn_paged", "attn", nullptr, nullptr, ref_attn_paged, nullptr), SIMPLE("ref_attn_dense", "attn_dense", "attn", "dense varlen attention over cu_seqlens", DT_FLOAT, ref_attn_dense), +SIMPLE("ref_attn_cross", "attn_cross", "attn", + "dense varlen attention, keys bounded apart from the queries (cu_k)", DT_FLOAT, + ref_attn_cross), +SIMPLE("ref_attn_na3d", "attn_na3d", "attn", "3-D neighborhood attention over a volume", DT_FLOAT, + ref_attn_na3d), ROW("ref_kv_store", "kv_store", "attn", "scatter k and v into the paged cache", DT_ANY, cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), nullptr, nullptr, ref_kv_store, nullptr), @@ -2117,6 +2260,27 @@ SIMPLE("ref_patch_fold", "patch_fold", "elem", "voxel rows to normalised patch r ref_patch_fold), SIMPLE("ref_flow_renoise", "flow_renoise", "elem", "a clean latent re-noised to a sigma", DT_FLOAT, ref_flow_renoise), +SIMPLE("ref_rope_split", "rope_split", "elem", "LTX-2's split rotary over coordinates", DT_FLOAT, + ref_rope_split), +SIMPLE("ref_head_gate", "head_gate", "elem", "each head times 2 sigmoid of its logit", DT_FLOAT, + ref_head_gate), +SIMPLE("ref_ltx_guide", "ltx_guide", "elem", "LTX-2's guided sampler step", DT_FLOAT, + ref_ltx_guide), +SIMPLE("ref_pixel_norm", "pixel_norm", "norm", "an RMS norm as bf16 tensors compute it", DT_FLOAT, + ref_pixel_norm), +SIMPLE("ref_d2s3d", "d2s3d", "elem", "depth to space over voxel rows", DT_FLOAT, ref_d2s3d), +SIMPLE("ref_s2d3d", "s2d3d", "elem", "space to depth over voxel rows", DT_FLOAT, ref_s2d3d), +SIMPLE("ref_pix_patch", "pix_patch", "elem", "an image to patch rows", DT_FLOAT, ref_pix_patch), +SIMPLE("ref_patch_pix8", "patch_pix8", "elem", "patch rows to RGB bytes", DT_FLOAT, ref_patch_pix8), +SIMPLE("ref_vol_index", "vol_index", "elem", "a volume's voxel coordinates", DT_ANY, ref_vol_index), +SIMPLE("ref_tile_grid", "tile_grid", "elem", "a tiled decode's boxes", DT_ANY, ref_tile_grid), +SIMPLE("ref_tile_crop", "tile_crop", "elem", "a tile out of a volume", DT_FLOAT, ref_tile_crop), +SIMPLE("ref_tile_stitch", "tile_stitch", "elem", "decoded tiles blended to RGB bytes", DT_FLOAT, + ref_tile_stitch), +SIMPLE("ref_stft_logmel", "stft_logmel", "elem", "a causal log-mel spectrogram", DT_FLOAT, + ref_stft_logmel), +SIMPLE("ref_bwe_up", "bwe_up", "elem", "a sinc-resampled waveform plus a residual, clamped", + DT_FLOAT, ref_bwe_up), SIMPLE("ref_conv1d", "conv1d", "conv", "a 1-D convolution over sequences, channels innermost", DT_FLOAT, ref_conv1d), SIMPLE("ref_conv_t1d", "conv_t1d", "conv", "a transposed 1-D convolution growing each sequence", @@ -2150,6 +2314,8 @@ SIMPLE("ref_interleave2", "interleave2", "elem", "two streams interleaved", DT_A ref_interleave2), SIMPLE("ref_iota", "iota", "elem", "an arithmetic index sequence", DT_ANY, ref_iota), SIMPLE("ref_cu_repeat", "cu_repeat", "elem", "bounds of equal sequences", DT_ANY, ref_cu_repeat), +SIMPLE("ref_int_affine", "int_affine", "elem", "integers derived from device geometry", DT_ANY, + ref_int_affine), }; /* ================================================================== plugin exports */ diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 30dbf06e..efa78320 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -1328,6 +1328,60 @@ int ref_attn_dense_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou return o.finish("attn_dense", operand, out); } +int ref_attn_cross_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t hd = gi(p, n_p, "head_dim", 0); + const int64_t gqa = gi(p, n_p, "gqa", 1); + if (M <= 0 || hd <= 0 || gqa <= 0) return RAD_E_UNSUPPORTED; + const int64_t nh = gqa, kvh = 1; + const uint32_t D = act_dt(p, n_p); + const int64_t S = n_seq_of(p, n_p); + + /* As many key rows as query rows, each side bounded by its own [0, ..., T]. */ + Opd o; + o.t(D, { M, nh, hd }); /* q */ + o.t(D, { M, kvh, hd }); /* k */ + o.t(D, { M, kvh, hd }); /* v */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_k */ + o.t(D, { M, nh, hd }); /* out */ + return o.finish("attn_cross", operand, out); +} + +int ref_table_add_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), L = gi(p, n_p, "L", 0); + if (M <= 0 || n <= 0 || L <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t(D, { M, n }); /* x */ + o.t(D, { L, n }); /* t */ + o.t(D, { M, L * n }); /* y */ + return o.finish("table_add", operand, out); +} + +int ref_mix_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), k = gi(p, n_p, "k", 0); + if (M <= 0 || n <= 0 || k <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t(D, { M * k, n }); /* x */ + o.t(D, { k }); /* w */ + o.t(D, { M, n }); /* y */ + return o.finish("mix_rows", operand, out); +} + +int ref_chan_stats_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t(D, { M, n }); /* x */ + o.t(D, { n }); /* mean */ + o.t_fill(D, { n }, (uint32_t)RAD_FILL_SIGMOID, 0); /* s -- a deviation or variance, > 0 */ + o.t(D, { M, n }); /* y */ + return o.finish("chan_stats", operand, out); +} + int ref_kv_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t hd = gi(p, n_p, "head_dim", 0); @@ -2407,7 +2461,10 @@ int ref_rms_mod_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) o.skip(); } o.t(D, { 1, 2 * n }); /* s: [shift | scale] */ - o.t(D, { n }); /* w */ + /* A LayerNorm without a gain passes none, and no norm takes none. */ + const char* nk = gs(p, n_p, "norm"); + if (nk && (std::strcmp(nk, "layer") == 0 || std::strcmp(nk, "none") == 0)) o.skip(); /* w */ + else o.t(D, { n }); /* w */ o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ o.t(D, { M, n }); /* x, INOUT */ o.t(D, { M, n }); /* z */ @@ -2426,7 +2483,9 @@ int ref_rms_mod_quant_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdD o.skip(); } o.t(D, { 1, 2 * n }); /* s */ - o.t(D, { n }); /* w */ + const char* nk = gs(p, n_p, "norm"); + if (nk && std::strcmp(nk, "layer") == 0) o.skip(); /* w: a LayerNorm without a gain */ + else o.t(D, { n }); /* w */ o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ o.t(D, { M, n }); /* x, INOUT */ o.t((uint32_t)RAD_F8E4M3, { M, n }); /* q */ @@ -3215,3 +3274,204 @@ int ref_cu_repeat_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out o.t_idx({ M }, 1, -1, 0); /* y */ return o.finish("cu_repeat", operand, out); } + +int ref_int_affine_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + if (M <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t_idx({ 16 }, 1000, -1, 0); /* x */ + o.t_idx({ M }, 1, -1, 0); /* y */ + return o.finish("int_affine", operand, out); +} + +/* ================================================================== LTX-2 (ref_ltx.cpp) */ +int ref_rope_split_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), nh = gi(p, n_p, "n_head", 0); + const int64_t hd = gi(p, n_p, "head_dim", 0), nd = gi(p, n_p, "n_dims", 0); + if (M <= 0 || nh <= 0 || hd <= 0 || nd <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t(act_dt(p, n_p), { M, nh * hd }); /* x, INOUT */ + o.t((uint32_t)RAD_F32, { nd, M }); /* positions */ + return o.finish("rope_split", operand, out); +} + +int ref_head_gate_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), nh = gi(p, n_p, "n_head", 0); + const int64_t hd = gi(p, n_p, "head_dim", 0); + if (M <= 0 || nh <= 0 || hd <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, nh }); /* g */ + o.t(D, { M, nh * hd }); /* x, INOUT */ + return o.finish("head_gate", operand, out); +} + +/* The four guidance passes bound, scales and sigmas in (0, 1): every term taken. */ +int ref_ltx_guide_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p), F = (uint32_t)RAD_F32; + Opd o; + for (int i = 0; i < 4; ++i) o.t(D, { M, n }); /* vc, vu, vs, vm */ + o.t_fill(F, { 4 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* scales */ + o.t_fill(F, { 2 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sched */ + o.t(F, { kLtxGuideStats }); /* stats, INOUT */ + o.t(F, { M, n }); /* x, INOUT */ + return o.finish("ltx_guide", operand, out); +} + +/* The rest of LTX-2's: its VAE's norm, resampling and patches, its vocoder's spectrogram and + * resampler. A volume op's `geom` is the cube of side cube_side(M), M its input's rows. */ +int ref_pixel_norm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), L = gi(p, n_p, "ileave", 1); + if (M <= 0 || n <= 0 || L <= 0 || M % L) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, n }); /* x */ + o.t(D, { M / L, n * L }); /* y */ + return o.finish("pixel_norm", operand, out); +} + +int ref_d2s3d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), C = gi(p, n_p, "C", 0), c = cube_side(M); + const int64_t st = gi(p, n_p, "st", 1), sh = gi(p, n_p, "sh", 1), sw = gi(p, n_p, "sw", 1); + if (c <= 0 || C <= 0 || st <= 0 || sh <= 0 || sw <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { c * c * c, C * st * sh * sw }); /* x */ + o.t_idx({ 3 }, 0, c, 0); /* geom */ + o.t(D, { (c * st - st + 1) * c * sh * c * sw, C }); /* y */ + return o.finish("d2s3d", operand, out); +} + +int ref_s2d3d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), C = gi(p, n_p, "C", 0), c = cube_side(M); + const int64_t st = gi(p, n_p, "st", 1), sh = gi(p, n_p, "sh", 1), sw = gi(p, n_p, "sw", 1); + const int64_t tpre = gi(p, n_p, "tpre", 0), g = gi(p, n_p, "group", 1); + const char* mode = gs(p, n_p, "mode"); + const bool mean = mode && !std::strcmp(mode, "mean"); + const int64_t P = C * st * sh * sw; + if (c <= 0 || C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || tpre < 0 || g <= 0 || + (c + tpre) % st || c % sh || c % sw || (mean && P % g)) + return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { c * c * c, C }); /* x */ + o.t_idx({ 3 }, 0, c, 0); /* geom */ + o.t(D, { ((c + tpre) / st) * (c / sh) * (c / sw), mean ? P / g : P }); /* y, INOUT */ + return o.finish("s2d3d", operand, out); +} + +int ref_pix_patch_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), pp = gi(p, n_p, "p", 0), C = gi(p, n_p, "C", 0); + const int64_t w = cols_for(M, 1), h = w ? M / w : 0; + if (!w || pp <= 0 || C <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { h * pp, w * pp * C }); /* x: the image */ + o.t(D, { h, w * C * pp * pp }); /* y: patch rows */ + return o.finish("pix_patch", operand, out); +} + +/* attn_na3d over a c x c x c volume, two heads. */ +int ref_attn_na3d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), hd = gi(p, n_p, "head_dim", 0), c = cube_side(M); + if (c <= 0 || hd <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + const int64_t V = c * c * c; + Opd o; + o.t(D, { V, 2 * hd }); /* q */ + o.t(D, { V, 2 * hd }); /* k */ + o.t(D, { V, 2 * hd }); /* v */ + o.t_idx({ 3 }, 0, c, 0); /* geom */ + o.t(D, { V, 2 * hd }); /* out */ + return o.finish("attn_na3d", operand, out); +} + +int ref_vol_index_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), c = cube_side(M); + if (c <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t_idx({ 3 }, 0, c, 0); /* geom: c x c x c */ + o.t_idx({ 3, c * c * c }, 1, -1, 0); /* y */ + return o.finish("vol_index", operand, out); +} + +/* The tiled decode's ops: a c x c x c volume (every geom entry c), tiles and boxes inside it. */ +int ref_tile_grid_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), stride = gi(p, n_p, "stride", 0); + int64_t k = 0; + while ((k + 1) * (k + 1) <= M) ++k; + if (k <= 0 || stride <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t_idx({ 3 }, 0, k * stride, 0); /* geom: k x k tiles */ + o.t_idx({ M, 8 }, 1, -1, 0); /* y */ + return o.finish("tile_grid", operand, out); +} + +int ref_tile_crop_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), C = gi(p, n_p, "C", 0); + int64_t k = 0; + while ((k + 1) * (k + 1) * (k + 1) <= M) ++k; + if (k <= 0 || C <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { 8 * k * k * k, C }); /* x: 2k x 2k x 2k */ + o.t_idx({ 3 }, 0, 2 * k, 0); /* geom */ + o.t_idx({ 6 }, 0, k, 0); /* box: k x k x k at (k, k, k) */ + o.t(D, { k * k * k, C }); /* y */ + return o.finish("tile_crop", operand, out); +} + +int ref_tile_stitch_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), tile = gi(p, n_p, "tile", 0); + const int64_t stride = gi(p, n_p, "stride", 0), sc = gi(p, n_p, "scale", 0); + const int64_t pp = gi(p, n_p, "p", 0), C = gi(p, n_p, "C", 0); + if (tile <= 0 || stride <= 0 || stride > tile || sc <= 0 || pp <= 0 || C <= 0) + return RAD_E_UNSUPPORTED; + int64_t c = 0; + while ((c + 1) * (c + 1) * sc * pp <= M) ++c; + if (c <= 0) return RAD_E_UNSUPPORTED; + int64_t span = 0; /* the tiles' rows along an axis */ + for (int64_t s0 = 0; s0 < c; s0 += stride) span += std::min(tile, c - s0); + Opd o; + o.t(act_dt(p, n_p), { c * sc * sc * span * span, C * pp * pp }); /* x: c frames of tiles */ + o.t_idx({ 3 }, 0, c, 0); /* geom */ + o.t_idx({ 1 }, 0, 0, 0); /* first: frame 0 */ + o.t((uint32_t)RAD_U8, { c * c * sc * pp, c * sc * pp * C }); /* y: every frame */ + return o.finish("tile_stitch", operand, out); +} + +int ref_patch_pix8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), pp = gi(p, n_p, "p", 0), C = gi(p, n_p, "C", 0); + const int64_t w = cols_for(M, 1), R = w ? M / w : 0; + if (!w || pp <= 0 || C <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t(act_dt(p, n_p), { R, w * C * pp * pp }); /* x: patch rows */ + o.t((uint32_t)RAD_U8, { R * pp, w * pp * C }); /* y: bytes */ + return o.finish("patch_pix8", operand, out); +} + +int ref_stft_logmel_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), hop = gi(p, n_p, "hop", 0), nfft = gi(p, n_p, "nfft", 0); + const int64_t nm = gi(p, n_p, "n_mel", 0), ch = gi(p, n_p, "ch", 0), F = nfft / 2 + 1; + if (M <= 0 || hop <= 0 || nfft < hop || nm <= 0 || ch <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M * hop, ch }); /* x: samples */ + o.t(D, { 2 * F, 1, nfft }); /* basis */ + o.t(D, { nm, F }); /* mel */ + o.t(D, { M, ch * nm }); /* y */ + return o.finish("stft_logmel", operand, out); +} + +int ref_bwe_up_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), r = gi(p, n_p, "ratio", 0), ch = gi(p, n_p, "ch", 0); + if (M <= 0 || r <= 0 || ch <= 0 || M % r) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M / r, ch }); /* x: the low-rate waveform */ + o.t(D, { M, ch }); /* res */ + o.t(D, { M, ch }); /* y */ + return o.finish("bwe_up", operand, out); +} diff --git a/libref/ref_video.cpp b/libref/ref_video.cpp index e6a2b35e..27dbeaf0 100644 --- a/libref/ref_video.cpp +++ b/libref/ref_video.cpp @@ -357,20 +357,30 @@ int ref_vtile_stitch(const RadArgs* a, RadStream) { * terms outside the volume zero. acc is f32, the taps in (dt, kh, kw) order and each tap's * channels ascending; rd is y's dtype. With `res` the convolution's output is rounded before the * residual is added, as a residual block's skip(x) + h adds two bf16 tensors. `res` may be y - * itself: each output element reads its own residual before its write, and no other. */ + * itself: each output element reads its own residual before its write, and no other. + * + * `tpad` sets the frames' padding (rows and columns stay zero-padded): `zero` (the default), + * `replicate` (the edge frame repeated, kt/2 a side: LTX-2's decoder) or `causal` (the first + * frame repeated kt - 1 times in front, nothing after: LTX-2's encoder). With `causal`, `tpre` + * more copies of the first frame stand in front of those, and y has T + tpre frames (LTX-2's + * temporal downsampler, which prepends its first frame before its convolution). */ int ref_conv3d_ndhwc(const RadArgs* a, RadStream) { if (a->n_t < 6 || !have(a, 4) || !t_in(a, 5)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *w = &a->t[1], *b = &a->t[2], *geom = &a->t[3]; const RadTensor *res = t_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(geom) < 3) + const int64_t k = p_int(a, "k", 0), kt = p_int(a, "kt", 0), tpre = p_int(a, "tpre", 0); + static const char* const kPads[] = { "zero", "replicate", "causal" }; + const int tpad = p_enum(a, "tpad", kPads, 3, 0); + 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(geom) < 3) return RAD_E_SHAPE; const int64_t T = ldi(geom, 0), H = ldi(geom, 1), W = ldi(geom, 2); if (T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE; - const int64_t rows = T * H * W, taps = kt * k * k; - if (rows_of(y, cout) < rows || rows_of(x, cin) < rows || (res && rows_of(res, cout) < rows) || - numel(w) < cout * cin * taps || numel(b) < cout) + const int64_t rows = (T + tpre) * H * W, taps = kt * k * k; + if (rows_of(y, cout) < rows || rows_of(x, cin) < T * H * W || + (res && rows_of(res, cout) < rows) || numel(w) < cout * cin * taps || numel(b) < cout) return RAD_E_SHAPE; const int64_t pz = kt / 2, ps = k / 2, xs = laststride(x), ys = laststride(y); const int64_t rs = res ? laststride(res) : 0; @@ -382,7 +392,11 @@ int ref_conv3d_ndhwc(const RadArgs* a, RadStream) { for (int64_t o = 0; o < cout; ++o) { float acc = 0.0f; for (int64_t dz = 0; dz < kt; ++dz) { - const int64_t tz = t + dz - pz; + /* The frame tap dz reads: zero pads, the edge frame repeated, or causal (the first + * frame repeated in front, `tpre` more copies of it before those). */ + int64_t tz = t + dz - pz; + if (tpad == 1) tz = std::min(std::max(tz, 0), T - 1); + else if (tpad == 2) tz = std::max(t + dz - (kt - 1) - tpre, 0); if (tz < 0 || tz >= T) continue; for (int64_t kh = 0; kh < k; ++kh) { const int64_t iy = i + kh - ps; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index bf2b8296..5482fc84 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -366,7 +366,7 @@ endif() # HIP names, each GPU thread is a fiber, and __syncthreads and cross-lane ops are barriers (one not # reached uniformly is reported as a deadlock). Checked against ports of libref's ref_attn_paged and # ref_qsa_select, the host arithmetic in ref_host.cpp, for the joins the unfused chain bit for bit, -# and for the LoRA pair libref itself when the test can load it. +# for the LoRA pair libref itself when the test can load it, and for KDA libref itself. # # Requires clang (ext_vector_type) and x86-64 (SysV fiber switch in inline assembly). With a clang # C++ compiler the .hip files build here as C++ (`-x c++`; the property is per directory, so @@ -437,7 +437,7 @@ else() list(APPEND objs ${dir}/${stem}.o) endif() endforeach() - # test_lora opens libref with dlopen to hold the emulated kernels to it. + # test_lora and test_kda open libref with dlopen to hold the emulated kernels to it. set(dl "") foreach(l ${CMAKE_DL_LIBS}) list(APPEND dl -l${l}) @@ -470,8 +470,9 @@ if(R4D_EMU_BUILT) r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora r4d_emu_mla r4d_emu_moefuse PROPERTIES LABELS "r4d_emu" TIMEOUT ${RAD_TEST_TIMEOUT}) # The LoRA pair has a libref oracle, and the test holds the emulated kernels to it when it can - # load one -- expand bit for bit, shrink to its bound. - set_tests_properties(r4d_emu_lora PROPERTIES + # load one -- expand bit for bit, shrink to its bound. kda_update is held to libref's within + # rounding, and that test needs it. + set_tests_properties(r4d_emu_lora r4d_emu_kda PROPERTIES ENVIRONMENT "RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home") # A seeded random sweep, mostly prefill shapes on the WMMA kernel, which the emulator runs at # about 2 s a case: `slow`. `r4d_emu_attn sweep 200` is a longer run by hand, a superset of it. diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index 22691472..9d8dcd1f 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -349,6 +349,19 @@ ABI_FIELD(RadGenBatch, dec_lane) ABI_FIELD(RadGenBatch, dec_height) ABI_FIELD(RadGenBatch, dec_width) ABI_FIELD(RadGenBatch, dec_preview) +ABI_FIELD(RadGenBatch, branch) +ABI_FIELD(RadGenBatch, n_pad) +ABI_FIELD(RadGenBatch, valid_cu) +ABI_FIELD(RadGenBatch, n_img) +ABI_FIELD(RadGenBatch, img_cu) +ABI_FIELD(RadGenBatch, img_rows) +ABI_FIELD(RadGenBatch, mode_cu) +ABI_FIELD(RadGenBatch, rope_f) +ABI_FIELD(RadGenBatch, mode_rows) +ABI_FIELD(RadGenBatch, mode_src) +ABI_FIELD(RadGenBatch, mode_ccu) +ABI_FIELD(RadGenBatch, n_mode_h) +ABI_FIELD(RadGenBatch, mode_rope_f) ABI_STRUCT(RadGeneratorDecl) ABI_FIELD(RadGeneratorDecl, name) ABI_FIELD(RadGeneratorDecl, layout) @@ -382,6 +395,14 @@ ABI_FIELD(RadGeneratorDecl, shift_terminal) ABI_FIELD(RadGeneratorDecl, default_cfg) ABI_FIELD(RadGeneratorDecl, max_lanes) ABI_FIELD(RadGeneratorDecl, image_out) +ABI_FIELD(RadGeneratorDecl, cond_rows) +ABI_FIELD(RadGeneratorDecl, rope_hw_scale) +ABI_FIELD(RadGeneratorDecl, rope_text_l) +ABI_FIELD(RadGeneratorDecl, pad_multiple) +ABI_FIELD(RadGeneratorDecl, pad_token) +ABI_FIELD(RadGeneratorDecl, cfg_original) +ABI_FIELD(RadGeneratorDecl, default_negative) +ABI_FIELD(RadGeneratorDecl, ref_shrink_only) ABI_STRUCT(RadKVGroupBatch) ABI_FIELD(RadKVGroupBatch, group) ABI_FIELD(RadKVGroupBatch, slot_mapping) @@ -615,6 +636,12 @@ ABI_FIELD(RadVideoGenBatch, n_frames_out) ABI_FIELD(RadVideoGenBatch, n_samples) ABI_FIELD(RadVideoGenBatch, geom_from) ABI_FIELD(RadVideoGenBatch, upscale) +ABI_FIELD(RadVideoGenBatch, n_neg) +ABI_FIELD(RadVideoGenBatch, guidance_h) +ABI_FIELD(RadVideoGenBatch, image) +ABI_FIELD(RadVideoGenBatch, has_image) +ABI_FIELD(RadVideoGenBatch, guidance) +ABI_FIELD(RadVideoGenBatch, decoder) ABI_STRUCT(RadVideoGenDecl) ABI_FIELD(RadVideoGenDecl, name) ABI_FIELD(RadVideoGenDecl, tmpl) @@ -653,6 +680,30 @@ ABI_FIELD(RadVideoGenDecl, n_rungs) ABI_FIELD(RadVideoGenDecl, rungs) ABI_FIELD(RadVideoGenDecl, upscale_max) ABI_FIELD(RadVideoGenDecl, upscale_refine) +ABI_FIELD(RadVideoGenDecl, sched_kind) +ABI_FIELD(RadVideoGenDecl, dyn_shift) +ABI_FIELD(RadVideoGenDecl, base_shift) +ABI_FIELD(RadVideoGenDecl, max_shift) +ABI_FIELD(RadVideoGenDecl, base_seq) +ABI_FIELD(RadVideoGenDecl, max_seq) +ABI_FIELD(RadVideoGenDecl, shift_terminal) +ABI_FIELD(RadVideoGenDecl, n_refine_rungs) +ABI_FIELD(RadVideoGenDecl, refine_rungs) +ABI_FIELD(RadVideoGenDecl, step_text_rows) +ABI_FIELD(RadVideoGenDecl, guidance) +ABI_FIELD(RadVideoGenDecl, guidance_default) +ABI_FIELD(RadVideoGenDecl, default_negative) +ABI_FIELD(RadVideoGenDecl, image_cond) +ABI_FIELD(RadVideoGenDecl, image_crf) +ABI_FIELD(RadVideoGenDecl, text_left_pad) +ABI_FIELD(RadVideoGenDecl, audio_streams) +ABI_FIELD(RadVideoGenDecl, upscale_exact) +ABI_FIELD(RadVideoGenDecl, duration_out) +ABI_FIELD(RadVideoGenDecl, duration_min) +ABI_FIELD(RadVideoGenDecl, duration_max) +ABI_FIELD(RadVideoGenDecl, duration_dtype) +ABI_FIELD(RadVideoGenDecl, decoders) +ABI_FIELD(RadVideoGenDecl, decoder_max_area) ABI_STRUCT(RadVideoGeom) ABI_FIELD(RadVideoGeom, n_text) ABI_FIELD(RadVideoGeom, frames) diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index 67222040..6fc89cfb 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -1,4 +1,4 @@ -/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 23 and +/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 24 and * RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot * of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it * from the test's printout only together with a version bump. */ @@ -315,7 +315,7 @@ { "RadFuseStep", "n_p", 584, 4 }, { "RadFuseStep", "from", 588, 32 }, { "RadFuseStep", "n_from", 620, 4 }, -{ "RadGenBatch", "", 0, 224 }, +{ "RadGenBatch", "", 0, 320 }, { "RadGenBatch", "rows", 0, 8 }, { "RadGenBatch", "src", 8, 8 }, { "RadGenBatch", "rope", 16, 8 }, @@ -346,7 +346,20 @@ { "RadGenBatch", "dec_height", 212, 4 }, { "RadGenBatch", "dec_width", 216, 4 }, { "RadGenBatch", "dec_preview", 220, 4 }, -{ "RadGeneratorDecl", "", 0, 248 }, +{ "RadGenBatch", "branch", 224, 4 }, +{ "RadGenBatch", "n_pad", 228, 4 }, +{ "RadGenBatch", "valid_cu", 232, 8 }, +{ "RadGenBatch", "n_img", 240, 8 }, +{ "RadGenBatch", "img_cu", 248, 8 }, +{ "RadGenBatch", "img_rows", 256, 8 }, +{ "RadGenBatch", "mode_cu", 264, 8 }, +{ "RadGenBatch", "rope_f", 272, 8 }, +{ "RadGenBatch", "mode_rows", 280, 8 }, +{ "RadGenBatch", "mode_src", 288, 8 }, +{ "RadGenBatch", "mode_ccu", 296, 8 }, +{ "RadGenBatch", "n_mode_h", 304, 8 }, +{ "RadGenBatch", "mode_rope_f", 312, 8 }, +{ "RadGeneratorDecl", "", 0, 296 }, { "RadGeneratorDecl", "name", 0, 8 }, { "RadGeneratorDecl", "layout", 8, 4 }, { "RadGeneratorDecl", "tmpl_text", 16, 8 }, @@ -379,6 +392,14 @@ { "RadGeneratorDecl", "default_cfg", 224, 8 }, { "RadGeneratorDecl", "max_lanes", 232, 8 }, { "RadGeneratorDecl", "image_out", 240, 4 }, +{ "RadGeneratorDecl", "cond_rows", 248, 8 }, +{ "RadGeneratorDecl", "rope_hw_scale", 256, 8 }, +{ "RadGeneratorDecl", "rope_text_l", 264, 4 }, +{ "RadGeneratorDecl", "pad_multiple", 268, 4 }, +{ "RadGeneratorDecl", "pad_token", 272, 4 }, +{ "RadGeneratorDecl", "cfg_original", 276, 4 }, +{ "RadGeneratorDecl", "default_negative", 280, 8 }, +{ "RadGeneratorDecl", "ref_shrink_only", 288, 4 }, { "RadKVGroupBatch", "", 0, 72 }, { "RadKVGroupBatch", "group", 0, 4 }, { "RadKVGroupBatch", "slot_mapping", 8, 8 }, @@ -590,7 +611,7 @@ { "RadTunable", "n_values", 16, 4 }, { "RadTunable", "deflt", 24, 8 }, { "RadTunable", "doc", 32, 8 }, -{ "RadVideoGenBatch", "", 0, 192 }, +{ "RadVideoGenBatch", "", 0, 240 }, { "RadVideoGenBatch", "lane", 0, 4 }, { "RadVideoGenBatch", "geom", 4, 24 }, { "RadVideoGenBatch", "geom_d", 32, 8 }, @@ -612,7 +633,13 @@ { "RadVideoGenBatch", "n_samples", 152, 8 }, { "RadVideoGenBatch", "geom_from", 160, 24 }, { "RadVideoGenBatch", "upscale", 184, 8 }, -{ "RadVideoGenDecl", "", 0, 288 }, +{ "RadVideoGenBatch", "n_neg", 192, 4 }, +{ "RadVideoGenBatch", "guidance_h", 200, 8 }, +{ "RadVideoGenBatch", "image", 208, 8 }, +{ "RadVideoGenBatch", "has_image", 216, 4 }, +{ "RadVideoGenBatch", "guidance", 224, 8 }, +{ "RadVideoGenBatch", "decoder", 232, 4 }, +{ "RadVideoGenDecl", "", 0, 512 }, { "RadVideoGenDecl", "name", 0, 8 }, { "RadVideoGenDecl", "tmpl", 8, 8 }, { "RadVideoGenDecl", "max_text", 16, 8 }, @@ -650,6 +677,30 @@ { "RadVideoGenDecl", "rungs", 264, 8 }, { "RadVideoGenDecl", "upscale_max", 272, 8 }, { "RadVideoGenDecl", "upscale_refine", 280, 4 }, +{ "RadVideoGenDecl", "sched_kind", 284, 4 }, +{ "RadVideoGenDecl", "dyn_shift", 288, 4 }, +{ "RadVideoGenDecl", "base_shift", 296, 8 }, +{ "RadVideoGenDecl", "max_shift", 304, 8 }, +{ "RadVideoGenDecl", "base_seq", 312, 8 }, +{ "RadVideoGenDecl", "max_seq", 320, 8 }, +{ "RadVideoGenDecl", "shift_terminal", 328, 8 }, +{ "RadVideoGenDecl", "n_refine_rungs", 336, 4 }, +{ "RadVideoGenDecl", "refine_rungs", 344, 8 }, +{ "RadVideoGenDecl", "step_text_rows", 352, 8 }, +{ "RadVideoGenDecl", "guidance", 360, 4 }, +{ "RadVideoGenDecl", "guidance_default", 368, 64 }, +{ "RadVideoGenDecl", "default_negative", 432, 8 }, +{ "RadVideoGenDecl", "image_cond", 440, 4 }, +{ "RadVideoGenDecl", "image_crf", 444, 4 }, +{ "RadVideoGenDecl", "text_left_pad", 448, 8 }, +{ "RadVideoGenDecl", "audio_streams", 456, 4 }, +{ "RadVideoGenDecl", "upscale_exact", 460, 4 }, +{ "RadVideoGenDecl", "duration_out", 464, 4 }, +{ "RadVideoGenDecl", "duration_min", 472, 8 }, +{ "RadVideoGenDecl", "duration_max", 480, 8 }, +{ "RadVideoGenDecl", "duration_dtype", 488, 4 }, +{ "RadVideoGenDecl", "decoders", 496, 8 }, +{ "RadVideoGenDecl", "decoder_max_area", 504, 8 }, { "RadVideoGeom", "", 0, 24 }, { "RadVideoGeom", "n_text", 0, 4 }, { "RadVideoGeom", "frames", 4, 4 }, diff --git a/tests/abi_layout_test.cpp b/tests/abi_layout_test.cpp index bc804bc0..bc51ff46 100644 --- a/tests/abi_layout_test.cpp +++ b/tests/abi_layout_test.cpp @@ -8,7 +8,7 @@ * * Checked: a C translation unit (abi_c_test.c, strict C11) lays every struct out as C++ does; every * struct's listed fields account for its size, so the list in abi_layout_rows.h is complete; and - * the layout agrees with the table below, taken at RAD_ABI_VERSION 23 and RAD_FORMAT_VER 2. Under + * the layout agrees with the table below, taken at RAD_ABI_VERSION 24 and RAD_FORMAT_VER 2. Under * those versions a listed field may not move or change size, an ABI struct may only grow by fields * past its old end, and an on-disk struct may not change at all. The table is a snapshot of the * headers: nothing else states the layout. When it disagrees the test prints the live table. @@ -57,8 +57,8 @@ std::vector cpp_rows() { }; } -/* The layout at RAD_ABI_VERSION 23 / RAD_FORMAT_VER 2 (see the file header). */ -constexpr uint32_t kTableAbi = 23, kTableFormat = 2; +/* The layout at RAD_ABI_VERSION 24 / RAD_FORMAT_VER 2 (see the file header). */ +constexpr uint32_t kTableAbi = 24, kTableFormat = 2; const AbiRow kTable[] = { #include "abi_layout_table.h" }; diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 84fbdf83..39ba088c 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -2375,7 +2375,6 @@ TEST(manifold_connections_preserve_saved_coefficients_and_use_a_separate_residua TEST(manifold_read_splits_its_projection_by_chunks_over_ranks_from_the_row_threshold) { using namespace rad::arch; - unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); for (int world : { 1, 2, 4, 8 }) for (int rank = 0; rank < world; ++rank) { RadBuilder b; @@ -2501,7 +2500,6 @@ TEST(glm_routing_keeps_f32_logits_and_correction_replicated_under_tp4) { TEST(glm_router_and_index_head_split_columns_over_ranks_from_the_row_threshold) { using namespace rad::arch; - unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); for (int world : { 1, 2, 4, 8 }) for (int rank = 0; rank < world; ++rank) { RadBuilder b; @@ -2578,44 +2576,6 @@ TEST(glm_router_and_index_head_split_columns_over_ranks_from_the_row_threshold) REQUIRE_EQ(ctx.issues.size(), (size_t)2); CHECK_EQ(ctx.issues[0].op, router.op_project); } - { - setenv("RADIANCE_GLM_TP_SPLIT_ROWS", "64", 1); - RadBuilder b; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 128; - g.world = 8; - g.rank = 5; - GlmRouter::Config cfg; - cfg.rows = 128; - GlmRouter::Wire w; - w.input = decl_b(&b, "hidden", RAD_BF16, { 128, 4096 }); - w.logits = decl_b(&b, "logits", RAD_F32, { 128, 288 }); - w.ids = decl_b(&b, "ids", RAD_I32, { 128, 8 }); - w.weights = decl_b(&b, "weights", RAD_F32, { 128, 8 }); - GlmRouter::Src src{ "model.layers.3.mlp.gate.weight", - "model.layers.3.mlp.gate.e_score_correction_bias" }; - GlmRouter router; - REQUIRE_EQ(router.declare(&b, nm, g, 3, "blk.3.router", cfg, w, src), RAD_OK); - RadCtx ctx; - router.step(&ctx, 0, 64); - router.step(&ctx, 0, 63); - REQUIRE_EQ(ctx.issues.size(), (size_t)5); - CHECK_EQ(ctx.issues[0].op, router.split.op_part); - CHECK_EQ(ctx.issues[3].op, router.op_project); - setenv("RADIANCE_GLM_TP_SPLIT_ROWS", "0", 1); - RadBuilder off; - GlmRouter whole; - auto w2 = w; - w2.input = decl_b(&off, "hidden", RAD_BF16, { 128, 4096 }); - w2.logits = decl_b(&off, "logits", RAD_F32, { 128, 288 }); - w2.ids = decl_b(&off, "ids", RAD_I32, { 128, 8 }); - w2.weights = decl_b(&off, "weights", RAD_F32, { 128, 8 }); - REQUIRE_EQ(whole.declare(&off, nm, g, 3, "blk.3.router", cfg, w2, src), RAD_OK); - CHECK_EQ(count_op(off, "all_gather"), 0); - unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); - } } TEST(absorbed_mla_shards_complete_heads_and_reads_one_latent_cache) { @@ -2681,7 +2641,6 @@ TEST( meta.kv_val = vals; const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); - unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); for (int world : { 1, 4, 8 }) for (int rank = 0; rank < world; ++rank) { RadBuilder b; @@ -2900,77 +2859,72 @@ TEST(glm53_sizing_declares_match_the_real_graph_at_every_arena_level) { meta.kv_val = vals; const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); - unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); - // 256 is the default threshold; at 2048 the 256- and 1024-row levels lie below it. const int world = 8, rank = 3; - for (const char* split : { "256", "2048" }) - for (int64_t R : { 256, 3072 }) { - setenv("RADIANCE_GLM_TP_SPLIT_ROWS", split, 1); - auto encs = [&](RadBuilder& b) { - b.kv_block = 4; - b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, - { "mtp.blk.45.ffn_down_exps", fp8 }, - { "ffn_gate_up_exps", mx }, - { "ffn_down_exps", mx }, - { "ffn_gate_up_shexp", mx }, - { "ffn_down_shexp", mx }, - { "ffn_gate_up.weight", fp8 }, - { "ffn_down.weight", fp8 } }; - }; - RadBuildCtx c{}; - c.rank = rank; - c.world_size = world; - c.max_tok = 4096; - c.max_seqs = 8; - c.max_ctx = 32768; - c.max_spec = 3; - RadBuilder full; - encs(full); - REQUIRE_EQ(glm5next::declare(&full, &meta, &c), RAD_OK); - RadBuildCtx p = c; - p.max_tok = R; - p.shape_probe = 1; - RadBuilder small; - encs(small); - REQUIRE_EQ(glm5next::declare(&small, &meta, &p), RAD_OK); - REQUIRE_EQ(small.ops.size(), full.ops.size()); - int differ = 0; - for (size_t i = 0; i < full.ops.size(); ++i) { - if (small.ops[i].op != full.ops[i].op) { - ++differ; + for (int64_t R : { 256, 3072 }) { + auto encs = [&](RadBuilder& b) { + b.kv_block = 4; + b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, + { "mtp.blk.45.ffn_down_exps", fp8 }, + { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx }, + { "ffn_gate_up.weight", fp8 }, + { "ffn_down.weight", fp8 } }; + }; + RadBuildCtx c{}; + c.rank = rank; + c.world_size = world; + c.max_tok = 4096; + c.max_seqs = 8; + c.max_ctx = 32768; + c.max_spec = 3; + RadBuilder full; + encs(full); + REQUIRE_EQ(glm5next::declare(&full, &meta, &c), RAD_OK); + RadBuildCtx p = c; + p.max_tok = R; + p.shape_probe = 1; + RadBuilder small; + encs(small); + REQUIRE_EQ(glm5next::declare(&small, &meta, &p), RAD_OK); + REQUIRE_EQ(small.ops.size(), full.ops.size()); + int differ = 0; + for (size_t i = 0; i < full.ops.size(); ++i) { + if (small.ops[i].op != full.ops[i].op) { + ++differ; + continue; + } + REQUIRE_EQ(small.ops[i].p.size(), full.ops[i].p.size()); + for (size_t k = 0; k < full.ops[i].p.size(); ++k) { + const RecParam& a = full.ops[i].p[k]; + const RecParam& q = small.ops[i].p[k]; + if (a.kind == RAD_P_RANGE) continue; + // A capacity may shrink: its kernel writes by its operands' extents. + if (full.ops[i].op == "qsa_work" && a.key == "work" && q.ival <= a.ival) continue; - } - REQUIRE_EQ(small.ops[i].p.size(), full.ops[i].p.size()); - for (size_t k = 0; k < full.ops[i].p.size(); ++k) { - const RecParam& a = full.ops[i].p[k]; - const RecParam& q = small.ops[i].p[k]; - if (a.kind == RAD_P_RANGE) continue; - // A capacity may shrink: its kernel writes by its operands' extents. - if (full.ops[i].op == "qsa_work" && a.key == "work" && q.ival <= a.ival) - continue; - if (a.ival != q.ival || a.sval != q.sval || a.dval != q.dval) { - fprintf(stderr, - " split %s R %lld: op %zu '%s' param '%s': " - "%lld real, %lld small\n", - split, (long long)R, i, full.ops[i].op.c_str(), a.key.c_str(), - a.ival, q.ival); - ++differ; - } + if (a.ival != q.ival || a.sval != q.sval || a.dval != q.dval) { + fprintf(stderr, + " R %lld: op %zu '%s' param '%s': " + "%lld real, %lld small\n", + (long long)R, i, full.ops[i].op.c_str(), a.key.c_str(), + a.ival, q.ival); + ++differ; } } - CHECK_EQ(differ, 0); - REQUIRE_EQ(small.bufs.size(), full.bufs.size()); - for (size_t i = 0; i < full.bufs.size(); ++i) - for (uint32_t d = 1; d < full.bufs[i].d.rank; ++d) - CHECK_EQ(small.bufs[i].d.shape[d], full.bufs[i].d.shape[d]); } - unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + CHECK_EQ(differ, 0); + REQUIRE_EQ(small.bufs.size(), full.bufs.size()); + for (size_t i = 0; i < full.bufs.size(); ++i) + for (uint32_t d = 1; d < full.bufs[i].d.rank; ++d) + CHECK_EQ(small.bufs[i].d.shape[d], full.bufs[i].d.shape[d]); + } } -/* The MoE block's decode fusions (RADIANCE_GLM_*): each switch, alone and with the others, changes - * exactly its launches against the step without switches, over a two-row trunk step, its draft - * pass and a 512-row prefill (past the router fusion's one-workgroup sort), with the step lint - * clean throughout. A switch value other than 0 or 1 is refused. */ +/* The MoE block's decode fusions: over a two-row trunk step, its draft pass and a 512-row prefill + * (past the router fusion's one-workgroup sort), each fused launch stands where it fits and the + * launches it replaces are gone, with the step lint clean throughout. The sort writes each slot's + * row (`moe_scatter_inv`) and the gather reads it (`moe_gather_inv`) in every MoE pass. */ TEST(glm53_moe_decode_fusions_replace_their_launches_where_they_fit) { const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", "index_topk" }; @@ -2985,175 +2939,122 @@ TEST(glm53_moe_decode_fusions_replace_their_launches_where_they_fit) { meta.kv_val = vals; const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); - const char* const env[] = { "RADIANCE_GLM_ROUTER_FUSE", "RADIANCE_GLM_SWIGLU_QUANT", - "RADIANCE_GLM_GATHER_INVERSE" }; - const int n_env = (int)(sizeof env / sizeof env[0]); - unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); - auto clear = [&]() { - for (const char* e : env) unsetenv(e); - }; using Counts = std::map; - /* Launches the first two switches remove (negative) and add, per step: trunk, draft pass, - * prefill. The trunk has 42 MoE layers, each a routed and a shared clamped SwiGLU, and three - * dense ones. The third turns every remaining sort and gather into its inverse form. */ - struct Delta { + /* Launches per step: trunk, draft pass, prefill. The trunk has 42 MoE layers, each a routed + * and a shared clamped SwiGLU, and three dense ones. */ + struct Want { const char* op; int trunk, draft, prefill; }; - const std::vector deltas[] = { - { { "router_sigmoid_topk_scatter", 42, 1, 0 }, - { "router_sigmoid_topk", -42, -1, 0 }, - { "moe_scatter", -42, -1, 0 }, - { "fill", -42, -1, 0 } }, - { { "swiglu_clamped_quant_fp8", 87, 2, 87 }, - { "swiglu_clamped", -87, -2, -87 }, - { "quant_act_fp8", -87, -2, -87 } }, + const Want wants[] = { + { "router_sigmoid_topk_scatter", 42, 1, 0 }, { "router_sigmoid_topk", 0, 0, 42 }, + { "swiglu_clamped_quant_fp8", 87, 2, 87 }, { "swiglu_clamped", 0, 0, 0 }, + { "moe_scatter", 0, 0, 0 }, { "moe_gather", 0, 0, 0 }, }; for (int world : { 1, 8 }) { - Counts base[3]; - for (int mask = 0; mask < (1 << n_env); ++mask) { - // At one rank only the extremes: no switch reads the world. - if (world == 1 && mask && mask != (1 << n_env) - 1) continue; - for (int e = 0; e < n_env; ++e) setenv(env[e], mask >> e & 1 ? "1" : "0", 1); - RadBuilder b; - b.kv_block = 4; - b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, - { "mtp.blk.45.ffn_down_exps", fp8 }, - { "ffn_gate_up_exps", mx }, - { "ffn_down_exps", mx }, - { "ffn_gate_up_shexp", mx }, - { "ffn_down_shexp", mx }, - { "ffn_gate_up.weight", fp8 }, - { "ffn_down.weight", fp8 } }; - RadBuildCtx build{}; - build.rank = 0; - build.world_size = world; - build.max_tok = 512; - build.max_seqs = 4; - build.max_ctx = 4096; - build.max_spec = 3; - REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK); - int32_t cu[] = { 0, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 0 }, ids[] = { 7, 9 }, - slots[] = { 0, 1 }, out[] = { 1 }; - int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[32]{}; - std::vector kv(b.kv_groups.size()); - for (size_t i = 0; i < kv.size(); ++i) { - kv[i].group = (rad_kvgroup)i + 1; - kv[i].slot_mapping = slots; - kv[i].block_table = tables; - kv[i].block_table_pitch = 32; - kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx; - kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6; - } - RadBatch batch{}; - batch.phase = RAD_PHASE_PREFILL; - batch.n_tok = 2; - batch.n_seq = 1; - batch.token_ids = ids; - batch.positions = positions; - batch.cu_seqlens = cu; - batch.ctx_lens = ctxlens; - batch.kv = kv.data(); - batch.n_kv_groups = (int)kv.size(); - batch.n_out = 1; - batch.out_ids = out; - RadCtx ctx; - ctx.b = &b; - ctx.rank = 0; - ctx.world = world; - ctx.batch = &batch; - Counts got[3]; - /* With the inverse, the fused selection writes it as its ninth operand and the gather - * reads it as its third. */ - const rad_buf inv = find_b(b, "expert_inverse") - ? (rad_buf)(find_b(b, "expert_inverse") - &b.bufs[0] + 1) - : 0; - CHECK_EQ(inv != 0, (mask & 4) != 0); - auto run = [&](int k) { - ctx.issues.clear(); - glm5next::step(&ctx, &batch); - CHECK(ctx.step_fail.empty()); - CHECK_LINT(b, &ctx); - for (const auto& op : issued_ops(b, ctx)) ++got[k][op]; - for (const auto& is : ctx.issues) { - const RecOp* o = b.op_of(is.op); - if (!o || !inv) continue; - if (o->op == "router_sigmoid_topk_scatter") - CHECK(is.opd.size() > 8 && is.opd[8].kind == RAD_OPK_BUF && - is.opd[8].handle == inv); - if (o->op == "moe_gather_inv") - CHECK(is.opd.size() > 2 && is.opd[2].kind == RAD_OPK_BUF && - is.opd[2].handle == inv); - } - }; - run(0); - batch.draft_pass = -1; - batch.n_draft_out = 1; - batch.draft_out_ids = out; - run(1); - std::vector long_ids(512, 7), long_positions(512), long_slots(512), - long_tables(1024); - for (int i = 0; i < 512; ++i) long_positions[i] = long_slots[i] = i; - int32_t long_cu[] = { 0, 512 }, last = 511; - for (auto& group : kv) { - group.slot_mapping = long_slots.data(); - group.block_table = long_tables.data(); - group.block_table_pitch = 1024; - } - batch.n_tok = 512; - batch.token_ids = long_ids.data(); - batch.positions = long_positions.data(); - batch.cu_seqlens = long_cu; - batch.out_ids = &last; - batch.draft_pass = 0; - batch.n_draft_out = 0; - batch.max_q_len = 512; - run(2); - if (mask == 0) { - for (int k = 0; k < 3; ++k) base[k] = got[k]; - continue; - } - for (int k = 0; k < 3; ++k) { - Counts want = base[k]; - for (int e = 0; e < 2; ++e) - if (mask >> e & 1) - for (const Delta& d : deltas[e]) - want[d.op] += k == 0 ? d.trunk : k == 1 ? d.draft : d.prefill; - if (mask & 4) { - want["moe_scatter_inv"] += want["moe_scatter"]; - want["moe_scatter"] = 0; - want["moe_gather_inv"] += want["moe_gather"]; - want["moe_gather"] = 0; - } - for (auto it = want.begin(); it != want.end();) - it = it->second == 0 ? want.erase(it) : std::next(it); - if (got[k] != want) { - fprintf(stderr, " world %d switches %d step %d:", world, mask, k); - for (const auto& [op, n] : want) - if (got[k][op] != n) - fprintf(stderr, " %s %d (want %d)", op.c_str(), got[k][op], n); - for (const auto& [op, n] : got[k]) - if (!want.count(op)) fprintf(stderr, " %s %d (want 0)", op.c_str(), n); - fprintf(stderr, "\n"); - } - CHECK(got[k] == want); - } - } - } - for (const char* e : env) { - clear(); - setenv(e, "2", 1); RadBuilder b; + b.kv_block = 4; + b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, + { "mtp.blk.45.ffn_down_exps", fp8 }, + { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx }, + { "ffn_gate_up.weight", fp8 }, + { "ffn_down.weight", fp8 } }; RadBuildCtx build{}; build.rank = 0; - build.world_size = 8; - build.max_tok = 64; + build.world_size = world; + build.max_tok = 512; build.max_seqs = 4; build.max_ctx = 4096; build.max_spec = 3; - CHECK_EQ(glm5next::declare(&b, &meta, &build), RAD_E_INVAL); + REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK); + int32_t cu[] = { 0, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 0 }, ids[] = { 7, 9 }, + slots[] = { 0, 1 }, out[] = { 1 }; + int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[32]{}; + std::vector kv(b.kv_groups.size()); + for (size_t i = 0; i < kv.size(); ++i) { + kv[i].group = (rad_kvgroup)i + 1; + kv[i].slot_mapping = slots; + kv[i].block_table = tables; + kv[i].block_table_pitch = 32; + kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx; + kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6; + } + RadBatch batch{}; + batch.phase = RAD_PHASE_PREFILL; + batch.n_tok = 2; + batch.n_seq = 1; + batch.token_ids = ids; + batch.positions = positions; + batch.cu_seqlens = cu; + batch.ctx_lens = ctxlens; + batch.kv = kv.data(); + batch.n_kv_groups = (int)kv.size(); + batch.n_out = 1; + batch.out_ids = out; + RadCtx ctx; + ctx.b = &b; + ctx.rank = 0; + ctx.world = world; + ctx.batch = &batch; + Counts got[3]; + /* With the inverse, the fused selection writes it as its ninth operand and the gather + * reads it as its third. */ + const rad_buf inv = find_b(b, "expert_inverse") + ? (rad_buf)(find_b(b, "expert_inverse") - &b.bufs[0] + 1) + : 0; + REQUIRE(inv != 0); + auto run = [&](int k) { + ctx.issues.clear(); + glm5next::step(&ctx, &batch); + CHECK(ctx.step_fail.empty()); + CHECK_LINT(b, &ctx); + for (const auto& op : issued_ops(b, ctx)) ++got[k][op]; + for (const auto& is : ctx.issues) { + const RecOp* o = b.op_of(is.op); + if (!o) continue; + if (o->op == "router_sigmoid_topk_scatter") + CHECK(is.opd.size() > 8 && is.opd[8].kind == RAD_OPK_BUF && + is.opd[8].handle == inv); + if (o->op == "moe_gather_inv") + CHECK(is.opd.size() > 2 && is.opd[2].kind == RAD_OPK_BUF && + is.opd[2].handle == inv); + } + }; + run(0); + batch.draft_pass = -1; + batch.n_draft_out = 1; + batch.draft_out_ids = out; + run(1); + std::vector long_ids(512, 7), long_positions(512), long_slots(512), + long_tables(1024); + for (int i = 0; i < 512; ++i) long_positions[i] = long_slots[i] = i; + int32_t long_cu[] = { 0, 512 }, last = 511; + for (auto& group : kv) { + group.slot_mapping = long_slots.data(); + group.block_table = long_tables.data(); + group.block_table_pitch = 1024; + } + batch.n_tok = 512; + batch.token_ids = long_ids.data(); + batch.positions = long_positions.data(); + batch.cu_seqlens = long_cu; + batch.out_ids = &last; + batch.draft_pass = 0; + batch.n_draft_out = 0; + batch.max_q_len = 512; + run(2); + for (int k = 0; k < 3; ++k) + for (const Want& w : wants) { + const int want = k == 0 ? w.trunk : k == 1 ? w.draft : w.prefill; + if (got[k][w.op] != want) + fprintf(stderr, " world %d step %d: %s %d (want %d)\n", world, k, w.op, + got[k][w.op], want); + CHECK_EQ(got[k][w.op], want); + } } - clear(); } TEST(dsa_cache_uses_distinct_index_and_attention_pages_and_a_speculative_tail_ring) { @@ -3296,7 +3197,7 @@ TEST(glm_dense_ffn_keeps_clipping_and_disables_the_unclipped_fp8_epilogue) { MlpFP8::Src src{ "post_attention_layernorm.weight", "mlp.gate_proj.weight", "mlp.up_proj.weight", "mlp.down_proj.weight" }; REQUIRE_EQ(block.declare(&b, nm, g, 0, w, src, false, false, kArNone, false, 10), RAD_OK); - CHECK_EQ(block.op_gated, 0); + CHECK_EQ(block.op_gated, 0u); CHECK_EQ(b.ops[block.gq_ffn.op - 1].op, std::string("swiglu_clamped")); RadCtx ctx; ctx.b = &b; @@ -3619,12 +3520,12 @@ TEST(mxfp4_expert_declarations_preserve_tp4_and_tp8_scale_geometry_and_movement_ if (glm) { CHECK_EQ(b.weights[moe.w_router - 1].d.dtype, RAD_F32); CHECK_EQ(b.ops[moe.op_topk - 1].op, std::string("router_sigmoid_topk")); - CHECK_EQ(moe.op_topk_scatter, 0); - CHECK_EQ(moe.op_router_fused, 0); + CHECK_EQ(moe.op_topk_scatter, 0u); + CHECK_EQ(moe.op_router_fused, 0u); CHECK_EQ(b.ops[moe.gq_exp.op - 1].op, std::string("swiglu_clamped")); CHECK_EQ(b.ops[moe.gq_sh.op - 1].op, std::string("swiglu_clamped")); CHECK_EQ(b.ops[moe.op_sgate - 1].op, std::string("fill")); - CHECK_EQ(moe.w_sgate, 0); + CHECK_EQ(moe.w_sgate, 0u); bool plain_shared = false; for (const auto& p : b.ops[moe.op_gather - 1].p) if (p.key == "act") plain_shared = p.sval == "none"; @@ -9475,10 +9376,9 @@ TEST(a_4096_budget_without_a_span_is_the_pinned_graph_and_steps) { } } -/* With the decode fusions switched off, GLM declares and steps the graph and launches it had - * before them, at one and eight ranks: a 4096-row prefill after history, a mixed step, a decode - * step, a verify and its draft passes. */ -TEST(glm53_without_fusion_switches_is_the_pinned_graph_and_steps) { +/* GLM declares and steps the pinned graph and launches at one and eight ranks: a 4096-row prefill + * after history, a mixed step, a decode step, a verify and its draft passes. */ +TEST(glm53_is_the_pinned_graph_and_steps) { const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", "index_topk" }; const char* vals[] = { "1", "4", "288", "2048" }; @@ -9496,12 +9396,8 @@ TEST(glm53_without_fusion_switches_is_the_pinned_graph_and_steps) { int world; uint64_t graph, steps; }; - const Case cases[] = { { 1, 0xd48139cb64abf0b1ull, 0x6982726c635df529ull }, - { 8, 0x90fc5bc69f1cfb10ull, 0x197c95726131b817ull } }; - for (const char* e : - { "RADIANCE_GLM_ROUTER_FUSE", "RADIANCE_GLM_SWIGLU_QUANT", "RADIANCE_GLM_GATHER_INVERSE" }) - setenv(e, "0", 1); - unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + const Case cases[] = { { 1, 0xed3fc26c486ea1b5ull, 0x98ba2952bb37b075ull }, + { 8, 0x8204e073efdeee0cull, 0x1279aecfe4e32d9aull } }; for (const Case& cs : cases) { RadBuilder b; b.kv_block = 4; @@ -9525,9 +9421,6 @@ TEST(glm53_without_fusion_switches_is_the_pinned_graph_and_steps) { CHECK_EQ(g, cs.graph); CHECK_EQ(s, cs.steps); } - for (const char* e : - { "RADIANCE_GLM_ROUTER_FUSE", "RADIANCE_GLM_SWIGLU_QUANT", "RADIANCE_GLM_GATHER_INVERSE" }) - unsetenv(e); } /* Under a span a Flash-Next prefill of two intervals runs a pass at a time. At every world its diff --git a/tests/chat_test.cpp b/tests/chat_test.cpp index 46b5e9cb..df154adb 100644 --- a/tests/chat_test.cpp +++ b/tests/chat_test.cpp @@ -1043,6 +1043,36 @@ TEST(a_dotted_integer_is_an_index_as_in_jinja2) { CHECK_EQ(p.prompt, std::string("hi|assistant")); } +/* A template that takes one system message, first, as many do, against conversations the Chat + * Completions API allows: a system message after a user turn, and two at the head. They are + * rendered with the system messages merged, in order, into one at the head (#137). Any other + * refusal comes back in the template's own words, without the parser-generation wrapper. */ +TEST(system_messages_a_template_takes_only_first_are_merged_at_the_head) { + ChatTemplate t; + CHECK_OK(t.load( + "{%- for m in messages %}" + "{%- if m.role == 'system' and not loop.first %}" + "{{- raise_exception('System message must be at the beginning.') }}{%- endif %}" + "{%- if m.role == 'user' and m.content == 'boom' %}{{- raise_exception('no boom') }}{%- endif %}" + "<{{ m.role }}>{{ m.content }}" + "{%- endfor %}{%- if add_generation_prompt %}{% endif %}", "", "")); + ChatOptions opt; + opt.quiet = true; + auto render = [&](const json& msgs, ChatPrompt* p) { return t.apply(msgs, json(), opt, p); }; + ChatPrompt a, b, c, d; + CHECK_OK(render(json::parse(R"([{"role":"system","content":"s"},{"role":"user","content":"hi"}])"), &a)); + CHECK_EQ(a.prompt, std::string("shi")); + CHECK_OK(render(json::parse(R"([{"role":"user","content":"hi"},{"role":"system","content":"s"}])"), &b)); + CHECK_EQ(b.prompt, std::string("shi")); + CHECK_OK(render(json::parse(R"([{"role":"system","content":"s1"},{"role":"system", + "content":[{"type":"text","text":"s2"}]},{"role":"user","content":"hi"}])"), &c)); + CHECK_EQ(c.prompt, std::string("s1\n\ns2hi")); + CHECK(render(json::parse(R"([{"role":"system","content":"s"},{"role":"user","content":"boom"}])"), + &d) < 0); + CHECK(d.error.find("no boom") != std::string::npos); + CHECK(d.error.find("Unable to generate parser") == std::string::npos); +} + /* Unparseable Jinja (common in hand-built containers) is reported at load time as an error value; * a throw would cross the bringup path. */ TEST(a_template_that_does_not_parse_is_a_value_and_not_a_throw) { diff --git a/tests/gen_test.cpp b/tests/gen_test.cpp index 3114a6a9..8a2ea500 100644 --- a/tests/gen_test.cpp +++ b/tests/gen_test.cpp @@ -327,4 +327,99 @@ TEST(the_generator_admits_in_order_and_shutdown_answers_every_ticket) { CHECK(f.drv.next(1) == nullptr); } +/* The joint layout (RAD_GEN_LAYOUT_JOINT_STEP): no KV group; the conditioning's prompt padded to + * the declared multiple (padding at position 1, valid_cu bounding the prompt), the reference + * picture's tokens after it with its own l and scaled positions, and stored for every lane of the + * request. A denoising entry is that conditioning, read from its lane and branch's store rows, + * then the image, both in the pass order and mode by mode. */ +TEST(the_joint_layout_carries_the_conditioning_in_every_step) { + Program prog; + prog.generator = decl_base(); + RadGeneratorDecl& d = prog.generator; + d.layout = RAD_GEN_LAYOUT_JOINT_STEP; + d.cond_rows = 64; + d.pad_multiple = 8; + d.pad_token = 99; + d.rope_hw_scale = 0.5; + d.rope_text_l = 1; + d.ref_area = 32 * 32; + prog.ctx.max_tok = 2048; + prog.ctx.max_seqs = 8; + prog.kv_groups.emplace_back(); + gen::Driver drv; + REQUIRE_EQ(drv.init(prog, nullptr, { gen::Driver::RankIO{} }), (int)RAD_OK); + auto r = std::make_unique(); + r->width = 64; + r->height = 32; + r->n = 2; + r->pos.tokens = { 1, 2, 3, 4, 5 }; + r->pos.n_drop = 1; + r->has_neg = true; + r->neg.tokens = { 1, 6 }; + r->neg.n_drop = 1; + r->cfg = 3.0f; + gen::Pixels px; + px.w = 32; + px.h = 32; + px.ch = 4; + px.bf16.assign(32 * 32 * 4, 0); + r->refs.push_back(px); + r->ticket = std::make_shared(); + std::string why; + REQUIRE_EQ(drv.submit(std::move(r), &why), (int)RAD_OK); + + /* The positive conditioning: 4 text rows padded to 8, then the picture's 2 x 2 tokens. */ + const RadBatch* b = drv.next(0); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_COND); + const RadGenBatch* G = b->gen_b; + CHECK_EQ(b->n_kv_groups, (int32_t)0); + CHECK_EQ(b->n_tok, (int64_t)9); /* five tokens and four padding */ + CHECK_EQ(G->rows, (int64_t)12); /* 8 text rows and 4 picture tokens */ + CHECK_EQ(G->n_pad, (int32_t)4); + CHECK_EQ(G->branch, (int32_t)0); + CHECK_EQ(G->valid_cu[1], (int32_t)5); + CHECK_EQ(b->token_ids[8], (int32_t)99); + CHECK_EQ(b->positions[8], (int32_t)1); + CHECK_EQ(G->n_lane, (int64_t)2); + CHECK_EQ(G->src[0], (int32_t)1); /* the prompt row after the drop */ + CHECK_EQ(G->src[8], (int32_t)-1); /* the picture's first latent row */ + CHECK_EQ(G->rope_f[3 * 12 + 2], 2.0f); /* text row 2: l = 2 */ + CHECK_EQ(G->rope_f[3 * 12 + 9], -1.0f); /* the picture: l = -1 */ + CHECK_EQ(G->rope_f[2 * 12 + 9], 0.5f); /* its token (0, 1): w = 0.5 */ + CHECK_OK(drv.done()); + b = drv.next(1); + REQUIRE(b != nullptr); + CHECK_EQ(b->gen_b->branch, (int32_t)1); + CHECK_EQ(b->gen_b->rows, (int64_t)12); /* one token padded to 8, the picture */ + CHECK_OK(drv.done()); + + /* A step: four entries (two images, each with its negative), 12 + 8 rows each. */ + b = drv.next(2); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_DENOISE); + G = b->gen_b; + REQUIRE_EQ(b->n_seq, (int64_t)4); + CHECK_EQ(b->n_tok, (int64_t)80); + CHECK_EQ(G->n_img, (int64_t)32); + CHECK_EQ(b->cu_seqlens[1], (int32_t)20); + const int32_t lane0 = G->lane_dh[0]; + CHECK_EQ(G->src[0], (int32_t)(2 * lane0 * 64)); /* lane 0's positive row 0 */ + CHECK_EQ(G->src[20], (int32_t)((2 * lane0 + 1) * 64)); /* its negative row 0 */ + CHECK_EQ(G->src[12], (int32_t)-1); /* the first image row */ + CHECK_EQ(G->img_rows[0], (int32_t)12); + CHECK_EQ(G->img_cu[1], (int32_t)8); + CHECK_EQ(G->mode_cu[1], (int32_t)8); /* entry 0: text 0..8 */ + CHECK_EQ(G->mode_cu[2], (int32_t)12); /* pictures 8..12 */ + CHECK_EQ(G->mode_cu[3], (int32_t)20); /* image to 20 */ + CHECK_EQ(G->n_mode_h[0], (int64_t)32); + CHECK_EQ(G->n_mode_h[1], (int64_t)16); + CHECK_EQ(G->n_mode_h[2], (int64_t)32); + CHECK_EQ(G->mode_rows[32], (int32_t)8); /* the first picture row */ + CHECK_EQ(G->mode_ccu[1 * 5 + 1], (int32_t)4); /* pictures: entry 1 from 4 */ + CHECK_EQ(G->mode_rope_f[4 * 32 + 3 * 16 + 0], -1.0f); /* the pictures' l plane */ + CHECK_EQ(G->rope_f[1 * 80 + 12 + 4], 0.5f); /* image token (1, 0): h = 0.5 */ + CHECK_OK(drv.done()); +} + RAD_TEST_MAIN() diff --git a/tests/images_test.cpp b/tests/images_test.cpp index 8fe577ea..2cc5b814 100644 --- a/tests/images_test.cpp +++ b/tests/images_test.cpp @@ -171,6 +171,33 @@ TEST(usage_counts_each_pictures_tokens_in_every_branch) { /* `background: auto` keeps an edited picture's transparency and is opaque otherwise; a mask must * be the first picture's size. */ +/* A model whose card states guidance as cond + s (cond - uncond) and guides by default (Krea 2): + * a request naming nothing is guided at the card's scale with the model's own empty negative + * prompt, handed on as s + 1; `guidance_scale` is the same field as `true_cfg_scale`, 0 turns it + * off, and naming both is refused. An RGB model refuses a transparent background. */ +TEST(guidance_follows_the_model_cards_terms_and_its_default_negative) { + Images s; + s.img.inf.cfg_original = true; + s.img.inf.default_cfg = 4.5; + s.img.inf.has_default_negative = true; + s.img.inf.default_negative = ""; + s.img.inf.pixel_channels = 3; + s.gen({ { "prompt", "a fox" } }); + REQUIRE(!s.img.got.empty()); + CHECK(s.last().has_neg); + CHECK_EQ(s.last().cfg, 5.5f); + s.gen({ { "prompt", "a fox" }, { "guidance_scale", 2.0 } }); + CHECK(s.last().has_neg); + CHECK_EQ(s.last().cfg, 3.0f); + s.gen({ { "prompt", "a fox" }, { "guidance_scale", 0.0 } }); + CHECK(!s.last().has_neg); + const json both = s.gen({ { "prompt", "x" }, { "guidance_scale", 2.0 }, { "true_cfg_scale", 2.0 } }, + 400); + CHECK_EQ(str_at(both["error"], "param"), std::string("guidance_scale")); + const json alpha = s.gen({ { "prompt", "x" }, { "background", "transparent" } }, 400); + CHECK_EQ(str_at(alpha["error"], "param"), std::string("background")); +} + TEST(an_auto_background_follows_the_pictures_alpha) { if (!mm::decoder_available()) return; Images s; diff --git a/tests/place_test.cpp b/tests/place_test.cpp index a9c34203..728c59c1 100644 --- a/tests/place_test.cpp +++ b/tests/place_test.cpp @@ -3834,48 +3834,57 @@ int process_vram(int64_t* out) { /* Tools and tests build and tear down movers repeatedly, and on a card every event or stream is * a hardware queue and VRAM. A mover that staged, promoted and filled a loan gives back every * event and every byte of device memory it took. */ +/* The runtime and the driver keep some memory for the life of the process once a path is first + * used: page tables for address ranges first mapped (a page, or a page and a 2 MiB directory), and + * on some hosts about 30 MiB the first copy sets up (#124: 2 MiB, 2 MiB + 4 KiB and 31 MiB + 348 + * KiB across runs on one host). So the work runs once before the count is taken, and the count + * after a second run may differ by a page and a directory, never by a buffer. */ TEST(a_mover_gives_back_every_event_and_device_byte) { - const int64_t events0 = rad_dev_live_events(); + auto run = [&]() { + const int64_t events0 = rad_dev_live_events(); + { + Fixture f; + build_dense(f, 8, 1 * MiB, /*host_kernel=*/false); + Config c = base_config(); + c.placement = "layer_offload"; + c.vram_weights_mib = 5; + c.host_pool_mib = 64; + PlannerInput in{&f.prog, &c, 0, 1, nullptr, 0}; + Plan p; + REQUIRE_EQ(Planner(in).plan(&p), RAD_OK); + Mover m; + MoverConfig mc; + REQUIRE_EQ(m.init(f.prog, p, mc), RAD_OK); + RadStream compute = nullptr; + REQUIRE_EQ(rad_stream_create(&compute, 0), RAD_OK); + CHECK_OK(m.bind_compute_stream(compute)); + CHECK(rad_dev_live_events() > events0); + ComputeWork work; + for (int d = 0; d < 20; ++d) { + CHECK_OK(m.begin_dispatch(d, nullptr)); + work.run(compute); + CHECK_OK(m.prefetch_to_op(p.prefetch[(size_t)d % p.prefetch.size()].at_op)); + } + CHECK(m.stats().prefetched > 0); + CHECK_OK(rad_stream_sync(compute)); + rad_stream_destroy(compute); + } + { + LoanRig r; + REQUIRE_EQ(r.build(), RAD_OK); + CHECK_OK(r.m.set_loan(Mover::kLendKV, Loan::kAll)); + for (Deadline dl; (r.m.flex_used_bytes() == 0 || any_busy(r.h, r.hf.plan)) && !dl.passed();) + CHECK_OK(r.dispatch()); + CHECK(r.m.stats().promotions > 0); + } + CHECK_EQ(rad_dev_live_events(), events0); + }; + run(); int64_t vram0 = 0, vram1 = 0; CHECK_OK(process_vram(&vram0)); - { - Fixture f; - build_dense(f, 8, 1 * MiB, /*host_kernel=*/false); - Config c = base_config(); - c.placement = "layer_offload"; - c.vram_weights_mib = 5; - c.host_pool_mib = 64; - PlannerInput in{&f.prog, &c, 0, 1, nullptr, 0}; - Plan p; - REQUIRE_EQ(Planner(in).plan(&p), RAD_OK); - Mover m; - MoverConfig mc; - REQUIRE_EQ(m.init(f.prog, p, mc), RAD_OK); - RadStream compute = nullptr; - REQUIRE_EQ(rad_stream_create(&compute, 0), RAD_OK); - CHECK_OK(m.bind_compute_stream(compute)); - CHECK(rad_dev_live_events() > events0); - ComputeWork work; - for (int d = 0; d < 20; ++d) { - CHECK_OK(m.begin_dispatch(d, nullptr)); - work.run(compute); - CHECK_OK(m.prefetch_to_op(p.prefetch[(size_t)d % p.prefetch.size()].at_op)); - } - CHECK(m.stats().prefetched > 0); - CHECK_OK(rad_stream_sync(compute)); - rad_stream_destroy(compute); - } - { - LoanRig r; - REQUIRE_EQ(r.build(), RAD_OK); - CHECK_OK(r.m.set_loan(Mover::kLendKV, Loan::kAll)); - for (Deadline dl; (r.m.flex_used_bytes() == 0 || any_busy(r.h, r.hf.plan)) && !dl.passed();) - CHECK_OK(r.dispatch()); - CHECK(r.m.stats().promotions > 0); - } - CHECK_EQ(rad_dev_live_events(), events0); + run(); CHECK_OK(process_vram(&vram1)); - CHECK_EQ(vram1, vram0); + CHECK(vram1 - vram0 <= 2 * MiB + 4096); } RAD_TEST_MAIN() diff --git a/tests/plugin_test.cpp b/tests/plugin_test.cpp index 67b6ed7c..4dd0689f 100644 --- a/tests/plugin_test.cpp +++ b/tests/plugin_test.cpp @@ -996,12 +996,10 @@ TEST(libr4d_resolves_the_vision_attention_without_a_window) { } /* GLM-5.3-Flash's MLA at eight heads a rank: the matrix row ranks above the wave row and serves - * every M up to its bound, a decode step's rows and a prefill chunk alike. RADIANCE_MLA_MATRIX_MAX_M - * lowers that bound, which this case does not cover. */ + * every M up to its bound, a decode step's rows and a prefill chunk alike. */ TEST(libr4d_resolves_the_mla_attention_by_rows) { const std::string so = libr4d(); if (so.empty()) return; - if (std::getenv("RADIANCE_MLA_MATRIX_MAX_M")) return; Registry r; CHECK(r.load_plugin(so, 0) >= 0); Geometry g; diff --git a/tests/r4d_emu/test_f32.cpp b/tests/r4d_emu/test_f32.cpp index b6232903..b67b6533 100644 --- a/tests/r4d_emu/test_f32.cpp +++ b/tests/r4d_emu/test_f32.cpp @@ -1,24 +1,24 @@ -/* tests/r4d_emu: gemm_nt_f32 (r4d_glm.hip) on the host SIMT emulator. Every tile form - * (RADIANCE_F32_GEMM_TILE) must match the one-wave-per-output legacy kernel bit for bit, and the - * legacy kernel must match its arithmetic written out here: lane l folds k = l, l+32, ... with - * fmaf, then the xor butterfly over 16, 8, 4, 2, 1. Tail rows and columns and the pitch's padding - * stay untouched. +/* tests/r4d_emu: gemm_nt_f32 (r4d_glm.hip) on the host SIMT emulator. The form the launcher picks + * at each shape (one wave an output at one row, else a tile of rows x columns a wave, by M; the + * shapes reach every one) must match the arithmetic written out here bit for bit: lane l folds + * k = l, l+32, ... with fmaf, then the xor butterfly over 16, 8, 4, 2, 1. Tail rows and columns + * and the pitch's padding stay untouched. * - * router_sigmoid_topk from the same unit: the wave-per-row select must match the serial scan - * (RADIANCE_ROUTER_SELECT=old) bit for bit, and the scan its arithmetic written out here, on - * random and on tied ranks, with the outputs' pitch padding untouched. */ + * router_sigmoid_topk from the same unit: the wave-per-row select must match a serial scan written + * out here bit for bit, on random and on tied ranks, with the outputs' pitch padding untouched. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" #include "ref_host.h" #include #include -#include #include #include #include -static float legacy_model(const uint16_t* x, const float* w, int k) { +extern const char* emu_last_kernel; + +static float gemm_model(const uint16_t* x, const float* w, int k) { float lane[32]; for (int l = 0; l < 32; ++l) { float s = 0; @@ -115,62 +115,41 @@ static void router_cases(std::mt19937& rng, int& cases, int& fails) { a.n_t = 4; a.p = p; a.n_p = 6; - auto run = [&](const char* form, std::vector& ids, std::vector& w) { - ids.assign((size_t)M * ip, -77); - w.assign((size_t)M * wp, -7.25f); - t[2].data = ids.data(); - t[3].data = w.data(); - if (form) - setenv("RADIANCE_ROUTER_SELECT", form, 1); - else - unsetenv("RADIANCE_ROUTER_SELECT"); - return r4d_rad_router_sigmoid_topk(&a, nullptr); - }; - std::vector ids_old, ids_new; - std::vector w_old, w_new; + std::vector ids((size_t)M * ip, -77); + std::vector w((size_t)M * wp, -7.25f); + t[2].data = ids.data(); + t[3].data = w.data(); ++cases; - if (run("old", ids_old, w_old) != RAD_OK) { - std::printf("FAIL router scan launch M=%d ne=%d\n", M, ne); - ++fails; - continue; - } + const int rc = r4d_rad_router_sigmoid_topk(&a, nullptr); int bad = 0; - for (int r = 0; r < M; ++r) { + for (int r = 0; r < M && rc == RAD_OK; ++r) { int mi[32]; float mw[32]; router_model(&lg[(size_t)r * lp], bias.data(), bp, ne, k, sh.norm, factor, mi, mw); - bad += std::memcmp(mi, &ids_old[(size_t)r * ip], (size_t)k * 4) != 0; - bad += std::memcmp(mw, &w_old[(size_t)r * wp], (size_t)k * 4) != 0; - for (int c = k; c < ip; ++c) bad += ids_old[(size_t)r * ip + c] != -77; - for (int c = k; c < wp; ++c) bad += w_old[(size_t)r * wp + c] != -7.25f; + bad += std::memcmp(mi, &ids[(size_t)r * ip], (size_t)k * 4) != 0; + bad += std::memcmp(mw, &w[(size_t)r * wp], (size_t)k * 4) != 0; + for (int c = k; c < ip; ++c) bad += ids[(size_t)r * ip + c] != -77; + for (int c = k; c < wp; ++c) bad += w[(size_t)r * wp + c] != -7.25f; } - if (bad) { - std::printf("FAIL router scan against its model at M=%d ne=%d k=%d: %d\n", M, ne, k, - bad); - ++fails; - } - ++cases; - const int rc = run(nullptr, ids_new, w_new); - if (rc != RAD_OK || ids_new != ids_old || - std::memcmp(w_new.data(), w_old.data(), w_new.size() * 4) != 0) { - std::printf("FAIL router wave select at M=%d ne=%d k=%d%s (rc %d)\n", M, ne, k, - sh.ties ? " tied" : "", rc); + if (rc != RAD_OK || bad) { + std::printf("FAIL router wave select against the scan at M=%d ne=%d k=%d%s (rc %d): " + "%d\n", + M, ne, k, sh.ties ? " tied" : "", rc, bad); ++fails; } } - unsetenv("RADIANCE_ROUTER_SELECT"); } int main() { std::mt19937 rng(17); std::normal_distribution nd(0.f, 1.f); - const char* forms[] = { "1x1", "2x1", "4x1", "8x1", "4x2", "8x2", - "4x4", "8x4", "16x2", "16x4", nullptr }; struct Shape { int M, N, K; }; - const Shape shapes[] = { { 1, 288, 512 }, { 3, 36, 129 }, { 8, 288, 129 }, { 33, 32, 512 }, - { 70, 36, 129 }, { 70, 4, 512 }, { 7, 31, 129 }, { 65, 13, 130 } }; + // One wave an output (M 1), the 2x1, 4x1 (M under 16 or N up to 8), 4x4 and 8x4 tiles. + const Shape shapes[] = { { 1, 288, 512 }, { 2, 288, 129 }, { 3, 36, 129 }, + { 8, 288, 129 }, { 33, 32, 512 }, { 70, 36, 129 }, + { 70, 4, 512 }, { 7, 31, 129 }, { 65, 13, 130 } }; int fails = 0, cases = 0; for (const Shape& sh : shapes) { const int M = sh.M, N = sh.N, K = sh.K, xp = K + 5, yp = N + 3; @@ -211,49 +190,24 @@ int main() { a.n_t = 3; a.p = p; a.n_p = 4; - auto run = [&](const char* form, std::vector& y) { - y.assign((size_t)M * yp, -7.25f); - t[2].data = y.data(); - if (form) - setenv("RADIANCE_F32_GEMM_TILE", form, 1); - else - unsetenv("RADIANCE_F32_GEMM_TILE"); - return r4d_rad_gemm_nt_f32(&a, nullptr); - }; - std::vector legacy, got; + std::vector y((size_t)M * yp, -7.25f); + t[2].data = y.data(); ++cases; - if (run("legacy", legacy) != RAD_OK) { - std::printf("FAIL legacy launch M=%d N=%d K=%d\n", M, N, K); - ++fails; - continue; - } + const int rc = r4d_rad_gemm_nt_f32(&a, nullptr); int bad = 0; - for (int r = 0; r < M; ++r) { + for (int r = 0; r < M && rc == RAD_OK; ++r) { for (int c = 0; c < N; ++c) { - const float e = legacy_model(&x[(size_t)r * xp], &w[(size_t)c * K], K); - bad += std::memcmp(&e, &legacy[(size_t)r * yp + c], 4) != 0; + const float e = gemm_model(&x[(size_t)r * xp], &w[(size_t)c * K], K); + bad += std::memcmp(&e, &y[(size_t)r * yp + c], 4) != 0; } - for (int c = N; c < yp; ++c) bad += legacy[(size_t)r * yp + c] != -7.25f; + for (int c = N; c < yp; ++c) bad += y[(size_t)r * yp + c] != -7.25f; } - if (bad) { - std::printf("FAIL legacy kernel against its model at M=%d N=%d K=%d: %d words\n", M, N, - K, bad); + if (rc != RAD_OK || bad) { + std::printf("FAIL %s at M=%d N=%d K=%d against its model (rc %d): %d words\n", + emu_last_kernel, M, N, K, rc, bad); ++fails; } - for (const char* const* f = forms;; ++f) { - ++cases; - const int rc = run(*f, got); - const bool same = - rc == RAD_OK && std::memcmp(got.data(), legacy.data(), got.size() * 4) == 0; - if (!same) { - std::printf("FAIL form %s at M=%d N=%d K=%d (rc %d)\n", *f ? *f : "default", M, N, - K, rc); - ++fails; - } - if (!*f) break; - } } - unsetenv("RADIANCE_F32_GEMM_TILE"); router_cases(rng, cases, fails); std::printf("%d case(s), %d failure(s)\n", cases, fails); return fails ? 1 : 0; diff --git a/tests/r4d_emu/test_fp8f32.cpp b/tests/r4d_emu/test_fp8f32.cpp index e68543e5..a8eadeec 100644 --- a/tests/r4d_emu/test_fp8f32.cpp +++ b/tests/r4d_emu/test_fp8f32.cpp @@ -1,20 +1,22 @@ /* tests/r4d_emu: the dense E4M3 GEMM with F32 block scales (r4d_fp8_f32scale.hip) on the host SIMT - * emulator. The decode and row-tile forms (RADIANCE_FP8F32_FORM, each R x S x C and row count) must - * match the legacy 16x64 tile - * bit for bit: the same fragments, the same mma chain per 128-K block and the same fold order. - * Ragged row counts, pitched rows and a K that leaves the decode form's last wave group partly - * idle are covered; the output's pitch padding stays untouched. */ + * emulator. The form the rule picks at each shape (the decode form at one and two column tiles a + * wave and one to eight waves a block, the 16- and 32-row tiles) must match the legacy 16x64 tile, + * which serves an activation pitch off 16 bytes, bit for bit: the same fragments, the same mma + * chain per 128-K block and the same fold order. Ragged row counts, pitched rows and a K that + * leaves the decode form's last wave group partly idle are covered; the output's pitch padding + * stays untouched. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" #include "ref_host.h" #include #include -#include #include #include #include +extern const char* emu_last_kernel; + static RadTensor mat(void* p, uint32_t dt, int64_t rows, int64_t cols, int64_t ld) { RadTensor t{}; t.data = p; @@ -32,19 +34,26 @@ int main() { std::normal_distribution nd(0.f, 1.f); struct Shape { int M, N, K; + const char* kernel; }; - const Shape shapes[] = { { 1, 256, 512 }, { 6, 128, 1536 }, { 17, 256, 512 }, - { 48, 128, 512 }, { 70, 128, 384 }, { 130, 128, 256 }, - { 3, 128, 4096 } }; - const char* forms[] = { "decode", "decode1x4", "decode1x32", "decode2x8", - "decode3x16", "decode1x8x2", "decode1x4x4", "decode2x8x2", - "decode3x4x2", "decode2x4x4", "rows1", "rows2", - "rows4", nullptr }; + const char* const dec1 = "(fp8_f32scale_decode<1, 1>)"; + const char* const dec2 = "(fp8_f32scale_decode<1, 2>)"; + const char* const rows = "fp8_f32scale_rows"; + // Decode at eight, four, two and one waves a block (K blocks 12/32, 4, 2, 1), at two column + // tiles a wave from 17 rows over N 1024 and 640; the 16-row tile, and the 32-row one at N 4096. + const Shape shapes[] = { { 1, 256, 512, dec1 }, { 6, 128, 1536, dec1 }, + { 17, 256, 512, dec1 }, { 48, 128, 512, dec1 }, + { 2, 128, 256, dec1 }, { 5, 256, 128, dec1 }, + { 3, 128, 4096, dec1 }, { 40, 1024, 512, dec2 }, + { 20, 640, 256, dec2 }, { 70, 128, 384, rows }, + { 130, 128, 256, rows }, { 33, 4096, 512, rows }, + { 70, 4096, 128, rows } }; int fails = 0, cases = 0; for (const Shape& sh : shapes) { - const int M = sh.M, N = sh.N, K = sh.K, kb = K / 128, ap = K + 16, yp = N + 8; - std::vector a((size_t)M * ap), w((size_t)N * K); + const int M = sh.M, N = sh.N, K = sh.K, kb = K / 128, ap = K + 16, lp = K + 8, yp = N + 8; + std::vector a((size_t)M * ap), al((size_t)M * lp), w((size_t)N * K); for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng)); + for (int r = 0; r < M; ++r) std::memcpy(&al[(size_t)r * lp], &a[(size_t)r * ap], K); for (auto& v : w) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f); std::vector as((size_t)M * kb), ws((size_t)(N / 128) * kb); // Scales over twelve octaves: K blocks of very different weight cancel, so a changed @@ -67,10 +76,12 @@ int main() { p[4].key = "dtype"; p[4].kind = RAD_P_STR; p[4].sval = "fp8a8f32"; - auto run = [&](const char* form, std::vector& y) { + // The pitch off 16 bytes takes the legacy tile. + auto run = [&](bool legacy, std::vector& y) { y.assign((size_t)M * yp, 0x7777); + t[0] = legacy ? mat(al.data(), RAD_F8E4M3, M, K, lp) + : mat(a.data(), RAD_F8E4M3, M, K, ap); t[4] = mat(y.data(), RAD_BF16, M, N, yp); - setenv("RADIANCE_FP8F32_FORM", form, 1); RadArgs ar{}; ar.t = t; ar.n_t = 7; @@ -80,8 +91,8 @@ int main() { }; std::vector legacy, got; ++cases; - if (run("legacy", legacy) != RAD_OK) { - std::printf("FAIL legacy M=%d N=%d K=%d\n", M, N, K); + if (run(true, legacy) != RAD_OK || std::strcmp(emu_last_kernel, "fp8_f32scale")) { + std::printf("FAIL legacy M=%d N=%d K=%d ran %s\n", M, N, K, emu_last_kernel); ++fails; continue; } @@ -92,19 +103,16 @@ int main() { std::printf("FAIL legacy output mostly zero at M=%d\n", M); ++fails; } - for (const char* const* f = forms; *f; ++f) { - ++cases; - const int rc = run(*f, got); - if (rc != RAD_OK || got != legacy) { - size_t i = 0; - while (rc == RAD_OK && i < got.size() && got[i] == legacy[i]) ++i; - std::printf("FAIL form %s at M=%d N=%d K=%d (rc %d, first word %zu)\n", *f, M, N, K, - rc, i); - ++fails; - } + ++cases; + const int rc = run(false, got); + if (rc != RAD_OK || std::strcmp(emu_last_kernel, sh.kernel) || got != legacy) { + size_t i = 0; + while (rc == RAD_OK && i < got.size() && got[i] == legacy[i]) ++i; + std::printf("FAIL %s (want %s) at M=%d N=%d K=%d (rc %d, first word %zu)\n", + emu_last_kernel, sh.kernel, M, N, K, rc, i); + ++fails; } } - unsetenv("RADIANCE_FP8F32_FORM"); std::printf("%d case(s), %d failure(s)\n", cases, fails); return fails ? 1 : 0; } diff --git a/tests/r4d_emu/test_kda.cpp b/tests/r4d_emu/test_kda.cpp index 65cdba48..72c36fcc 100644 --- a/tests/r4d_emu/test_kda.cpp +++ b/tests/r4d_emu/test_kda.cpp @@ -1,15 +1,19 @@ -/* tests/r4d_emu: kda_update (r4d_kda.hip) on the host SIMT emulator. Every row and prefetch form - * must give the old one-row kernel's output and whole state buffer bit for bit, in all four modes: - * prefill per candidate and anchored, verify per candidate and anchored (after the replay of the - * accepted prefix). Cold starts, an unseated sequence, an empty sequence and an unwritten slot - * are mixed in. The GPU check of the same claim is r4d_selftest's kda_forms. */ +/* tests/r4d_emu: kda_update (r4d_kda.hip) on the host SIMT emulator, held to libref's kda_update + * (from $RADIANCE_HOME, which ctest sets) over the output and the whole state buffer, in all four + * modes: prefill per candidate and anchored, verify per candidate and anchored (after the replay + * of the accepted prefix). Cold starts, an unseated sequence, an empty sequence and an unwritten + * slot are mixed in, so a byte the reference leaves alone must stay as it was. The kernel's lane + * reductions sum in another order than libref's loops: f32 state within 2e-5 + 2e-5 |x|, bf16 + * output within one rounding step. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" +#include #include #include #include #include +#include #include #include #include @@ -33,6 +37,32 @@ static uint16_t f2b(float f) { return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); } +/* libref's kda_update, through the plugin's own exports, or null. */ +static RadLaunchFn load_libref() { + const char* home = std::getenv("RADIANCE_HOME"); + if (!home || !*home) return nullptr; + const std::string p = std::string(home) + "/kernels/libref.so"; + void* h = dlopen(p.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!h) return nullptr; + auto open = (int (*)(void))dlsym(h, "rad_plugin_open"); /* as the loader does */ + if (open && open() < 0) return nullptr; + auto cnt = (int (*)(void))dlsym(h, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(h, "rad_kernel_at"); + if (!cnt || !at) return nullptr; + for (int i = 0; i < cnt(); ++i) { + const RadKernelInfo* k = at(i); + if (k && k->op && !std::strcmp(k->op, "kda_update")) return k->launch; + } + return nullptr; +} + +static float bf16_value(uint16_t b) { + const uint32_t u = (uint32_t)b << 16; + float f; + std::memcpy(&f, &u, 4); + return f; +} + struct Case { const char* name; const char* mode; @@ -43,6 +73,11 @@ struct Case { }; int main() { + const RadLaunchFn reference = load_libref(); + if (!reference) { + std::printf("FAIL libref's kda_update not loadable (set RADIANCE_HOME)\n"); + return 1; + } std::mt19937 rng(41); std::uniform_real_distribution u(-1.f, 1.f); const int64_t H = 2, D = 128, slots = 16, tokens = 9; @@ -93,12 +128,6 @@ int main() { { 1, 1, 0 }, { { 5, 4.f }, { 6, 3.f }, { 7, 0.f } } }, }; - struct Form { - const char* rows; - const char* prefetch; - }; - const Form forms[] = { { "1", "1" }, { "2", "1" }, { "4", "1" }, - { "1", "0" }, { "2", "0" }, { "4", "0" } }; int fails = 0, checks = 0; for (const Case& c : cases) { std::vector start = state0; @@ -106,7 +135,7 @@ int main() { for (int64_t h = 0; h < H; ++h) start[(size_t)((sc.first * H + h) * D * D)] = sc.second; const int64_t seqs = (int64_t)c.cu.size() - 1; std::vector idx = c.idx, cu = c.cu, acc = c.accepted, init = c.init; - auto run = [&](std::vector& out, std::vector& state) { + auto run = [&](RadLaunchFn launch, std::vector& out, std::vector& state) { out.assign((size_t)(tokens * H * D), 0x7777); state = start; RadTensor t[13] = { tens(in[0].data(), RAD_BF16, { tokens, H, D }), @@ -149,39 +178,40 @@ int main() { a.n_t = 13; a.p = p; a.n_p = 9; - return r4d_rad_kda_update(&a, nullptr); + return launch(&a, nullptr); }; std::vector ref_out, out; std::vector ref_state, state; - setenv("RADIANCE_KDA_FORM", "old", 1); - if (run(ref_out, ref_state) != RAD_OK) { - std::printf("FAIL %s: old form refused\n", c.name); + ++checks; + if (run(reference, ref_out, ref_state) != RAD_OK || + run(r4d_rad_kda_update, out, state) != RAD_OK) { + std::printf("FAIL %s: refused\n", c.name); ++fails; continue; } - unsetenv("RADIANCE_KDA_FORM"); bool written = false; for (size_t i = 0; i < ref_out.size(); ++i) written = written || ref_out[i] != 0x7777; - if (!written) { - std::printf("FAIL %s: the old form wrote no output\n", c.name); - ++fails; + size_t bad = 0; + double out_err = 0, state_err = 0; + for (size_t i = 0; i < out.size(); ++i) { + if (out[i] == ref_out[i]) continue; + const float x = bf16_value(out[i]), y = bf16_value(ref_out[i]); + const double e = std::fabs((double)x - y); + out_err = std::max(out_err, e); + if (!std::isfinite(x) || ref_out[i] == 0x7777 || out[i] == 0x7777 || + e > 1e-6 + 0.008 * std::fabs(y)) + ++bad; } - for (const Form& f : forms) { - setenv("RADIANCE_KDA_ROWS", f.rows, 1); - setenv("RADIANCE_KDA_PREFETCH", f.prefetch, 1); - ++checks; - const bool same = run(out, state) == RAD_OK && out == ref_out && - std::memcmp(state.data(), ref_state.data(), state.size() * 4) == 0; - if (!same) { - ++fails; - std::printf("FAIL %s, %s rows a wave, prefetch %s: differs from the old form\n", - c.name, f.rows, f.prefetch); - } + for (size_t i = 0; i < state.size(); ++i) { + if (state[i] == ref_state[i]) continue; + const double e = std::fabs((double)state[i] - ref_state[i]); + state_err = std::max(state_err, e); + if (!std::isfinite(state[i]) || e > 2e-5 + 2e-5 * std::fabs(ref_state[i])) ++bad; } - unsetenv("RADIANCE_KDA_ROWS"); - unsetenv("RADIANCE_KDA_PREFETCH"); + std::printf("%-24s output max %.3g, state max %.3g%s\n", c.name, out_err, state_err, + !written ? " NO OUTPUT" : bad ? " FAIL" : ""); + if (!written || bad) ++fails; } - std::printf("kda_update forms against the old kernel: %d of %d bit-identical\n", checks - fails, - checks); + std::printf("kda_update against libref: %d of %d within bounds\n", checks - fails, checks); return fails ? 1 : 0; } diff --git a/tests/r4d_emu/test_mhc.cpp b/tests/r4d_emu/test_mhc.cpp index 82bd77e6..520942bf 100644 --- a/tests/r4d_emu/test_mhc.cpp +++ b/tests/r4d_emu/test_mhc.cpp @@ -1,8 +1,9 @@ /* tests/r4d_emu: GLM's mHC read split by residual chunks (r4d_mhc.hip) on the host SIMT emulator. * Each rank's mhc_pre_partial over its chunks, the partials joined row by row as the * row-interleaved all_gather lays them out, then mhc_pre_finish, must give mhc_pre's x, post and - * comb bit for bit, under each of mhc_pre's kernel switches; the partial matrix's padding slots - * are zero. Every form is also held to the old dispatch, bit for bit. */ + * comb bit for bit; the partial matrix's padding slots are zero. On 16-byte rows the vector forms + * run, and they are held bit for bit to the same operands on pitched rows, where the scalar forms + * run. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" @@ -42,148 +43,123 @@ int main() { std::vector fn((size_t)(mix * W)), scale = { 0.7f, 0.9f, 1.1f }, base((size_t)mix); for (auto& v : fn) v = nd(rng) * 0.01f; for (auto& v : base) v = nd(rng) * 0.5f; - struct Form { - const char* env; - const char* value; - }; - const Form forms[] = { { nullptr, nullptr }, - { "RADIANCE_MHC_PREFILL_COEFF4", "0" }, - { "RADIANCE_MHC_PREFILL_ROWS4", "0" }, - { "RADIANCE_MHC_PREFILL_WARP", "0" } }; int fails = 0, cases = 0; for (int64_t rows : { 1, 5, 37 }) { const int64_t hp = W + 6, xp = n + 2; std::vector h((size_t)(rows * hp)); for (auto& v : h) v = f2b(nd(rng)); - for (const Form& f : forms) { - if (f.env) setenv(f.env, f.value, 1); - RadParam coef[8]{}; - coef[0] = { "M", RAD_P_INT, rows }; - coef[1] = { "n", RAD_P_INT, n }; - coef[2] = { "hc", RAD_P_INT, hc }; - coef[3] = { "iterations", RAD_P_INT, 20 }; - coef[4].key = "eps"; - coef[4].kind = RAD_P_F64; - coef[4].dval = 1e-5; - coef[5].key = "hc_eps"; - coef[5].kind = RAD_P_F64; - coef[5].dval = 1e-6; - coef[6].key = "dtype"; - coef[6].kind = RAD_P_STR; - coef[6].sval = "bf16"; - std::vector x((size_t)(rows * xp), 0x7777); - std::vector post((size_t)(rows * hc)), comb((size_t)(rows * hc * hc)); - RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, hp), - mat(fn.data(), RAD_F32, mix, W, W), - vec(scale.data(), 3), - vec(base.data(), mix), - mat(x.data(), RAD_BF16, rows, n, xp), - mat(post.data(), RAD_F32, rows, hc, hc), - mat(comb.data(), RAD_F32, rows, hc * hc, hc * hc) }; - RadArgs a{}; - a.t = t; - a.n_t = 7; - a.p = coef; - a.n_p = 7; - if (r4d_rad_mhc_pre(&a, nullptr) != RAD_OK) { - std::printf("FAIL mhc_pre M=%lld\n", (long long)rows); + RadParam coef[8]{}; + coef[0] = { "M", RAD_P_INT, rows }; + coef[1] = { "n", RAD_P_INT, n }; + coef[2] = { "hc", RAD_P_INT, hc }; + coef[3] = { "iterations", RAD_P_INT, 20 }; + coef[4].key = "eps"; + coef[4].kind = RAD_P_F64; + coef[4].dval = 1e-5; + coef[5].key = "hc_eps"; + coef[5].kind = RAD_P_F64; + coef[5].dval = 1e-6; + coef[6].key = "dtype"; + coef[6].kind = RAD_P_STR; + coef[6].sval = "bf16"; + std::vector x((size_t)(rows * xp), 0x7777); + std::vector post((size_t)(rows * hc)), comb((size_t)(rows * hc * hc)); + RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, hp), + mat(fn.data(), RAD_F32, mix, W, W), + vec(scale.data(), 3), + vec(base.data(), mix), + mat(x.data(), RAD_BF16, rows, n, xp), + mat(post.data(), RAD_F32, rows, hc, hc), + mat(comb.data(), RAD_F32, rows, hc * hc, hc * hc) }; + RadArgs a{}; + a.t = t; + a.n_t = 7; + a.p = coef; + a.n_p = 7; + if (r4d_rad_mhc_pre(&a, nullptr) != RAD_OK) { + std::printf("FAIL mhc_pre M=%lld\n", (long long)rows); + ++fails; + continue; + } + for (int world : { 2, 4, 8 }) { + ++cases; + const int64_t mine = total / world; + std::vector gathered((size_t)(rows * total * S)); + bool padded = true, launched = true; + for (int rank = 0; rank < world; ++rank) { + std::vector part((size_t)(rows * mine * S), 7.0f); + RadTensor pt[3] = { t[0], t[1], + mat(part.data(), RAD_F32, rows, mine * S, mine * S) }; + RadParam pp[7]{}; + pp[0] = { "M", RAD_P_INT, rows }; + pp[1] = { "n", RAD_P_INT, n }; + pp[2] = { "hc", RAD_P_INT, hc }; + pp[3] = { "chunk", RAD_P_INT, 2048 }; + pp[4] = { "first", RAD_P_INT, rank * mine }; + pp[5] = { "chunks", RAD_P_INT, mine }; + pp[6].key = "dtype"; + pp[6].kind = RAD_P_STR; + pp[6].sval = "bf16"; + RadArgs pa{}; + pa.t = pt; + pa.n_t = 3; + pa.p = pp; + pa.n_p = 7; + launched = launched && r4d_rad_mhc_pre_partial(&pa, nullptr) == RAD_OK; + for (int64_t r = 0; r < rows; ++r) { + for (int64_t c = 0; c < mine; ++c) + for (int64_t j = mix + 1; j < S; ++j) + padded = padded && part[(size_t)(r * mine * S + c * S + j)] == 0.0f; + std::memcpy(&gathered[(size_t)(r * total * S + rank * mine * S)], + &part[(size_t)(r * mine * S)], (size_t)(mine * S * 4)); + } + } + std::vector x2((size_t)(rows * xp), 0x7777); + std::vector post2(post.size()), comb2(comb.size()); + RadTensor ft[7] = { mat(gathered.data(), RAD_F32, rows, total * S, total * S), + t[0], + t[2], + t[3], + mat(x2.data(), RAD_BF16, rows, n, xp), + mat(post2.data(), RAD_F32, rows, hc, hc), + mat(comb2.data(), RAD_F32, rows, hc * hc, hc * hc) }; + RadParam fp[8]; + std::memcpy(fp, coef, sizeof coef); + fp[6] = { "chunk", RAD_P_INT, 2048 }; + fp[7].key = "dtype"; + fp[7].kind = RAD_P_STR; + fp[7].sval = "bf16"; + RadArgs fa{}; + fa.t = ft; + fa.n_t = 7; + fa.p = fp; + fa.n_p = 8; + launched = launched && r4d_rad_mhc_pre_finish(&fa, nullptr) == RAD_OK; + const bool same = launched && x2 == x && + std::memcmp(post2.data(), post.data(), post.size() * 4) == 0 && + std::memcmp(comb2.data(), comb.data(), comb.size() * 4) == 0; + if (!same || !padded) { + std::printf("FAIL M=%lld world %d: %s\n", (long long)rows, world, + !launched ? "launch" + : !padded ? "padding" + : "differs"); ++fails; - continue; } - for (int world : { 2, 4, 8 }) { - ++cases; - const int64_t mine = total / world; - std::vector gathered((size_t)(rows * total * S)); - bool padded = true, launched = true; - for (int rank = 0; rank < world; ++rank) { - std::vector part((size_t)(rows * mine * S), 7.0f); - RadTensor pt[3] = { t[0], t[1], - mat(part.data(), RAD_F32, rows, mine * S, mine * S) }; - RadParam pp[7]{}; - pp[0] = { "M", RAD_P_INT, rows }; - pp[1] = { "n", RAD_P_INT, n }; - pp[2] = { "hc", RAD_P_INT, hc }; - pp[3] = { "chunk", RAD_P_INT, 2048 }; - pp[4] = { "first", RAD_P_INT, rank * mine }; - pp[5] = { "chunks", RAD_P_INT, mine }; - pp[6].key = "dtype"; - pp[6].kind = RAD_P_STR; - pp[6].sval = "bf16"; - RadArgs pa{}; - pa.t = pt; - pa.n_t = 3; - pa.p = pp; - pa.n_p = 7; - launched = launched && r4d_rad_mhc_pre_partial(&pa, nullptr) == RAD_OK; - for (int64_t r = 0; r < rows; ++r) { - for (int64_t c = 0; c < mine; ++c) - for (int64_t j = mix + 1; j < S; ++j) - padded = padded && part[(size_t)(r * mine * S + c * S + j)] == 0.0f; - std::memcpy(&gathered[(size_t)(r * total * S + rank * mine * S)], - &part[(size_t)(r * mine * S)], (size_t)(mine * S * 4)); - } - } - std::vector x2((size_t)(rows * xp), 0x7777); - std::vector post2(post.size()), comb2(comb.size()); - RadTensor ft[7] = { mat(gathered.data(), RAD_F32, rows, total * S, total * S), - t[0], - t[2], - t[3], - mat(x2.data(), RAD_BF16, rows, n, xp), - mat(post2.data(), RAD_F32, rows, hc, hc), - mat(comb2.data(), RAD_F32, rows, hc * hc, hc * hc) }; - RadParam fp[8]; - std::memcpy(fp, coef, sizeof coef); - fp[6] = { "chunk", RAD_P_INT, 2048 }; - fp[7].key = "dtype"; - fp[7].kind = RAD_P_STR; - fp[7].sval = "bf16"; - RadArgs fa{}; - fa.t = ft; - fa.n_t = 7; - fa.p = fp; - fa.n_p = 8; - launched = launched && r4d_rad_mhc_pre_finish(&fa, nullptr) == RAD_OK; - const bool same = launched && x2 == x && - std::memcmp(post2.data(), post.data(), post.size() * 4) == 0 && - std::memcmp(comb2.data(), comb.data(), comb.size() * 4) == 0; - if (!same || !padded) { - std::printf("FAIL M=%lld world %d %s%s%s: %s\n", (long long)rows, world, - f.env ? f.env : "default", f.env ? "=" : "", f.env ? f.value : "", - !launched ? "launch" - : !padded ? "padding" - : "differs"); - ++fails; - } - } - if (f.env) unsetenv(f.env); } } - /* Every form against the old dispatch (one-wave finish from 32 rows, scalar mix and read - * below, scalar-row and rows4 partials, the per-output mhc_post) on 16-byte rows, where the - * vector paths run: mhc_pre's x, post and comb, mhc_pre_partial's matrix and mhc_post's - * output, bit for bit. */ - struct Pin { - const char* what; - const char* finish; - const char* vec; - const char* prow; - }; - const Pin pins[] = { { "rule", nullptr, nullptr, nullptr }, - { "finish scalar", "scalar", nullptr, nullptr }, - { "partials four-slot, 1 row a wave", nullptr, "1", "1" }, - { "partials four-slot, 2 rows a wave", nullptr, "1", "2" }, - { "partials four-slot, 4 rows a wave", nullptr, "1", "4" } }; - auto pin = [](const char* k, const char* v) { - if (v) - setenv(k, v, 1); - else - unsetenv(k); - }; + /* The vector forms (four-slot partials, the finish's 16-byte collapse, the eight-column + * mhc_post) on 16-byte rows against the scalar forms (one slot a thread, four rows and four + * coefficients a block from 32 rows, the per-output mhc_post) on the same operands with the + * residual pitched by two elements: mhc_pre's x, post and comb, mhc_pre_partial's matrix and + * mhc_post's output, bit for bit. */ for (int64_t rows : { 1, 5, 16, 37, 64 }) { std::vector h((size_t)(rows * W)), y((size_t)(rows * n)); for (auto& v : h) v = f2b(nd(rng)); for (auto& v : y) v = f2b(nd(rng)); + const int64_t pitched = W + 2; + std::vector hp((size_t)(rows * pitched), 0x7777); + for (int64_t r = 0; r < rows; ++r) + std::memcpy(&hp[(size_t)(r * pitched)], &h[(size_t)(r * W)], (size_t)W * 2); RadParam coef[7]{}; coef[0] = { "M", RAD_P_INT, rows }; coef[1] = { "n", RAD_P_INT, n }; @@ -202,13 +178,13 @@ int main() { std::vector x, o; std::vector p, c, part; }; - auto run = [&](Out* r) { + auto run = [&](Out* r, const uint16_t* hd, int64_t ld) { r->x.assign((size_t)(rows * n), 0x7777); r->o.assign((size_t)(rows * W), 0x7777); r->p.assign((size_t)(rows * hc), 0); r->c.assign((size_t)(rows * hc * hc), 0); r->part.assign((size_t)(rows * total * S), 7.0f); - RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, W), + RadTensor t[7] = { mat((void*)hd, RAD_BF16, rows, W, ld), mat(fn.data(), RAD_F32, mix, W, W), vec(scale.data(), 3), vec(base.data(), mix), @@ -249,34 +225,21 @@ int main() { return okay && r4d_rad_mhc_post(&oa, nullptr) == RAD_OK; }; Out ref, got; - pin("RADIANCE_MHC_FINISH", "old"); - pin("RADIANCE_MHC_PARTIAL_VEC", "0"); - pin("RADIANCE_MHC_POST_VEC", "0"); - const bool ref_ok = run(&ref); - pin("RADIANCE_MHC_POST_VEC", nullptr); - for (const Pin& f : pins) { - ++cases; - pin("RADIANCE_MHC_FINISH", f.finish); - pin("RADIANCE_MHC_PARTIAL_VEC", f.vec); - pin("RADIANCE_MHC_PARTIAL_ROWS", f.prow); - const bool launched = ref_ok && run(&got); - const char* bad = !launched ? "launch" - : got.x != ref.x ? "x" - : std::memcmp(got.p.data(), ref.p.data(), ref.p.size() * 4) ? "post" - : std::memcmp(got.c.data(), ref.c.data(), ref.c.size() * 4) ? "comb" - : std::memcmp(got.part.data(), ref.part.data(), ref.part.size() * 4) - ? "partials" - : got.o != ref.o ? "mhc_post" - : nullptr; - if (bad) { - std::printf("FAIL M=%lld %s against the old dispatch: %s differs\n", - (long long)rows, f.what, bad); - ++fails; - } + ++cases; + const bool launched = run(&ref, hp.data(), pitched) && run(&got, h.data(), W); + const char* bad = !launched ? "launch" + : got.x != ref.x ? "x" + : std::memcmp(got.p.data(), ref.p.data(), ref.p.size() * 4) ? "post" + : std::memcmp(got.c.data(), ref.c.data(), ref.c.size() * 4) ? "comb" + : std::memcmp(got.part.data(), ref.part.data(), ref.part.size() * 4) + ? "partials" + : got.o != ref.o ? "mhc_post" + : nullptr; + if (bad) { + std::printf("FAIL M=%lld 16-byte rows against pitched rows: %s differs\n", + (long long)rows, bad); + ++fails; } - for (const char* k : - { "RADIANCE_MHC_FINISH", "RADIANCE_MHC_PARTIAL_VEC", "RADIANCE_MHC_PARTIAL_ROWS" }) - unsetenv(k); } std::printf("%d case(s), %d failure(s)\n", cases, fails); return fails ? 1 : 0; diff --git a/tests/r4d_emu/test_mla.cpp b/tests/r4d_emu/test_mla.cpp index fd8d5330..95d125c7 100644 --- a/tests/r4d_emu/test_mla.cpp +++ b/tests/r4d_emu/test_mla.cpp @@ -3,7 +3,9 @@ * tile (eight heads of two neighbouring rows) on the tables it meets in serving: a prefill chunk * whose rows share one table, and rows past the DSA budget, where each row selects its own top * blocks and neighbours share most blocks but rarely a table position. The conflict counters - * (RADIANCE_MLA_CONFLICT_STATS) show which of the two the pairing saw. */ + * (RADIANCE_MLA_CONFLICT_STATS) show which of the two the pairing saw. Both pairings run on the + * same operands: the union at the case's table width, the positional pairing on the table + * widened past the union's lists (kUnionBlocks, 520 entries) with absent entries no row reaches. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" @@ -22,7 +24,7 @@ extern "C" void r4d_mla_matrix_stats(unsigned long long* out); namespace { -constexpr int D = 512, BS = 4; +constexpr int D = 512, BS = 4, kUnionBlocks = 520; enum class Fill { prefill, topk, ragged, repeat }; @@ -35,6 +37,7 @@ struct Case { bool scratch = false; /* lets the launcher split the history */ int form = 0; /* r4d_mla_matrix_pin_form */ int expect_second = -1; /* positional pairing: 0 no second pass, 1 some, -1 either */ + /* Unsplit only: with scratch the widened table gives the positional run more splits. */ bool bitwise_a = true; /* the union's request r equals the positional pairing's bit for bit */ bool bitwise_all = false; /* both requests do (the tables agree position by position) */ bool union_falls_back = false; /* the table is wider than the union's lists */ @@ -234,14 +237,24 @@ int run(const Case& c, std::mt19937& rng) { want[((size_t)r * H + h) * D + d] = sum > 0 ? acc[d] / sum : 0.0; } - /* Both pairings on the same operands: the positional one (RADIANCE_MLA_PAIR=pos) and the - * union, which must never take a second pass. */ + /* Both pairings on the same operands: the positional one, on the table widened past the + * union's lists, and at the case's own width the launcher's choice, the union, which must + * never take a second pass. A tile of 16 heads has no pairing and runs once. */ const bool paired = H % 16 == 8; + const int wide = std::max(B, kUnionBlocks + 1); + std::vector bt_wide((size_t)M * wide, -1); + for (int r = 0; r < M; ++r) + std::copy(bt.begin() + (size_t)r * B, bt.begin() + (size_t)(r + 1) * B, + bt_wide.begin() + (size_t)r * wide); std::vector by_pos; int fails = 0; for (const char* pairing : { "pos", "union" }) { - if (!paired && !std::strcmp(pairing, "union")) break; - setenv("RADIANCE_MLA_PAIR", pairing, 1); + const bool by_page = !std::strcmp(pairing, "union"); + if (!paired && by_page) break; + const bool widened = paired && !by_page; + t[2] = widened ? tens(bt_wide.data(), RAD_I32, { M, wide }) + : tens(bt.data(), RAD_I32, { M, B }); + p[3].ival = widened ? wide : B; std::fill(out.begin(), out.end(), 0xffff); unsigned long long stats[3]; r4d_mla_matrix_stats(stats); @@ -249,7 +262,6 @@ int run(const Case& c, std::mt19937& rng) { const int rc = r4d_rad_mla_attn_matrix(&a, nullptr); r4d_mla_matrix_pin_form(0); r4d_mla_matrix_stats(stats); - unsetenv("RADIANCE_MLA_PAIR"); if (rc != RAD_OK) { std::printf("%-40s %-5s launch returned %d\n", c.name.c_str(), pairing, rc); ++fails; @@ -265,7 +277,6 @@ int run(const Case& c, std::mt19937& rng) { } bool ok = bad == 0; std::string note; - const bool by_page = !std::strcmp(pairing, "union"); if (!by_page) { by_pos = out; if (c.expect_second >= 0 && (stats[1] > 0) != (c.expect_second == 1)) { @@ -297,11 +308,11 @@ int run(const Case& c, std::mt19937& rng) { std::snprintf(buf, sizeof buf, " vs pos: %zu/%zu differ (r/r+1), max abs %.2e", first_diff_a, diff_b, max_ab); note += buf; - if (c.bitwise_a && first_diff_a) { + if (c.bitwise_a && !c.scratch && first_diff_a) { note += " (request r differs)"; ok = false; } - if (c.bitwise_all && diff_b) { + if (c.bitwise_all && !c.scratch && diff_b) { note += " (request r+1 differs)"; ok = false; } diff --git a/tests/r4d_emu/test_moemx.cpp b/tests/r4d_emu/test_moemx.cpp index 1ef630ce..63f461b2 100644 --- a/tests/r4d_emu/test_moemx.cpp +++ b/tests/r4d_emu/test_moemx.cpp @@ -1,30 +1,28 @@ -/* tests/r4d_emu: the MXFP4 expert GEMM (r4d_moe_mxfp4.hip) on the host SIMT emulator. Every form - * the RADIANCE_MXFP4_* switches reach must match the arithmetic-decode row-group form bit for bit, - * and both a host restatement of the per-element sequence: per 128 of K in order, per 32-wide group - * a fresh 32-product sum in k order (the emulated WMMA pair), folded as raw * activation scale * - * E8M0 scale with two roundings and an add. Runs of 0, 1, 15, 16, 17, 63, 64, 65 and 130 rows, - * dropped slots inside runs and past the routed rows, columns an odd expert does not have, a - * shorter K for odd experts, E8M0 codes 0 and 255, parts 2, token and sorted rows, stacked planes - * and pointer tables. The P64 forms (RADIANCE_MXFP4_PREFILL_P64) run at every BM, BN, stage and - * column-tile count, pinned below their row bound, with jobs cut at 32 and 64 rows, column - * blocks past N and the output through LDS at aligned and odd pitches. The table decode is also - * held to the arithmetic one over every code. */ +/* tests/r4d_emu: the MXFP4 expert GEMM (r4d_moe_mxfp4.hip) on the host SIMT emulator. The form the + * rule picks at each case (named per case, so a moved bound shows) must match a host restatement + * of the per-element sequence bit for bit: per 128 of K in order, per 32-wide group a fresh + * 32-product sum in k order (the emulated WMMA pair), folded as raw * activation scale * E8M0 + * scale with two roundings and an add. Away from GLM's slices the expert-major forms (K 256 and a + * longer K) and the row groups; at GLM's TP4 down slice the GLM prefill form, at its TP8 gate_up + * slice the P64 form with streamed A. Runs of 0, 1, 15, 16, 17, 63, 64, 65 and 130 rows, dropped + * slots inside runs and past the routed rows, columns an odd expert does not have, a shorter K for + * odd experts, E8M0 codes 0 and 255, parts 2, token and sorted rows, stacked planes and pointer + * tables. The table decode is also held to the arithmetic one over every code. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" #include "r4d_mxfp4.h" #include #include -#include #include #include -#include #include extern const char* emu_last_kernel; -/* The arithmetic decode the kernels used before the table (r4d_moe_mxfp4.hip, fp4x4 and its - * byte interleave), restated as the reference of r4d_mxfp4_unpack8_exact. */ +/* The bytewise arithmetic decode, the reference of r4d_mxfp4_unpack8_exact: per byte, magnitudes + * from 2 map to (m + 12) * 4, 0 and 1 to 0 and 48, the sign to bit 7; then the low and high + * nibbles' bytes interleave in k order. */ static uint32_t fp4x4_ref(uint32_t n) { const uint32_t mag = n & 0x07070707u, flag = (mag + 0x06060606u) & 0x08080808u; const uint32_t mask = (flag << 5) - (flag >> 3); @@ -76,6 +74,7 @@ struct Case { bool sorted_a, tables, exceptional; std::vector runs; int tail; // dropped slots past the routed rows + const char* kernel; // the form the rule picks }; /* Byte equality with every bf16 NaN taken as one value. On x86 inf - inf gives the negative @@ -87,9 +86,6 @@ static size_t first_diff(const std::vector& a, const std::vector& a, const std::vector& b) { - return a.size() == b.size() && first_diff(a, b) == a.size(); -} static RadTensor ten(void* p, uint32_t dt, std::vector shape, std::vector stride) { @@ -104,18 +100,30 @@ static RadTensor ten(void* p, uint32_t dt, std::vector shape, return t; } +/* GLM's 288 experts: the given runs at experts spread over both classes, every other one empty. */ +static std::vector glm_runs(std::vector live) { + static const int at[] = { 2, 3, 50, 101, 150, 199, 200, 241, 286, 287 }; + std::vector runs(288, 0); + for (size_t i = 0; i < live.size() && i < sizeof at / sizeof at[0]; ++i) runs[at[i]] = live[i]; + return runs; +} + int main() { int fails = check_decode(), cases = 1; if (fails) std::printf("FAIL table decode: %d mismatches\n", fails); const std::vector runs9 = { 0, 1, 15, 16, 17, 63, 64, 65, 130, 141 }; + const char* const staged = "(moe_mxfp4_expert_staged_kernel<128, 4>)"; + const char* const expert = "(moe_mxfp4_expert_kernel<4, 256>)"; + const char* const groups = "moe_mxfp4_fp8_kernel"; const Case all[] = { - { "gate_up-like, token rows", 128, 384, 128, 384, 2, 4, false, false, false, runs9, 6 }, + { "gate_up-like, token rows", 128, 384, 128, 384, 2, 4, false, false, false, runs9, 6, + groups }, { "odd experts narrower and shorter", 128, 384, 64, 256, 2, 4, false, true, false, runs9, - 2 }, - { "down-like, sorted rows", 64, 256, 64, 256, 1, 2, true, true, false, runs9, 4 }, - { "exceptional E8M0 codes", 64, 256, 64, 256, 2, 4, false, false, true, runs9, 4 }, - { "decode band, row groups of 4", + 2, groups }, + { "down-like, sorted rows", 64, 256, 64, 256, 1, 2, true, true, false, runs9, 4, groups }, + { "exceptional E8M0 codes", 64, 256, 64, 256, 2, 4, false, false, true, runs9, 4, groups }, + { "expert-major, K 384", 64, 384, 64, @@ -126,8 +134,9 @@ int main() { true, false, { 0, 1, 15, 16, 17, 30 }, - 3 }, - { "decode band, row groups of 1", + 3, + expert }, + { "expert-major, K 256, exceptional codes", 64, 256, 32, @@ -138,8 +147,9 @@ int main() { false, true, { 1, 0, 3, 15, 1 }, - 2 }, - { "P64 jobs at 32 and 64 rows, N under a block", + 2, + staged }, + { "expert-major, K 512:384, runs past 64 rows, N under a block", 96, 512, 96, @@ -150,8 +160,9 @@ int main() { false, false, { 32, 33, 31, 96, 128, 129, 0, 2 }, - 9 }, - { "P64 resident A, column tiles cut", + 9, + expert }, + { "expert-major, K 256:128, column tiles cut", 192, 256, 128, @@ -162,83 +173,47 @@ int main() { true, true, { 64, 63, 65, 1, 0, 127, 17 }, - 5 }, - }; - struct Form { - const char* env; - int stage, tiles, lut; - const char* kernel; - bool prefill; - bool pipe = false; - }; - /* env: DECODE_EXPERTS, ALIGNED_JOBS, PREFILL_N32, PREFILL_M32, PREFILL_N64, PREFILL_CACHE_ROWS */ - const Form forms[] = { - { "100000", 256, 1, 0, "moe_mxfp4_expert_kernel<4, 256, false>", false }, - { "100000", 256, 1, 1, "moe_mxfp4_expert_kernel<4, 256, true>", false }, - { "100000", 256, 4, 0, "moe_mxfp4_expert_staged_kernel<256, 4, false>", false }, - { "100000", 256, 4, 1, "moe_mxfp4_expert_staged_kernel<256, 4, true>", false }, - { "100000", 128, 1, 0, "moe_mxfp4_expert_staged_kernel<128, 1, false>", false }, - { "100000", 128, 1, 1, "moe_mxfp4_expert_staged_kernel<128, 1, true>", false }, - { "100000", 128, 4, 0, "moe_mxfp4_expert_staged_kernel<128, 4, false>", false }, - { "100000", 128, 4, 1, "moe_mxfp4_expert_staged_kernel<128, 4, true>", false }, - { "000000", 0, 0, 1, "moe_mxfp4_fp8_kernel<1, 1, false, true>", false }, - { "010000", 0, 0, 1, "moe_mxfp4_fp8_kernel<1, 1, false, true>", true }, - { "001000", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 1, false, true>", true }, - { "011000", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 1, false, true>", true }, - { "011100", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 2, false, true>", true }, - { "011110", 0, 0, 1, "moe_mxfp4_fp8_kernel<4, 2, false, true>", true }, - { "011111", 0, 0, 0, "moe_mxfp4_fp8_kernel<4, 2, true, false>", true }, - { "011111", 0, 0, 1, "moe_mxfp4_fp8_kernel<4, 2, true, true>", true }, - { "011111", 0, 0, 0, "moe_mxfp4_prefill_kernel", true, true }, - { "011111", 0, 0, 1, "moe_mxfp4_prefill_kernel", true, true }, - }; - /* P64 at every raster point, column tiles 4 (the resident form's default) and 1, and the LDS - * output at the default; the K of a case picks streamed or resident A. */ - struct P64 { - int bm, bn, sk, ct, out, db = 0; - }; - std::vector p64s; - for (int bm : { 32, 64 }) - for (int bn : { 64, 128 }) - for (int sk : { 128, 256 }) - for (int ct : { 1, 4 }) p64s.push_back({ bm, bn, sk, ct, 0 }); - p64s.push_back({ 64, 128, 128, 4, 1 }); - p64s.push_back({ 32, 64, 256, 1, 1 }); - /* The double buffer at every BM x BN x stage: where two stages do not fit in LDS, and with - * resident A, the single-buffer form runs. */ - for (int bm : { 32, 64 }) - for (int bn : { 64, 128 }) - for (int sk : { 128, 256 }) p64s.push_back({ bm, bn, sk, 4, 0, 1 }); - p64s.push_back({ 64, 128, 128, 4, 1, 1 }); - static const char* const kP64[] = { "RADIANCE_MXFP4_PREFILL_P64", - "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", - "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN", - "RADIANCE_MXFP4_PREFILL_P64_BM", - "RADIANCE_MXFP4_PREFILL_P64_BN", - "RADIANCE_MXFP4_PREFILL_P64_STAGE_K", - "RADIANCE_MXFP4_PREFILL_P64_COLTILES", - "RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", - "RADIANCE_MXFP4_PREFILL_P64_T_BM64", - "RADIANCE_MXFP4_PREFILL_P64_T_BN128", - "RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", - "RADIANCE_MXFP4_PREFILL_P64_DB" }; - /* The rule's tile with nothing pinned, by its row bounds (unset: this test's few rows are - * under all of them); the widest tiles take the LDS output. */ - struct Rule { - const char* t_bm64; - const char* t_bn128; - const char* t_down; - const char* streamed; - const char* resident; - }; - const Rule rules[] = { { nullptr, nullptr, nullptr, "<32, 64, 256, 1, false>", - "<32, 64, 128, 4, true>" }, - { "0", nullptr, nullptr, "<64, 64, 256, 1, false>", "<32, 64, 128, 4, true>" }, - { "0", "0", "0", "<64, 128, 128, 1, false>", "<64, 128, 128, 4, true>" } }; - static const char* const kEnv[] = { - "RADIANCE_MXFP4_DECODE_EXPERTS", "RADIANCE_MXFP4_ALIGNED_JOBS", - "RADIANCE_MXFP4_PREFILL_N32", "RADIANCE_MXFP4_PREFILL_M32", - "RADIANCE_MXFP4_PREFILL_N64", "RADIANCE_MXFP4_PREFILL_CACHE_ROWS" + 5, + staged }, + { "GLM TP4 down, the GLM prefill form", + 4096, + 512, + 4096, + 512, + 1, + 8, + true, + true, + true, + glm_runs({ 63, 96, 1, 130, 32, 31, 33, 64, 65 }), + 13, + "moe_mxfp4_prefill_kernel" }, + { "GLM TP8 gate_up, P64 BM32 BN64 K256", + 512, + 4096, + 512, + 4096, + 2, + 8, + false, + true, + false, + glm_runs({ 200, 33, 300, 31, 200 }), + 20, + "(moe_mxfp4_p64_kernel<32, 64, 256, 1, false>)" }, + { "GLM TP8 down, P64 BM32 BN64 K128 x4, A resident", + 4096, + 256, + 4096, + 256, + 1, + 8, + true, + true, + true, + glm_runs({ 900, 801, 779, 700, 700, 581, 600, 600, 63, 1 }), + 40, + "(moe_mxfp4_p64_kernel<32, 64, 128, 4, true>)" }, }; for (const Case& c : all) { @@ -264,21 +239,37 @@ int main() { // A dropped slot about every eleventh row, the first rows of some runs included. sorted[r] = (r * 13 + e) % 11 == 0 ? -1 : (int)(rng() % (uint32_t)T); } + /* Stacked planes hold every expert; a pointer table names one of at most three slices a + * class, so GLM's 288 experts stay small. */ const int n[2] = { c.N, c.N_odd }, k[2] = { c.K, c.K_odd }, nexp[2] = { (E + 1) / 2, E / 2 }; std::vector w[2], s[2]; std::vector wt[2], st[2]; + std::vector> wf[2]; + int slices[2]; for (int q = 0; q < 2; ++q) { - w[q].resize((size_t)nexp[q] * n[q] * k[q] / 2); - s[q].resize((size_t)nexp[q] * n[q] * k[q] / 32); + slices[q] = c.tables ? std::min(nexp[q], 3) : nexp[q]; + w[q].resize((size_t)slices[q] * n[q] * k[q] / 2); + s[q].resize((size_t)slices[q] * n[q] * k[q] / 32); for (auto& v : w[q]) v = (uint8_t)rng(); static const uint8_t special[] = { 0, 255, 1, 254, 127 }; for (size_t i = 0; i < s[q].size(); ++i) s[q][i] = c.exceptional && rng() % 9 == 0 ? special[rng() % 5] : (uint8_t)(118 + rng() % 16); for (int x = 0; x < nexp[q]; ++x) { - wt[q].push_back(w[q].data() + (size_t)x * n[q] * k[q] / 2); - st[q].push_back(s[q].data() + (size_t)x * n[q] * k[q] / 32); + wt[q].push_back(w[q].data() + (size_t)(x % slices[q]) * n[q] * k[q] / 2); + st[q].push_back(s[q].data() + (size_t)(x % slices[q]) * n[q] * k[q] / 32); + } + /* each slice's codes as the E4M3 values the table decode gives */ + for (int x = 0; x < slices[q]; ++x) { + std::vector f((size_t)n[q] * k[q]); + const uint8_t* src = w[q].data() + (size_t)x * n[q] * k[q] / 2; + for (size_t i = 0; i < f.size(); ++i) { + uint32_t lo, hi; + r4d_mxfp4_unpack8_exact((src[i / 2] >> (4 * (i & 1))) & 15u, &lo, &hi); + f[i] = rad_fp8e4m3_to_f32((uint8_t)(lo & 0xffu)); + } + wf[q].push_back(std::move(f)); } } auto plane = [&](int q, bool scale) { @@ -291,6 +282,8 @@ int main() { }; /* the per-element sequence, on the host */ + std::vector af(a.size()); + for (size_t i = 0; i < a.size(); ++i) af[i] = rad_fp8e4m3_to_f32(a[i]); std::vector ref((size_t)T * yp, 0x7777); for (int r = 0; r < T; ++r) for (int col = 0; col < OUT; ++col) { @@ -301,21 +294,15 @@ int main() { const int pw = OUT / c.parts, cw = n[q] / c.parts, within = col % pw; const bool valid = within < cw; const int wn = (col / pw) * cw + within; - const uint8_t* wr = - w[q].data() + (size_t)(e / 2) * n[q] * k[q] / 2 + (size_t)wn * k[q] / 2; - const uint8_t* sr = - s[q].data() + (size_t)(e / 2) * n[q] * k[q] / 32 + (size_t)wn * k[q] / 32; + const float* wr = wf[q][(size_t)((e / 2) % slices[q])].data() + (size_t)wn * k[q]; + const uint8_t* sr = (const uint8_t*)st[q][(size_t)(e / 2)] + (size_t)wn * k[q] / 32; + const float* arow = af.data() + (size_t)ar * ap; float total = 0.f; for (int kb = 0; kb < k[q]; kb += 128) for (int g = 0; g < 4; ++g) { float raw = 0.f; - for (int kk = kb + g * 32; kk < kb + g * 32 + 32; ++kk) { - const uint32_t code = valid ? (wr[kk / 2] >> (4 * (kk & 1))) & 15u : 0u; - uint32_t lo, hi; - r4d_mxfp4_unpack8_exact(code, &lo, &hi); - raw += rad_fp8e4m3_to_f32(a[(size_t)ar * ap + kk]) * - rad_fp8e4m3_to_f32((uint8_t)(lo & 0xffu)); - } + for (int kk = kb + g * 32; kk < kb + g * 32 + 32; ++kk) + raw += arow[kk] * (valid ? wr[kk] : 0.f); const uint32_t x = valid ? sr[kb / 32 + g] : 127u; uint32_t bits = x == 255 ? 0x7fc00000u : x ? x << 23 : 0x00400000u; float scale; @@ -329,6 +316,12 @@ int main() { out = (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); // f32_to_bf16, r4d_common.h } + int live = 0; + for (uint16_t v : ref) live += v != 0 && v != 0x7777; + if (live < T * OUT / 3) { + std::printf("FAIL %s: output mostly zero\n", c.name); + ++fails; + } RadTensor t[9] = { ten(a.data(), RAD_F8E4M3, { Arows, NK }, { ap, 1 }), ten(as.data(), RAD_F32, { Arows, NK / 128 }, { asp, 1 }), @@ -365,118 +358,25 @@ int main() { p[8] = pi("group", 128); p[9] = ps("a_order", c.sorted_a ? "sorted" : "token"); p[10] = ps("dtype", "mxfp4a8"); - auto run = [&](const Form& f, std::vector& y) { - y.assign((size_t)T * yp, 0x7777); - t[8] = ten(y.data(), RAD_BF16, { T, OUT }, { yp, 1 }); - for (int i = 0; i < 6; ++i) setenv(kEnv[i], f.env[i] == '1' ? "1" : "0", 1); - if (f.stage) { - setenv("RADIANCE_MXFP4_EXPERTS_STAGE_K", std::to_string(f.stage).c_str(), 1); - setenv("RADIANCE_MXFP4_EXPERTS_COLTILES", std::to_string(f.tiles).c_str(), 1); - } - setenv("RADIANCE_MXFP4_LUT", f.lut ? "1" : "0", 1); - setenv("RADIANCE_MXFP4_PREFILL_PIPE", f.pipe ? "1" : "0", 1); - RadArgs ar{}; - ar.t = t; - ar.n_t = 9; - ar.p = p; - ar.n_p = 11; - emu_last_kernel = ""; - return r4d_rad_moe_mxfp4(&ar, nullptr); - }; - auto run_p64 = [&](const P64& f, std::vector& y) { - const int v[8] = { 1, 0, 0, f.bm, f.bn, f.sk, f.ct, f.out }; - for (int i = 0; i < 8; ++i) setenv(kP64[i], std::to_string(v[i]).c_str(), 1); - setenv(kP64[11], f.db ? "1" : "0", 1); - const Form base = { "000000", 0, 0, 1, "", false }; - const int rc = run(base, y); - setenv(kP64[0], "0", 1); - return rc; - }; - const Form alt = { "000000", 0, 0, 0, "moe_mxfp4_fp8_kernel<1, 1, false, false>", false }; - std::vector legacy, got; + std::vector got((size_t)T * yp, 0x7777); + t[8] = ten(got.data(), RAD_BF16, { T, OUT }, { yp, 1 }); + RadArgs ar{}; + ar.t = t; + ar.n_t = 9; + ar.p = p; + ar.n_p = 11; + emu_last_kernel = ""; ++cases; - int rc = run(alt, legacy); - if (rc != RAD_OK || !std::strstr(emu_last_kernel, alt.kernel)) { - std::printf("FAIL %s: reference form rc %d kernel %s\n", c.name, rc, emu_last_kernel); + const int rc = r4d_rad_moe_mxfp4(&ar, nullptr); + const size_t i = first_diff(got, ref); + if (rc != RAD_OK || std::strcmp(emu_last_kernel, c.kernel) || i != got.size()) { + std::printf("FAIL %s (T %d): ran %s (want %s), rc %d, first word %zu (row %zu col %zu: " + "%04x, want %04x)\n", + c.name, T, emu_last_kernel, c.kernel, rc, i, i / yp, i % yp, + i < got.size() ? got[i] : 0, i < ref.size() ? ref[i] : 0); ++fails; - continue; - } - if (!same16(legacy, ref)) { - const size_t i = first_diff(legacy, ref); - std::printf("FAIL %s: reference form against the host sequence at row %zu col %zu: " - "%04x, want %04x\n", - c.name, i / yp, i % yp, legacy[i], ref[i]); - ++fails; - } - int live = 0; - for (uint16_t v : ref) live += v != 0 && v != 0x7777; - if (live < T * OUT / 3) { - std::printf("FAIL %s: output mostly zero\n", c.name); - ++fails; - } - for (const Form& f : forms) { - if (f.prefill && T < 512) continue; - ++cases; - rc = run(f, got); - const bool reached = std::strstr(emu_last_kernel, f.kernel) != nullptr; - if (rc != RAD_OK || !reached || !same16(got, legacy)) { - const size_t i = first_diff(got, legacy); - std::printf( - "FAIL %s: form %s stage %d tiles %d lut %d ran %s (want %s), rc %d, first " - "word %zu\n", - c.name, f.env, f.stage, f.tiles, f.lut, emu_last_kernel, f.kernel, rc, i); - ++fails; - } - } - const bool resident = NK <= 256; - for (const Rule& u : rules) { - ++cases; - for (const char* v : kP64) unsetenv(v); - setenv(kP64[0], "1", 1); - setenv(kP64[1], "0", 1); - setenv(kP64[2], "0", 1); - if (u.t_bm64) setenv(kP64[8], u.t_bm64, 1); - if (u.t_bn128) setenv(kP64[9], u.t_bn128, 1); - if (u.t_down) setenv(kP64[10], u.t_down, 1); - const Form base = { "000000", 0, 0, 1, "", false }; - rc = run(base, got); - for (const char* v : kP64) unsetenv(v); - const std::string want = - std::string("moe_mxfp4_p64_kernel") + (resident ? u.resident : u.streamed); - if (rc != RAD_OK || !std::strstr(emu_last_kernel, want.c_str()) || - !same16(got, legacy)) { - std::printf("FAIL %s: P64 rule ran %s (want %s), rc %d, first word %zu\n", c.name, - emu_last_kernel, want.c_str(), rc, first_diff(got, legacy)); - ++fails; - } - } - for (const P64& f : p64s) { - ++cases; - rc = run_p64(f, got); - const bool db = f.db && !resident && (f.sk == 128 || (f.bm == 32 && f.bn == 64)); - const std::string want = "moe_mxfp4_p64_kernel<" + std::to_string(f.bm) + ", " + - std::to_string(f.bn) + ", " + std::to_string(f.sk) + ", " + - (resident ? std::to_string(f.ct) : "1") + ", " + - (resident ? "true" : "false") + (db ? ", true>" : ">"); - const bool reached = std::strstr(emu_last_kernel, want.c_str()) != nullptr; - if (rc != RAD_OK || !reached || !same16(got, legacy)) { - const size_t i = first_diff(got, legacy); - std::printf("FAIL %s: P64 bm %d bn %d stage %d tiles %d out %d db %d ran %s (want " - "%s), rc %d, " - "first word %zu (row %zu col %zu: %04x, want %04x)\n", - c.name, f.bm, f.bn, f.sk, f.ct, f.out, f.db, emu_last_kernel, - want.c_str(), rc, i, i / yp, i % yp, i < got.size() ? got[i] : 0, - i < legacy.size() ? legacy[i] : 0); - ++fails; - } } } - for (const char* v : kEnv) unsetenv(v); - for (const char* v : kP64) unsetenv(v); - unsetenv("RADIANCE_MXFP4_EXPERTS_STAGE_K"); - unsetenv("RADIANCE_MXFP4_EXPERTS_COLTILES"); - unsetenv("RADIANCE_MXFP4_LUT"); - unsetenv("RADIANCE_MXFP4_PREFILL_PIPE"); std::printf("%d case(s), %d failure(s)\n", cases, fails); return fails ? 1 : 0; } diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 03e63ce7..052f5835 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -966,7 +966,7 @@ TEST(op_vocabulary) { * denoiser, and the index helpers that feed them. */ "conv1d", "conv_t1d", "snake", "cfg_topk_sample", "rvq_embed", "frame_mix_store", "end_status", "resample_nearest", "fourier_embed", "win_input", "win_prep", "win_finish", - "chan_split", "interleave2", "iota", "cu_repeat", "frame_store", + "chan_split", "interleave2", "iota", "cu_repeat", "int_affine", "frame_store", /* The video generator's (MiniMax-H3): its DiT's modulated norm and sampler step, its * decoder's patch unfold, tiles, stitch and positions, and the vocoder's alias-free * activation. */ @@ -979,6 +979,20 @@ TEST(op_vocabulary) { * the fold back into patch rows and the re-noising. */ "conv3d_ndhwc", "group_norm", "tconv_dw", "resize_bilinear", "patch_fold", "flow_renoise", + /* The joint image generators' (Krea 2, FLUX.3): attention over separate key bounds, a + * per-layer table added to every row, a learned mix of consecutive rows, and the VAE's + * channel statistics. */ + "attn_cross", "table_add", "mix_rows", "chan_stats", + /* LTX-2's: its rotary over fractional coordinates, the per-head gate and the guided + * sampler step. */ + "rope_split", "head_gate", "ltx_guide", + /* Its VAE's norm, resampling and patches; its vocoder's spectrogram and resampler. */ + "pixel_norm", "d2s3d", "s2d3d", "pix_patch", "patch_pix8", "stft_logmel", "bwe_up", + /* Its VAE decoded in tiles: the boxes, a tile's latent, the blended stitch. */ + "tile_grid", "tile_crop", "tile_stitch", + /* LTX-2.5's diffusion decoder: its rotary's voxel coordinates and its neighborhood + * attention. */ + "vol_index", "attn_na3d", }; for (const char* op : kOps) { if (!kern(op)) fprintf(stderr, " missing op '%s'\n", op); @@ -7063,6 +7077,188 @@ TEST(scale_rows_gates_each_row_by_its_scalar) { CHECK_EQ(y2.at(2), 36.0f); CHECK_EQ(y2.at(3), 48.0f); } +/* tile_grid: diffusers' tiled_decode boxes -- a tile every `stride` latents while it starts inside + * the axis, `tile` long or to the edge -- one row (t, h, w, t0, y0, x0, k, count) a tile, rows past + * the count zero. 29 rows at stride 14 are bands of 16, 15 and 1; 16 columns are bands of 16 and + * 2. Under `intervals` (the diffusion decoder's _tile_intervals) an axis of `tile` cells or fewer + * is one band and a last band shorter than `min` joins the one before: 61 frames at 40 / 28 are + * [0, 40) and [28, 61); 68 rows at 96 / 88 one band; 100 columns at 96 / 88, min 13, one band + * of 96 and then [88, 100) is 12 < 13, merged: [0, 100). The last time band carries `tail` more. */ +TEST(tile_grid_cuts_where_tiled_decode_does) { + T g(RAD_I32, {3}); g.n({3, 29, 16}); + T y(RAD_I32, {7, 8}); + A a; a.t(g).t(y).i("M", 7).i("tile", 16).i("stride", 14); + CHECK_OK(run("tile_grid", a)); + const int32_t want[7][8] = { { 3, 16, 16, 0, 0, 0, 0, 6 }, { 3, 16, 2, 0, 0, 14, 1, 6 }, + { 3, 15, 16, 0, 14, 0, 2, 6 }, { 3, 15, 2, 0, 14, 14, 3, 6 }, + { 3, 1, 16, 0, 28, 0, 4, 6 }, { 3, 1, 2, 0, 28, 14, 5, 6 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }; + for (int k = 0; k < 7; ++k) + for (int e = 0; e < 8; ++e) CHECK_EQ(y.iat(k * 8 + e), want[k][e]); + T g2(RAD_I32, {3}); g2.n({61, 68, 100}); + T y2(RAD_I32, {3, 8}); + A b; b.t(g2).t(y2).i("M", 3).i("tile", 96).i("stride", 88).s("rule", "intervals").i("min", 13) + .i("tile_t", 40).i("stride_t", 28).i("min_t", 6).i("tail", 8); + CHECK_OK(run("tile_grid", b)); + const int32_t want2[3][8] = { { 40, 68, 100, 0, 0, 0, 0, 2 }, { 41, 68, 100, 28, 0, 0, 1, 2 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }; + for (int k = 0; k < 3; ++k) + for (int e = 0; e < 8; ++e) CHECK_EQ(y2.iat(k * 8 + e), want2[k][e]); +} + +/* attn_na3d is attention over each query's window: on a 2 x 4 x 5 volume with a 3 x 3 x 3 window + * (2 in time, the axis's length), the window of the corner voxel (0, 0, 0) is shifted inward to + * start at (0, 0, 0), and of (1, 3, 4) to start at (0, 1, 2); against attention over exactly those + * keys. */ +TEST(attn_na3d_attends_the_inward_shifted_window) { + const int64_t Tn = 2, Hn = 4, Wn = 5, V = Tn * Hn * Wn, hd = 4; + auto val = [](int64_t i) { return (float)((i * 29) % 23 - 11) / 8.0f; }; + std::vector qv((size_t)(V * hd)), kv((size_t)(V * hd)), vv((size_t)(V * hd)); + for (int64_t i = 0; i < V * hd; ++i) { qv[(size_t)i] = val(i); kv[(size_t)i] = val(i + 7); vv[(size_t)i] = val(i + 13); } + T q(RAD_F32, {V, hd}); q.f(qv); + T k(RAD_F32, {V, hd}); k.f(kv); + T v(RAD_F32, {V, hd}); v.f(vv); + T g(RAD_I32, {3}); g.n({Tn, Hn, Wn}); + T o(RAD_F32, {V, hd}); + A a; a.t(q).t(k).t(v).t(g).t(o).i("M", V).i("head_dim", hd).i("kt", 3).i("kh", 3).i("kw", 3) + .s("dtype", "f32"); + CHECK_OK(run("attn_na3d", a)); + struct Q { int64_t t, i, j, t0, i0, j0; }; + for (const Q c : { Q{ 0, 0, 0, 0, 0, 0 }, Q{ 1, 3, 4, 0, 1, 2 }, Q{ 0, 2, 2, 0, 1, 1 } }) { + const int64_t r = (c.t * Hn + c.i) * Wn + c.j; + std::vector sc; + std::vector keys; + for (int64_t a1 = c.t0; a1 < c.t0 + 2; ++a1) + for (int64_t b1 = c.i0; b1 < c.i0 + 3; ++b1) + for (int64_t c1 = c.j0; c1 < c.j0 + 3; ++c1) { + const int64_t key = (a1 * Hn + b1) * Wn + c1; + double d = 0; + for (int64_t e = 0; e < hd; ++e) d += (double)qv[(size_t)(r * hd + e)] * kv[(size_t)(key * hd + e)]; + sc.push_back(d / 2.0); + keys.push_back(key); + } + double mx = -1e30, sum = 0; + for (double x : sc) mx = std::max(mx, x); + for (double& x : sc) { x = std::exp(x - mx); sum += x; } + for (int64_t e = 0; e < hd; ++e) { + double want = 0; + for (size_t n = 0; n < keys.size(); ++n) want += sc[n] / sum * vv[(size_t)(keys[n] * hd + e)]; + CHECK_NEAR(o.at(r * hd + e), want, 1e-5); + } + } +} + +/* vol_index: a 2 x 2 x 3 volume's coordinates, component-major; voxel 7 is (1, 0, 1). */ +TEST(vol_index_writes_each_voxels_coordinates) { + T g(RAD_I32, {3}); g.n({2, 2, 3}); + T y(RAD_I32, {3, 12}); + A a; a.t(g).t(y).i("M", 12); + CHECK_OK(run("vol_index", a)); + CHECK_EQ(y.iat(7), 1); CHECK_EQ(y.iat(12 + 7), 0); CHECK_EQ(y.iat(24 + 7), 1); + CHECK_EQ(y.iat(11), 1); CHECK_EQ(y.iat(12 + 11), 1); CHECK_EQ(y.iat(24 + 11), 2); +} + +/* tile_crop copies a box out of the volume: a 2 x 3 x 4 volume of its row indices, the 1 x 2 x 2 + * box at (1, 1, 1). */ +TEST(tile_crop_copies_the_box) { + T x(RAD_F32, {24, 1}); + std::vector v(24); + for (int i = 0; i < 24; ++i) v[(size_t)i] = (float)i; + x.f(v); + T g(RAD_I32, {3}); g.n({2, 3, 4}); + T b(RAD_I32, {6}); b.n({1, 2, 2, 1, 1, 1}); + T y(RAD_F32, {4, 1}); + A a; a.t(x).t(g).t(b).t(y).i("M", 4).i("C", 1).s("dtype", "f32"); + CHECK_OK(run("tile_crop", a)); + CHECK_EQ(y.at(0), 17.0f); CHECK_EQ(y.at(1), 18.0f); + CHECK_EQ(y.at(2), 21.0f); CHECK_EQ(y.at(3), 22.0f); +} + +/* tile_stitch: tiles cut from one picture stitch back to that picture's bytes (every blend mixes + * equal values; with an extent of 2 the weights are 0, 0.5 and 1, so exactly); and across a seam + * between a tile of zeros and one of ones, the first column of the right tile is the left tile's + * margin and the second their mean. A 5 x 5 latent grid at tile 4, stride 3, a latent 1 x 1 patch + * of 2 x 2 pixels: bands of 4 and 2 latents, 8 and 4 pixels, kept to 6. */ +TEST(tile_stitch_blends_as_tiled_decode_and_keeps_a_cut_picture) { + const int64_t H = 5, W = 5, tile = 4, stride = 3, p = 2, Hp = H * p, Wp = W * p; + auto band = [&](int64_t L, int64_t k) { return std::min(tile, L - k * stride); }; + auto band_of = [](int64_t L, int64_t k, int64_t t, int64_t s) { return std::min(t, L - k * s); }; + std::vector img((size_t)(Hp * Wp)); + for (int64_t i = 0; i < Hp * Wp; ++i) img[(size_t)i] = (float)((i * 37) % 63 - 31) / 32.0f; + auto store = [&](auto value) { + std::vector v; + for (int64_t i = 0; i < 2; ++i) + for (int64_t j = 0; j < 2; ++j) + for (int64_t py = 0; py < band(H, i); ++py) /* patch rows of the tile */ + for (int64_t px = 0; px < band(W, j); ++px) + for (int64_t dx = 0; dx < p; ++dx) /* order wh: column offset outer */ + for (int64_t dy = 0; dy < p; ++dy) + v.push_back(value(i, j, py * p + dy, px * p + dx)); + return v; + }; + auto run_stitch = [&](const std::vector& tiles, std::vector* out) { + T x(RAD_F32, {(int64_t)tiles.size() / (p * p), p * p}); x.f(tiles); + T g(RAD_I32, {3}); g.n({1, H, W}); + T f(RAD_I32, {1}); f.n({0}); + T y(RAD_U8, {Hp, Wp}); + A a; a.t(x).t(g).t(f).t(y).i("M", Hp).i("tile", tile).i("stride", stride).i("scale", 1) + .i("p", p).i("C", 1).s("dtype", "f32"); + CHECK_OK(run("tile_stitch", a)); + out->resize((size_t)(Hp * Wp)); + for (int64_t i = 0; i < Hp * Wp; ++i) (*out)[(size_t)i] = y.mem[(size_t)i]; + }; + std::vector got; + run_stitch(store([&](int64_t i, int64_t j, int64_t yy, int64_t xx) { + return img[(size_t)((i * stride * p + yy) * Wp + j * stride * p + xx)]; + }), &got); + for (int64_t i = 0; i < Hp * Wp; ++i) { + const float u = std::min(std::max(img[(size_t)i] / 2.0f + 0.5f, 0.0f), 1.0f); + CHECK_EQ((int)got[(size_t)i], (int)std::nearbyint(u * 255.0f)); + } + /* Left tiles zeros, right tiles ones: row 0 is 0 to column 6, the margin (0) at 6, the mean at + * 7, then 1 (bytes 128, 128, 191, 255). */ + run_stitch(store([](int64_t, int64_t j, int64_t, int64_t) { return j ? 1.0f : 0.0f; }), &got); + CHECK_EQ((int)got[5], 128); CHECK_EQ((int)got[6], 128); + CHECK_EQ((int)got[7], 191); CHECK_EQ((int)got[8], 255); + + /* In time too: 4 cells of 2 frames, the first one frame (7 frames), cut at tile_t 3, stride_t 2 + * into cells [0, 3) (frames 0..4) and [2, 4) (frames 3..6); each tile is its box of a 7-frame + * clip, and every frame stitches back to the clip's bytes. */ + const int64_t nfr = 7; + std::vector clip((size_t)(nfr * Hp * Wp)); + for (int64_t i = 0; i < (int64_t)clip.size(); ++i) clip[(size_t)i] = (float)((i * 53) % 61 - 30) / 32.0f; + std::vector tiles3; + for (int64_t kt = 0; kt < 2; ++kt) { + const int64_t P = kt == 0 ? 0 : 3, F = kt == 0 ? 5 : 4; + for (int64_t i = 0; i < 2; ++i) + for (int64_t j = 0; j < 2; ++j) + for (int64_t f = 0; f < F; ++f) + for (int64_t py = 0; py < band_of(H, i, tile, stride); ++py) + for (int64_t px = 0; px < band_of(W, j, tile, stride); ++px) + for (int64_t dx = 0; dx < p; ++dx) + for (int64_t dy = 0; dy < p; ++dy) + tiles3.push_back(clip[(size_t)(((P + f) * Hp + i * stride * p + + py * p + dy) * Wp + + j * stride * p + px * p + dx)]); + } + { + T x(RAD_F32, {(int64_t)tiles3.size() / (p * p), p * p}); x.f(tiles3); + T g(RAD_I32, {3}); g.n({4, H, W}); + T f(RAD_I32, {1}); f.n({0}); + T y(RAD_U8, {nfr * Hp, Wp}); + A a; a.t(x).t(g).t(f).t(y).i("M", nfr * Hp).i("tile", tile).i("stride", stride) + .i("tile_t", 3).i("stride_t", 2).i("scale", 1).i("scale_t", 2).i("p", p).i("C", 1) + .s("dtype", "f32"); + CHECK_OK(run("tile_stitch", a)); + int64_t bad = 0; + for (int64_t i = 0; i < nfr * Hp * Wp; ++i) { + const float u = std::min(std::max(clip[(size_t)i] / 2.0f + 0.5f, 0.0f), 1.0f); + bad += (int)y.mem[(size_t)i] != (int)std::nearbyint(u * 255.0f); + } + CHECK_EQ(bad, (int64_t)0); + } +} + TEST(sigmoid_is_the_logistic_function) { T x(RAD_F32, {1, 4}); x.f({0, 100, -100, 1}); T y(RAD_F32, {1, 4}); @@ -7749,6 +7945,7 @@ std::vector geometries() { G("interleave2", "M", 4, a.i("M", R).s("dtype", "f32")), G("iota", "M", 4, a.i("M", R).i("start", 0).i("step", 1)), G("cu_repeat", "M", 3, a.i("M", R).i("mult", 2)), + G("int_affine", "M", 3, a.i("M", R).s("src", "0 -1 2").s("mul", "2 0 4").s("add", "-1 5 -3")), G("frame_store", "M", 2, a.i("M", R).i("n_codes", 4).i("stride", 6).i("rep", 2) .i("skip", 0)), G("rms_mod", "M", 4, a.i("M", R).i("n", 8).d("eps", 1e-6).i("gated", 1).s("dtype", "bf16")), @@ -7784,6 +7981,35 @@ std::vector geometries() { G("patch_fold", "M", 8, a.i("M", R).i("C", 3).i("pt", 1).i("ph", 2).i("pw", 2) .s("mul", "1 2 3").s("add", "0 1 2").s("dtype", "f32")), G("flow_renoise", "M", 3, a.i("M", R).i("n", 8).i("stream", 1).s("dtype", "f32")), + G("attn_cross", "M", 6, a.i("M", R).i("head_dim", 8).i("gqa", 2).i("causal", 0) + .s("dtype", "f32").i("n_head", 2)), + G("table_add", "M", 3, a.i("M", R).i("n", 8).i("L", 3).s("dtype", "f32")), + G("mix_rows", "M", 3, a.i("M", R).i("n", 8).i("k", 4).s("dtype", "f32")), + G("chan_stats", "M", 3, a.i("M", R).i("n", 8).s("mode", "norm").s("dtype", "f32")), + G("rope_split", "M", 3, a.i("M", R).i("n_head", 2).i("head_dim", 8).i("dim", 16) + .i("n_dims", 3).d("theta", 10000.0).s("max", "20 2048 2048") + .s("dtype", "f32")), + G("head_gate", "M", 3, a.i("M", R).i("n_head", 2).i("head_dim", 8).s("dtype", "f32")), + G("ltx_guide", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), + G("pixel_norm", "M", 4, a.i("M", R).i("n", 8).d("eps", 1e-6).s("form", "rsqrt") + .i("ileave", 2).d("mult", 2.5).s("dtype", "f32")), + /* M 7 is a cube of side 1 and 14 one of side 2, so the zero-row call sees the volume + * change. */ + G("d2s3d", "M", 7, a.i("M", R).i("C", 3).i("st", 2).i("sh", 2).i("sw", 2).s("dtype", "f32")), + G("s2d3d", "M", 7, a.i("M", R).i("C", 6).i("st", 1).i("sh", 1).i("sw", 1) + .i("group", 2).s("mode", "mean").s("dtype", "f32")), + G("pix_patch", "M", 4, a.i("M", R).i("p", 2).i("C", 3).s("dtype", "f32")), + G("patch_pix8", "M", 4, a.i("M", R).i("p", 2).i("C", 3).s("dtype", "f32")), + G("stft_logmel", "M", 3, a.i("M", R).i("hop", 4).i("nfft", 8).i("n_mel", 3).i("ch", 2) + .s("dtype", "f32")), + G("bwe_up", "M", 6, a.i("M", R).i("ratio", 3).i("ch", 2).s("dtype", "f32")), + G("tile_grid", "M", 4, a.i("M", R).i("tile", 4).i("stride", 3)), + G("vol_index", "M", 7, a.i("M", R)), + G("attn_na3d", "M", 7, a.i("M", R).i("head_dim", 8).i("kt", 3).i("kh", 3).i("kw", 3) + .s("dtype", "f32")), + G("tile_crop", "M", 7, a.i("M", R).i("C", 3).s("dtype", "f32")), + G("tile_stitch", "M", 100, a.i("M", R).i("tile", 4).i("stride", 3).i("scale", 2).i("p", 2) + .i("C", 3).s("dtype", "f32")), }; } #undef G diff --git a/tests/runtime_test.cpp b/tests/runtime_test.cpp index b90bf499..da6fbd01 100644 --- a/tests/runtime_test.cpp +++ b/tests/runtime_test.cpp @@ -229,7 +229,7 @@ struct Fixture { return (rad_op)(P.ops.size() - 1); } - int start(rad::ResidencyTable* res = nullptr, bool profile = false) { + int start(rad::ResidencyTable* res = nullptr, bool profile = false, bool record = false) { CtxDesc d; d.program = &P; d.rank = 1; @@ -241,8 +241,8 @@ struct Fixture { d.registry = registry; /* The arch bodies here issue whatever a case asks, which the batch does not describe, so * no pass may be recorded and replayed under the batch's key (a card records passes; the - * host backend cannot). */ - d.record_passes = false; + * host backend cannot). A case about the recording decision itself asks for it. */ + d.record_passes = record; return ctx.init(d); } @@ -1869,6 +1869,25 @@ TEST(a_lane_built_mid_step_starts_behind_lane_zero) { CHECK_EQ(dev_get(f, f.ctx.buf_ptr(y)), 4242); } +/* A calibration tap's gram_accum sums across passes while its plugin counts the summed rows in + * step; a played pass reissues the sum without calling step (#122). A program holding one records + * no passes; one without records them wherever the backend can. */ +TEST(a_program_with_a_calibration_tap_records_no_passes) { + { + Fixture f; + f.add_buffer("x", RAD_BF16, 64, 4, 0); + loose_op(f); + CHECK_OK(f.start(nullptr, false, /*record=*/true)); + CHECK_EQ(f.ctx.records_passes(), rad::tape_supported()); + } + Fixture f; + f.add_buffer("x", RAD_BF16, 64, 4, 0); + loose_op(f); + loose_op(f, "gram_accum"); + CHECK_OK(f.start(nullptr, false, /*record=*/true)); + CHECK(!f.ctx.records_passes()); +} + /* ================================================================== the pass key */ /* A recorded pass is replayed while its key holds, so the key must change with every batch field * and runtime state a pass's shape or arguments read, and must not change with the step number diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index fe015b94..4fd32561 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -1746,6 +1746,23 @@ static Interleaved interleave_run(int64_t n, bool decoder, int steps) { return out; } +/* Between a commit and the next step (where an encoder pass is prepared) the committed step's + * plan names a request the scheduler may already have released: a client cancelled it and the + * server reaped it. prefill_continues() reads only an open step's plan (#127). */ +TEST(prefill_continues_reads_no_committed_plan) { + Fixture f; + f.build(); + CHECK_OK(f.start()); + f.sch.set_stage_rows(64); + const uint64_t p = f.submit(2000, 4); + CHECK(f.sch.step() != nullptr); + CHECK(f.sch.prefill_continues()); + f.commit_plain(12); + CHECK_OK(f.sch.cancel(p)); + CHECK_OK(f.sch.reap(p)); + CHECK(!f.sch.prefill_continues()); +} + TEST(interleave_off_puts_a_chunk_in_every_step) { const Interleaved r = interleave_run(0, /*decoder=*/true, 8); CHECK_EQ(r.shape, std::string("CCCCCCCC")); @@ -2717,9 +2734,9 @@ TEST(the_decode_floor_records_only_single_sequence_decode_steps) { f.build(/*blocks=*/4096, /*states=*/64); CHECK_OK(f.start()); - /* A prefill step samples nothing. Budget 128 tokens: this test walks 1 prefill + - * (kWindow-1) + 1 + kWindow = 65 steps, so 64 would run dry one step short. */ - uint64_t a = f.submit(160, 128, /*priority=*/0, /*ignore_eos=*/true); + /* A prefill step samples nothing. Budget 320 tokens: this test walks 1 prefill + one window, + * at most six windows until the floor is set and one more, 257 steps. */ + uint64_t a = f.submit(160, 320, /*priority=*/0, /*ignore_eos=*/true); REQUIRE(f.sch.step() != nullptr); f.commit_plain(11); f.sch.step_finished(); @@ -2745,9 +2762,11 @@ TEST(the_decode_floor_records_only_single_sequence_decode_steps) { f.sch.step_finished(); CHECK_EQ(f.sch.metrics().step_ns_decode_best, (int64_t)0); - /* The SECOND window is the first gated one and sets the floor: positive, and no larger than - * the cumulative decode time it was drawn from. */ - for (int i = 0; i < rad::DecodeFloor::kWindow; ++i) { + /* The first gated window sets the floor: positive, and no larger than the cumulative decode + * time it was drawn from. The fixture's steps take microseconds and vary widely, so the gate + * may reject some and the window take more than kWindow steps to fill. */ + for (int i = 0; i < 6 * rad::DecodeFloor::kWindow && !f.sch.metrics().step_ns_decode_best; + ++i) { REQUIRE(f.sch.step() != nullptr); f.commit_plain(14); f.sch.step_finished(); @@ -2769,27 +2788,23 @@ TEST(the_decode_floor_records_only_single_sequence_decode_steps) { } TEST(the_decode_floor_ignores_a_decode_step_issued_behind_a_prefill) { - /* The live defect was a raw min latching the first decode step, which is issued ahead behind - * the prefill's host-side staging and whose bracket holds no GPU work. The fix does NOT - * exclude that step -- it is a real single-sequence decode step and belongs in the floor. It - * is made harmless by averaging: the floor is a min over window means, so the one degenerate - * bracket is diluted by the honest steps sharing its window. This pins that the - * prefill-following decode step IS eligible: a full window of decode steps that BEGINS with it - * produces a floor. Under the old predecessor-phase gate the first step was dropped, so a - * window of exactly kWindow decode steps fed only kWindow-1 samples and left the floor unset - * -- this test would have failed on that design. */ + /* The decode step issued behind the prefill's host-side staging is a real single-sequence + * decode step: it is eligible, and the window mean dilutes its short bracket. Decode steps + * that begin with it produce a floor. The fixture's steps take microseconds and vary widely, + * so the gate may reject some and a window take more than kWindow steps to fill. */ Fixture f; f.build(/*blocks=*/4096, /*states=*/64); CHECK_OK(f.start()); - uint64_t a = f.submit(160, 128, /*priority=*/0, /*ignore_eos=*/true); + uint64_t a = f.submit(160, 256, /*priority=*/0, /*ignore_eos=*/true); REQUIRE(f.sch.step() != nullptr); /* prefill */ f.commit_plain(21); f.sch.step_finished(); - /* Two windows: window 1 (holding the prefill-following step) is the un-gated warmup, so the - * floor only appears once a second, gated window completes. */ - for (int i = 0; i < 2 * rad::DecodeFloor::kWindow; ++i) { + /* Window 1 (holding the prefill-following step) is the un-gated warmup, so the floor only + * appears once a gated window completes. */ + for (int i = 0; i < 6 * rad::DecodeFloor::kWindow && !f.sch.metrics().step_ns_decode_best; + ++i) { REQUIRE(f.sch.step() != nullptr); CHECK_EQ(f.sch.plan().phase, RAD_PHASE_DECODE); CHECK_EQ(f.sch.plan().n_seq_decode, 1); diff --git a/tests/server_fakes.h b/tests/server_fakes.h index 7bcb18fd..51f183d0 100644 --- a/tests/server_fakes.h +++ b/tests/server_fakes.h @@ -144,6 +144,8 @@ struct FakeChatTemplate : IChatTemplate { if (!tools.empty()) s += "[tools:" + std::to_string(tools.size()) + "]"; if (!opt.enable_thinking) s += "[nothink]"; for (const auto& kv : opt.template_kwargs) s += "[" + kv.first + "=" + kv.second + "]"; + if (!default_effort.empty() && !opt.template_kwargs.count("reasoning_effort")) + s += "[reasoning_effort=" + default_effort + "]"; size_t n_msg = 0; int tool_msgs = 0; for (const auto& m : messages) { @@ -203,6 +205,8 @@ struct FakeChatTemplate : IChatTemplate { std::string refusal; std::string refuse_kwarg; std::vector efforts; /* JSON text, as the template context carries them */ + /* The effort a render naming none is written as, as Qwen3.8's template writes xhigh. */ + std::string default_effort; /* The reasoning block a render reports. FakeTokenizer makes a one-byte marker one token. */ std::string think_open, think_close; bool think_starts_open = false; diff --git a/tests/server_test.cpp b/tests/server_test.cpp index 368f4c9e..c8862fa9 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -946,6 +946,14 @@ TEST(an_effort_the_template_refuses_is_answered_with_the_set_it_takes) { CHECK_EQ(set[0], std::string("low")); CHECK_EQ(set[1], std::string("medium")); CHECK_EQ(set[2], std::string("xhigh")); + CHECK(f.srv->template_default_effort().empty()); /* no level renders as no level */ + /* A template that writes one level when a request names none, as Qwen3.8's writes xhigh + * (#113): the probe names it. */ + f.tmpl.default_effort = "\"xhigh\""; + f.srv->probe_reasoning_efforts(); + CHECK_EQ(f.srv->template_default_effort(), std::string("xhigh")); + f.tmpl.default_effort.clear(); + f.srv->probe_reasoning_efforts(); OaiLimits lim = f.limits(); lim.reasoning_efforts = set; @@ -4016,6 +4024,56 @@ TEST(a_responses_request_becomes_the_chat_request_it_means) { &echo, &e) < 0); } +/* A namespace groups function tools (Codex sends every MCP server's tools that way). They reach + * the model flattened to __, the reply's function_call item reports the two apart, + * streamed and not, and the next turn's call and tool_choice come back joined (#119). */ +TEST(a_namespaces_tools_are_offered_flat_and_answered_apart) { + OaiLimits lim; + std::string chat, echo; + ApiError e; + std::map> ns; + CHECK_OK(responses_to_chat(R"({ + "tools":[{"type":"function","name":"plain","parameters":{"type":"object"}}, + {"type":"namespace","name":"crm","description":"d","tools":[ + {"type":"function","name":"find","parameters":{"type":"object"}}, + {"type":"custom","name":"raw"}]}], + "tool_choice":{"type":"function","namespace":"crm","name":"find"}, + "input":[{"role":"user","content":"x"}, + {"type":"function_call","call_id":"c1","namespace":"crm","name":"find","arguments":"{}"}, + {"type":"function_call_output","call_id":"c1","output":"y"}]})", + lim, &chat, &echo, &e, &ns)); + const json c = json::parse(chat); + CHECK_EQ(c["tools"].size(), (size_t)2); /* the custom tool left out */ + CHECK_EQ(c["tools"][1]["function"].value("name", ""), std::string("crm__find")); + CHECK_EQ(c["messages"][1]["tool_calls"][0]["function"].value("name", ""), std::string("crm__find")); + CHECK_EQ(c["tool_choice"]["function"].value("name", ""), std::string("crm__find")); + CHECK_EQ(ns.size(), (size_t)1); + CHECK_EQ(ns["crm__find"].first, std::string("crm")); + CHECK_EQ(json::parse(echo)["tools"].size(), (size_t)2); /* echoed as sent */ + + /* A flattened name may not shadow a top-level tool's. */ + CHECK(responses_to_chat(R"({"input":"x","tools":[{"type":"function","name":"crm__find"}, + {"type":"namespace","name":"crm","tools":[{"type":"function","name":"find"}]}]})", + lim, &chat, &echo, &e, &ns) < 0); + + Fixture f; + f.sched.reply = R"(TOOL:crm__find:{"q":"P"})"; + const std::string tools = R"("tools":[{"type":"namespace","name":"crm","tools":[)" + R"({"type":"function","name":"find","parameters":{"type":"object"}}]}],)"; + HttpResponse r = f.post("/v1/responses", "{" + tools + R"("input":"find P"})"); + CHECK_EQ(r.status, 200); + const json o = json::parse(r.body); + CHECK_EQ(o["output"][0].value("type", ""), std::string("function_call")); + CHECK_EQ(o["output"][0].value("namespace", ""), std::string("crm")); + CHECK_EQ(o["output"][0].value("name", ""), std::string("find")); + f.sched.join_all(); + HttpResponse st = f.post("/v1/responses", "{" + tools + R"("stream":true,"input":"find P"})"); + const std::string body = drain(st); + CHECK(has(body, R"("namespace":"crm")")); + CHECK(!has(body, "crm__find")); + f.sched.join_all(); +} + TEST(the_responses_api_answers_with_a_response_object_and_its_events) { Fixture f; HttpResponse r = f.post("/v1/responses", R"({"model":"m","input":"hi"})"); diff --git a/tests/shipped_plugins_test.cpp b/tests/shipped_plugins_test.cpp index 10bc8aa2..78a8a144 100644 --- a/tests/shipped_plugins_test.cpp +++ b/tests/shipped_plugins_test.cpp @@ -88,12 +88,13 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) { CHECK(keys.emplace(std::make_pair(p.arch_id, p.arch_quant), p.name).second); } const std::set> want = { - { "breeze", "" }, { "embeddinggemma2", "" }, { "gemma3", "" }, { "gemma4", "" }, + { "breeze", "" }, { "embeddinggemma2", "" }, { "flux3", "" }, { "flux3distilled", "" }, + { "gemma3", "" }, { "gemma4", "" }, { "gemma4", "compressed-tensors" }, { "glm5next", "" }, { "lfm2", "" }, { "llama", "" }, { "llama", "fp8_e4m3" }, { "qwen35", "" }, { "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" }, - { "qwen3asr", "" }, - { "minimaxh3", "" }, { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" } }; + { "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" }, + { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" } }; std::set> got; for (const auto& [k, name] : keys) got.insert(k); if (got != want) diff --git a/tests/video_gen_test.cpp b/tests/video_gen_test.cpp index c1380d4e..9861d9e0 100644 --- a/tests/video_gen_test.cpp +++ b/tests/video_gen_test.cpp @@ -8,8 +8,10 @@ using namespace sched_fake; #include "gen/video_driver.h" +#include "rad_plugin.h" #include +#include #include #include @@ -55,9 +57,13 @@ RadVideoGenDecl decl_small() { return d; } +/* The soundtrack's rows a latent in fake_positions' layout: the declaration's audio_streams, or its + * two channels. */ +int g_audio_streams = 2; + /* The packed layout's rows, each position the row's index; a decode pass, ten rows a frame. */ int64_t fake_positions(int which, const RadVideoGeom* g, float* pos, int64_t cap) { - const int64_t rows = g->n_text + 2 * (int64_t)g->n_audio + + const int64_t rows = g->n_text + g_audio_streams * (int64_t)g->n_audio + (int64_t)g->lat_frames * (g->lat_h / 2) * (g->lat_w / 2); if (which == RAD_VPOS_DECODE) return 10 * (int64_t)g->frames; if (pos) { @@ -409,7 +415,7 @@ TEST(an_upscale_that_cannot_run_is_refused_at_submit) { /* What can never run is refused at submit: an empty or long prompt, a size off the multiple, * below the least side, over the area or the aspect, a length outside the chunks, steps outside - * 2..max. */ + * 2..max. A length of 0 chunks is none named. */ TEST(a_request_that_cannot_run_is_refused_at_submit) { VideoFixture f; f.build(); @@ -438,9 +444,395 @@ TEST(a_request_that_cannot_run_is_refused_at_submit) { r->height = 96; refused(std::move(r), "size"); refused(f.req(4), "chunks"); - refused(f.req(0), "chunks"); refused(f.req(1, 6), "num_inference_steps"); refused(f.req(1, 1), "num_inference_steps"); + /* No length named is the model's default. */ + auto none = f.req(0); + gen::VideoTicket* t = none->ticket.get(); + CHECK_OK(f.drv.submit(std::move(none), &why)); + CHECK_EQ(t->frames, 3); +} + +/* Decoders (RadVideoGenDecl::decoders): a request's index reaches every VDECODE pass; an index past + * the list, or a frame over the decoder's area, is refused at submit. */ +TEST(the_decoder_a_request_names_reaches_its_decode_passes) { + VideoFixture f; + f.build(); + f.prog.vgen_str.decoders = { "vae", "diffusion" }; + f.prog.vgen_str.decoder_max_area = { 64 * 64, 32 * 32 }; + CHECK_OK(f.start()); + std::string why; + auto r = f.req(1); + r->decoder = 1; + CHECK_EQ(f.drv.submit(std::move(r), &why), (int)RAD_E_INVAL); /* 64 x 32 over 32 x 32 */ + CHECK(why.find("diffusion") != std::string::npos); + r = f.req(1); + r->decoder = 2; + CHECK_EQ(f.drv.submit(std::move(r), &why), (int)RAD_E_INVAL); + r = f.req(1); + r->decoder = 1; + r->width = 32; + r->height = 32; + CHECK_OK(f.drv.submit(std::move(r), &why)); + int decodes = 0; + for (int i = 0; i < 20; ++i) { + const RadBatch* b = f.drv.next(i); + if (!b) break; + if (b->gen == RAD_GEN_PASS_VDECODE) { + CHECK_EQ(b->vgen_b->decoder, 1); + ++decodes; + } + f.answer(0); + CHECK_OK(f.drv.done()); + } + CHECK(decodes > 0); +} + +/* A length head (RadVideoGenDecl::duration_out): a request that names no length is shaped at the + * default until its VCOND pass, whose prediction (ln seconds, read back) the driver turns into + * chunks -- clamped to the declared seconds, rounded half to even to frames, floored to the chunk + * grid and lifted a chunk under the minimum -- then held to the chunks the model makes. */ +TEST(a_length_head_sets_the_length_after_the_prompt_pass) { + struct Case { double sec; int32_t frames; }; + /* 4 fps, 2 frames a chunk + 1, 1..3 chunks, 0.5..2 s (2..8 frames): 1.3 s is 5.2 frames, 5; + * 1.125 s is 4.5, which rounds to 4 (half to even) and floors to 3; 0.1 s is held to 2 + * frames, which floor to 1 and are lifted to 3; 9 s is held to 8 frames, 7 on the grid. */ + const Case cases[] = { { 1.3, 5 }, { 1.125, 3 }, { 0.1, 3 }, { 9.0, 7 } }; + for (const Case& k : cases) { + VideoFixture f; + f.build(); + f.prog.video_gen.duration_out = 3; + f.prog.video_gen.duration_min = 0.5; + f.prog.video_gen.duration_max = 2.0; + f.prog.video_gen.duration_dtype = RAD_F32; + CHECK_OK(f.start()); + std::string why; + auto r = f.req(0); + std::shared_ptr t = r->ticket; + CHECK_OK(f.drv.submit(std::move(r), &why)); + CHECK_EQ(t->frames, 3); /* the default, one chunk */ + const RadBatch* b = f.drv.next(0); + REQUIRE(b != nullptr); + CHECK_EQ(b->gen, (int)RAD_GEN_PASS_VCOND); + REQUIRE_EQ(f.drv.readbacks().size(), (size_t)1); + CHECK_EQ(f.drv.readbacks()[0].buf, (rad_buf)3); + *static_cast(f.drv.readbacks()[0].host) = (float)std::log(k.sec); + CHECK_OK(f.drv.done()); + CHECK_EQ(t->frames, k.frames); + gen::VideoEvent e; + bool to = false; + REQUIRE(t->next(&e, 0, &to)); + CHECK_EQ(e.kind, (int)gen::VideoEvent::LENGTH); + CHECK_EQ(e.n, k.frames); + /* The steps run at that length. */ + b = f.drv.next(1); + REQUIRE(b != nullptr); + CHECK_EQ(b->gen, (int)RAD_GEN_PASS_VSTEP); + CHECK_EQ(b->vgen_b->geom.frames, k.frames); + } +} + +/* ---- form 1 (LTX-2's FlowMatchEulerDiscrete): evaluations, not grid points */ + +static uint32_t bits(float v) { + uint32_t u; + std::memcpy(&u, &v, 4); + return u; +} + +/* The dev schedule bit for bit against diffusers' scheduler (numpy 2.5): 30 evaluations of a + * 6144-token video shift by mu 2.7833 and stretch to end at 0.1; and 7 of a 1500-token one. */ +TEST(form_one_is_ltx2s_dynamically_shifted_schedule_bit_for_bit) { + RadVideoGenDecl d = decl_small(); + d.sched_kind = 1; + d.dyn_shift = 1; + d.base_shift = 0.95; + d.max_shift = 2.05; + d.base_seq = 1024; + d.max_seq = 4096; + d.shift_terminal = 0.1; + const gen::VideoSchedule s = gen::video_schedule(d, 30, 6144); + REQUIRE_EQ(s.sig_v.size(), (size_t)31); + CHECK_EQ(s.steps, 30); + const std::pair want[] = { + { 0, 0x3f800000u }, { 1, 0x3f7f3c87u }, { 2, 0x3f7e6c02u }, { 15, 0x3f6b19eeu }, + { 27, 0x3eff5f82u }, { 28, 0x3eb2f452u }, { 29, 0x3dccccd0u }, { 30, 0u }, + }; + for (const auto& w : want) CHECK_EQ(bits(s.sig_v[(size_t)w.first]), w.second); + CHECK(s.sig_a == s.sig_v); + const gen::VideoSchedule s7 = gen::video_schedule(d, 7, 1500); + const uint32_t want7[] = { 0x3f800000u, 0x3f6e0d50u, 0x3f57d30eu, 0x3f3b945eu, 0x3f167dc8u, + 0x3ec74586u, 0x3dccccd0u, 0u }; + REQUIRE_EQ(s7.sig_v.size(), (size_t)8); + for (int i = 0; i < 8; ++i) CHECK_EQ(bits(s7.sig_v[(size_t)i]), want7[i]); + /* One evaluation is a schedule of form 1. */ + CHECK_EQ(gen::video_schedule(d, 1, 6144).steps, 1); +} + +static const double kDistilled[] = { 1.0, 0.99375, 0.9875, 0.98125, 0.975, 0.909375, 0.725, + 0.421875 }; +static const double kStage2[] = { 0.909375, 0.725, 0.421875 }; + +RadVideoGenDecl decl_distilled() { + RadVideoGenDecl d = decl_small(); + d.sched_kind = 1; + d.n_rungs = 8; + d.rungs = kDistilled; + d.default_steps = d.max_steps = 8; + d.upscale_max = 2.0; + d.n_refine_rungs = 3; + d.refine_rungs = kStage2; + d.upscale_refine = 3; + return d; +} + +/* A trained schedule of form 1 is its rungs as given, and with refinement the second stage's rungs + * follow the first's in place of the 0. */ +TEST(form_one_rungs_are_used_as_given_and_the_refinement_follows_them) { + const RadVideoGenDecl d = decl_distilled(); + const gen::VideoSchedule s = gen::video_schedule(d, 8); + REQUIRE_EQ(s.sig_v.size(), (size_t)9); + CHECK_EQ(s.steps, 8); + for (int i = 0; i < 8; ++i) CHECK_EQ(s.sig_v[(size_t)i], (float)kDistilled[i]); + CHECK_EQ(s.sig_v[8], 0.0f); + CHECK_EQ(gen::video_schedule(d, 9).steps, 0); + const gen::VideoSchedule r = gen::video_schedule(d, 8, 0, true); + REQUIRE_EQ(r.sig_v.size(), (size_t)12); + CHECK_EQ(r.steps, 11); + CHECK_EQ(r.sig_v[8], (float)kStage2[0]); + CHECK_EQ(r.sig_v[10], (float)kStage2[2]); + CHECK_EQ(r.sig_v[11], 0.0f); +} + +/* Two stages: every first-stage rung at the small size, the last to the clean estimate; the + * upscale re-noises to the second stage's first sigma; the second stage's rungs at the full size. + * The request's refinement is the second stage's length or nothing. */ +TEST(a_two_stage_request_runs_the_second_stages_own_rungs_after_the_upscale) { + VideoFixture f; + f.build(); + f.prog.video_gen = decl_distilled(); + f.prog.video_gen.rungs = nullptr; + f.prog.video_gen.refine_rungs = nullptr; + f.prog.vgen_str.rungs.assign(kDistilled, kDistilled + 8); + f.prog.vgen_str.refine_rungs.assign(kStage2, kStage2 + 3); + CHECK_OK(f.start()); + std::string why; + auto bad = f.req(1, 0); + bad->width = bad->height = 64; + bad->upscale = 2.0; + bad->refine = 2; + CHECK_EQ(f.drv.submit(std::move(bad), &why), (int)RAD_E_INVAL); + CHECK(has(why, "upscale_refine_steps must be 3")); + auto r = f.req(1, 0); + r->width = r->height = 64; + r->upscale = 2.0; + auto t = r->ticket; + CHECK_OK(f.drv.submit(std::move(r), &why)); + CHECK_EQ(t->steps, 11); + CHECK_EQ(t->refine, 3); + std::string kinds; + int n = 0; + for (int i = 0; i < 40; ++i) { + const RadBatch* b = f.drv.next(i); + if (!b) break; + const RadVideoGenBatch* V = b->vgen_b; + kinds += kind_of(b->gen); + if (b->gen == RAD_GEN_PASS_VSTEP) { + const float cur = n < 8 ? (float)kDistilled[n] : (float)kStage2[n - 8]; + const float nxt = n == 7 || n == 10 ? 0.0f + : n < 7 ? (float)kDistilled[n + 1] : (float)kStage2[n - 7]; + CHECK_EQ(V->sched[1], cur); + CHECK_EQ(V->sched[2], nxt); + CHECK_EQ(V->geom.lat_h, n < 8 ? 2 : 4); + ++n; + } else if (b->gen == RAD_GEN_PASS_VUPSCALE) { + CHECK_EQ(V->sched[1], (float)kStage2[0]); + CHECK_EQ(V->sched[4], (float)kStage2[0]); + } + f.answer(0); + CHECK_OK(f.drv.done()); + } + CHECK_EQ(kinds, std::string("CSSSSSSSSUSSSAD")); + CHECK_EQ(t->status(), (int)RAD_OK); +} + +/* A guided model: the request's terms over the model's defaults reach every pass; the negative + * prompt rides in the VCOND pass after the prompt, each from position 0, only while a scale asks + * for the unconditional branch; the text rows of a step are the model's fixed count. */ +TEST(guidance_and_the_negative_prompt_reach_the_passes) { + VideoFixture f; + f.build(); + RadVideoGenDecl& d = f.prog.video_gen; + d.guidance = 1; + const double defaults[8] = { 3.0, 1.0, 3.0, 0.7, 7.0, 1.0, 3.0, 0.7 }; + std::memcpy(d.guidance_default, defaults, sizeof defaults); + d.step_text_rows = 6; + CHECK_OK(f.start()); + std::string why; + auto r = f.req(1, 3); + r->neg_tokens = { 9, 8 }; + r->guidance[1] = 0.0; + CHECK_OK(f.drv.submit(std::move(r), &why)); + const RadBatch* b = f.drv.next(0); + REQUIRE(b && b->gen == RAD_GEN_PASS_VCOND); + const RadVideoGenBatch* V = b->vgen_b; + CHECK_EQ(b->n_tok, (int64_t)5); + CHECK_EQ(b->n_seq, 2); + CHECK_EQ(V->n_neg, 2); + CHECK(std::vector(b->cu_seqlens, b->cu_seqlens + 3) == std::vector({ 0, 3, 5 })); + CHECK(std::vector(b->token_ids, b->token_ids + 5) == + std::vector({ 1, 2, 3, 9, 8 })); + CHECK(std::vector(b->positions, b->positions + 5) == + std::vector({ 0, 1, 2, 0, 1 })); + CHECK_EQ(V->geom.n_text, 6); + REQUIRE(V->guidance_h != nullptr); + CHECK_EQ(V->guidance_h[0], 3.0f); + CHECK_EQ(V->guidance_h[1], 0.0f); + CHECK_EQ(V->guidance_h[3], 0.7f); + CHECK_OK(f.drv.done()); + b = f.drv.next(1); + REQUIRE(b && b->gen == RAD_GEN_PASS_VSTEP); + CHECK_EQ(b->n_tok, (int64_t)(6 + 60 + 2 * 2)); + CHECK_EQ(b->vgen_b->guidance_h[4], 7.0f); + /* The device copy the ops read. */ + REQUIRE(b->vgen_b->guidance != nullptr); + CHECK_EQ(b->vgen_b->guidance[0], 3.0f); + CHECK_EQ(b->vgen_b->guidance[4], 7.0f); + CHECK_OK(f.drv.done()); + + /* Both scales 1: no unconditional branch, so no negative prompt. */ + VideoFixture g; + g.build(); + g.prog.video_gen = d; + CHECK_OK(g.start()); + auto u = g.req(1, 3); + u->neg_tokens = { 9 }; + u->guidance[0] = 1.0; + u->guidance[4] = 1.0; + CHECK_OK(g.drv.submit(std::move(u), &why)); + b = g.drv.next(0); + REQUIRE(b && b->gen == RAD_GEN_PASS_VCOND); + CHECK_EQ(b->n_tok, (int64_t)3); + CHECK_EQ(b->n_seq, 1); + CHECK_EQ(b->vgen_b->n_neg, 0); + + /* A guided request with no negative prompt cannot run; an unguided model takes no terms. */ + auto m = g.req(1, 3); + why.clear(); + CHECK_EQ(g.drv.submit(std::move(m), &why), (int)RAD_E_INVAL); + CHECK(has(why, "negative prompt")); + VideoFixture h; + h.build(); + CHECK_OK(h.start()); + auto q = h.req(1, 3); + q->guidance[2] = 2.0; + why.clear(); + CHECK_EQ(h.drv.submit(std::move(q), &why), (int)RAD_E_INVAL); + CHECK(has(why, "no guidance")); +} + +/* A first frame reaches the VCOND pass as bf16 x / 255 * 2 - 1 at the size the first steps run + * at, and every pass of the request says it has one; a model without image conditioning, or a + * frame of another size, is refused. */ +TEST(a_first_frame_reaches_the_prompt_pass_at_the_first_steps_size) { + VideoFixture f; + f.build(); + f.prog.video_gen.image_cond = 1; + f.prog.video_gen.upscale_max = 2.0; + f.prog.video_gen.upscale_refine = 1; + CHECK_OK(f.start()); + std::string why; + auto r = f.req(1, 3); + r->width = r->height = 64; + r->upscale = 2.0; + r->image.assign(32 * 32 * 3, 0); + r->image[0] = 255; + r->image[1] = 128; + auto wrong = f.req(1, 3); + wrong->image.assign(64 * 32 * 3, 0); + wrong->width = wrong->height = 64; + wrong->upscale = 2.0; + CHECK_EQ(f.drv.submit(std::move(wrong), &why), (int)RAD_E_INVAL); + CHECK(has(why, "32x32")); + CHECK_OK(f.drv.submit(std::move(r), &why)); + const RadBatch* b = f.drv.next(0); + REQUIRE(b && b->gen == RAD_GEN_PASS_VCOND); + const RadVideoGenBatch* V = b->vgen_b; + REQUIRE(V->image != nullptr); + CHECK_EQ(V->has_image, 1); + CHECK_EQ(V->image[0], rad_f32_to_bf16(1.0f)); + CHECK_EQ(V->image[1], rad_f32_to_bf16(2.0f * (128.0f / 255.0f) - 1.0f)); + CHECK_EQ(V->image[2], rad_f32_to_bf16(-1.0f)); + CHECK_OK(f.drv.done()); + b = f.drv.next(1); + REQUIRE(b && b->gen == RAD_GEN_PASS_VSTEP); + CHECK(b->vgen_b->image == nullptr); + CHECK_EQ(b->vgen_b->has_image, 1); + + VideoFixture g; + g.build(); + CHECK_OK(g.start()); + auto q = g.req(1, 3); + q->image.assign(64 * 32 * 3, 0); + why.clear(); + CHECK_EQ(g.drv.submit(std::move(q), &why), (int)RAD_E_INVAL); + CHECK(has(why, "picture")); +} + +/* A left-padded encoder's prompt ends at text_left_pad - 1, the negative prompt too; one stream of + * soundtrack rows a latent; an exact upscaler takes its factor only, over sides it divides. */ +TEST(left_padded_prompts_one_audio_stream_and_an_exact_upscaler) { + VideoFixture f; + f.build(); + RadVideoGenDecl& d = f.prog.video_gen; + d.guidance = 1; + d.guidance_default[0] = 3.0; + d.guidance_default[4] = 1.0; + d.text_left_pad = 8; + d.audio_streams = 1; + d.upscale_max = 2.0; + d.upscale_refine = 1; + d.upscale_exact = 1; + g_audio_streams = 1; + CHECK_OK(f.start()); + std::string why; + auto r = f.req(1, 3); + r->neg_tokens = { 9, 8 }; + CHECK_OK(f.drv.submit(std::move(r), &why)); + const RadBatch* b = f.drv.next(0); + REQUIRE(b && b->gen == RAD_GEN_PASS_VCOND); + CHECK(std::vector(b->positions, b->positions + 5) == + std::vector({ 5, 6, 7, 6, 7 })); + CHECK_OK(f.drv.done()); + b = f.drv.next(1); + REQUIRE(b && b->gen == RAD_GEN_PASS_VSTEP); + /* 3 text rows, 30 soundtrack latents in one stream, 2 x 2 video patches. */ + CHECK_EQ(b->n_tok, (int64_t)(3 + 30 + 2 * 2)); + /* The soundtrack as a (30, 1, 1) volume; the video's rows cut at its first latent frame. */ + const int32_t* gd = b->vgen_b->geom_d; + CHECK(std::vector(gd + RAD_VGEOM_AUDIO_VOL, gd + RAD_VGEOM_AUDIO_VOL + 3) == + std::vector({ 30, 1, 1 })); + CHECK_EQ(gd[RAD_VGEOM_FIRST_CU], 0); + CHECK_EQ(gd[RAD_VGEOM_FIRST_CU + 2], 4); + CHECK_EQ(gd[RAD_VGEOM_FIRST_CU + 1] * gd[RAD_VGEOM_LAT_FRAMES], 4); + CHECK_OK(f.drv.done()); + + auto u = f.req(1, 3); + u->width = 64; + u->height = 32; + u->upscale = 2.0; + u->neg_tokens = { 9 }; + why.clear(); + CHECK_EQ(f.drv.submit(std::move(u), &why), (int)RAD_E_INVAL); + CHECK(has(why, "multiples of 64")); + auto v = f.req(1, 3); + v->width = v->height = 64; + v->upscale = 1.5; + v->neg_tokens = { 9 }; + why.clear(); + CHECK_EQ(f.drv.submit(std::move(v), &why), (int)RAD_E_INVAL); + CHECK(has(why, "exactly 2")); + g_audio_streams = 2; } RAD_TEST_MAIN() diff --git a/tests/videos_test.cpp b/tests/videos_test.cpp index 76ba6905..27c93a23 100644 --- a/tests/videos_test.cpp +++ b/tests/videos_test.cpp @@ -10,6 +10,7 @@ #include "server_fakes.h" #include "gen/video.h" +#include "mm/media.h" #include #include @@ -65,6 +66,13 @@ struct FakeVideoGen : IVideoGen { t.refine = r->refine > 0 ? r->refine : (int32_t)inf.upscale_refine; } if (finish_status == RAD_OK) { + /* A request that named no length learns the one the model chose first. */ + if (r->chunks == 0) { + gen::VideoEvent l; + l.kind = gen::VideoEvent::LENGTH; + l.n = 3; + t.push(std::move(l)); + } for (int s = 1; s <= 2; ++s) { gen::VideoEvent e; e.kind = gen::VideoEvent::STEP; @@ -209,6 +217,57 @@ TEST(the_generator_gets_the_size_the_chunks_and_the_steps) { v.wait(str_at(json::parse(r.body, nullptr, false), "id")); } +/* A model with a length head chooses the length of a request that names none or says "auto": the + * generator gets 0 chunks, the video object says "auto" until the model has chosen and then the + * length chosen. A length named is as for any model; without a head, none named is the default. */ +TEST(a_length_head_chooses_the_length_of_a_request_that_names_none) { + Videos v; + HttpResponse r = v.create(Videos::body()); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(v.gen.last().chunks, 7); + v.wait(str_at(json::parse(r.body, nullptr, false), "id")); + + v.gen.inf.length_head = true; + for (const json& b : { Videos::body(), Videos::body({ { "seconds", "auto" } }) }) { + r = v.create(b); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(v.gen.last().chunks, 0); + json o = json::parse(r.body, nullptr, false); + CHECK_EQ(str_at(o, "seconds"), std::string("auto")); + o = v.wait(str_at(o, "id")); + CHECK_EQ(str_at(o, "status"), std::string("completed")); + CHECK_EQ(str_at(o, "seconds"), std::string("0.12")); /* 3 frames at 24 a second */ + } + r = v.create(Videos::body({ { "seconds", "8" } })); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(v.gen.last().chunks, 11); + v.wait(str_at(json::parse(r.body, nullptr, false), "id")); +} + +/* A model with more than one decoder takes `decoder` by name, the default first: the generator gets + * its index, the video object names a decoder other than the default, an unknown name or a frame + * over the decoder's area is a 400 naming the field. A model with one decoder takes no name. */ +TEST(a_decoder_is_named_and_held_to_its_area) { + Videos v; + CHECK_EQ(v.refused(Videos::body({ { "decoder", "vae" } })), std::string("decoder")); + v.gen.inf.decoders = { "vae", "diffusion" }; + v.gen.inf.decoder_max_area = { 1344 * 768, 512 * 256 }; + HttpResponse r = v.create(Videos::body({ { "decoder", "diffusion" }, { "size", "512x256" } })); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(v.gen.last().decoder, 1); + json o = json::parse(r.body, nullptr, false); + CHECK_EQ(str_at(o, "decoder"), std::string("diffusion")); + v.wait(str_at(o, "id")); + r = v.create(Videos::body({ { "decoder", "vae" } })); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(v.gen.last().decoder, 0); + CHECK(!json::parse(r.body, nullptr, false).contains("decoder")); + v.wait(str_at(json::parse(r.body, nullptr, false), "id")); + CHECK_EQ(v.refused(Videos::body({ { "decoder", "magic" } })), std::string("decoder")); + CHECK_EQ(v.refused(Videos::body({ { "decoder", "diffusion" }, { "size", "768x512" } })), + std::string("decoder")); +} + /* Latent upscaling: refused by a model without an upscaler; with one, the factor and the refine * steps reach the generator, a factor of 1 is none, and the refine steps need a factor. */ TEST(latent_upscale_reaches_the_generator_where_the_model_has_an_upscaler) { @@ -340,4 +399,163 @@ TEST(the_video_routes_are_501_without_a_video_model) { CHECK_EQ(f.get("/v1/videos").status, 501); } +namespace { + +/* A PNG of w x h, every pixel (r, g, b). */ +std::string png_rgb(int32_t w, int32_t h, uint8_t r, uint8_t g, uint8_t b) { + std::vector px; + for (int64_t i = 0; i < (int64_t)w * h; ++i) px.insert(px.end(), { r, g, b }); + std::vector file; + std::string why; + if (mm::encode_image(px.data(), w, h, 3, "png", 0, &file, &why) < 0) return std::string(); + return std::string(file.begin(), file.end()); +} + +std::string png_url(const std::string& bytes) { + return "data:image/png;base64," + base64_encode(bytes.data(), bytes.size()); +} + +/* A guided model that starts from a picture, as LTX-2.5's dev weights. */ +void guided(Videos& v, int32_t crf) { + VideoGenInfo& in = v.gen.inf; + in.guidance = true; + const double d[8] = { 3.0, 1.0, 3.0, 0.7, 7.0, 1.0, 3.0, 0.7 }; + std::copy(d, d + 8, in.guidance_default); + in.default_negative = "ugly"; + in.image_cond = true; + in.image_crf = crf; + in.step_evals = true; + in.upscale_max = 2.0; + in.upscale_refine = 3; +} + +std::string text_of(const std::vector& ids) { + std::string s; + for (int32_t c : ids) s += (char)c; + return s; +} + +} /* namespace */ + +/* Guidance terms and the negative prompt: refused by a model without guidance; on a guided one the + * named terms reach the generator (the rest NaN, the model's default), the negative prompt is + * rendered in the template (the model's own when none is named), and the video object reports the + * resolved terms. Steps count evaluations there, from 1. */ +TEST(guidance_and_the_negative_prompt_reach_a_guided_model) { + { + Videos v; + CHECK_EQ(v.refused(Videos::body({ { "negative_prompt", "x" } })), + std::string("negative_prompt")); + CHECK_EQ(v.refused(Videos::body({ { "stg_scale", 1 } })), std::string("stg_scale")); + } + Videos v; + guided(v, 0); + CHECK_EQ(v.refused(Videos::body({ { "guidance_rescale", 1.5 } })), + std::string("guidance_rescale")); + CHECK_EQ(v.refused(Videos::body({ { "audio_guidance_scale", -1 } })), + std::string("audio_guidance_scale")); + CHECK_EQ(v.refused(Videos::body({ { "negative_prompt", 3 } })), std::string("negative_prompt")); + HttpResponse r = v.create(Videos::body({ { "guidance_scale", 5 }, { "audio_stg_scale", "0" }, + { "negative_prompt", "blurry" }, + { "num_inference_steps", 1 } })); + REQUIRE_EQ(r.status, 200); + const gen::VideoRequest& q = v.gen.last(); + CHECK_EQ(q.guidance[0], 5.0); + CHECK_EQ(q.guidance[5], 0.0); + CHECK(std::isnan(q.guidance[1]) && std::isnan(q.guidance[4])); + CHECK(q.has_neg); + CHECK_EQ(text_of(q.neg_tokens), std::string("blurry")); + CHECK_EQ(q.steps, 1); + json o = json::parse(r.body, nullptr, false); + CHECK_EQ(o["guidance_scale"].get(), 5.0); + CHECK_EQ(o["guidance_rescale"].get(), 0.7); + CHECK_EQ(o["audio_guidance_scale"].get(), 7.0); + CHECK_EQ(str_at(o, "negative_prompt"), std::string("blurry")); + v.wait(str_at(o, "id")); + + r = v.create(Videos::body()); + REQUIRE_EQ(r.status, 200); + CHECK(!v.gen.last().has_neg); + CHECK_EQ(text_of(v.gen.last().neg_tokens), std::string("ugly")); + v.wait(str_at(json::parse(r.body, nullptr, false), "id")); + + /* Both scales 1: unguided, so the object names no negative prompt. */ + r = v.create(Videos::body({ { "guidance_scale", 1 }, { "audio_guidance_scale", 1 } })); + REQUIRE_EQ(r.status, 200); + o = json::parse(r.body, nullptr, false); + CHECK(!o.contains("negative_prompt")); + v.wait(str_at(o, "id")); +} + +/* input_reference: refused by a text-only model; on a model that starts from a picture, a data URL + * in JSON or a file in a form becomes the first frame at the size the first steps run at (the + * small size under latent upscaling), an even colour staying that colour; task i2va goes with it. */ +TEST(input_reference_becomes_the_first_frame_at_the_first_steps_size) { + const std::string pic = png_rgb(300, 170, 200, 40, 90); + { + Videos v; + CHECK_EQ(v.refused(Videos::body({ { "input_reference", png_url(pic) } })), + std::string("input_reference")); + } + Videos v; + guided(v, 0); + CHECK_EQ(v.refused(Videos::body({ { "input_reference", "data:image/png;base64,AAAA" } })), + std::string("input_reference")); + CHECK_EQ(v.refused(Videos::body({ { "input_reference", png_url(pic) }, { "task", "t2va" } })), + std::string("task")); + HttpResponse r = v.create(Videos::body({ { "input_reference", { { "image_url", png_url(pic) } } }, + { "task", "i2va" } })); + REQUIRE_EQ(r.status, 200); + const gen::VideoRequest& q = v.gen.last(); + REQUIRE_EQ(q.image.size(), (size_t)256 * 256 * 3); + CHECK_EQ((int)q.image[0], 200); + CHECK_EQ((int)q.image[1], 40); + CHECK_EQ((int)q.image[q.image.size() - 1], 90); + json o = json::parse(r.body, nullptr, false); + CHECK(o.value("input_reference", false)); + v.wait(str_at(o, "id")); + + r = v.create(Videos::body({ { "input_reference", png_url(pic) }, { "size", "512x512" }, + { "latent_upscale", 2 } })); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(v.gen.last().image.size(), (size_t)256 * 256 * 3); + v.wait(str_at(json::parse(r.body, nullptr, false), "id")); + + HttpRequest f; + f.method = "POST"; + f.path = "/v1/videos"; + f.form = { FormPart{ "prompt", "", "", "a boat" }, FormPart{ "size", "", "", "512x256" }, + FormPart{ "input_reference", "boat.png", "image/png", pic } }; + r = v.f->srv->router().dispatch(f); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(v.gen.last().image.size(), (size_t)512 * 256 * 3); + v.wait(str_at(json::parse(r.body, nullptr, false), "id")); +} + +/* With the model's H.264 quality the picture goes through the round trip first: an even colour + * comes back within a few levels (yuv420p's rounding), an odd size losing its last column. */ +TEST(input_reference_takes_the_models_h264_round_trip) { + Videos v; + guided(v, 18); + const std::string pic = png_rgb(301, 171, 200, 40, 90); + HttpResponse r = v.create(Videos::body({ { "input_reference", png_url(pic) } })); + if (r.status == 503) return; /* a build without libx264 refuses it, as it should */ + REQUIRE_EQ(r.status, 200); + const gen::VideoRequest& q = v.gen.last(); + REQUIRE_EQ(q.image.size(), (size_t)256 * 256 * 3); + const int want[3] = { 200, 40, 90 }; + for (size_t i = 0; i < q.image.size(); i += 997) + CHECK(std::abs((int)q.image[i] - want[i % 3]) <= 3); + v.wait(str_at(json::parse(r.body, nullptr, false), "id")); + + mm::Frame in, out; + in.w = 7; + in.h = 5; + in.rgb.assign(7 * 5 * 3, 128); + std::string why; + REQUIRE_EQ(mm::h264_roundtrip(in, 18, &out, &why), (int)RAD_OK); + CHECK_EQ(out.w, 6); + CHECK_EQ(out.h, 4); +} + RAD_TEST_MAIN() diff --git a/vendor/UPSTREAM b/vendor/UPSTREAM index 12b439eb..9faf508b 100644 --- a/vendor/UPSTREAM +++ b/vendor/UPSTREAM @@ -552,9 +552,9 @@ PATCH SERIES An escaped space or non-ASCII character is itself. \x and \u in a class need their hex digits; "\0" before a digit (a legacy octal) is refused. Every other class escape is now refused at conversion with a message naming it. Limits: a negated class still admits the - \u form of a character it leaves out (\u0009 for \t), and a positive class admits \t \n - \r \f \b only in their short form. gbnf_test covers each escape in and out of a class, quantified, and negated, and the - refusals. + \u form of a character it leaves out (\u0009 for \t), and a positive class admits \t \n \r \f + \b only in their short form. gbnf_test covers each escape in and out of a class, quantified, + and negated, and the refusals. patches/0021-jinja-a-dotted-integer-is-an-index.patch